PackageManagerService.java revision 5cf5578a457e448dda9fd47943e91f0f3b67690f
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.security.KeyStore; 199import android.security.SystemKeyStore; 200import android.system.ErrnoException; 201import android.system.Os; 202import android.text.TextUtils; 203import android.text.format.DateUtils; 204import android.util.ArrayMap; 205import android.util.ArraySet; 206import android.util.AtomicFile; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.util.jar.StrictJarFile; 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.telephony.CarrierAppUtils; 233import com.android.internal.util.ArrayUtils; 234import com.android.internal.util.FastPrintWriter; 235import com.android.internal.util.FastXmlSerializer; 236import com.android.internal.util.IndentingPrintWriter; 237import com.android.internal.util.Preconditions; 238import com.android.internal.util.XmlUtils; 239import com.android.server.EventLogTags; 240import com.android.server.FgThread; 241import com.android.server.IntentResolver; 242import com.android.server.LocalServices; 243import com.android.server.ServiceThread; 244import com.android.server.SystemConfig; 245import com.android.server.Watchdog; 246import com.android.server.pm.PermissionsState.PermissionState; 247import com.android.server.pm.Settings.DatabaseVersion; 248import com.android.server.pm.Settings.VersionInfo; 249import com.android.server.storage.DeviceStorageMonitorInternal; 250 251import dalvik.system.CloseGuard; 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.Certificate; 281import java.security.cert.CertificateEncodingException; 282import java.security.cert.CertificateException; 283import java.text.SimpleDateFormat; 284import java.util.ArrayList; 285import java.util.Arrays; 286import java.util.Collection; 287import java.util.Collections; 288import java.util.Comparator; 289import java.util.Date; 290import java.util.HashSet; 291import java.util.Iterator; 292import java.util.List; 293import java.util.Map; 294import java.util.Objects; 295import java.util.Set; 296import java.util.concurrent.CountDownLatch; 297import java.util.concurrent.TimeUnit; 298import java.util.concurrent.atomic.AtomicBoolean; 299import java.util.concurrent.atomic.AtomicInteger; 300import java.util.concurrent.atomic.AtomicLong; 301 302/** 303 * Keep track of all those APKs everywhere. 304 * <p> 305 * Internally there are two important locks: 306 * <ul> 307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 308 * and other related state. It is a fine-grained lock that should only be held 309 * momentarily, as it's one of the most contended locks in the system. 310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 311 * operations typically involve heavy lifting of application data on disk. Since 312 * {@code installd} is single-threaded, and it's operations can often be slow, 313 * this lock should never be acquired while already holding {@link #mPackages}. 314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 315 * holding {@link #mInstallLock}. 316 * </ul> 317 * Many internal methods rely on the caller to hold the appropriate locks, and 318 * this contract is expressed through method name suffixes: 319 * <ul> 320 * <li>fooLI(): the caller must hold {@link #mInstallLock} 321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 322 * being modified must be frozen 323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 325 * </ul> 326 * <p> 327 * Because this class is very central to the platform's security; please run all 328 * CTS and unit tests whenever making modifications: 329 * 330 * <pre> 331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 333 * </pre> 334 */ 335public class PackageManagerService extends IPackageManager.Stub { 336 static final String TAG = "PackageManager"; 337 static final boolean DEBUG_SETTINGS = false; 338 static final boolean DEBUG_PREFERRED = false; 339 static final boolean DEBUG_UPGRADE = false; 340 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 341 private static final boolean DEBUG_BACKUP = false; 342 private static final boolean DEBUG_INSTALL = false; 343 private static final boolean DEBUG_REMOVE = false; 344 private static final boolean DEBUG_BROADCASTS = false; 345 private static final boolean DEBUG_SHOW_INFO = false; 346 private static final boolean DEBUG_PACKAGE_INFO = false; 347 private static final boolean DEBUG_INTENT_MATCHING = false; 348 private static final boolean DEBUG_PACKAGE_SCANNING = false; 349 private static final boolean DEBUG_VERIFY = false; 350 private static final boolean DEBUG_FILTERS = false; 351 352 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 353 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 354 // user, but by default initialize to this. 355 static final boolean DEBUG_DEXOPT = false; 356 357 private static final boolean DEBUG_ABI_SELECTION = false; 358 private static final boolean DEBUG_EPHEMERAL = false; 359 private static final boolean DEBUG_TRIAGED_MISSING = false; 360 private static final boolean DEBUG_APP_DATA = false; 361 362 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 363 364 private static final boolean DISABLE_EPHEMERAL_APPS = true; 365 366 private static final int RADIO_UID = Process.PHONE_UID; 367 private static final int LOG_UID = Process.LOG_UID; 368 private static final int NFC_UID = Process.NFC_UID; 369 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 370 private static final int SHELL_UID = Process.SHELL_UID; 371 372 // Cap the size of permission trees that 3rd party apps can define 373 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 374 375 // Suffix used during package installation when copying/moving 376 // package apks to install directory. 377 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 378 379 static final int SCAN_NO_DEX = 1<<1; 380 static final int SCAN_FORCE_DEX = 1<<2; 381 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 382 static final int SCAN_NEW_INSTALL = 1<<4; 383 static final int SCAN_NO_PATHS = 1<<5; 384 static final int SCAN_UPDATE_TIME = 1<<6; 385 static final int SCAN_DEFER_DEX = 1<<7; 386 static final int SCAN_BOOTING = 1<<8; 387 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 388 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 389 static final int SCAN_REPLACING = 1<<11; 390 static final int SCAN_REQUIRE_KNOWN = 1<<12; 391 static final int SCAN_MOVE = 1<<13; 392 static final int SCAN_INITIAL = 1<<14; 393 static final int SCAN_CHECK_ONLY = 1<<15; 394 static final int SCAN_DONT_KILL_APP = 1<<17; 395 static final int SCAN_IGNORE_FROZEN = 1<<18; 396 397 static final int REMOVE_CHATTY = 1<<16; 398 399 private static final int[] EMPTY_INT_ARRAY = new int[0]; 400 401 /** 402 * Timeout (in milliseconds) after which the watchdog should declare that 403 * our handler thread is wedged. The usual default for such things is one 404 * minute but we sometimes do very lengthy I/O operations on this thread, 405 * such as installing multi-gigabyte applications, so ours needs to be longer. 406 */ 407 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 408 409 /** 410 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 411 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 412 * settings entry if available, otherwise we use the hardcoded default. If it's been 413 * more than this long since the last fstrim, we force one during the boot sequence. 414 * 415 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 416 * one gets run at the next available charging+idle time. This final mandatory 417 * no-fstrim check kicks in only of the other scheduling criteria is never met. 418 */ 419 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 420 421 /** 422 * Whether verification is enabled by default. 423 */ 424 private static final boolean DEFAULT_VERIFY_ENABLE = true; 425 426 /** 427 * The default maximum time to wait for the verification agent to return in 428 * milliseconds. 429 */ 430 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 431 432 /** 433 * The default response for package verification timeout. 434 * 435 * This can be either PackageManager.VERIFICATION_ALLOW or 436 * PackageManager.VERIFICATION_REJECT. 437 */ 438 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 439 440 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 441 442 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 443 DEFAULT_CONTAINER_PACKAGE, 444 "com.android.defcontainer.DefaultContainerService"); 445 446 private static final String KILL_APP_REASON_GIDS_CHANGED = 447 "permission grant or revoke changed gids"; 448 449 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 450 "permissions revoked"; 451 452 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 453 454 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 455 456 /** Permission grant: not grant the permission. */ 457 private static final int GRANT_DENIED = 1; 458 459 /** Permission grant: grant the permission as an install permission. */ 460 private static final int GRANT_INSTALL = 2; 461 462 /** Permission grant: grant the permission as a runtime one. */ 463 private static final int GRANT_RUNTIME = 3; 464 465 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 466 private static final int GRANT_UPGRADE = 4; 467 468 /** Canonical intent used to identify what counts as a "web browser" app */ 469 private static final Intent sBrowserIntent; 470 static { 471 sBrowserIntent = new Intent(); 472 sBrowserIntent.setAction(Intent.ACTION_VIEW); 473 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 474 sBrowserIntent.setData(Uri.parse("http:")); 475 } 476 477 /** 478 * The set of all protected actions [i.e. those actions for which a high priority 479 * intent filter is disallowed]. 480 */ 481 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 482 static { 483 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 485 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 486 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 487 } 488 489 // Compilation reasons. 490 public static final int REASON_FIRST_BOOT = 0; 491 public static final int REASON_BOOT = 1; 492 public static final int REASON_INSTALL = 2; 493 public static final int REASON_BACKGROUND_DEXOPT = 3; 494 public static final int REASON_AB_OTA = 4; 495 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 496 public static final int REASON_SHARED_APK = 6; 497 public static final int REASON_FORCED_DEXOPT = 7; 498 499 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 500 501 final ServiceThread mHandlerThread; 502 503 final PackageHandler mHandler; 504 505 private final ProcessLoggingHandler mProcessLoggingHandler; 506 507 /** 508 * Messages for {@link #mHandler} that need to wait for system ready before 509 * being dispatched. 510 */ 511 private ArrayList<Message> mPostSystemReadyMessages; 512 513 final int mSdkVersion = Build.VERSION.SDK_INT; 514 515 final Context mContext; 516 final boolean mFactoryTest; 517 final boolean mOnlyCore; 518 final DisplayMetrics mMetrics; 519 final int mDefParseFlags; 520 final String[] mSeparateProcesses; 521 final boolean mIsUpgrade; 522 final boolean mIsPreNUpgrade; 523 524 /** The location for ASEC container files on internal storage. */ 525 final String mAsecInternalPath; 526 527 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 528 // LOCK HELD. Can be called with mInstallLock held. 529 @GuardedBy("mInstallLock") 530 final Installer mInstaller; 531 532 /** Directory where installed third-party apps stored */ 533 final File mAppInstallDir; 534 final File mEphemeralInstallDir; 535 536 /** 537 * Directory to which applications installed internally have their 538 * 32 bit native libraries copied. 539 */ 540 private File mAppLib32InstallDir; 541 542 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 543 // apps. 544 final File mDrmAppPrivateInstallDir; 545 546 // ---------------------------------------------------------------- 547 548 // Lock for state used when installing and doing other long running 549 // operations. Methods that must be called with this lock held have 550 // the suffix "LI". 551 final Object mInstallLock = new Object(); 552 553 // ---------------------------------------------------------------- 554 555 // Keys are String (package name), values are Package. This also serves 556 // as the lock for the global state. Methods that must be called with 557 // this lock held have the prefix "LP". 558 @GuardedBy("mPackages") 559 final ArrayMap<String, PackageParser.Package> mPackages = 560 new ArrayMap<String, PackageParser.Package>(); 561 562 final ArrayMap<String, Set<String>> mKnownCodebase = 563 new ArrayMap<String, Set<String>>(); 564 565 // Tracks available target package names -> overlay package paths. 566 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 567 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 568 569 /** 570 * Tracks new system packages [received in an OTA] that we expect to 571 * find updated user-installed versions. Keys are package name, values 572 * are package location. 573 */ 574 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 575 /** 576 * Tracks high priority intent filters for protected actions. During boot, certain 577 * filter actions are protected and should never be allowed to have a high priority 578 * intent filter for them. However, there is one, and only one exception -- the 579 * setup wizard. It must be able to define a high priority intent filter for these 580 * actions to ensure there are no escapes from the wizard. We need to delay processing 581 * of these during boot as we need to look at all of the system packages in order 582 * to know which component is the setup wizard. 583 */ 584 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 585 /** 586 * Whether or not processing protected filters should be deferred. 587 */ 588 private boolean mDeferProtectedFilters = true; 589 590 /** 591 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 592 */ 593 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 594 /** 595 * Whether or not system app permissions should be promoted from install to runtime. 596 */ 597 boolean mPromoteSystemApps; 598 599 @GuardedBy("mPackages") 600 final Settings mSettings; 601 602 /** 603 * Set of package names that are currently "frozen", which means active 604 * surgery is being done on the code/data for that package. The platform 605 * will refuse to launch frozen packages to avoid race conditions. 606 * 607 * @see PackageFreezer 608 */ 609 @GuardedBy("mPackages") 610 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 611 612 boolean mRestoredSettings; 613 614 // System configuration read by SystemConfig. 615 final int[] mGlobalGids; 616 final SparseArray<ArraySet<String>> mSystemPermissions; 617 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 618 619 // If mac_permissions.xml was found for seinfo labeling. 620 boolean mFoundPolicyFile; 621 622 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 623 624 public static final class SharedLibraryEntry { 625 public final String path; 626 public final String apk; 627 628 SharedLibraryEntry(String _path, String _apk) { 629 path = _path; 630 apk = _apk; 631 } 632 } 633 634 // Currently known shared libraries. 635 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 636 new ArrayMap<String, SharedLibraryEntry>(); 637 638 // All available activities, for your resolving pleasure. 639 final ActivityIntentResolver mActivities = 640 new ActivityIntentResolver(); 641 642 // All available receivers, for your resolving pleasure. 643 final ActivityIntentResolver mReceivers = 644 new ActivityIntentResolver(); 645 646 // All available services, for your resolving pleasure. 647 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 648 649 // All available providers, for your resolving pleasure. 650 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 651 652 // Mapping from provider base names (first directory in content URI codePath) 653 // to the provider information. 654 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 655 new ArrayMap<String, PackageParser.Provider>(); 656 657 // Mapping from instrumentation class names to info about them. 658 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 659 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 660 661 // Mapping from permission names to info about them. 662 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 663 new ArrayMap<String, PackageParser.PermissionGroup>(); 664 665 // Packages whose data we have transfered into another package, thus 666 // should no longer exist. 667 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 668 669 // Broadcast actions that are only available to the system. 670 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 671 672 /** List of packages waiting for verification. */ 673 final SparseArray<PackageVerificationState> mPendingVerification 674 = new SparseArray<PackageVerificationState>(); 675 676 /** Set of packages associated with each app op permission. */ 677 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 678 679 final PackageInstallerService mInstallerService; 680 681 private final PackageDexOptimizer mPackageDexOptimizer; 682 683 private AtomicInteger mNextMoveId = new AtomicInteger(); 684 private final MoveCallbacks mMoveCallbacks; 685 686 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 687 688 // Cache of users who need badging. 689 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 690 691 /** Token for keys in mPendingVerification. */ 692 private int mPendingVerificationToken = 0; 693 694 volatile boolean mSystemReady; 695 volatile boolean mSafeMode; 696 volatile boolean mHasSystemUidErrors; 697 698 ApplicationInfo mAndroidApplication; 699 final ActivityInfo mResolveActivity = new ActivityInfo(); 700 final ResolveInfo mResolveInfo = new ResolveInfo(); 701 ComponentName mResolveComponentName; 702 PackageParser.Package mPlatformPackage; 703 ComponentName mCustomResolverComponentName; 704 705 boolean mResolverReplaced = false; 706 707 private final @Nullable ComponentName mIntentFilterVerifierComponent; 708 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 709 710 private int mIntentFilterVerificationToken = 0; 711 712 /** Component that knows whether or not an ephemeral application exists */ 713 final ComponentName mEphemeralResolverComponent; 714 /** The service connection to the ephemeral resolver */ 715 final EphemeralResolverConnection mEphemeralResolverConnection; 716 717 /** Component used to install ephemeral applications */ 718 final ComponentName mEphemeralInstallerComponent; 719 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 720 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 721 722 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 723 = new SparseArray<IntentFilterVerificationState>(); 724 725 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 726 new DefaultPermissionGrantPolicy(this); 727 728 // List of packages names to keep cached, even if they are uninstalled for all users 729 private List<String> mKeepUninstalledPackages; 730 731 private static class IFVerificationParams { 732 PackageParser.Package pkg; 733 boolean replacing; 734 int userId; 735 int verifierUid; 736 737 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 738 int _userId, int _verifierUid) { 739 pkg = _pkg; 740 replacing = _replacing; 741 userId = _userId; 742 replacing = _replacing; 743 verifierUid = _verifierUid; 744 } 745 } 746 747 private interface IntentFilterVerifier<T extends IntentFilter> { 748 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 749 T filter, String packageName); 750 void startVerifications(int userId); 751 void receiveVerificationResponse(int verificationId); 752 } 753 754 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 755 private Context mContext; 756 private ComponentName mIntentFilterVerifierComponent; 757 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 758 759 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 760 mContext = context; 761 mIntentFilterVerifierComponent = verifierComponent; 762 } 763 764 private String getDefaultScheme() { 765 return IntentFilter.SCHEME_HTTPS; 766 } 767 768 @Override 769 public void startVerifications(int userId) { 770 // Launch verifications requests 771 int count = mCurrentIntentFilterVerifications.size(); 772 for (int n=0; n<count; n++) { 773 int verificationId = mCurrentIntentFilterVerifications.get(n); 774 final IntentFilterVerificationState ivs = 775 mIntentFilterVerificationStates.get(verificationId); 776 777 String packageName = ivs.getPackageName(); 778 779 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 780 final int filterCount = filters.size(); 781 ArraySet<String> domainsSet = new ArraySet<>(); 782 for (int m=0; m<filterCount; m++) { 783 PackageParser.ActivityIntentInfo filter = filters.get(m); 784 domainsSet.addAll(filter.getHostsList()); 785 } 786 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 787 synchronized (mPackages) { 788 if (mSettings.createIntentFilterVerificationIfNeededLPw( 789 packageName, domainsList) != null) { 790 scheduleWriteSettingsLocked(); 791 } 792 } 793 sendVerificationRequest(userId, verificationId, ivs); 794 } 795 mCurrentIntentFilterVerifications.clear(); 796 } 797 798 private void sendVerificationRequest(int userId, int verificationId, 799 IntentFilterVerificationState ivs) { 800 801 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 802 verificationIntent.putExtra( 803 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 804 verificationId); 805 verificationIntent.putExtra( 806 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 807 getDefaultScheme()); 808 verificationIntent.putExtra( 809 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 810 ivs.getHostsString()); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 813 ivs.getPackageName()); 814 verificationIntent.setComponent(mIntentFilterVerifierComponent); 815 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 816 817 UserHandle user = new UserHandle(userId); 818 mContext.sendBroadcastAsUser(verificationIntent, user); 819 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 820 "Sending IntentFilter verification broadcast"); 821 } 822 823 public void receiveVerificationResponse(int verificationId) { 824 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 825 826 final boolean verified = ivs.isVerified(); 827 828 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 829 final int count = filters.size(); 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.i(TAG, "Received verification response " + verificationId 832 + " for " + count + " filters, verified=" + verified); 833 } 834 for (int n=0; n<count; n++) { 835 PackageParser.ActivityIntentInfo filter = filters.get(n); 836 filter.setVerified(verified); 837 838 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 839 + " verified with result:" + verified + " and hosts:" 840 + ivs.getHostsString()); 841 } 842 843 mIntentFilterVerificationStates.remove(verificationId); 844 845 final String packageName = ivs.getPackageName(); 846 IntentFilterVerificationInfo ivi = null; 847 848 synchronized (mPackages) { 849 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 850 } 851 if (ivi == null) { 852 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 853 + verificationId + " packageName:" + packageName); 854 return; 855 } 856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 857 "Updating IntentFilterVerificationInfo for package " + packageName 858 +" verificationId:" + verificationId); 859 860 synchronized (mPackages) { 861 if (verified) { 862 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 863 } else { 864 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 865 } 866 scheduleWriteSettingsLocked(); 867 868 final int userId = ivs.getUserId(); 869 if (userId != UserHandle.USER_ALL) { 870 final int userStatus = 871 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 872 873 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 874 boolean needUpdate = false; 875 876 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 877 // already been set by the User thru the Disambiguation dialog 878 switch (userStatus) { 879 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 880 if (verified) { 881 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 882 } else { 883 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 884 } 885 needUpdate = true; 886 break; 887 888 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 889 if (verified) { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 891 needUpdate = true; 892 } 893 break; 894 895 default: 896 // Nothing to do 897 } 898 899 if (needUpdate) { 900 mSettings.updateIntentFilterVerificationStatusLPw( 901 packageName, updatedStatus, userId); 902 scheduleWritePackageRestrictionsLocked(userId); 903 } 904 } 905 } 906 } 907 908 @Override 909 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 910 ActivityIntentInfo filter, String packageName) { 911 if (!hasValidDomains(filter)) { 912 return false; 913 } 914 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 915 if (ivs == null) { 916 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 917 packageName); 918 } 919 if (DEBUG_DOMAIN_VERIFICATION) { 920 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 921 } 922 ivs.addFilter(filter); 923 return true; 924 } 925 926 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 927 int userId, int verificationId, String packageName) { 928 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 929 verifierUid, userId, packageName); 930 ivs.setPendingState(); 931 synchronized (mPackages) { 932 mIntentFilterVerificationStates.append(verificationId, ivs); 933 mCurrentIntentFilterVerifications.add(verificationId); 934 } 935 return ivs; 936 } 937 } 938 939 private static boolean hasValidDomains(ActivityIntentInfo filter) { 940 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 941 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 942 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 943 } 944 945 // Set of pending broadcasts for aggregating enable/disable of components. 946 static class PendingPackageBroadcasts { 947 // for each user id, a map of <package name -> components within that package> 948 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 949 950 public PendingPackageBroadcasts() { 951 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 952 } 953 954 public ArrayList<String> get(int userId, String packageName) { 955 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 956 return packages.get(packageName); 957 } 958 959 public void put(int userId, String packageName, ArrayList<String> components) { 960 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 961 packages.put(packageName, components); 962 } 963 964 public void remove(int userId, String packageName) { 965 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 966 if (packages != null) { 967 packages.remove(packageName); 968 } 969 } 970 971 public void remove(int userId) { 972 mUidMap.remove(userId); 973 } 974 975 public int userIdCount() { 976 return mUidMap.size(); 977 } 978 979 public int userIdAt(int n) { 980 return mUidMap.keyAt(n); 981 } 982 983 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 984 return mUidMap.get(userId); 985 } 986 987 public int size() { 988 // total number of pending broadcast entries across all userIds 989 int num = 0; 990 for (int i = 0; i< mUidMap.size(); i++) { 991 num += mUidMap.valueAt(i).size(); 992 } 993 return num; 994 } 995 996 public void clear() { 997 mUidMap.clear(); 998 } 999 1000 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1001 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1002 if (map == null) { 1003 map = new ArrayMap<String, ArrayList<String>>(); 1004 mUidMap.put(userId, map); 1005 } 1006 return map; 1007 } 1008 } 1009 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1010 1011 // Service Connection to remote media container service to copy 1012 // package uri's from external media onto secure containers 1013 // or internal storage. 1014 private IMediaContainerService mContainerService = null; 1015 1016 static final int SEND_PENDING_BROADCAST = 1; 1017 static final int MCS_BOUND = 3; 1018 static final int END_COPY = 4; 1019 static final int INIT_COPY = 5; 1020 static final int MCS_UNBIND = 6; 1021 static final int START_CLEANING_PACKAGE = 7; 1022 static final int FIND_INSTALL_LOC = 8; 1023 static final int POST_INSTALL = 9; 1024 static final int MCS_RECONNECT = 10; 1025 static final int MCS_GIVE_UP = 11; 1026 static final int UPDATED_MEDIA_STATUS = 12; 1027 static final int WRITE_SETTINGS = 13; 1028 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1029 static final int PACKAGE_VERIFIED = 15; 1030 static final int CHECK_PENDING_VERIFICATION = 16; 1031 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1032 static final int INTENT_FILTER_VERIFIED = 18; 1033 1034 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1035 1036 // Delay time in millisecs 1037 static final int BROADCAST_DELAY = 10 * 1000; 1038 1039 static UserManagerService sUserManager; 1040 1041 // Stores a list of users whose package restrictions file needs to be updated 1042 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1043 1044 final private DefaultContainerConnection mDefContainerConn = 1045 new DefaultContainerConnection(); 1046 class DefaultContainerConnection implements ServiceConnection { 1047 public void onServiceConnected(ComponentName name, IBinder service) { 1048 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1049 IMediaContainerService imcs = 1050 IMediaContainerService.Stub.asInterface(service); 1051 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1052 } 1053 1054 public void onServiceDisconnected(ComponentName name) { 1055 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1056 } 1057 } 1058 1059 // Recordkeeping of restore-after-install operations that are currently in flight 1060 // between the Package Manager and the Backup Manager 1061 static class PostInstallData { 1062 public InstallArgs args; 1063 public PackageInstalledInfo res; 1064 1065 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1066 args = _a; 1067 res = _r; 1068 } 1069 } 1070 1071 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1072 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1073 1074 // XML tags for backup/restore of various bits of state 1075 private static final String TAG_PREFERRED_BACKUP = "pa"; 1076 private static final String TAG_DEFAULT_APPS = "da"; 1077 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1078 1079 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1080 private static final String TAG_ALL_GRANTS = "rt-grants"; 1081 private static final String TAG_GRANT = "grant"; 1082 private static final String ATTR_PACKAGE_NAME = "pkg"; 1083 1084 private static final String TAG_PERMISSION = "perm"; 1085 private static final String ATTR_PERMISSION_NAME = "name"; 1086 private static final String ATTR_IS_GRANTED = "g"; 1087 private static final String ATTR_USER_SET = "set"; 1088 private static final String ATTR_USER_FIXED = "fixed"; 1089 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1090 1091 // System/policy permission grants are not backed up 1092 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1093 FLAG_PERMISSION_POLICY_FIXED 1094 | FLAG_PERMISSION_SYSTEM_FIXED 1095 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1096 1097 // And we back up these user-adjusted states 1098 private static final int USER_RUNTIME_GRANT_MASK = 1099 FLAG_PERMISSION_USER_SET 1100 | FLAG_PERMISSION_USER_FIXED 1101 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1102 1103 final @Nullable String mRequiredVerifierPackage; 1104 final @NonNull String mRequiredInstallerPackage; 1105 final @Nullable String mSetupWizardPackage; 1106 final @NonNull String mServicesSystemSharedLibraryPackageName; 1107 final @NonNull String mSharedSystemSharedLibraryPackageName; 1108 1109 private final PackageUsage mPackageUsage = new PackageUsage(); 1110 1111 private class PackageUsage { 1112 private static final int WRITE_INTERVAL 1113 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1114 1115 private final Object mFileLock = new Object(); 1116 private final AtomicLong mLastWritten = new AtomicLong(0); 1117 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1118 1119 private boolean mIsHistoricalPackageUsageAvailable = true; 1120 1121 boolean isHistoricalPackageUsageAvailable() { 1122 return mIsHistoricalPackageUsageAvailable; 1123 } 1124 1125 void write(boolean force) { 1126 if (force) { 1127 writeInternal(); 1128 return; 1129 } 1130 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1131 && !DEBUG_DEXOPT) { 1132 return; 1133 } 1134 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1135 new Thread("PackageUsage_DiskWriter") { 1136 @Override 1137 public void run() { 1138 try { 1139 writeInternal(); 1140 } finally { 1141 mBackgroundWriteRunning.set(false); 1142 } 1143 } 1144 }.start(); 1145 } 1146 } 1147 1148 private void writeInternal() { 1149 synchronized (mPackages) { 1150 synchronized (mFileLock) { 1151 AtomicFile file = getFile(); 1152 FileOutputStream f = null; 1153 try { 1154 f = file.startWrite(); 1155 BufferedOutputStream out = new BufferedOutputStream(f); 1156 FileUtils.setPermissions(file.getBaseFile().getPath(), 1157 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1158 StringBuilder sb = new StringBuilder(); 1159 1160 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1161 sb.append('\n'); 1162 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1163 1164 for (PackageParser.Package pkg : mPackages.values()) { 1165 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1166 continue; 1167 } 1168 sb.setLength(0); 1169 sb.append(pkg.packageName); 1170 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1171 sb.append(' '); 1172 sb.append(usageTimeInMillis); 1173 } 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 } 1177 out.flush(); 1178 file.finishWrite(f); 1179 } catch (IOException e) { 1180 if (f != null) { 1181 file.failWrite(f); 1182 } 1183 Log.e(TAG, "Failed to write package usage times", e); 1184 } 1185 } 1186 } 1187 mLastWritten.set(SystemClock.elapsedRealtime()); 1188 } 1189 1190 void readLP() { 1191 synchronized (mFileLock) { 1192 AtomicFile file = getFile(); 1193 BufferedInputStream in = null; 1194 try { 1195 in = new BufferedInputStream(file.openRead()); 1196 StringBuffer sb = new StringBuffer(); 1197 1198 String firstLine = readLine(in, sb); 1199 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1200 readVersion1LP(in, sb); 1201 } else { 1202 readVersion0LP(in, sb, firstLine); 1203 } 1204 } catch (FileNotFoundException expected) { 1205 mIsHistoricalPackageUsageAvailable = false; 1206 } catch (IOException e) { 1207 Log.w(TAG, "Failed to read package usage times", e); 1208 } finally { 1209 IoUtils.closeQuietly(in); 1210 } 1211 } 1212 mLastWritten.set(SystemClock.elapsedRealtime()); 1213 } 1214 1215 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1216 throws IOException { 1217 // Initial version of the file had no version number and stored one 1218 // package-timestamp pair per line. 1219 // Note that the first line has already been read from the InputStream. 1220 String line = firstLine; 1221 while (true) { 1222 if (line == null) { 1223 break; 1224 } 1225 1226 String[] tokens = line.split(" "); 1227 if (tokens.length != 2) { 1228 throw new IOException("Failed to parse " + line + 1229 " as package-timestamp pair."); 1230 } 1231 1232 String packageName = tokens[0]; 1233 PackageParser.Package pkg = mPackages.get(packageName); 1234 if (pkg == null) { 1235 continue; 1236 } 1237 1238 long timestamp = parseAsLong(tokens[1]); 1239 for (int reason = 0; 1240 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1241 reason++) { 1242 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1243 } 1244 1245 line = readLine(in, sb); 1246 } 1247 } 1248 1249 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1250 // Version 1 of the file started with the corresponding version 1251 // number and then stored a package name and eight timestamps per line. 1252 String line; 1253 while ((line = readLine(in, sb)) != null) { 1254 String[] tokens = line.split(" "); 1255 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1256 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1257 } 1258 1259 String packageName = tokens[0]; 1260 PackageParser.Package pkg = mPackages.get(packageName); 1261 if (pkg == null) { 1262 continue; 1263 } 1264 1265 for (int reason = 0; 1266 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1267 reason++) { 1268 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1269 } 1270 } 1271 } 1272 1273 private long parseAsLong(String token) throws IOException { 1274 try { 1275 return Long.parseLong(token); 1276 } catch (NumberFormatException e) { 1277 throw new IOException("Failed to parse " + token + " as a long.", e); 1278 } 1279 } 1280 1281 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1282 return readToken(in, sb, '\n'); 1283 } 1284 1285 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1286 throws IOException { 1287 sb.setLength(0); 1288 while (true) { 1289 int ch = in.read(); 1290 if (ch == -1) { 1291 if (sb.length() == 0) { 1292 return null; 1293 } 1294 throw new IOException("Unexpected EOF"); 1295 } 1296 if (ch == endOfToken) { 1297 return sb.toString(); 1298 } 1299 sb.append((char)ch); 1300 } 1301 } 1302 1303 private AtomicFile getFile() { 1304 File dataDir = Environment.getDataDirectory(); 1305 File systemDir = new File(dataDir, "system"); 1306 File fname = new File(systemDir, "package-usage.list"); 1307 return new AtomicFile(fname); 1308 } 1309 1310 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1311 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1312 } 1313 1314 class PackageHandler extends Handler { 1315 private boolean mBound = false; 1316 final ArrayList<HandlerParams> mPendingInstalls = 1317 new ArrayList<HandlerParams>(); 1318 1319 private boolean connectToService() { 1320 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1321 " DefaultContainerService"); 1322 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1323 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1324 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1325 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1326 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1327 mBound = true; 1328 return true; 1329 } 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 return false; 1332 } 1333 1334 private void disconnectService() { 1335 mContainerService = null; 1336 mBound = false; 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1338 mContext.unbindService(mDefContainerConn); 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1340 } 1341 1342 PackageHandler(Looper looper) { 1343 super(looper); 1344 } 1345 1346 public void handleMessage(Message msg) { 1347 try { 1348 doHandleMessage(msg); 1349 } finally { 1350 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1351 } 1352 } 1353 1354 void doHandleMessage(Message msg) { 1355 switch (msg.what) { 1356 case INIT_COPY: { 1357 HandlerParams params = (HandlerParams) msg.obj; 1358 int idx = mPendingInstalls.size(); 1359 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1360 // If a bind was already initiated we dont really 1361 // need to do anything. The pending install 1362 // will be processed later on. 1363 if (!mBound) { 1364 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1365 System.identityHashCode(mHandler)); 1366 // If this is the only one pending we might 1367 // have to bind to the service again. 1368 if (!connectToService()) { 1369 Slog.e(TAG, "Failed to bind to media container service"); 1370 params.serviceError(); 1371 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1372 System.identityHashCode(mHandler)); 1373 if (params.traceMethod != null) { 1374 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1375 params.traceCookie); 1376 } 1377 return; 1378 } else { 1379 // Once we bind to the service, the first 1380 // pending request will be processed. 1381 mPendingInstalls.add(idx, params); 1382 } 1383 } else { 1384 mPendingInstalls.add(idx, params); 1385 // Already bound to the service. Just make 1386 // sure we trigger off processing the first request. 1387 if (idx == 0) { 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 } 1391 break; 1392 } 1393 case MCS_BOUND: { 1394 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1395 if (msg.obj != null) { 1396 mContainerService = (IMediaContainerService) msg.obj; 1397 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1398 System.identityHashCode(mHandler)); 1399 } 1400 if (mContainerService == null) { 1401 if (!mBound) { 1402 // Something seriously wrong since we are not bound and we are not 1403 // waiting for connection. Bail out. 1404 Slog.e(TAG, "Cannot bind to media container service"); 1405 for (HandlerParams params : mPendingInstalls) { 1406 // Indicate service bind error 1407 params.serviceError(); 1408 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1409 System.identityHashCode(params)); 1410 if (params.traceMethod != null) { 1411 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1412 params.traceMethod, params.traceCookie); 1413 } 1414 return; 1415 } 1416 mPendingInstalls.clear(); 1417 } else { 1418 Slog.w(TAG, "Waiting to connect to media container service"); 1419 } 1420 } else if (mPendingInstalls.size() > 0) { 1421 HandlerParams params = mPendingInstalls.get(0); 1422 if (params != null) { 1423 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1424 System.identityHashCode(params)); 1425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1426 if (params.startCopy()) { 1427 // We are done... look for more work or to 1428 // go idle. 1429 if (DEBUG_SD_INSTALL) Log.i(TAG, 1430 "Checking for more work or unbind..."); 1431 // Delete pending install 1432 if (mPendingInstalls.size() > 0) { 1433 mPendingInstalls.remove(0); 1434 } 1435 if (mPendingInstalls.size() == 0) { 1436 if (mBound) { 1437 if (DEBUG_SD_INSTALL) Log.i(TAG, 1438 "Posting delayed MCS_UNBIND"); 1439 removeMessages(MCS_UNBIND); 1440 Message ubmsg = obtainMessage(MCS_UNBIND); 1441 // Unbind after a little delay, to avoid 1442 // continual thrashing. 1443 sendMessageDelayed(ubmsg, 10000); 1444 } 1445 } else { 1446 // There are more pending requests in queue. 1447 // Just post MCS_BOUND message to trigger processing 1448 // of next pending install. 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, 1450 "Posting MCS_BOUND for next work"); 1451 mHandler.sendEmptyMessage(MCS_BOUND); 1452 } 1453 } 1454 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1455 } 1456 } else { 1457 // Should never happen ideally. 1458 Slog.w(TAG, "Empty queue"); 1459 } 1460 break; 1461 } 1462 case MCS_RECONNECT: { 1463 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1464 if (mPendingInstalls.size() > 0) { 1465 if (mBound) { 1466 disconnectService(); 1467 } 1468 if (!connectToService()) { 1469 Slog.e(TAG, "Failed to bind to media container service"); 1470 for (HandlerParams params : mPendingInstalls) { 1471 // Indicate service bind error 1472 params.serviceError(); 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1474 System.identityHashCode(params)); 1475 } 1476 mPendingInstalls.clear(); 1477 } 1478 } 1479 break; 1480 } 1481 case MCS_UNBIND: { 1482 // If there is no actual work left, then time to unbind. 1483 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1484 1485 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1486 if (mBound) { 1487 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1488 1489 disconnectService(); 1490 } 1491 } else if (mPendingInstalls.size() > 0) { 1492 // There are more pending requests in queue. 1493 // Just post MCS_BOUND message to trigger processing 1494 // of next pending install. 1495 mHandler.sendEmptyMessage(MCS_BOUND); 1496 } 1497 1498 break; 1499 } 1500 case MCS_GIVE_UP: { 1501 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1502 HandlerParams params = mPendingInstalls.remove(0); 1503 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1504 System.identityHashCode(params)); 1505 break; 1506 } 1507 case SEND_PENDING_BROADCAST: { 1508 String packages[]; 1509 ArrayList<String> components[]; 1510 int size = 0; 1511 int uids[]; 1512 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1513 synchronized (mPackages) { 1514 if (mPendingBroadcasts == null) { 1515 return; 1516 } 1517 size = mPendingBroadcasts.size(); 1518 if (size <= 0) { 1519 // Nothing to be done. Just return 1520 return; 1521 } 1522 packages = new String[size]; 1523 components = new ArrayList[size]; 1524 uids = new int[size]; 1525 int i = 0; // filling out the above arrays 1526 1527 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1528 int packageUserId = mPendingBroadcasts.userIdAt(n); 1529 Iterator<Map.Entry<String, ArrayList<String>>> it 1530 = mPendingBroadcasts.packagesForUserId(packageUserId) 1531 .entrySet().iterator(); 1532 while (it.hasNext() && i < size) { 1533 Map.Entry<String, ArrayList<String>> ent = it.next(); 1534 packages[i] = ent.getKey(); 1535 components[i] = ent.getValue(); 1536 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1537 uids[i] = (ps != null) 1538 ? UserHandle.getUid(packageUserId, ps.appId) 1539 : -1; 1540 i++; 1541 } 1542 } 1543 size = i; 1544 mPendingBroadcasts.clear(); 1545 } 1546 // Send broadcasts 1547 for (int i = 0; i < size; i++) { 1548 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1549 } 1550 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1551 break; 1552 } 1553 case START_CLEANING_PACKAGE: { 1554 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1555 final String packageName = (String)msg.obj; 1556 final int userId = msg.arg1; 1557 final boolean andCode = msg.arg2 != 0; 1558 synchronized (mPackages) { 1559 if (userId == UserHandle.USER_ALL) { 1560 int[] users = sUserManager.getUserIds(); 1561 for (int user : users) { 1562 mSettings.addPackageToCleanLPw( 1563 new PackageCleanItem(user, packageName, andCode)); 1564 } 1565 } else { 1566 mSettings.addPackageToCleanLPw( 1567 new PackageCleanItem(userId, packageName, andCode)); 1568 } 1569 } 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1571 startCleaningPackages(); 1572 } break; 1573 case POST_INSTALL: { 1574 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1575 1576 PostInstallData data = mRunningInstalls.get(msg.arg1); 1577 final boolean didRestore = (msg.arg2 != 0); 1578 mRunningInstalls.delete(msg.arg1); 1579 1580 if (data != null) { 1581 InstallArgs args = data.args; 1582 PackageInstalledInfo parentRes = data.res; 1583 1584 final boolean grantPermissions = (args.installFlags 1585 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1586 final boolean killApp = (args.installFlags 1587 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1588 final String[] grantedPermissions = args.installGrantPermissions; 1589 1590 // Handle the parent package 1591 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1592 grantedPermissions, didRestore, args.installerPackageName, 1593 args.observer); 1594 1595 // Handle the child packages 1596 final int childCount = (parentRes.addedChildPackages != null) 1597 ? parentRes.addedChildPackages.size() : 0; 1598 for (int i = 0; i < childCount; i++) { 1599 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1600 handlePackagePostInstall(childRes, grantPermissions, killApp, 1601 grantedPermissions, false, args.installerPackageName, 1602 args.observer); 1603 } 1604 1605 // Log tracing if needed 1606 if (args.traceMethod != null) { 1607 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1608 args.traceCookie); 1609 } 1610 } else { 1611 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1612 } 1613 1614 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1615 } break; 1616 case UPDATED_MEDIA_STATUS: { 1617 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1618 boolean reportStatus = msg.arg1 == 1; 1619 boolean doGc = msg.arg2 == 1; 1620 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1621 if (doGc) { 1622 // Force a gc to clear up stale containers. 1623 Runtime.getRuntime().gc(); 1624 } 1625 if (msg.obj != null) { 1626 @SuppressWarnings("unchecked") 1627 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1628 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1629 // Unload containers 1630 unloadAllContainers(args); 1631 } 1632 if (reportStatus) { 1633 try { 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1635 PackageHelper.getMountService().finishMediaUpdate(); 1636 } catch (RemoteException e) { 1637 Log.e(TAG, "MountService not running?"); 1638 } 1639 } 1640 } break; 1641 case WRITE_SETTINGS: { 1642 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1643 synchronized (mPackages) { 1644 removeMessages(WRITE_SETTINGS); 1645 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1646 mSettings.writeLPr(); 1647 mDirtyUsers.clear(); 1648 } 1649 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1650 } break; 1651 case WRITE_PACKAGE_RESTRICTIONS: { 1652 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1653 synchronized (mPackages) { 1654 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1655 for (int userId : mDirtyUsers) { 1656 mSettings.writePackageRestrictionsLPr(userId); 1657 } 1658 mDirtyUsers.clear(); 1659 } 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1661 } break; 1662 case CHECK_PENDING_VERIFICATION: { 1663 final int verificationId = msg.arg1; 1664 final PackageVerificationState state = mPendingVerification.get(verificationId); 1665 1666 if ((state != null) && !state.timeoutExtended()) { 1667 final InstallArgs args = state.getInstallArgs(); 1668 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1669 1670 Slog.i(TAG, "Verification timed out for " + originUri); 1671 mPendingVerification.remove(verificationId); 1672 1673 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1674 1675 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1676 Slog.i(TAG, "Continuing with installation of " + originUri); 1677 state.setVerifierResponse(Binder.getCallingUid(), 1678 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1679 broadcastPackageVerified(verificationId, originUri, 1680 PackageManager.VERIFICATION_ALLOW, 1681 state.getInstallArgs().getUser()); 1682 try { 1683 ret = args.copyApk(mContainerService, true); 1684 } catch (RemoteException e) { 1685 Slog.e(TAG, "Could not contact the ContainerService"); 1686 } 1687 } else { 1688 broadcastPackageVerified(verificationId, originUri, 1689 PackageManager.VERIFICATION_REJECT, 1690 state.getInstallArgs().getUser()); 1691 } 1692 1693 Trace.asyncTraceEnd( 1694 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1695 1696 processPendingInstall(args, ret); 1697 mHandler.sendEmptyMessage(MCS_UNBIND); 1698 } 1699 break; 1700 } 1701 case PACKAGE_VERIFIED: { 1702 final int verificationId = msg.arg1; 1703 1704 final PackageVerificationState state = mPendingVerification.get(verificationId); 1705 if (state == null) { 1706 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1707 break; 1708 } 1709 1710 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1711 1712 state.setVerifierResponse(response.callerUid, response.code); 1713 1714 if (state.isVerificationComplete()) { 1715 mPendingVerification.remove(verificationId); 1716 1717 final InstallArgs args = state.getInstallArgs(); 1718 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1719 1720 int ret; 1721 if (state.isInstallAllowed()) { 1722 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1723 broadcastPackageVerified(verificationId, originUri, 1724 response.code, state.getInstallArgs().getUser()); 1725 try { 1726 ret = args.copyApk(mContainerService, true); 1727 } catch (RemoteException e) { 1728 Slog.e(TAG, "Could not contact the ContainerService"); 1729 } 1730 } else { 1731 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1732 } 1733 1734 Trace.asyncTraceEnd( 1735 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1736 1737 processPendingInstall(args, ret); 1738 mHandler.sendEmptyMessage(MCS_UNBIND); 1739 } 1740 1741 break; 1742 } 1743 case START_INTENT_FILTER_VERIFICATIONS: { 1744 IFVerificationParams params = (IFVerificationParams) msg.obj; 1745 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1746 params.replacing, params.pkg); 1747 break; 1748 } 1749 case INTENT_FILTER_VERIFIED: { 1750 final int verificationId = msg.arg1; 1751 1752 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1753 verificationId); 1754 if (state == null) { 1755 Slog.w(TAG, "Invalid IntentFilter verification token " 1756 + verificationId + " received"); 1757 break; 1758 } 1759 1760 final int userId = state.getUserId(); 1761 1762 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1763 "Processing IntentFilter verification with token:" 1764 + verificationId + " and userId:" + userId); 1765 1766 final IntentFilterVerificationResponse response = 1767 (IntentFilterVerificationResponse) msg.obj; 1768 1769 state.setVerifierResponse(response.callerUid, response.code); 1770 1771 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1772 "IntentFilter verification with token:" + verificationId 1773 + " and userId:" + userId 1774 + " is settings verifier response with response code:" 1775 + response.code); 1776 1777 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1778 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1779 + response.getFailedDomainsString()); 1780 } 1781 1782 if (state.isVerificationComplete()) { 1783 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1784 } else { 1785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1786 "IntentFilter verification with token:" + verificationId 1787 + " was not said to be complete"); 1788 } 1789 1790 break; 1791 } 1792 } 1793 } 1794 } 1795 1796 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1797 boolean killApp, String[] grantedPermissions, 1798 boolean launchedForRestore, String installerPackage, 1799 IPackageInstallObserver2 installObserver) { 1800 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1801 // Send the removed broadcasts 1802 if (res.removedInfo != null) { 1803 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1804 } 1805 1806 // Now that we successfully installed the package, grant runtime 1807 // permissions if requested before broadcasting the install. 1808 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1809 >= Build.VERSION_CODES.M) { 1810 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1811 } 1812 1813 final boolean update = res.removedInfo != null 1814 && res.removedInfo.removedPackage != null; 1815 1816 // If this is the first time we have child packages for a disabled privileged 1817 // app that had no children, we grant requested runtime permissions to the new 1818 // children if the parent on the system image had them already granted. 1819 if (res.pkg.parentPackage != null) { 1820 synchronized (mPackages) { 1821 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1822 } 1823 } 1824 1825 synchronized (mPackages) { 1826 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1827 } 1828 1829 final String packageName = res.pkg.applicationInfo.packageName; 1830 Bundle extras = new Bundle(1); 1831 extras.putInt(Intent.EXTRA_UID, res.uid); 1832 1833 // Determine the set of users who are adding this package for 1834 // the first time vs. those who are seeing an update. 1835 int[] firstUsers = EMPTY_INT_ARRAY; 1836 int[] updateUsers = EMPTY_INT_ARRAY; 1837 if (res.origUsers == null || res.origUsers.length == 0) { 1838 firstUsers = res.newUsers; 1839 } else { 1840 for (int newUser : res.newUsers) { 1841 boolean isNew = true; 1842 for (int origUser : res.origUsers) { 1843 if (origUser == newUser) { 1844 isNew = false; 1845 break; 1846 } 1847 } 1848 if (isNew) { 1849 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1850 } else { 1851 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1852 } 1853 } 1854 } 1855 1856 // Send installed broadcasts if the install/update is not ephemeral 1857 if (!isEphemeral(res.pkg)) { 1858 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1859 1860 // Send added for users that see the package for the first time 1861 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1862 extras, 0 /*flags*/, null /*targetPackage*/, 1863 null /*finishedReceiver*/, firstUsers); 1864 1865 // Send added for users that don't see the package for the first time 1866 if (update) { 1867 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1868 } 1869 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1870 extras, 0 /*flags*/, null /*targetPackage*/, 1871 null /*finishedReceiver*/, updateUsers); 1872 1873 // Send replaced for users that don't see the package for the first time 1874 if (update) { 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1876 packageName, extras, 0 /*flags*/, 1877 null /*targetPackage*/, null /*finishedReceiver*/, 1878 updateUsers); 1879 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1880 null /*package*/, null /*extras*/, 0 /*flags*/, 1881 packageName /*targetPackage*/, 1882 null /*finishedReceiver*/, updateUsers); 1883 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1884 // First-install and we did a restore, so we're responsible for the 1885 // first-launch broadcast. 1886 if (DEBUG_BACKUP) { 1887 Slog.i(TAG, "Post-restore of " + packageName 1888 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1889 } 1890 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1891 } 1892 1893 // Send broadcast package appeared if forward locked/external for all users 1894 // treat asec-hosted packages like removable media on upgrade 1895 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1896 if (DEBUG_INSTALL) { 1897 Slog.i(TAG, "upgrading pkg " + res.pkg 1898 + " is ASEC-hosted -> AVAILABLE"); 1899 } 1900 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1901 ArrayList<String> pkgList = new ArrayList<>(1); 1902 pkgList.add(packageName); 1903 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1904 } 1905 } 1906 1907 // Work that needs to happen on first install within each user 1908 if (firstUsers != null && firstUsers.length > 0) { 1909 synchronized (mPackages) { 1910 for (int userId : firstUsers) { 1911 // If this app is a browser and it's newly-installed for some 1912 // users, clear any default-browser state in those users. The 1913 // app's nature doesn't depend on the user, so we can just check 1914 // its browser nature in any user and generalize. 1915 if (packageIsBrowser(packageName, userId)) { 1916 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1917 } 1918 1919 // We may also need to apply pending (restored) runtime 1920 // permission grants within these users. 1921 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1922 } 1923 } 1924 } 1925 1926 // Log current value of "unknown sources" setting 1927 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1928 getUnknownSourcesSettings()); 1929 1930 // Force a gc to clear up things 1931 Runtime.getRuntime().gc(); 1932 1933 // Remove the replaced package's older resources safely now 1934 // We delete after a gc for applications on sdcard. 1935 if (res.removedInfo != null && res.removedInfo.args != null) { 1936 synchronized (mInstallLock) { 1937 res.removedInfo.args.doPostDeleteLI(true); 1938 } 1939 } 1940 } 1941 1942 // If someone is watching installs - notify them 1943 if (installObserver != null) { 1944 try { 1945 Bundle extras = extrasForInstallResult(res); 1946 installObserver.onPackageInstalled(res.name, res.returnCode, 1947 res.returnMsg, extras); 1948 } catch (RemoteException e) { 1949 Slog.i(TAG, "Observer no longer exists."); 1950 } 1951 } 1952 } 1953 1954 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1955 PackageParser.Package pkg) { 1956 if (pkg.parentPackage == null) { 1957 return; 1958 } 1959 if (pkg.requestedPermissions == null) { 1960 return; 1961 } 1962 final PackageSetting disabledSysParentPs = mSettings 1963 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1964 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1965 || !disabledSysParentPs.isPrivileged() 1966 || (disabledSysParentPs.childPackageNames != null 1967 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1968 return; 1969 } 1970 final int[] allUserIds = sUserManager.getUserIds(); 1971 final int permCount = pkg.requestedPermissions.size(); 1972 for (int i = 0; i < permCount; i++) { 1973 String permission = pkg.requestedPermissions.get(i); 1974 BasePermission bp = mSettings.mPermissions.get(permission); 1975 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1976 continue; 1977 } 1978 for (int userId : allUserIds) { 1979 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1980 permission, userId)) { 1981 grantRuntimePermission(pkg.packageName, permission, userId); 1982 } 1983 } 1984 } 1985 } 1986 1987 private StorageEventListener mStorageListener = new StorageEventListener() { 1988 @Override 1989 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1990 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1991 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1992 final String volumeUuid = vol.getFsUuid(); 1993 1994 // Clean up any users or apps that were removed or recreated 1995 // while this volume was missing 1996 reconcileUsers(volumeUuid); 1997 reconcileApps(volumeUuid); 1998 1999 // Clean up any install sessions that expired or were 2000 // cancelled while this volume was missing 2001 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2002 2003 loadPrivatePackages(vol); 2004 2005 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2006 unloadPrivatePackages(vol); 2007 } 2008 } 2009 2010 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2011 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2012 updateExternalMediaStatus(true, false); 2013 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2014 updateExternalMediaStatus(false, false); 2015 } 2016 } 2017 } 2018 2019 @Override 2020 public void onVolumeForgotten(String fsUuid) { 2021 if (TextUtils.isEmpty(fsUuid)) { 2022 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2023 return; 2024 } 2025 2026 // Remove any apps installed on the forgotten volume 2027 synchronized (mPackages) { 2028 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2029 for (PackageSetting ps : packages) { 2030 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2031 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2032 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2033 } 2034 2035 mSettings.onVolumeForgotten(fsUuid); 2036 mSettings.writeLPr(); 2037 } 2038 } 2039 }; 2040 2041 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2042 String[] grantedPermissions) { 2043 for (int userId : userIds) { 2044 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2045 } 2046 2047 // We could have touched GID membership, so flush out packages.list 2048 synchronized (mPackages) { 2049 mSettings.writePackageListLPr(); 2050 } 2051 } 2052 2053 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2054 String[] grantedPermissions) { 2055 SettingBase sb = (SettingBase) pkg.mExtras; 2056 if (sb == null) { 2057 return; 2058 } 2059 2060 PermissionsState permissionsState = sb.getPermissionsState(); 2061 2062 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2063 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2064 2065 synchronized (mPackages) { 2066 for (String permission : pkg.requestedPermissions) { 2067 BasePermission bp = mSettings.mPermissions.get(permission); 2068 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2069 && (grantedPermissions == null 2070 || ArrayUtils.contains(grantedPermissions, permission))) { 2071 final int flags = permissionsState.getPermissionFlags(permission, userId); 2072 // Installer cannot change immutable permissions. 2073 if ((flags & immutableFlags) == 0) { 2074 grantRuntimePermission(pkg.packageName, permission, userId); 2075 } 2076 } 2077 } 2078 } 2079 } 2080 2081 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2082 Bundle extras = null; 2083 switch (res.returnCode) { 2084 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2085 extras = new Bundle(); 2086 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2087 res.origPermission); 2088 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2089 res.origPackage); 2090 break; 2091 } 2092 case PackageManager.INSTALL_SUCCEEDED: { 2093 extras = new Bundle(); 2094 extras.putBoolean(Intent.EXTRA_REPLACING, 2095 res.removedInfo != null && res.removedInfo.removedPackage != null); 2096 break; 2097 } 2098 } 2099 return extras; 2100 } 2101 2102 void scheduleWriteSettingsLocked() { 2103 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2104 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2105 } 2106 } 2107 2108 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2109 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2110 scheduleWritePackageRestrictionsLocked(userId); 2111 } 2112 2113 void scheduleWritePackageRestrictionsLocked(int userId) { 2114 final int[] userIds = (userId == UserHandle.USER_ALL) 2115 ? sUserManager.getUserIds() : new int[]{userId}; 2116 for (int nextUserId : userIds) { 2117 if (!sUserManager.exists(nextUserId)) return; 2118 mDirtyUsers.add(nextUserId); 2119 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2120 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2121 } 2122 } 2123 } 2124 2125 public static PackageManagerService main(Context context, Installer installer, 2126 boolean factoryTest, boolean onlyCore) { 2127 // Self-check for initial settings. 2128 PackageManagerServiceCompilerMapping.checkProperties(); 2129 2130 PackageManagerService m = new PackageManagerService(context, installer, 2131 factoryTest, onlyCore); 2132 m.enableSystemUserPackages(); 2133 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2134 // disabled after already being started. 2135 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2136 UserHandle.USER_SYSTEM); 2137 ServiceManager.addService("package", m); 2138 return m; 2139 } 2140 2141 private void enableSystemUserPackages() { 2142 if (!UserManager.isSplitSystemUser()) { 2143 return; 2144 } 2145 // For system user, enable apps based on the following conditions: 2146 // - app is whitelisted or belong to one of these groups: 2147 // -- system app which has no launcher icons 2148 // -- system app which has INTERACT_ACROSS_USERS permission 2149 // -- system IME app 2150 // - app is not in the blacklist 2151 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2152 Set<String> enableApps = new ArraySet<>(); 2153 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2154 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2155 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2156 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2157 enableApps.addAll(wlApps); 2158 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2159 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2160 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2161 enableApps.removeAll(blApps); 2162 Log.i(TAG, "Applications installed for system user: " + enableApps); 2163 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2164 UserHandle.SYSTEM); 2165 final int allAppsSize = allAps.size(); 2166 synchronized (mPackages) { 2167 for (int i = 0; i < allAppsSize; i++) { 2168 String pName = allAps.get(i); 2169 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2170 // Should not happen, but we shouldn't be failing if it does 2171 if (pkgSetting == null) { 2172 continue; 2173 } 2174 boolean install = enableApps.contains(pName); 2175 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2176 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2177 + " for system user"); 2178 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2179 } 2180 } 2181 } 2182 } 2183 2184 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2185 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2186 Context.DISPLAY_SERVICE); 2187 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2188 } 2189 2190 public PackageManagerService(Context context, Installer installer, 2191 boolean factoryTest, boolean onlyCore) { 2192 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2193 SystemClock.uptimeMillis()); 2194 2195 if (mSdkVersion <= 0) { 2196 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2197 } 2198 2199 mContext = context; 2200 mFactoryTest = factoryTest; 2201 mOnlyCore = onlyCore; 2202 mMetrics = new DisplayMetrics(); 2203 mSettings = new Settings(mPackages); 2204 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2205 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2206 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2207 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2208 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2209 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2210 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2211 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2212 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2213 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2214 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2215 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2216 2217 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2218 if (separateProcesses != null && separateProcesses.length() > 0) { 2219 if ("*".equals(separateProcesses)) { 2220 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2221 mSeparateProcesses = null; 2222 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2223 } else { 2224 mDefParseFlags = 0; 2225 mSeparateProcesses = separateProcesses.split(","); 2226 Slog.w(TAG, "Running with debug.separate_processes: " 2227 + separateProcesses); 2228 } 2229 } else { 2230 mDefParseFlags = 0; 2231 mSeparateProcesses = null; 2232 } 2233 2234 mInstaller = installer; 2235 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2236 "*dexopt*"); 2237 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2238 2239 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2240 FgThread.get().getLooper()); 2241 2242 getDefaultDisplayMetrics(context, mMetrics); 2243 2244 SystemConfig systemConfig = SystemConfig.getInstance(); 2245 mGlobalGids = systemConfig.getGlobalGids(); 2246 mSystemPermissions = systemConfig.getSystemPermissions(); 2247 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2248 2249 synchronized (mInstallLock) { 2250 // writer 2251 synchronized (mPackages) { 2252 mHandlerThread = new ServiceThread(TAG, 2253 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2254 mHandlerThread.start(); 2255 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2256 mProcessLoggingHandler = new ProcessLoggingHandler(); 2257 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2258 2259 File dataDir = Environment.getDataDirectory(); 2260 mAppInstallDir = new File(dataDir, "app"); 2261 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2262 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2263 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2264 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2265 2266 sUserManager = new UserManagerService(context, this, mPackages); 2267 2268 // Propagate permission configuration in to package manager. 2269 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2270 = systemConfig.getPermissions(); 2271 for (int i=0; i<permConfig.size(); i++) { 2272 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2273 BasePermission bp = mSettings.mPermissions.get(perm.name); 2274 if (bp == null) { 2275 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2276 mSettings.mPermissions.put(perm.name, bp); 2277 } 2278 if (perm.gids != null) { 2279 bp.setGids(perm.gids, perm.perUser); 2280 } 2281 } 2282 2283 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2284 for (int i=0; i<libConfig.size(); i++) { 2285 mSharedLibraries.put(libConfig.keyAt(i), 2286 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2287 } 2288 2289 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2290 2291 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2292 2293 String customResolverActivity = Resources.getSystem().getString( 2294 R.string.config_customResolverActivity); 2295 if (TextUtils.isEmpty(customResolverActivity)) { 2296 customResolverActivity = null; 2297 } else { 2298 mCustomResolverComponentName = ComponentName.unflattenFromString( 2299 customResolverActivity); 2300 } 2301 2302 long startTime = SystemClock.uptimeMillis(); 2303 2304 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2305 startTime); 2306 2307 // Set flag to monitor and not change apk file paths when 2308 // scanning install directories. 2309 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2310 2311 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2312 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2313 2314 if (bootClassPath == null) { 2315 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2316 } 2317 2318 if (systemServerClassPath == null) { 2319 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2320 } 2321 2322 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2323 final String[] dexCodeInstructionSets = 2324 getDexCodeInstructionSets( 2325 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2326 2327 /** 2328 * Ensure all external libraries have had dexopt run on them. 2329 */ 2330 if (mSharedLibraries.size() > 0) { 2331 // NOTE: For now, we're compiling these system "shared libraries" 2332 // (and framework jars) into all available architectures. It's possible 2333 // to compile them only when we come across an app that uses them (there's 2334 // already logic for that in scanPackageLI) but that adds some complexity. 2335 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2336 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2337 final String lib = libEntry.path; 2338 if (lib == null) { 2339 continue; 2340 } 2341 2342 try { 2343 // Shared libraries do not have profiles so we perform a full 2344 // AOT compilation (if needed). 2345 int dexoptNeeded = DexFile.getDexOptNeeded( 2346 lib, dexCodeInstructionSet, 2347 getCompilerFilterForReason(REASON_SHARED_APK), 2348 false /* newProfile */); 2349 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2350 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2351 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2352 getCompilerFilterForReason(REASON_SHARED_APK), 2353 StorageManager.UUID_PRIVATE_INTERNAL); 2354 } 2355 } catch (FileNotFoundException e) { 2356 Slog.w(TAG, "Library not found: " + lib); 2357 } catch (IOException | InstallerException e) { 2358 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2359 + e.getMessage()); 2360 } 2361 } 2362 } 2363 } 2364 2365 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2366 2367 final VersionInfo ver = mSettings.getInternalVersion(); 2368 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2369 2370 // when upgrading from pre-M, promote system app permissions from install to runtime 2371 mPromoteSystemApps = 2372 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2373 2374 // save off the names of pre-existing system packages prior to scanning; we don't 2375 // want to automatically grant runtime permissions for new system apps 2376 if (mPromoteSystemApps) { 2377 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2378 while (pkgSettingIter.hasNext()) { 2379 PackageSetting ps = pkgSettingIter.next(); 2380 if (isSystemApp(ps)) { 2381 mExistingSystemPackages.add(ps.name); 2382 } 2383 } 2384 } 2385 2386 // When upgrading from pre-N, we need to handle package extraction like first boot, 2387 // as there is no profiling data available. 2388 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2389 mSettings.setNWorkDone(); 2390 2391 // Collect vendor overlay packages. 2392 // (Do this before scanning any apps.) 2393 // For security and version matching reason, only consider 2394 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2395 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2396 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2397 | PackageParser.PARSE_IS_SYSTEM 2398 | PackageParser.PARSE_IS_SYSTEM_DIR 2399 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2400 2401 // Find base frameworks (resource packages without code). 2402 scanDirTracedLI(frameworkDir, mDefParseFlags 2403 | PackageParser.PARSE_IS_SYSTEM 2404 | PackageParser.PARSE_IS_SYSTEM_DIR 2405 | PackageParser.PARSE_IS_PRIVILEGED, 2406 scanFlags | SCAN_NO_DEX, 0); 2407 2408 // Collected privileged system packages. 2409 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2410 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2411 | PackageParser.PARSE_IS_SYSTEM 2412 | PackageParser.PARSE_IS_SYSTEM_DIR 2413 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2414 2415 // Collect ordinary system packages. 2416 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2417 scanDirTracedLI(systemAppDir, mDefParseFlags 2418 | PackageParser.PARSE_IS_SYSTEM 2419 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2420 2421 // Collect all vendor packages. 2422 File vendorAppDir = new File("/vendor/app"); 2423 try { 2424 vendorAppDir = vendorAppDir.getCanonicalFile(); 2425 } catch (IOException e) { 2426 // failed to look up canonical path, continue with original one 2427 } 2428 scanDirTracedLI(vendorAppDir, mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2431 2432 // Collect all OEM packages. 2433 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2434 scanDirTracedLI(oemAppDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2437 2438 // Prune any system packages that no longer exist. 2439 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2440 if (!mOnlyCore) { 2441 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2442 while (psit.hasNext()) { 2443 PackageSetting ps = psit.next(); 2444 2445 /* 2446 * If this is not a system app, it can't be a 2447 * disable system app. 2448 */ 2449 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2450 continue; 2451 } 2452 2453 /* 2454 * If the package is scanned, it's not erased. 2455 */ 2456 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2457 if (scannedPkg != null) { 2458 /* 2459 * If the system app is both scanned and in the 2460 * disabled packages list, then it must have been 2461 * added via OTA. Remove it from the currently 2462 * scanned package so the previously user-installed 2463 * application can be scanned. 2464 */ 2465 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2466 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2467 + ps.name + "; removing system app. Last known codePath=" 2468 + ps.codePathString + ", installStatus=" + ps.installStatus 2469 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2470 + scannedPkg.mVersionCode); 2471 removePackageLI(scannedPkg, true); 2472 mExpectingBetter.put(ps.name, ps.codePath); 2473 } 2474 2475 continue; 2476 } 2477 2478 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2479 psit.remove(); 2480 logCriticalInfo(Log.WARN, "System package " + ps.name 2481 + " no longer exists; it's data will be wiped"); 2482 // Actual deletion of code and data will be handled by later 2483 // reconciliation step 2484 } else { 2485 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2486 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2487 possiblyDeletedUpdatedSystemApps.add(ps.name); 2488 } 2489 } 2490 } 2491 } 2492 2493 //look for any incomplete package installations 2494 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2495 for (int i = 0; i < deletePkgsList.size(); i++) { 2496 // Actual deletion of code and data will be handled by later 2497 // reconciliation step 2498 final String packageName = deletePkgsList.get(i).name; 2499 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2500 synchronized (mPackages) { 2501 mSettings.removePackageLPw(packageName); 2502 } 2503 } 2504 2505 //delete tmp files 2506 deleteTempPackageFiles(); 2507 2508 // Remove any shared userIDs that have no associated packages 2509 mSettings.pruneSharedUsersLPw(); 2510 2511 if (!mOnlyCore) { 2512 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2513 SystemClock.uptimeMillis()); 2514 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2515 2516 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2517 | PackageParser.PARSE_FORWARD_LOCK, 2518 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2519 2520 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2521 | PackageParser.PARSE_IS_EPHEMERAL, 2522 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2523 2524 /** 2525 * Remove disable package settings for any updated system 2526 * apps that were removed via an OTA. If they're not a 2527 * previously-updated app, remove them completely. 2528 * Otherwise, just revoke their system-level permissions. 2529 */ 2530 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2531 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2532 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2533 2534 String msg; 2535 if (deletedPkg == null) { 2536 msg = "Updated system package " + deletedAppName 2537 + " no longer exists; it's data will be wiped"; 2538 // Actual deletion of code and data will be handled by later 2539 // reconciliation step 2540 } else { 2541 msg = "Updated system app + " + deletedAppName 2542 + " no longer present; removing system privileges for " 2543 + deletedAppName; 2544 2545 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2546 2547 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2548 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2549 } 2550 logCriticalInfo(Log.WARN, msg); 2551 } 2552 2553 /** 2554 * Make sure all system apps that we expected to appear on 2555 * the userdata partition actually showed up. If they never 2556 * appeared, crawl back and revive the system version. 2557 */ 2558 for (int i = 0; i < mExpectingBetter.size(); i++) { 2559 final String packageName = mExpectingBetter.keyAt(i); 2560 if (!mPackages.containsKey(packageName)) { 2561 final File scanFile = mExpectingBetter.valueAt(i); 2562 2563 logCriticalInfo(Log.WARN, "Expected better " + packageName 2564 + " but never showed up; reverting to system"); 2565 2566 int reparseFlags = mDefParseFlags; 2567 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2568 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2569 | PackageParser.PARSE_IS_SYSTEM_DIR 2570 | PackageParser.PARSE_IS_PRIVILEGED; 2571 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2572 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2573 | PackageParser.PARSE_IS_SYSTEM_DIR; 2574 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2575 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2576 | PackageParser.PARSE_IS_SYSTEM_DIR; 2577 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2578 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2579 | PackageParser.PARSE_IS_SYSTEM_DIR; 2580 } else { 2581 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2582 continue; 2583 } 2584 2585 mSettings.enableSystemPackageLPw(packageName); 2586 2587 try { 2588 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2589 } catch (PackageManagerException e) { 2590 Slog.e(TAG, "Failed to parse original system package: " 2591 + e.getMessage()); 2592 } 2593 } 2594 } 2595 } 2596 mExpectingBetter.clear(); 2597 2598 // Resolve protected action filters. Only the setup wizard is allowed to 2599 // have a high priority filter for these actions. 2600 mSetupWizardPackage = getSetupWizardPackageName(); 2601 if (mProtectedFilters.size() > 0) { 2602 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2603 Slog.i(TAG, "No setup wizard;" 2604 + " All protected intents capped to priority 0"); 2605 } 2606 for (ActivityIntentInfo filter : mProtectedFilters) { 2607 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2608 if (DEBUG_FILTERS) { 2609 Slog.i(TAG, "Found setup wizard;" 2610 + " allow priority " + filter.getPriority() + ";" 2611 + " package: " + filter.activity.info.packageName 2612 + " activity: " + filter.activity.className 2613 + " priority: " + filter.getPriority()); 2614 } 2615 // skip setup wizard; allow it to keep the high priority filter 2616 continue; 2617 } 2618 Slog.w(TAG, "Protected action; cap priority to 0;" 2619 + " package: " + filter.activity.info.packageName 2620 + " activity: " + filter.activity.className 2621 + " origPrio: " + filter.getPriority()); 2622 filter.setPriority(0); 2623 } 2624 } 2625 mDeferProtectedFilters = false; 2626 mProtectedFilters.clear(); 2627 2628 // Now that we know all of the shared libraries, update all clients to have 2629 // the correct library paths. 2630 updateAllSharedLibrariesLPw(); 2631 2632 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2633 // NOTE: We ignore potential failures here during a system scan (like 2634 // the rest of the commands above) because there's precious little we 2635 // can do about it. A settings error is reported, though. 2636 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2637 false /* boot complete */); 2638 } 2639 2640 // Now that we know all the packages we are keeping, 2641 // read and update their last usage times. 2642 mPackageUsage.readLP(); 2643 2644 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2645 SystemClock.uptimeMillis()); 2646 Slog.i(TAG, "Time to scan packages: " 2647 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2648 + " seconds"); 2649 2650 // If the platform SDK has changed since the last time we booted, 2651 // we need to re-grant app permission to catch any new ones that 2652 // appear. This is really a hack, and means that apps can in some 2653 // cases get permissions that the user didn't initially explicitly 2654 // allow... it would be nice to have some better way to handle 2655 // this situation. 2656 int updateFlags = UPDATE_PERMISSIONS_ALL; 2657 if (ver.sdkVersion != mSdkVersion) { 2658 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2659 + mSdkVersion + "; regranting permissions for internal storage"); 2660 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2661 } 2662 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2663 ver.sdkVersion = mSdkVersion; 2664 2665 // If this is the first boot or an update from pre-M, and it is a normal 2666 // boot, then we need to initialize the default preferred apps across 2667 // all defined users. 2668 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2669 for (UserInfo user : sUserManager.getUsers(true)) { 2670 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2671 applyFactoryDefaultBrowserLPw(user.id); 2672 primeDomainVerificationsLPw(user.id); 2673 } 2674 } 2675 2676 // Prepare storage for system user really early during boot, 2677 // since core system apps like SettingsProvider and SystemUI 2678 // can't wait for user to start 2679 final int storageFlags; 2680 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2681 storageFlags = StorageManager.FLAG_STORAGE_DE; 2682 } else { 2683 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2684 } 2685 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2686 storageFlags); 2687 2688 // If this is first boot after an OTA, and a normal boot, then 2689 // we need to clear code cache directories. 2690 if (mIsUpgrade && !onlyCore) { 2691 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2692 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2693 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2694 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2695 // No apps are running this early, so no need to freeze 2696 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2697 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2698 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2699 } 2700 clearAppProfilesLIF(ps.pkg); 2701 } 2702 ver.fingerprint = Build.FINGERPRINT; 2703 } 2704 2705 checkDefaultBrowser(); 2706 2707 // clear only after permissions and other defaults have been updated 2708 mExistingSystemPackages.clear(); 2709 mPromoteSystemApps = false; 2710 2711 // All the changes are done during package scanning. 2712 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2713 2714 // can downgrade to reader 2715 mSettings.writeLPr(); 2716 2717 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2718 SystemClock.uptimeMillis()); 2719 2720 if (!mOnlyCore) { 2721 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2722 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2723 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2724 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2725 mIntentFilterVerifierComponent); 2726 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2727 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2728 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2729 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2730 } else { 2731 mRequiredVerifierPackage = null; 2732 mRequiredInstallerPackage = null; 2733 mIntentFilterVerifierComponent = null; 2734 mIntentFilterVerifier = null; 2735 mServicesSystemSharedLibraryPackageName = null; 2736 mSharedSystemSharedLibraryPackageName = null; 2737 } 2738 2739 mInstallerService = new PackageInstallerService(context, this); 2740 2741 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2742 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2743 // both the installer and resolver must be present to enable ephemeral 2744 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2745 if (DEBUG_EPHEMERAL) { 2746 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2747 + " installer:" + ephemeralInstallerComponent); 2748 } 2749 mEphemeralResolverComponent = ephemeralResolverComponent; 2750 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2751 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2752 mEphemeralResolverConnection = 2753 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2754 } else { 2755 if (DEBUG_EPHEMERAL) { 2756 final String missingComponent = 2757 (ephemeralResolverComponent == null) 2758 ? (ephemeralInstallerComponent == null) 2759 ? "resolver and installer" 2760 : "resolver" 2761 : "installer"; 2762 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2763 } 2764 mEphemeralResolverComponent = null; 2765 mEphemeralInstallerComponent = null; 2766 mEphemeralResolverConnection = null; 2767 } 2768 2769 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2770 } // synchronized (mPackages) 2771 } // synchronized (mInstallLock) 2772 2773 // Now after opening every single application zip, make sure they 2774 // are all flushed. Not really needed, but keeps things nice and 2775 // tidy. 2776 Runtime.getRuntime().gc(); 2777 2778 // The initial scanning above does many calls into installd while 2779 // holding the mPackages lock, but we're mostly interested in yelling 2780 // once we have a booted system. 2781 mInstaller.setWarnIfHeld(mPackages); 2782 2783 // Expose private service for system components to use. 2784 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2785 } 2786 2787 @Override 2788 public boolean isFirstBoot() { 2789 return !mRestoredSettings; 2790 } 2791 2792 @Override 2793 public boolean isOnlyCoreApps() { 2794 return mOnlyCore; 2795 } 2796 2797 @Override 2798 public boolean isUpgrade() { 2799 return mIsUpgrade; 2800 } 2801 2802 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2803 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2804 2805 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2806 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2807 UserHandle.USER_SYSTEM); 2808 if (matches.size() == 1) { 2809 return matches.get(0).getComponentInfo().packageName; 2810 } else { 2811 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2812 return null; 2813 } 2814 } 2815 2816 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2817 synchronized (mPackages) { 2818 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2819 if (libraryEntry == null) { 2820 throw new IllegalStateException("Missing required shared library:" + libraryName); 2821 } 2822 return libraryEntry.apk; 2823 } 2824 } 2825 2826 private @NonNull String getRequiredInstallerLPr() { 2827 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2828 intent.addCategory(Intent.CATEGORY_DEFAULT); 2829 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2830 2831 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2832 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2833 UserHandle.USER_SYSTEM); 2834 if (matches.size() == 1) { 2835 ResolveInfo resolveInfo = matches.get(0); 2836 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2837 throw new RuntimeException("The installer must be a privileged app"); 2838 } 2839 return matches.get(0).getComponentInfo().packageName; 2840 } else { 2841 throw new RuntimeException("There must be exactly one installer; found " + matches); 2842 } 2843 } 2844 2845 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2846 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2847 2848 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2849 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2850 UserHandle.USER_SYSTEM); 2851 ResolveInfo best = null; 2852 final int N = matches.size(); 2853 for (int i = 0; i < N; i++) { 2854 final ResolveInfo cur = matches.get(i); 2855 final String packageName = cur.getComponentInfo().packageName; 2856 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2857 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2858 continue; 2859 } 2860 2861 if (best == null || cur.priority > best.priority) { 2862 best = cur; 2863 } 2864 } 2865 2866 if (best != null) { 2867 return best.getComponentInfo().getComponentName(); 2868 } else { 2869 throw new RuntimeException("There must be at least one intent filter verifier"); 2870 } 2871 } 2872 2873 private @Nullable ComponentName getEphemeralResolverLPr() { 2874 final String[] packageArray = 2875 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2876 if (packageArray.length == 0) { 2877 if (DEBUG_EPHEMERAL) { 2878 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2879 } 2880 return null; 2881 } 2882 2883 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2884 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2885 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2886 UserHandle.USER_SYSTEM); 2887 2888 final int N = resolvers.size(); 2889 if (N == 0) { 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2892 } 2893 return null; 2894 } 2895 2896 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2897 for (int i = 0; i < N; i++) { 2898 final ResolveInfo info = resolvers.get(i); 2899 2900 if (info.serviceInfo == null) { 2901 continue; 2902 } 2903 2904 final String packageName = info.serviceInfo.packageName; 2905 if (!possiblePackages.contains(packageName)) { 2906 if (DEBUG_EPHEMERAL) { 2907 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2908 + " pkg: " + packageName + ", info:" + info); 2909 } 2910 continue; 2911 } 2912 2913 if (DEBUG_EPHEMERAL) { 2914 Slog.v(TAG, "Ephemeral resolver found;" 2915 + " pkg: " + packageName + ", info:" + info); 2916 } 2917 return new ComponentName(packageName, info.serviceInfo.name); 2918 } 2919 if (DEBUG_EPHEMERAL) { 2920 Slog.v(TAG, "Ephemeral resolver NOT found"); 2921 } 2922 return null; 2923 } 2924 2925 private @Nullable ComponentName getEphemeralInstallerLPr() { 2926 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2927 intent.addCategory(Intent.CATEGORY_DEFAULT); 2928 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2929 2930 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2931 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2932 UserHandle.USER_SYSTEM); 2933 if (matches.size() == 0) { 2934 return null; 2935 } else if (matches.size() == 1) { 2936 return matches.get(0).getComponentInfo().getComponentName(); 2937 } else { 2938 throw new RuntimeException( 2939 "There must be at most one ephemeral installer; found " + matches); 2940 } 2941 } 2942 2943 private void primeDomainVerificationsLPw(int userId) { 2944 if (DEBUG_DOMAIN_VERIFICATION) { 2945 Slog.d(TAG, "Priming domain verifications in user " + userId); 2946 } 2947 2948 SystemConfig systemConfig = SystemConfig.getInstance(); 2949 ArraySet<String> packages = systemConfig.getLinkedApps(); 2950 ArraySet<String> domains = new ArraySet<String>(); 2951 2952 for (String packageName : packages) { 2953 PackageParser.Package pkg = mPackages.get(packageName); 2954 if (pkg != null) { 2955 if (!pkg.isSystemApp()) { 2956 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2957 continue; 2958 } 2959 2960 domains.clear(); 2961 for (PackageParser.Activity a : pkg.activities) { 2962 for (ActivityIntentInfo filter : a.intents) { 2963 if (hasValidDomains(filter)) { 2964 domains.addAll(filter.getHostsList()); 2965 } 2966 } 2967 } 2968 2969 if (domains.size() > 0) { 2970 if (DEBUG_DOMAIN_VERIFICATION) { 2971 Slog.v(TAG, " + " + packageName); 2972 } 2973 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2974 // state w.r.t. the formal app-linkage "no verification attempted" state; 2975 // and then 'always' in the per-user state actually used for intent resolution. 2976 final IntentFilterVerificationInfo ivi; 2977 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2978 new ArrayList<String>(domains)); 2979 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2980 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2981 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2982 } else { 2983 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2984 + "' does not handle web links"); 2985 } 2986 } else { 2987 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2988 } 2989 } 2990 2991 scheduleWritePackageRestrictionsLocked(userId); 2992 scheduleWriteSettingsLocked(); 2993 } 2994 2995 private void applyFactoryDefaultBrowserLPw(int userId) { 2996 // The default browser app's package name is stored in a string resource, 2997 // with a product-specific overlay used for vendor customization. 2998 String browserPkg = mContext.getResources().getString( 2999 com.android.internal.R.string.default_browser); 3000 if (!TextUtils.isEmpty(browserPkg)) { 3001 // non-empty string => required to be a known package 3002 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3003 if (ps == null) { 3004 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3005 browserPkg = null; 3006 } else { 3007 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3008 } 3009 } 3010 3011 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3012 // default. If there's more than one, just leave everything alone. 3013 if (browserPkg == null) { 3014 calculateDefaultBrowserLPw(userId); 3015 } 3016 } 3017 3018 private void calculateDefaultBrowserLPw(int userId) { 3019 List<String> allBrowsers = resolveAllBrowserApps(userId); 3020 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3021 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3022 } 3023 3024 private List<String> resolveAllBrowserApps(int userId) { 3025 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3026 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3027 PackageManager.MATCH_ALL, userId); 3028 3029 final int count = list.size(); 3030 List<String> result = new ArrayList<String>(count); 3031 for (int i=0; i<count; i++) { 3032 ResolveInfo info = list.get(i); 3033 if (info.activityInfo == null 3034 || !info.handleAllWebDataURI 3035 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3036 || result.contains(info.activityInfo.packageName)) { 3037 continue; 3038 } 3039 result.add(info.activityInfo.packageName); 3040 } 3041 3042 return result; 3043 } 3044 3045 private boolean packageIsBrowser(String packageName, int userId) { 3046 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3047 PackageManager.MATCH_ALL, userId); 3048 final int N = list.size(); 3049 for (int i = 0; i < N; i++) { 3050 ResolveInfo info = list.get(i); 3051 if (packageName.equals(info.activityInfo.packageName)) { 3052 return true; 3053 } 3054 } 3055 return false; 3056 } 3057 3058 private void checkDefaultBrowser() { 3059 final int myUserId = UserHandle.myUserId(); 3060 final String packageName = getDefaultBrowserPackageName(myUserId); 3061 if (packageName != null) { 3062 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3063 if (info == null) { 3064 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3065 synchronized (mPackages) { 3066 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3067 } 3068 } 3069 } 3070 } 3071 3072 @Override 3073 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3074 throws RemoteException { 3075 try { 3076 return super.onTransact(code, data, reply, flags); 3077 } catch (RuntimeException e) { 3078 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3079 Slog.wtf(TAG, "Package Manager Crash", e); 3080 } 3081 throw e; 3082 } 3083 } 3084 3085 static int[] appendInts(int[] cur, int[] add) { 3086 if (add == null) return cur; 3087 if (cur == null) return add; 3088 final int N = add.length; 3089 for (int i=0; i<N; i++) { 3090 cur = appendInt(cur, add[i]); 3091 } 3092 return cur; 3093 } 3094 3095 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3096 if (!sUserManager.exists(userId)) return null; 3097 if (ps == null) { 3098 return null; 3099 } 3100 final PackageParser.Package p = ps.pkg; 3101 if (p == null) { 3102 return null; 3103 } 3104 3105 final PermissionsState permissionsState = ps.getPermissionsState(); 3106 3107 final int[] gids = permissionsState.computeGids(userId); 3108 final Set<String> permissions = permissionsState.getPermissions(userId); 3109 final PackageUserState state = ps.readUserState(userId); 3110 3111 return PackageParser.generatePackageInfo(p, gids, flags, 3112 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3113 } 3114 3115 @Override 3116 public void checkPackageStartable(String packageName, int userId) { 3117 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3118 3119 synchronized (mPackages) { 3120 final PackageSetting ps = mSettings.mPackages.get(packageName); 3121 if (ps == null) { 3122 throw new SecurityException("Package " + packageName + " was not found!"); 3123 } 3124 3125 if (!ps.getInstalled(userId)) { 3126 throw new SecurityException( 3127 "Package " + packageName + " was not installed for user " + userId + "!"); 3128 } 3129 3130 if (mSafeMode && !ps.isSystem()) { 3131 throw new SecurityException("Package " + packageName + " not a system app!"); 3132 } 3133 3134 if (mFrozenPackages.contains(packageName)) { 3135 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3136 } 3137 3138 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3139 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3140 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3141 } 3142 } 3143 } 3144 3145 @Override 3146 public boolean isPackageAvailable(String packageName, int userId) { 3147 if (!sUserManager.exists(userId)) return false; 3148 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3149 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3150 synchronized (mPackages) { 3151 PackageParser.Package p = mPackages.get(packageName); 3152 if (p != null) { 3153 final PackageSetting ps = (PackageSetting) p.mExtras; 3154 if (ps != null) { 3155 final PackageUserState state = ps.readUserState(userId); 3156 if (state != null) { 3157 return PackageParser.isAvailable(state); 3158 } 3159 } 3160 } 3161 } 3162 return false; 3163 } 3164 3165 @Override 3166 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3167 if (!sUserManager.exists(userId)) return null; 3168 flags = updateFlagsForPackage(flags, userId, packageName); 3169 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3170 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3171 // reader 3172 synchronized (mPackages) { 3173 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3174 PackageParser.Package p = null; 3175 if (matchFactoryOnly) { 3176 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3177 if (ps != null) { 3178 return generatePackageInfo(ps, flags, userId); 3179 } 3180 } 3181 if (p == null) { 3182 p = mPackages.get(packageName); 3183 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3184 return null; 3185 } 3186 } 3187 if (DEBUG_PACKAGE_INFO) 3188 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3189 if (p != null) { 3190 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3191 } 3192 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3193 final PackageSetting ps = mSettings.mPackages.get(packageName); 3194 return generatePackageInfo(ps, flags, userId); 3195 } 3196 } 3197 return null; 3198 } 3199 3200 @Override 3201 public String[] currentToCanonicalPackageNames(String[] names) { 3202 String[] out = new String[names.length]; 3203 // reader 3204 synchronized (mPackages) { 3205 for (int i=names.length-1; i>=0; i--) { 3206 PackageSetting ps = mSettings.mPackages.get(names[i]); 3207 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3208 } 3209 } 3210 return out; 3211 } 3212 3213 @Override 3214 public String[] canonicalToCurrentPackageNames(String[] names) { 3215 String[] out = new String[names.length]; 3216 // reader 3217 synchronized (mPackages) { 3218 for (int i=names.length-1; i>=0; i--) { 3219 String cur = mSettings.mRenamedPackages.get(names[i]); 3220 out[i] = cur != null ? cur : names[i]; 3221 } 3222 } 3223 return out; 3224 } 3225 3226 @Override 3227 public int getPackageUid(String packageName, int flags, int userId) { 3228 if (!sUserManager.exists(userId)) return -1; 3229 flags = updateFlagsForPackage(flags, userId, packageName); 3230 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3231 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3232 3233 // reader 3234 synchronized (mPackages) { 3235 final PackageParser.Package p = mPackages.get(packageName); 3236 if (p != null && p.isMatch(flags)) { 3237 return UserHandle.getUid(userId, p.applicationInfo.uid); 3238 } 3239 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3240 final PackageSetting ps = mSettings.mPackages.get(packageName); 3241 if (ps != null && ps.isMatch(flags)) { 3242 return UserHandle.getUid(userId, ps.appId); 3243 } 3244 } 3245 } 3246 3247 return -1; 3248 } 3249 3250 @Override 3251 public int[] getPackageGids(String packageName, int flags, int userId) { 3252 if (!sUserManager.exists(userId)) return null; 3253 flags = updateFlagsForPackage(flags, userId, packageName); 3254 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3255 false /* requireFullPermission */, false /* checkShell */, 3256 "getPackageGids"); 3257 3258 // reader 3259 synchronized (mPackages) { 3260 final PackageParser.Package p = mPackages.get(packageName); 3261 if (p != null && p.isMatch(flags)) { 3262 PackageSetting ps = (PackageSetting) p.mExtras; 3263 return ps.getPermissionsState().computeGids(userId); 3264 } 3265 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3266 final PackageSetting ps = mSettings.mPackages.get(packageName); 3267 if (ps != null && ps.isMatch(flags)) { 3268 return ps.getPermissionsState().computeGids(userId); 3269 } 3270 } 3271 } 3272 3273 return null; 3274 } 3275 3276 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3277 if (bp.perm != null) { 3278 return PackageParser.generatePermissionInfo(bp.perm, flags); 3279 } 3280 PermissionInfo pi = new PermissionInfo(); 3281 pi.name = bp.name; 3282 pi.packageName = bp.sourcePackage; 3283 pi.nonLocalizedLabel = bp.name; 3284 pi.protectionLevel = bp.protectionLevel; 3285 return pi; 3286 } 3287 3288 @Override 3289 public PermissionInfo getPermissionInfo(String name, int flags) { 3290 // reader 3291 synchronized (mPackages) { 3292 final BasePermission p = mSettings.mPermissions.get(name); 3293 if (p != null) { 3294 return generatePermissionInfo(p, flags); 3295 } 3296 return null; 3297 } 3298 } 3299 3300 @Override 3301 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3302 int flags) { 3303 // reader 3304 synchronized (mPackages) { 3305 if (group != null && !mPermissionGroups.containsKey(group)) { 3306 // This is thrown as NameNotFoundException 3307 return null; 3308 } 3309 3310 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3311 for (BasePermission p : mSettings.mPermissions.values()) { 3312 if (group == null) { 3313 if (p.perm == null || p.perm.info.group == null) { 3314 out.add(generatePermissionInfo(p, flags)); 3315 } 3316 } else { 3317 if (p.perm != null && group.equals(p.perm.info.group)) { 3318 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3319 } 3320 } 3321 } 3322 return new ParceledListSlice<>(out); 3323 } 3324 } 3325 3326 @Override 3327 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3328 // reader 3329 synchronized (mPackages) { 3330 return PackageParser.generatePermissionGroupInfo( 3331 mPermissionGroups.get(name), flags); 3332 } 3333 } 3334 3335 @Override 3336 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3337 // reader 3338 synchronized (mPackages) { 3339 final int N = mPermissionGroups.size(); 3340 ArrayList<PermissionGroupInfo> out 3341 = new ArrayList<PermissionGroupInfo>(N); 3342 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3343 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3344 } 3345 return new ParceledListSlice<>(out); 3346 } 3347 } 3348 3349 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3350 int userId) { 3351 if (!sUserManager.exists(userId)) return null; 3352 PackageSetting ps = mSettings.mPackages.get(packageName); 3353 if (ps != null) { 3354 if (ps.pkg == null) { 3355 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3356 if (pInfo != null) { 3357 return pInfo.applicationInfo; 3358 } 3359 return null; 3360 } 3361 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3362 ps.readUserState(userId), userId); 3363 } 3364 return null; 3365 } 3366 3367 @Override 3368 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3369 if (!sUserManager.exists(userId)) return null; 3370 flags = updateFlagsForApplication(flags, userId, packageName); 3371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3372 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3373 // writer 3374 synchronized (mPackages) { 3375 PackageParser.Package p = mPackages.get(packageName); 3376 if (DEBUG_PACKAGE_INFO) Log.v( 3377 TAG, "getApplicationInfo " + packageName 3378 + ": " + p); 3379 if (p != null) { 3380 PackageSetting ps = mSettings.mPackages.get(packageName); 3381 if (ps == null) return null; 3382 // Note: isEnabledLP() does not apply here - always return info 3383 return PackageParser.generateApplicationInfo( 3384 p, flags, ps.readUserState(userId), userId); 3385 } 3386 if ("android".equals(packageName)||"system".equals(packageName)) { 3387 return mAndroidApplication; 3388 } 3389 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3390 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3391 } 3392 } 3393 return null; 3394 } 3395 3396 @Override 3397 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3398 final IPackageDataObserver observer) { 3399 mContext.enforceCallingOrSelfPermission( 3400 android.Manifest.permission.CLEAR_APP_CACHE, null); 3401 // Queue up an async operation since clearing cache may take a little while. 3402 mHandler.post(new Runnable() { 3403 public void run() { 3404 mHandler.removeCallbacks(this); 3405 boolean success = true; 3406 synchronized (mInstallLock) { 3407 try { 3408 mInstaller.freeCache(volumeUuid, freeStorageSize); 3409 } catch (InstallerException e) { 3410 Slog.w(TAG, "Couldn't clear application caches: " + e); 3411 success = false; 3412 } 3413 } 3414 if (observer != null) { 3415 try { 3416 observer.onRemoveCompleted(null, success); 3417 } catch (RemoteException e) { 3418 Slog.w(TAG, "RemoveException when invoking call back"); 3419 } 3420 } 3421 } 3422 }); 3423 } 3424 3425 @Override 3426 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3427 final IntentSender pi) { 3428 mContext.enforceCallingOrSelfPermission( 3429 android.Manifest.permission.CLEAR_APP_CACHE, null); 3430 // Queue up an async operation since clearing cache may take a little while. 3431 mHandler.post(new Runnable() { 3432 public void run() { 3433 mHandler.removeCallbacks(this); 3434 boolean success = true; 3435 synchronized (mInstallLock) { 3436 try { 3437 mInstaller.freeCache(volumeUuid, freeStorageSize); 3438 } catch (InstallerException e) { 3439 Slog.w(TAG, "Couldn't clear application caches: " + e); 3440 success = false; 3441 } 3442 } 3443 if(pi != null) { 3444 try { 3445 // Callback via pending intent 3446 int code = success ? 1 : 0; 3447 pi.sendIntent(null, code, null, 3448 null, null); 3449 } catch (SendIntentException e1) { 3450 Slog.i(TAG, "Failed to send pending intent"); 3451 } 3452 } 3453 } 3454 }); 3455 } 3456 3457 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3458 synchronized (mInstallLock) { 3459 try { 3460 mInstaller.freeCache(volumeUuid, freeStorageSize); 3461 } catch (InstallerException e) { 3462 throw new IOException("Failed to free enough space", e); 3463 } 3464 } 3465 } 3466 3467 /** 3468 * Return if the user key is currently unlocked. 3469 */ 3470 private boolean isUserKeyUnlocked(int userId) { 3471 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3472 final IMountService mount = IMountService.Stub 3473 .asInterface(ServiceManager.getService("mount")); 3474 if (mount == null) { 3475 Slog.w(TAG, "Early during boot, assuming locked"); 3476 return false; 3477 } 3478 final long token = Binder.clearCallingIdentity(); 3479 try { 3480 return mount.isUserKeyUnlocked(userId); 3481 } catch (RemoteException e) { 3482 throw e.rethrowAsRuntimeException(); 3483 } finally { 3484 Binder.restoreCallingIdentity(token); 3485 } 3486 } else { 3487 return true; 3488 } 3489 } 3490 3491 /** 3492 * Update given flags based on encryption status of current user. 3493 */ 3494 private int updateFlags(int flags, int userId) { 3495 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3496 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3497 // Caller expressed an explicit opinion about what encryption 3498 // aware/unaware components they want to see, so fall through and 3499 // give them what they want 3500 } else { 3501 // Caller expressed no opinion, so match based on user state 3502 if (isUserKeyUnlocked(userId)) { 3503 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3504 } else { 3505 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3506 } 3507 } 3508 return flags; 3509 } 3510 3511 /** 3512 * Update given flags when being used to request {@link PackageInfo}. 3513 */ 3514 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3515 boolean triaged = true; 3516 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3517 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3518 // Caller is asking for component details, so they'd better be 3519 // asking for specific encryption matching behavior, or be triaged 3520 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3521 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3522 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3523 triaged = false; 3524 } 3525 } 3526 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3527 | PackageManager.MATCH_SYSTEM_ONLY 3528 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3529 triaged = false; 3530 } 3531 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3532 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3533 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3534 } 3535 return updateFlags(flags, userId); 3536 } 3537 3538 /** 3539 * Update given flags when being used to request {@link ApplicationInfo}. 3540 */ 3541 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3542 return updateFlagsForPackage(flags, userId, cookie); 3543 } 3544 3545 /** 3546 * Update given flags when being used to request {@link ComponentInfo}. 3547 */ 3548 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3549 if (cookie instanceof Intent) { 3550 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3551 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3552 } 3553 } 3554 3555 boolean triaged = true; 3556 // Caller is asking for component details, so they'd better be 3557 // asking for specific encryption matching behavior, or be triaged 3558 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3559 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3560 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3561 triaged = false; 3562 } 3563 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3564 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3565 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3566 } 3567 3568 return updateFlags(flags, userId); 3569 } 3570 3571 /** 3572 * Update given flags when being used to request {@link ResolveInfo}. 3573 */ 3574 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3575 // Safe mode means we shouldn't match any third-party components 3576 if (mSafeMode) { 3577 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3578 } 3579 3580 return updateFlagsForComponent(flags, userId, cookie); 3581 } 3582 3583 @Override 3584 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3585 if (!sUserManager.exists(userId)) return null; 3586 flags = updateFlagsForComponent(flags, userId, component); 3587 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3588 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3589 synchronized (mPackages) { 3590 PackageParser.Activity a = mActivities.mActivities.get(component); 3591 3592 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3593 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3594 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3595 if (ps == null) return null; 3596 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3597 userId); 3598 } 3599 if (mResolveComponentName.equals(component)) { 3600 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3601 new PackageUserState(), userId); 3602 } 3603 } 3604 return null; 3605 } 3606 3607 @Override 3608 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3609 String resolvedType) { 3610 synchronized (mPackages) { 3611 if (component.equals(mResolveComponentName)) { 3612 // The resolver supports EVERYTHING! 3613 return true; 3614 } 3615 PackageParser.Activity a = mActivities.mActivities.get(component); 3616 if (a == null) { 3617 return false; 3618 } 3619 for (int i=0; i<a.intents.size(); i++) { 3620 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3621 intent.getData(), intent.getCategories(), TAG) >= 0) { 3622 return true; 3623 } 3624 } 3625 return false; 3626 } 3627 } 3628 3629 @Override 3630 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3631 if (!sUserManager.exists(userId)) return null; 3632 flags = updateFlagsForComponent(flags, userId, component); 3633 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3634 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3635 synchronized (mPackages) { 3636 PackageParser.Activity a = mReceivers.mActivities.get(component); 3637 if (DEBUG_PACKAGE_INFO) Log.v( 3638 TAG, "getReceiverInfo " + component + ": " + a); 3639 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3640 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3641 if (ps == null) return null; 3642 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3643 userId); 3644 } 3645 } 3646 return null; 3647 } 3648 3649 @Override 3650 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3651 if (!sUserManager.exists(userId)) return null; 3652 flags = updateFlagsForComponent(flags, userId, component); 3653 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3654 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3655 synchronized (mPackages) { 3656 PackageParser.Service s = mServices.mServices.get(component); 3657 if (DEBUG_PACKAGE_INFO) Log.v( 3658 TAG, "getServiceInfo " + component + ": " + s); 3659 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3660 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3661 if (ps == null) return null; 3662 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3663 userId); 3664 } 3665 } 3666 return null; 3667 } 3668 3669 @Override 3670 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3671 if (!sUserManager.exists(userId)) return null; 3672 flags = updateFlagsForComponent(flags, userId, component); 3673 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3674 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3675 synchronized (mPackages) { 3676 PackageParser.Provider p = mProviders.mProviders.get(component); 3677 if (DEBUG_PACKAGE_INFO) Log.v( 3678 TAG, "getProviderInfo " + component + ": " + p); 3679 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3680 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3681 if (ps == null) return null; 3682 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3683 userId); 3684 } 3685 } 3686 return null; 3687 } 3688 3689 @Override 3690 public String[] getSystemSharedLibraryNames() { 3691 Set<String> libSet; 3692 synchronized (mPackages) { 3693 libSet = mSharedLibraries.keySet(); 3694 int size = libSet.size(); 3695 if (size > 0) { 3696 String[] libs = new String[size]; 3697 libSet.toArray(libs); 3698 return libs; 3699 } 3700 } 3701 return null; 3702 } 3703 3704 @Override 3705 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3706 synchronized (mPackages) { 3707 return mServicesSystemSharedLibraryPackageName; 3708 } 3709 } 3710 3711 @Override 3712 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3713 synchronized (mPackages) { 3714 return mSharedSystemSharedLibraryPackageName; 3715 } 3716 } 3717 3718 @Override 3719 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3720 synchronized (mPackages) { 3721 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3722 3723 final FeatureInfo fi = new FeatureInfo(); 3724 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3725 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3726 res.add(fi); 3727 3728 return new ParceledListSlice<>(res); 3729 } 3730 } 3731 3732 @Override 3733 public boolean hasSystemFeature(String name, int version) { 3734 synchronized (mPackages) { 3735 final FeatureInfo feat = mAvailableFeatures.get(name); 3736 if (feat == null) { 3737 return false; 3738 } else { 3739 return feat.version >= version; 3740 } 3741 } 3742 } 3743 3744 @Override 3745 public int checkPermission(String permName, String pkgName, int userId) { 3746 if (!sUserManager.exists(userId)) { 3747 return PackageManager.PERMISSION_DENIED; 3748 } 3749 3750 synchronized (mPackages) { 3751 final PackageParser.Package p = mPackages.get(pkgName); 3752 if (p != null && p.mExtras != null) { 3753 final PackageSetting ps = (PackageSetting) p.mExtras; 3754 final PermissionsState permissionsState = ps.getPermissionsState(); 3755 if (permissionsState.hasPermission(permName, userId)) { 3756 return PackageManager.PERMISSION_GRANTED; 3757 } 3758 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3759 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3760 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3761 return PackageManager.PERMISSION_GRANTED; 3762 } 3763 } 3764 } 3765 3766 return PackageManager.PERMISSION_DENIED; 3767 } 3768 3769 @Override 3770 public int checkUidPermission(String permName, int uid) { 3771 final int userId = UserHandle.getUserId(uid); 3772 3773 if (!sUserManager.exists(userId)) { 3774 return PackageManager.PERMISSION_DENIED; 3775 } 3776 3777 synchronized (mPackages) { 3778 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3779 if (obj != null) { 3780 final SettingBase ps = (SettingBase) obj; 3781 final PermissionsState permissionsState = ps.getPermissionsState(); 3782 if (permissionsState.hasPermission(permName, userId)) { 3783 return PackageManager.PERMISSION_GRANTED; 3784 } 3785 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3786 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3787 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3788 return PackageManager.PERMISSION_GRANTED; 3789 } 3790 } else { 3791 ArraySet<String> perms = mSystemPermissions.get(uid); 3792 if (perms != null) { 3793 if (perms.contains(permName)) { 3794 return PackageManager.PERMISSION_GRANTED; 3795 } 3796 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3797 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3798 return PackageManager.PERMISSION_GRANTED; 3799 } 3800 } 3801 } 3802 } 3803 3804 return PackageManager.PERMISSION_DENIED; 3805 } 3806 3807 @Override 3808 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3809 if (UserHandle.getCallingUserId() != userId) { 3810 mContext.enforceCallingPermission( 3811 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3812 "isPermissionRevokedByPolicy for user " + userId); 3813 } 3814 3815 if (checkPermission(permission, packageName, userId) 3816 == PackageManager.PERMISSION_GRANTED) { 3817 return false; 3818 } 3819 3820 final long identity = Binder.clearCallingIdentity(); 3821 try { 3822 final int flags = getPermissionFlags(permission, packageName, userId); 3823 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3824 } finally { 3825 Binder.restoreCallingIdentity(identity); 3826 } 3827 } 3828 3829 @Override 3830 public String getPermissionControllerPackageName() { 3831 synchronized (mPackages) { 3832 return mRequiredInstallerPackage; 3833 } 3834 } 3835 3836 /** 3837 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3838 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3839 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3840 * @param message the message to log on security exception 3841 */ 3842 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3843 boolean checkShell, String message) { 3844 if (userId < 0) { 3845 throw new IllegalArgumentException("Invalid userId " + userId); 3846 } 3847 if (checkShell) { 3848 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3849 } 3850 if (userId == UserHandle.getUserId(callingUid)) return; 3851 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3852 if (requireFullPermission) { 3853 mContext.enforceCallingOrSelfPermission( 3854 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3855 } else { 3856 try { 3857 mContext.enforceCallingOrSelfPermission( 3858 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3859 } catch (SecurityException se) { 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3862 } 3863 } 3864 } 3865 } 3866 3867 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3868 if (callingUid == Process.SHELL_UID) { 3869 if (userHandle >= 0 3870 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3871 throw new SecurityException("Shell does not have permission to access user " 3872 + userHandle); 3873 } else if (userHandle < 0) { 3874 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3875 + Debug.getCallers(3)); 3876 } 3877 } 3878 } 3879 3880 private BasePermission findPermissionTreeLP(String permName) { 3881 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3882 if (permName.startsWith(bp.name) && 3883 permName.length() > bp.name.length() && 3884 permName.charAt(bp.name.length()) == '.') { 3885 return bp; 3886 } 3887 } 3888 return null; 3889 } 3890 3891 private BasePermission checkPermissionTreeLP(String permName) { 3892 if (permName != null) { 3893 BasePermission bp = findPermissionTreeLP(permName); 3894 if (bp != null) { 3895 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3896 return bp; 3897 } 3898 throw new SecurityException("Calling uid " 3899 + Binder.getCallingUid() 3900 + " is not allowed to add to permission tree " 3901 + bp.name + " owned by uid " + bp.uid); 3902 } 3903 } 3904 throw new SecurityException("No permission tree found for " + permName); 3905 } 3906 3907 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3908 if (s1 == null) { 3909 return s2 == null; 3910 } 3911 if (s2 == null) { 3912 return false; 3913 } 3914 if (s1.getClass() != s2.getClass()) { 3915 return false; 3916 } 3917 return s1.equals(s2); 3918 } 3919 3920 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3921 if (pi1.icon != pi2.icon) return false; 3922 if (pi1.logo != pi2.logo) return false; 3923 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3924 if (!compareStrings(pi1.name, pi2.name)) return false; 3925 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3926 // We'll take care of setting this one. 3927 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3928 // These are not currently stored in settings. 3929 //if (!compareStrings(pi1.group, pi2.group)) return false; 3930 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3931 //if (pi1.labelRes != pi2.labelRes) return false; 3932 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3933 return true; 3934 } 3935 3936 int permissionInfoFootprint(PermissionInfo info) { 3937 int size = info.name.length(); 3938 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3939 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3940 return size; 3941 } 3942 3943 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3944 int size = 0; 3945 for (BasePermission perm : mSettings.mPermissions.values()) { 3946 if (perm.uid == tree.uid) { 3947 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3948 } 3949 } 3950 return size; 3951 } 3952 3953 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3954 // We calculate the max size of permissions defined by this uid and throw 3955 // if that plus the size of 'info' would exceed our stated maximum. 3956 if (tree.uid != Process.SYSTEM_UID) { 3957 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3958 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3959 throw new SecurityException("Permission tree size cap exceeded"); 3960 } 3961 } 3962 } 3963 3964 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3965 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3966 throw new SecurityException("Label must be specified in permission"); 3967 } 3968 BasePermission tree = checkPermissionTreeLP(info.name); 3969 BasePermission bp = mSettings.mPermissions.get(info.name); 3970 boolean added = bp == null; 3971 boolean changed = true; 3972 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3973 if (added) { 3974 enforcePermissionCapLocked(info, tree); 3975 bp = new BasePermission(info.name, tree.sourcePackage, 3976 BasePermission.TYPE_DYNAMIC); 3977 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3978 throw new SecurityException( 3979 "Not allowed to modify non-dynamic permission " 3980 + info.name); 3981 } else { 3982 if (bp.protectionLevel == fixedLevel 3983 && bp.perm.owner.equals(tree.perm.owner) 3984 && bp.uid == tree.uid 3985 && comparePermissionInfos(bp.perm.info, info)) { 3986 changed = false; 3987 } 3988 } 3989 bp.protectionLevel = fixedLevel; 3990 info = new PermissionInfo(info); 3991 info.protectionLevel = fixedLevel; 3992 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3993 bp.perm.info.packageName = tree.perm.info.packageName; 3994 bp.uid = tree.uid; 3995 if (added) { 3996 mSettings.mPermissions.put(info.name, bp); 3997 } 3998 if (changed) { 3999 if (!async) { 4000 mSettings.writeLPr(); 4001 } else { 4002 scheduleWriteSettingsLocked(); 4003 } 4004 } 4005 return added; 4006 } 4007 4008 @Override 4009 public boolean addPermission(PermissionInfo info) { 4010 synchronized (mPackages) { 4011 return addPermissionLocked(info, false); 4012 } 4013 } 4014 4015 @Override 4016 public boolean addPermissionAsync(PermissionInfo info) { 4017 synchronized (mPackages) { 4018 return addPermissionLocked(info, true); 4019 } 4020 } 4021 4022 @Override 4023 public void removePermission(String name) { 4024 synchronized (mPackages) { 4025 checkPermissionTreeLP(name); 4026 BasePermission bp = mSettings.mPermissions.get(name); 4027 if (bp != null) { 4028 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4029 throw new SecurityException( 4030 "Not allowed to modify non-dynamic permission " 4031 + name); 4032 } 4033 mSettings.mPermissions.remove(name); 4034 mSettings.writeLPr(); 4035 } 4036 } 4037 } 4038 4039 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4040 BasePermission bp) { 4041 int index = pkg.requestedPermissions.indexOf(bp.name); 4042 if (index == -1) { 4043 throw new SecurityException("Package " + pkg.packageName 4044 + " has not requested permission " + bp.name); 4045 } 4046 if (!bp.isRuntime() && !bp.isDevelopment()) { 4047 throw new SecurityException("Permission " + bp.name 4048 + " is not a changeable permission type"); 4049 } 4050 } 4051 4052 @Override 4053 public void grantRuntimePermission(String packageName, String name, final int userId) { 4054 if (!sUserManager.exists(userId)) { 4055 Log.e(TAG, "No such user:" + userId); 4056 return; 4057 } 4058 4059 mContext.enforceCallingOrSelfPermission( 4060 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4061 "grantRuntimePermission"); 4062 4063 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4064 true /* requireFullPermission */, true /* checkShell */, 4065 "grantRuntimePermission"); 4066 4067 final int uid; 4068 final SettingBase sb; 4069 4070 synchronized (mPackages) { 4071 final PackageParser.Package pkg = mPackages.get(packageName); 4072 if (pkg == null) { 4073 throw new IllegalArgumentException("Unknown package: " + packageName); 4074 } 4075 4076 final BasePermission bp = mSettings.mPermissions.get(name); 4077 if (bp == null) { 4078 throw new IllegalArgumentException("Unknown permission: " + name); 4079 } 4080 4081 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4082 4083 // If a permission review is required for legacy apps we represent 4084 // their permissions as always granted runtime ones since we need 4085 // to keep the review required permission flag per user while an 4086 // install permission's state is shared across all users. 4087 if (Build.PERMISSIONS_REVIEW_REQUIRED 4088 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4089 && bp.isRuntime()) { 4090 return; 4091 } 4092 4093 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4094 sb = (SettingBase) pkg.mExtras; 4095 if (sb == null) { 4096 throw new IllegalArgumentException("Unknown package: " + packageName); 4097 } 4098 4099 final PermissionsState permissionsState = sb.getPermissionsState(); 4100 4101 final int flags = permissionsState.getPermissionFlags(name, userId); 4102 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4103 throw new SecurityException("Cannot grant system fixed permission " 4104 + name + " for package " + packageName); 4105 } 4106 4107 if (bp.isDevelopment()) { 4108 // Development permissions must be handled specially, since they are not 4109 // normal runtime permissions. For now they apply to all users. 4110 if (permissionsState.grantInstallPermission(bp) != 4111 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4112 scheduleWriteSettingsLocked(); 4113 } 4114 return; 4115 } 4116 4117 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4118 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4119 return; 4120 } 4121 4122 final int result = permissionsState.grantRuntimePermission(bp, userId); 4123 switch (result) { 4124 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4125 return; 4126 } 4127 4128 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4129 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4130 mHandler.post(new Runnable() { 4131 @Override 4132 public void run() { 4133 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4134 } 4135 }); 4136 } 4137 break; 4138 } 4139 4140 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4141 4142 // Not critical if that is lost - app has to request again. 4143 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4144 } 4145 4146 // Only need to do this if user is initialized. Otherwise it's a new user 4147 // and there are no processes running as the user yet and there's no need 4148 // to make an expensive call to remount processes for the changed permissions. 4149 if (READ_EXTERNAL_STORAGE.equals(name) 4150 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4151 final long token = Binder.clearCallingIdentity(); 4152 try { 4153 if (sUserManager.isInitialized(userId)) { 4154 MountServiceInternal mountServiceInternal = LocalServices.getService( 4155 MountServiceInternal.class); 4156 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4157 } 4158 } finally { 4159 Binder.restoreCallingIdentity(token); 4160 } 4161 } 4162 } 4163 4164 @Override 4165 public void revokeRuntimePermission(String packageName, String name, int userId) { 4166 if (!sUserManager.exists(userId)) { 4167 Log.e(TAG, "No such user:" + userId); 4168 return; 4169 } 4170 4171 mContext.enforceCallingOrSelfPermission( 4172 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4173 "revokeRuntimePermission"); 4174 4175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4176 true /* requireFullPermission */, true /* checkShell */, 4177 "revokeRuntimePermission"); 4178 4179 final int appId; 4180 4181 synchronized (mPackages) { 4182 final PackageParser.Package pkg = mPackages.get(packageName); 4183 if (pkg == null) { 4184 throw new IllegalArgumentException("Unknown package: " + packageName); 4185 } 4186 4187 final BasePermission bp = mSettings.mPermissions.get(name); 4188 if (bp == null) { 4189 throw new IllegalArgumentException("Unknown permission: " + name); 4190 } 4191 4192 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4193 4194 // If a permission review is required for legacy apps we represent 4195 // their permissions as always granted runtime ones since we need 4196 // to keep the review required permission flag per user while an 4197 // install permission's state is shared across all users. 4198 if (Build.PERMISSIONS_REVIEW_REQUIRED 4199 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4200 && bp.isRuntime()) { 4201 return; 4202 } 4203 4204 SettingBase sb = (SettingBase) pkg.mExtras; 4205 if (sb == null) { 4206 throw new IllegalArgumentException("Unknown package: " + packageName); 4207 } 4208 4209 final PermissionsState permissionsState = sb.getPermissionsState(); 4210 4211 final int flags = permissionsState.getPermissionFlags(name, userId); 4212 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4213 throw new SecurityException("Cannot revoke system fixed permission " 4214 + name + " for package " + packageName); 4215 } 4216 4217 if (bp.isDevelopment()) { 4218 // Development permissions must be handled specially, since they are not 4219 // normal runtime permissions. For now they apply to all users. 4220 if (permissionsState.revokeInstallPermission(bp) != 4221 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4222 scheduleWriteSettingsLocked(); 4223 } 4224 return; 4225 } 4226 4227 if (permissionsState.revokeRuntimePermission(bp, userId) == 4228 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4229 return; 4230 } 4231 4232 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4233 4234 // Critical, after this call app should never have the permission. 4235 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4236 4237 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4238 } 4239 4240 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4241 } 4242 4243 @Override 4244 public void resetRuntimePermissions() { 4245 mContext.enforceCallingOrSelfPermission( 4246 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4247 "revokeRuntimePermission"); 4248 4249 int callingUid = Binder.getCallingUid(); 4250 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4251 mContext.enforceCallingOrSelfPermission( 4252 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4253 "resetRuntimePermissions"); 4254 } 4255 4256 synchronized (mPackages) { 4257 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4258 for (int userId : UserManagerService.getInstance().getUserIds()) { 4259 final int packageCount = mPackages.size(); 4260 for (int i = 0; i < packageCount; i++) { 4261 PackageParser.Package pkg = mPackages.valueAt(i); 4262 if (!(pkg.mExtras instanceof PackageSetting)) { 4263 continue; 4264 } 4265 PackageSetting ps = (PackageSetting) pkg.mExtras; 4266 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4267 } 4268 } 4269 } 4270 } 4271 4272 @Override 4273 public int getPermissionFlags(String name, String packageName, int userId) { 4274 if (!sUserManager.exists(userId)) { 4275 return 0; 4276 } 4277 4278 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4279 4280 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4281 true /* requireFullPermission */, false /* checkShell */, 4282 "getPermissionFlags"); 4283 4284 synchronized (mPackages) { 4285 final PackageParser.Package pkg = mPackages.get(packageName); 4286 if (pkg == null) { 4287 throw new IllegalArgumentException("Unknown package: " + packageName); 4288 } 4289 4290 final BasePermission bp = mSettings.mPermissions.get(name); 4291 if (bp == null) { 4292 throw new IllegalArgumentException("Unknown permission: " + name); 4293 } 4294 4295 SettingBase sb = (SettingBase) pkg.mExtras; 4296 if (sb == null) { 4297 throw new IllegalArgumentException("Unknown package: " + packageName); 4298 } 4299 4300 PermissionsState permissionsState = sb.getPermissionsState(); 4301 return permissionsState.getPermissionFlags(name, userId); 4302 } 4303 } 4304 4305 @Override 4306 public void updatePermissionFlags(String name, String packageName, int flagMask, 4307 int flagValues, int userId) { 4308 if (!sUserManager.exists(userId)) { 4309 return; 4310 } 4311 4312 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4313 4314 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4315 true /* requireFullPermission */, true /* checkShell */, 4316 "updatePermissionFlags"); 4317 4318 // Only the system can change these flags and nothing else. 4319 if (getCallingUid() != Process.SYSTEM_UID) { 4320 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4321 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4322 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4323 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4324 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4325 } 4326 4327 synchronized (mPackages) { 4328 final PackageParser.Package pkg = mPackages.get(packageName); 4329 if (pkg == null) { 4330 throw new IllegalArgumentException("Unknown package: " + packageName); 4331 } 4332 4333 final BasePermission bp = mSettings.mPermissions.get(name); 4334 if (bp == null) { 4335 throw new IllegalArgumentException("Unknown permission: " + name); 4336 } 4337 4338 SettingBase sb = (SettingBase) pkg.mExtras; 4339 if (sb == null) { 4340 throw new IllegalArgumentException("Unknown package: " + packageName); 4341 } 4342 4343 PermissionsState permissionsState = sb.getPermissionsState(); 4344 4345 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4346 4347 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4348 // Install and runtime permissions are stored in different places, 4349 // so figure out what permission changed and persist the change. 4350 if (permissionsState.getInstallPermissionState(name) != null) { 4351 scheduleWriteSettingsLocked(); 4352 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4353 || hadState) { 4354 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4355 } 4356 } 4357 } 4358 } 4359 4360 /** 4361 * Update the permission flags for all packages and runtime permissions of a user in order 4362 * to allow device or profile owner to remove POLICY_FIXED. 4363 */ 4364 @Override 4365 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4366 if (!sUserManager.exists(userId)) { 4367 return; 4368 } 4369 4370 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4371 4372 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4373 true /* requireFullPermission */, true /* checkShell */, 4374 "updatePermissionFlagsForAllApps"); 4375 4376 // Only the system can change system fixed flags. 4377 if (getCallingUid() != Process.SYSTEM_UID) { 4378 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4379 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4380 } 4381 4382 synchronized (mPackages) { 4383 boolean changed = false; 4384 final int packageCount = mPackages.size(); 4385 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4386 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4387 SettingBase sb = (SettingBase) pkg.mExtras; 4388 if (sb == null) { 4389 continue; 4390 } 4391 PermissionsState permissionsState = sb.getPermissionsState(); 4392 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4393 userId, flagMask, flagValues); 4394 } 4395 if (changed) { 4396 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4397 } 4398 } 4399 } 4400 4401 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4402 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4403 != PackageManager.PERMISSION_GRANTED 4404 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4405 != PackageManager.PERMISSION_GRANTED) { 4406 throw new SecurityException(message + " requires " 4407 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4408 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4409 } 4410 } 4411 4412 @Override 4413 public boolean shouldShowRequestPermissionRationale(String permissionName, 4414 String packageName, int userId) { 4415 if (UserHandle.getCallingUserId() != userId) { 4416 mContext.enforceCallingPermission( 4417 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4418 "canShowRequestPermissionRationale for user " + userId); 4419 } 4420 4421 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4422 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4423 return false; 4424 } 4425 4426 if (checkPermission(permissionName, packageName, userId) 4427 == PackageManager.PERMISSION_GRANTED) { 4428 return false; 4429 } 4430 4431 final int flags; 4432 4433 final long identity = Binder.clearCallingIdentity(); 4434 try { 4435 flags = getPermissionFlags(permissionName, 4436 packageName, userId); 4437 } finally { 4438 Binder.restoreCallingIdentity(identity); 4439 } 4440 4441 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4442 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4443 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4444 4445 if ((flags & fixedFlags) != 0) { 4446 return false; 4447 } 4448 4449 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4450 } 4451 4452 @Override 4453 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4454 mContext.enforceCallingOrSelfPermission( 4455 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4456 "addOnPermissionsChangeListener"); 4457 4458 synchronized (mPackages) { 4459 mOnPermissionChangeListeners.addListenerLocked(listener); 4460 } 4461 } 4462 4463 @Override 4464 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4465 synchronized (mPackages) { 4466 mOnPermissionChangeListeners.removeListenerLocked(listener); 4467 } 4468 } 4469 4470 @Override 4471 public boolean isProtectedBroadcast(String actionName) { 4472 synchronized (mPackages) { 4473 if (mProtectedBroadcasts.contains(actionName)) { 4474 return true; 4475 } else if (actionName != null) { 4476 // TODO: remove these terrible hacks 4477 if (actionName.startsWith("android.net.netmon.lingerExpired") 4478 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4479 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4480 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4481 return true; 4482 } 4483 } 4484 } 4485 return false; 4486 } 4487 4488 @Override 4489 public int checkSignatures(String pkg1, String pkg2) { 4490 synchronized (mPackages) { 4491 final PackageParser.Package p1 = mPackages.get(pkg1); 4492 final PackageParser.Package p2 = mPackages.get(pkg2); 4493 if (p1 == null || p1.mExtras == null 4494 || p2 == null || p2.mExtras == null) { 4495 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4496 } 4497 return compareSignatures(p1.mSignatures, p2.mSignatures); 4498 } 4499 } 4500 4501 @Override 4502 public int checkUidSignatures(int uid1, int uid2) { 4503 // Map to base uids. 4504 uid1 = UserHandle.getAppId(uid1); 4505 uid2 = UserHandle.getAppId(uid2); 4506 // reader 4507 synchronized (mPackages) { 4508 Signature[] s1; 4509 Signature[] s2; 4510 Object obj = mSettings.getUserIdLPr(uid1); 4511 if (obj != null) { 4512 if (obj instanceof SharedUserSetting) { 4513 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4514 } else if (obj instanceof PackageSetting) { 4515 s1 = ((PackageSetting)obj).signatures.mSignatures; 4516 } else { 4517 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4518 } 4519 } else { 4520 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4521 } 4522 obj = mSettings.getUserIdLPr(uid2); 4523 if (obj != null) { 4524 if (obj instanceof SharedUserSetting) { 4525 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4526 } else if (obj instanceof PackageSetting) { 4527 s2 = ((PackageSetting)obj).signatures.mSignatures; 4528 } else { 4529 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4530 } 4531 } else { 4532 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4533 } 4534 return compareSignatures(s1, s2); 4535 } 4536 } 4537 4538 /** 4539 * This method should typically only be used when granting or revoking 4540 * permissions, since the app may immediately restart after this call. 4541 * <p> 4542 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4543 * guard your work against the app being relaunched. 4544 */ 4545 private void killUid(int appId, int userId, String reason) { 4546 final long identity = Binder.clearCallingIdentity(); 4547 try { 4548 IActivityManager am = ActivityManagerNative.getDefault(); 4549 if (am != null) { 4550 try { 4551 am.killUid(appId, userId, reason); 4552 } catch (RemoteException e) { 4553 /* ignore - same process */ 4554 } 4555 } 4556 } finally { 4557 Binder.restoreCallingIdentity(identity); 4558 } 4559 } 4560 4561 /** 4562 * Compares two sets of signatures. Returns: 4563 * <br /> 4564 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4565 * <br /> 4566 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4567 * <br /> 4568 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4569 * <br /> 4570 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4571 * <br /> 4572 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4573 */ 4574 static int compareSignatures(Signature[] s1, Signature[] s2) { 4575 if (s1 == null) { 4576 return s2 == null 4577 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4578 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4579 } 4580 4581 if (s2 == null) { 4582 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4583 } 4584 4585 if (s1.length != s2.length) { 4586 return PackageManager.SIGNATURE_NO_MATCH; 4587 } 4588 4589 // Since both signature sets are of size 1, we can compare without HashSets. 4590 if (s1.length == 1) { 4591 return s1[0].equals(s2[0]) ? 4592 PackageManager.SIGNATURE_MATCH : 4593 PackageManager.SIGNATURE_NO_MATCH; 4594 } 4595 4596 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4597 for (Signature sig : s1) { 4598 set1.add(sig); 4599 } 4600 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4601 for (Signature sig : s2) { 4602 set2.add(sig); 4603 } 4604 // Make sure s2 contains all signatures in s1. 4605 if (set1.equals(set2)) { 4606 return PackageManager.SIGNATURE_MATCH; 4607 } 4608 return PackageManager.SIGNATURE_NO_MATCH; 4609 } 4610 4611 /** 4612 * If the database version for this type of package (internal storage or 4613 * external storage) is less than the version where package signatures 4614 * were updated, return true. 4615 */ 4616 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4617 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4618 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4619 } 4620 4621 /** 4622 * Used for backward compatibility to make sure any packages with 4623 * certificate chains get upgraded to the new style. {@code existingSigs} 4624 * will be in the old format (since they were stored on disk from before the 4625 * system upgrade) and {@code scannedSigs} will be in the newer format. 4626 */ 4627 private int compareSignaturesCompat(PackageSignatures existingSigs, 4628 PackageParser.Package scannedPkg) { 4629 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4630 return PackageManager.SIGNATURE_NO_MATCH; 4631 } 4632 4633 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4634 for (Signature sig : existingSigs.mSignatures) { 4635 existingSet.add(sig); 4636 } 4637 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4638 for (Signature sig : scannedPkg.mSignatures) { 4639 try { 4640 Signature[] chainSignatures = sig.getChainSignatures(); 4641 for (Signature chainSig : chainSignatures) { 4642 scannedCompatSet.add(chainSig); 4643 } 4644 } catch (CertificateEncodingException e) { 4645 scannedCompatSet.add(sig); 4646 } 4647 } 4648 /* 4649 * Make sure the expanded scanned set contains all signatures in the 4650 * existing one. 4651 */ 4652 if (scannedCompatSet.equals(existingSet)) { 4653 // Migrate the old signatures to the new scheme. 4654 existingSigs.assignSignatures(scannedPkg.mSignatures); 4655 // The new KeySets will be re-added later in the scanning process. 4656 synchronized (mPackages) { 4657 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4658 } 4659 return PackageManager.SIGNATURE_MATCH; 4660 } 4661 return PackageManager.SIGNATURE_NO_MATCH; 4662 } 4663 4664 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4665 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4666 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4667 } 4668 4669 private int compareSignaturesRecover(PackageSignatures existingSigs, 4670 PackageParser.Package scannedPkg) { 4671 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4672 return PackageManager.SIGNATURE_NO_MATCH; 4673 } 4674 4675 String msg = null; 4676 try { 4677 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4678 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4679 + scannedPkg.packageName); 4680 return PackageManager.SIGNATURE_MATCH; 4681 } 4682 } catch (CertificateException e) { 4683 msg = e.getMessage(); 4684 } 4685 4686 logCriticalInfo(Log.INFO, 4687 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4688 return PackageManager.SIGNATURE_NO_MATCH; 4689 } 4690 4691 @Override 4692 public List<String> getAllPackages() { 4693 synchronized (mPackages) { 4694 return new ArrayList<String>(mPackages.keySet()); 4695 } 4696 } 4697 4698 @Override 4699 public String[] getPackagesForUid(int uid) { 4700 uid = UserHandle.getAppId(uid); 4701 // reader 4702 synchronized (mPackages) { 4703 Object obj = mSettings.getUserIdLPr(uid); 4704 if (obj instanceof SharedUserSetting) { 4705 final SharedUserSetting sus = (SharedUserSetting) obj; 4706 final int N = sus.packages.size(); 4707 final String[] res = new String[N]; 4708 final Iterator<PackageSetting> it = sus.packages.iterator(); 4709 int i = 0; 4710 while (it.hasNext()) { 4711 res[i++] = it.next().name; 4712 } 4713 return res; 4714 } else if (obj instanceof PackageSetting) { 4715 final PackageSetting ps = (PackageSetting) obj; 4716 return new String[] { ps.name }; 4717 } 4718 } 4719 return null; 4720 } 4721 4722 @Override 4723 public String getNameForUid(int uid) { 4724 // reader 4725 synchronized (mPackages) { 4726 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4727 if (obj instanceof SharedUserSetting) { 4728 final SharedUserSetting sus = (SharedUserSetting) obj; 4729 return sus.name + ":" + sus.userId; 4730 } else if (obj instanceof PackageSetting) { 4731 final PackageSetting ps = (PackageSetting) obj; 4732 return ps.name; 4733 } 4734 } 4735 return null; 4736 } 4737 4738 @Override 4739 public int getUidForSharedUser(String sharedUserName) { 4740 if(sharedUserName == null) { 4741 return -1; 4742 } 4743 // reader 4744 synchronized (mPackages) { 4745 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4746 if (suid == null) { 4747 return -1; 4748 } 4749 return suid.userId; 4750 } 4751 } 4752 4753 @Override 4754 public int getFlagsForUid(int uid) { 4755 synchronized (mPackages) { 4756 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4757 if (obj instanceof SharedUserSetting) { 4758 final SharedUserSetting sus = (SharedUserSetting) obj; 4759 return sus.pkgFlags; 4760 } else if (obj instanceof PackageSetting) { 4761 final PackageSetting ps = (PackageSetting) obj; 4762 return ps.pkgFlags; 4763 } 4764 } 4765 return 0; 4766 } 4767 4768 @Override 4769 public int getPrivateFlagsForUid(int uid) { 4770 synchronized (mPackages) { 4771 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4772 if (obj instanceof SharedUserSetting) { 4773 final SharedUserSetting sus = (SharedUserSetting) obj; 4774 return sus.pkgPrivateFlags; 4775 } else if (obj instanceof PackageSetting) { 4776 final PackageSetting ps = (PackageSetting) obj; 4777 return ps.pkgPrivateFlags; 4778 } 4779 } 4780 return 0; 4781 } 4782 4783 @Override 4784 public boolean isUidPrivileged(int uid) { 4785 uid = UserHandle.getAppId(uid); 4786 // reader 4787 synchronized (mPackages) { 4788 Object obj = mSettings.getUserIdLPr(uid); 4789 if (obj instanceof SharedUserSetting) { 4790 final SharedUserSetting sus = (SharedUserSetting) obj; 4791 final Iterator<PackageSetting> it = sus.packages.iterator(); 4792 while (it.hasNext()) { 4793 if (it.next().isPrivileged()) { 4794 return true; 4795 } 4796 } 4797 } else if (obj instanceof PackageSetting) { 4798 final PackageSetting ps = (PackageSetting) obj; 4799 return ps.isPrivileged(); 4800 } 4801 } 4802 return false; 4803 } 4804 4805 @Override 4806 public String[] getAppOpPermissionPackages(String permissionName) { 4807 synchronized (mPackages) { 4808 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4809 if (pkgs == null) { 4810 return null; 4811 } 4812 return pkgs.toArray(new String[pkgs.size()]); 4813 } 4814 } 4815 4816 @Override 4817 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4818 int flags, int userId) { 4819 try { 4820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4821 4822 if (!sUserManager.exists(userId)) return null; 4823 flags = updateFlagsForResolve(flags, userId, intent); 4824 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4825 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4826 4827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4828 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4829 flags, userId); 4830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4831 4832 final ResolveInfo bestChoice = 4833 chooseBestActivity(intent, resolvedType, flags, query, userId); 4834 4835 if (isEphemeralAllowed(intent, query, userId)) { 4836 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4837 final EphemeralResolveInfo ai = 4838 getEphemeralResolveInfo(intent, resolvedType, userId); 4839 if (ai != null) { 4840 if (DEBUG_EPHEMERAL) { 4841 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4842 } 4843 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4844 bestChoice.ephemeralResolveInfo = ai; 4845 } 4846 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4847 } 4848 return bestChoice; 4849 } finally { 4850 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4851 } 4852 } 4853 4854 @Override 4855 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4856 IntentFilter filter, int match, ComponentName activity) { 4857 final int userId = UserHandle.getCallingUserId(); 4858 if (DEBUG_PREFERRED) { 4859 Log.v(TAG, "setLastChosenActivity intent=" + intent 4860 + " resolvedType=" + resolvedType 4861 + " flags=" + flags 4862 + " filter=" + filter 4863 + " match=" + match 4864 + " activity=" + activity); 4865 filter.dump(new PrintStreamPrinter(System.out), " "); 4866 } 4867 intent.setComponent(null); 4868 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4869 userId); 4870 // Find any earlier preferred or last chosen entries and nuke them 4871 findPreferredActivity(intent, resolvedType, 4872 flags, query, 0, false, true, false, userId); 4873 // Add the new activity as the last chosen for this filter 4874 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4875 "Setting last chosen"); 4876 } 4877 4878 @Override 4879 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4880 final int userId = UserHandle.getCallingUserId(); 4881 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4882 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4883 userId); 4884 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4885 false, false, false, userId); 4886 } 4887 4888 4889 private boolean isEphemeralAllowed( 4890 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4891 // Short circuit and return early if possible. 4892 if (DISABLE_EPHEMERAL_APPS) { 4893 return false; 4894 } 4895 final int callingUser = UserHandle.getCallingUserId(); 4896 if (callingUser != UserHandle.USER_SYSTEM) { 4897 return false; 4898 } 4899 if (mEphemeralResolverConnection == null) { 4900 return false; 4901 } 4902 if (intent.getComponent() != null) { 4903 return false; 4904 } 4905 if (intent.getPackage() != null) { 4906 return false; 4907 } 4908 final boolean isWebUri = hasWebURI(intent); 4909 if (!isWebUri) { 4910 return false; 4911 } 4912 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4913 synchronized (mPackages) { 4914 final int count = resolvedActivites.size(); 4915 for (int n = 0; n < count; n++) { 4916 ResolveInfo info = resolvedActivites.get(n); 4917 String packageName = info.activityInfo.packageName; 4918 PackageSetting ps = mSettings.mPackages.get(packageName); 4919 if (ps != null) { 4920 // Try to get the status from User settings first 4921 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4922 int status = (int) (packedStatus >> 32); 4923 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4924 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4925 if (DEBUG_EPHEMERAL) { 4926 Slog.v(TAG, "DENY ephemeral apps;" 4927 + " pkg: " + packageName + ", status: " + status); 4928 } 4929 return false; 4930 } 4931 } 4932 } 4933 } 4934 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4935 return true; 4936 } 4937 4938 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4939 int userId) { 4940 MessageDigest digest = null; 4941 try { 4942 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4943 } catch (NoSuchAlgorithmException e) { 4944 // If we can't create a digest, ignore ephemeral apps. 4945 return null; 4946 } 4947 4948 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4949 final byte[] digestBytes = digest.digest(hostBytes); 4950 int shaPrefix = 4951 digestBytes[0] << 24 4952 | digestBytes[1] << 16 4953 | digestBytes[2] << 8 4954 | digestBytes[3] << 0; 4955 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4956 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4957 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4958 // No hash prefix match; there are no ephemeral apps for this domain. 4959 return null; 4960 } 4961 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4962 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4963 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4964 continue; 4965 } 4966 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4967 // No filters; this should never happen. 4968 if (filters.isEmpty()) { 4969 continue; 4970 } 4971 // We have a domain match; resolve the filters to see if anything matches. 4972 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4973 for (int j = filters.size() - 1; j >= 0; --j) { 4974 final EphemeralResolveIntentInfo intentInfo = 4975 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4976 ephemeralResolver.addFilter(intentInfo); 4977 } 4978 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4979 intent, resolvedType, false /*defaultOnly*/, userId); 4980 if (!matchedResolveInfoList.isEmpty()) { 4981 return matchedResolveInfoList.get(0); 4982 } 4983 } 4984 // Hash or filter mis-match; no ephemeral apps for this domain. 4985 return null; 4986 } 4987 4988 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4989 int flags, List<ResolveInfo> query, int userId) { 4990 if (query != null) { 4991 final int N = query.size(); 4992 if (N == 1) { 4993 return query.get(0); 4994 } else if (N > 1) { 4995 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4996 // If there is more than one activity with the same priority, 4997 // then let the user decide between them. 4998 ResolveInfo r0 = query.get(0); 4999 ResolveInfo r1 = query.get(1); 5000 if (DEBUG_INTENT_MATCHING || debug) { 5001 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5002 + r1.activityInfo.name + "=" + r1.priority); 5003 } 5004 // If the first activity has a higher priority, or a different 5005 // default, then it is always desirable to pick it. 5006 if (r0.priority != r1.priority 5007 || r0.preferredOrder != r1.preferredOrder 5008 || r0.isDefault != r1.isDefault) { 5009 return query.get(0); 5010 } 5011 // If we have saved a preference for a preferred activity for 5012 // this Intent, use that. 5013 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5014 flags, query, r0.priority, true, false, debug, userId); 5015 if (ri != null) { 5016 return ri; 5017 } 5018 ri = new ResolveInfo(mResolveInfo); 5019 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5020 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5021 ri.activityInfo.applicationInfo = new ApplicationInfo( 5022 ri.activityInfo.applicationInfo); 5023 if (userId != 0) { 5024 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5025 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5026 } 5027 // Make sure that the resolver is displayable in car mode 5028 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5029 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5030 return ri; 5031 } 5032 } 5033 return null; 5034 } 5035 5036 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5037 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5038 final int N = query.size(); 5039 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5040 .get(userId); 5041 // Get the list of persistent preferred activities that handle the intent 5042 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5043 List<PersistentPreferredActivity> pprefs = ppir != null 5044 ? ppir.queryIntent(intent, resolvedType, 5045 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5046 : null; 5047 if (pprefs != null && pprefs.size() > 0) { 5048 final int M = pprefs.size(); 5049 for (int i=0; i<M; i++) { 5050 final PersistentPreferredActivity ppa = pprefs.get(i); 5051 if (DEBUG_PREFERRED || debug) { 5052 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5053 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5054 + "\n component=" + ppa.mComponent); 5055 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5056 } 5057 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5058 flags | MATCH_DISABLED_COMPONENTS, userId); 5059 if (DEBUG_PREFERRED || debug) { 5060 Slog.v(TAG, "Found persistent preferred activity:"); 5061 if (ai != null) { 5062 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5063 } else { 5064 Slog.v(TAG, " null"); 5065 } 5066 } 5067 if (ai == null) { 5068 // This previously registered persistent preferred activity 5069 // component is no longer known. Ignore it and do NOT remove it. 5070 continue; 5071 } 5072 for (int j=0; j<N; j++) { 5073 final ResolveInfo ri = query.get(j); 5074 if (!ri.activityInfo.applicationInfo.packageName 5075 .equals(ai.applicationInfo.packageName)) { 5076 continue; 5077 } 5078 if (!ri.activityInfo.name.equals(ai.name)) { 5079 continue; 5080 } 5081 // Found a persistent preference that can handle the intent. 5082 if (DEBUG_PREFERRED || debug) { 5083 Slog.v(TAG, "Returning persistent preferred activity: " + 5084 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5085 } 5086 return ri; 5087 } 5088 } 5089 } 5090 return null; 5091 } 5092 5093 // TODO: handle preferred activities missing while user has amnesia 5094 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5095 List<ResolveInfo> query, int priority, boolean always, 5096 boolean removeMatches, boolean debug, int userId) { 5097 if (!sUserManager.exists(userId)) return null; 5098 flags = updateFlagsForResolve(flags, userId, intent); 5099 // writer 5100 synchronized (mPackages) { 5101 if (intent.getSelector() != null) { 5102 intent = intent.getSelector(); 5103 } 5104 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5105 5106 // Try to find a matching persistent preferred activity. 5107 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5108 debug, userId); 5109 5110 // If a persistent preferred activity matched, use it. 5111 if (pri != null) { 5112 return pri; 5113 } 5114 5115 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5116 // Get the list of preferred activities that handle the intent 5117 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5118 List<PreferredActivity> prefs = pir != null 5119 ? pir.queryIntent(intent, resolvedType, 5120 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5121 : null; 5122 if (prefs != null && prefs.size() > 0) { 5123 boolean changed = false; 5124 try { 5125 // First figure out how good the original match set is. 5126 // We will only allow preferred activities that came 5127 // from the same match quality. 5128 int match = 0; 5129 5130 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5131 5132 final int N = query.size(); 5133 for (int j=0; j<N; j++) { 5134 final ResolveInfo ri = query.get(j); 5135 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5136 + ": 0x" + Integer.toHexString(match)); 5137 if (ri.match > match) { 5138 match = ri.match; 5139 } 5140 } 5141 5142 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5143 + Integer.toHexString(match)); 5144 5145 match &= IntentFilter.MATCH_CATEGORY_MASK; 5146 final int M = prefs.size(); 5147 for (int i=0; i<M; i++) { 5148 final PreferredActivity pa = prefs.get(i); 5149 if (DEBUG_PREFERRED || debug) { 5150 Slog.v(TAG, "Checking PreferredActivity ds=" 5151 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5152 + "\n component=" + pa.mPref.mComponent); 5153 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5154 } 5155 if (pa.mPref.mMatch != match) { 5156 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5157 + Integer.toHexString(pa.mPref.mMatch)); 5158 continue; 5159 } 5160 // If it's not an "always" type preferred activity and that's what we're 5161 // looking for, skip it. 5162 if (always && !pa.mPref.mAlways) { 5163 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5164 continue; 5165 } 5166 final ActivityInfo ai = getActivityInfo( 5167 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5168 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5169 userId); 5170 if (DEBUG_PREFERRED || debug) { 5171 Slog.v(TAG, "Found preferred activity:"); 5172 if (ai != null) { 5173 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5174 } else { 5175 Slog.v(TAG, " null"); 5176 } 5177 } 5178 if (ai == null) { 5179 // This previously registered preferred activity 5180 // component is no longer known. Most likely an update 5181 // to the app was installed and in the new version this 5182 // component no longer exists. Clean it up by removing 5183 // it from the preferred activities list, and skip it. 5184 Slog.w(TAG, "Removing dangling preferred activity: " 5185 + pa.mPref.mComponent); 5186 pir.removeFilter(pa); 5187 changed = true; 5188 continue; 5189 } 5190 for (int j=0; j<N; j++) { 5191 final ResolveInfo ri = query.get(j); 5192 if (!ri.activityInfo.applicationInfo.packageName 5193 .equals(ai.applicationInfo.packageName)) { 5194 continue; 5195 } 5196 if (!ri.activityInfo.name.equals(ai.name)) { 5197 continue; 5198 } 5199 5200 if (removeMatches) { 5201 pir.removeFilter(pa); 5202 changed = true; 5203 if (DEBUG_PREFERRED) { 5204 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5205 } 5206 break; 5207 } 5208 5209 // Okay we found a previously set preferred or last chosen app. 5210 // If the result set is different from when this 5211 // was created, we need to clear it and re-ask the 5212 // user their preference, if we're looking for an "always" type entry. 5213 if (always && !pa.mPref.sameSet(query)) { 5214 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5215 + intent + " type " + resolvedType); 5216 if (DEBUG_PREFERRED) { 5217 Slog.v(TAG, "Removing preferred activity since set changed " 5218 + pa.mPref.mComponent); 5219 } 5220 pir.removeFilter(pa); 5221 // Re-add the filter as a "last chosen" entry (!always) 5222 PreferredActivity lastChosen = new PreferredActivity( 5223 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5224 pir.addFilter(lastChosen); 5225 changed = true; 5226 return null; 5227 } 5228 5229 // Yay! Either the set matched or we're looking for the last chosen 5230 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5231 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5232 return ri; 5233 } 5234 } 5235 } finally { 5236 if (changed) { 5237 if (DEBUG_PREFERRED) { 5238 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5239 } 5240 scheduleWritePackageRestrictionsLocked(userId); 5241 } 5242 } 5243 } 5244 } 5245 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5246 return null; 5247 } 5248 5249 /* 5250 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5251 */ 5252 @Override 5253 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5254 int targetUserId) { 5255 mContext.enforceCallingOrSelfPermission( 5256 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5257 List<CrossProfileIntentFilter> matches = 5258 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5259 if (matches != null) { 5260 int size = matches.size(); 5261 for (int i = 0; i < size; i++) { 5262 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5263 } 5264 } 5265 if (hasWebURI(intent)) { 5266 // cross-profile app linking works only towards the parent. 5267 final UserInfo parent = getProfileParent(sourceUserId); 5268 synchronized(mPackages) { 5269 int flags = updateFlagsForResolve(0, parent.id, intent); 5270 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5271 intent, resolvedType, flags, sourceUserId, parent.id); 5272 return xpDomainInfo != null; 5273 } 5274 } 5275 return false; 5276 } 5277 5278 private UserInfo getProfileParent(int userId) { 5279 final long identity = Binder.clearCallingIdentity(); 5280 try { 5281 return sUserManager.getProfileParent(userId); 5282 } finally { 5283 Binder.restoreCallingIdentity(identity); 5284 } 5285 } 5286 5287 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5288 String resolvedType, int userId) { 5289 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5290 if (resolver != null) { 5291 return resolver.queryIntent(intent, resolvedType, false, userId); 5292 } 5293 return null; 5294 } 5295 5296 @Override 5297 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5298 String resolvedType, int flags, int userId) { 5299 try { 5300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5301 5302 return new ParceledListSlice<>( 5303 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5304 } finally { 5305 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5306 } 5307 } 5308 5309 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5310 String resolvedType, int flags, int userId) { 5311 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5312 flags = updateFlagsForResolve(flags, userId, intent); 5313 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5314 false /* requireFullPermission */, false /* checkShell */, 5315 "query intent activities"); 5316 ComponentName comp = intent.getComponent(); 5317 if (comp == null) { 5318 if (intent.getSelector() != null) { 5319 intent = intent.getSelector(); 5320 comp = intent.getComponent(); 5321 } 5322 } 5323 5324 if (comp != null) { 5325 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5326 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5327 if (ai != null) { 5328 final ResolveInfo ri = new ResolveInfo(); 5329 ri.activityInfo = ai; 5330 list.add(ri); 5331 } 5332 return list; 5333 } 5334 5335 // reader 5336 synchronized (mPackages) { 5337 final String pkgName = intent.getPackage(); 5338 if (pkgName == null) { 5339 List<CrossProfileIntentFilter> matchingFilters = 5340 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5341 // Check for results that need to skip the current profile. 5342 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5343 resolvedType, flags, userId); 5344 if (xpResolveInfo != null) { 5345 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5346 result.add(xpResolveInfo); 5347 return filterIfNotSystemUser(result, userId); 5348 } 5349 5350 // Check for results in the current profile. 5351 List<ResolveInfo> result = mActivities.queryIntent( 5352 intent, resolvedType, flags, userId); 5353 result = filterIfNotSystemUser(result, userId); 5354 5355 // Check for cross profile results. 5356 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5357 xpResolveInfo = queryCrossProfileIntents( 5358 matchingFilters, intent, resolvedType, flags, userId, 5359 hasNonNegativePriorityResult); 5360 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5361 boolean isVisibleToUser = filterIfNotSystemUser( 5362 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5363 if (isVisibleToUser) { 5364 result.add(xpResolveInfo); 5365 Collections.sort(result, mResolvePrioritySorter); 5366 } 5367 } 5368 if (hasWebURI(intent)) { 5369 CrossProfileDomainInfo xpDomainInfo = null; 5370 final UserInfo parent = getProfileParent(userId); 5371 if (parent != null) { 5372 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5373 flags, userId, parent.id); 5374 } 5375 if (xpDomainInfo != null) { 5376 if (xpResolveInfo != null) { 5377 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5378 // in the result. 5379 result.remove(xpResolveInfo); 5380 } 5381 if (result.size() == 0) { 5382 result.add(xpDomainInfo.resolveInfo); 5383 return result; 5384 } 5385 } else if (result.size() <= 1) { 5386 return result; 5387 } 5388 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5389 xpDomainInfo, userId); 5390 Collections.sort(result, mResolvePrioritySorter); 5391 } 5392 return result; 5393 } 5394 final PackageParser.Package pkg = mPackages.get(pkgName); 5395 if (pkg != null) { 5396 return filterIfNotSystemUser( 5397 mActivities.queryIntentForPackage( 5398 intent, resolvedType, flags, pkg.activities, userId), 5399 userId); 5400 } 5401 return new ArrayList<ResolveInfo>(); 5402 } 5403 } 5404 5405 private static class CrossProfileDomainInfo { 5406 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5407 ResolveInfo resolveInfo; 5408 /* Best domain verification status of the activities found in the other profile */ 5409 int bestDomainVerificationStatus; 5410 } 5411 5412 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5413 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5414 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5415 sourceUserId)) { 5416 return null; 5417 } 5418 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5419 resolvedType, flags, parentUserId); 5420 5421 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5422 return null; 5423 } 5424 CrossProfileDomainInfo result = null; 5425 int size = resultTargetUser.size(); 5426 for (int i = 0; i < size; i++) { 5427 ResolveInfo riTargetUser = resultTargetUser.get(i); 5428 // Intent filter verification is only for filters that specify a host. So don't return 5429 // those that handle all web uris. 5430 if (riTargetUser.handleAllWebDataURI) { 5431 continue; 5432 } 5433 String packageName = riTargetUser.activityInfo.packageName; 5434 PackageSetting ps = mSettings.mPackages.get(packageName); 5435 if (ps == null) { 5436 continue; 5437 } 5438 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5439 int status = (int)(verificationState >> 32); 5440 if (result == null) { 5441 result = new CrossProfileDomainInfo(); 5442 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5443 sourceUserId, parentUserId); 5444 result.bestDomainVerificationStatus = status; 5445 } else { 5446 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5447 result.bestDomainVerificationStatus); 5448 } 5449 } 5450 // Don't consider matches with status NEVER across profiles. 5451 if (result != null && result.bestDomainVerificationStatus 5452 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5453 return null; 5454 } 5455 return result; 5456 } 5457 5458 /** 5459 * Verification statuses are ordered from the worse to the best, except for 5460 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5461 */ 5462 private int bestDomainVerificationStatus(int status1, int status2) { 5463 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5464 return status2; 5465 } 5466 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5467 return status1; 5468 } 5469 return (int) MathUtils.max(status1, status2); 5470 } 5471 5472 private boolean isUserEnabled(int userId) { 5473 long callingId = Binder.clearCallingIdentity(); 5474 try { 5475 UserInfo userInfo = sUserManager.getUserInfo(userId); 5476 return userInfo != null && userInfo.isEnabled(); 5477 } finally { 5478 Binder.restoreCallingIdentity(callingId); 5479 } 5480 } 5481 5482 /** 5483 * Filter out activities with systemUserOnly flag set, when current user is not System. 5484 * 5485 * @return filtered list 5486 */ 5487 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5488 if (userId == UserHandle.USER_SYSTEM) { 5489 return resolveInfos; 5490 } 5491 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5492 ResolveInfo info = resolveInfos.get(i); 5493 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5494 resolveInfos.remove(i); 5495 } 5496 } 5497 return resolveInfos; 5498 } 5499 5500 /** 5501 * @param resolveInfos list of resolve infos in descending priority order 5502 * @return if the list contains a resolve info with non-negative priority 5503 */ 5504 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5505 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5506 } 5507 5508 private static boolean hasWebURI(Intent intent) { 5509 if (intent.getData() == null) { 5510 return false; 5511 } 5512 final String scheme = intent.getScheme(); 5513 if (TextUtils.isEmpty(scheme)) { 5514 return false; 5515 } 5516 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5517 } 5518 5519 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5520 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5521 int userId) { 5522 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5523 5524 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5525 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5526 candidates.size()); 5527 } 5528 5529 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5530 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5531 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5532 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5533 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5534 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5535 5536 synchronized (mPackages) { 5537 final int count = candidates.size(); 5538 // First, try to use linked apps. Partition the candidates into four lists: 5539 // one for the final results, one for the "do not use ever", one for "undefined status" 5540 // and finally one for "browser app type". 5541 for (int n=0; n<count; n++) { 5542 ResolveInfo info = candidates.get(n); 5543 String packageName = info.activityInfo.packageName; 5544 PackageSetting ps = mSettings.mPackages.get(packageName); 5545 if (ps != null) { 5546 // Add to the special match all list (Browser use case) 5547 if (info.handleAllWebDataURI) { 5548 matchAllList.add(info); 5549 continue; 5550 } 5551 // Try to get the status from User settings first 5552 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5553 int status = (int)(packedStatus >> 32); 5554 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5555 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5556 if (DEBUG_DOMAIN_VERIFICATION) { 5557 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5558 + " : linkgen=" + linkGeneration); 5559 } 5560 // Use link-enabled generation as preferredOrder, i.e. 5561 // prefer newly-enabled over earlier-enabled. 5562 info.preferredOrder = linkGeneration; 5563 alwaysList.add(info); 5564 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5565 if (DEBUG_DOMAIN_VERIFICATION) { 5566 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5567 } 5568 neverList.add(info); 5569 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5570 if (DEBUG_DOMAIN_VERIFICATION) { 5571 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5572 } 5573 alwaysAskList.add(info); 5574 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5575 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5576 if (DEBUG_DOMAIN_VERIFICATION) { 5577 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5578 } 5579 undefinedList.add(info); 5580 } 5581 } 5582 } 5583 5584 // We'll want to include browser possibilities in a few cases 5585 boolean includeBrowser = false; 5586 5587 // First try to add the "always" resolution(s) for the current user, if any 5588 if (alwaysList.size() > 0) { 5589 result.addAll(alwaysList); 5590 } else { 5591 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5592 result.addAll(undefinedList); 5593 // Maybe add one for the other profile. 5594 if (xpDomainInfo != null && ( 5595 xpDomainInfo.bestDomainVerificationStatus 5596 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5597 result.add(xpDomainInfo.resolveInfo); 5598 } 5599 includeBrowser = true; 5600 } 5601 5602 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5603 // If there were 'always' entries their preferred order has been set, so we also 5604 // back that off to make the alternatives equivalent 5605 if (alwaysAskList.size() > 0) { 5606 for (ResolveInfo i : result) { 5607 i.preferredOrder = 0; 5608 } 5609 result.addAll(alwaysAskList); 5610 includeBrowser = true; 5611 } 5612 5613 if (includeBrowser) { 5614 // Also add browsers (all of them or only the default one) 5615 if (DEBUG_DOMAIN_VERIFICATION) { 5616 Slog.v(TAG, " ...including browsers in candidate set"); 5617 } 5618 if ((matchFlags & MATCH_ALL) != 0) { 5619 result.addAll(matchAllList); 5620 } else { 5621 // Browser/generic handling case. If there's a default browser, go straight 5622 // to that (but only if there is no other higher-priority match). 5623 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5624 int maxMatchPrio = 0; 5625 ResolveInfo defaultBrowserMatch = null; 5626 final int numCandidates = matchAllList.size(); 5627 for (int n = 0; n < numCandidates; n++) { 5628 ResolveInfo info = matchAllList.get(n); 5629 // track the highest overall match priority... 5630 if (info.priority > maxMatchPrio) { 5631 maxMatchPrio = info.priority; 5632 } 5633 // ...and the highest-priority default browser match 5634 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5635 if (defaultBrowserMatch == null 5636 || (defaultBrowserMatch.priority < info.priority)) { 5637 if (debug) { 5638 Slog.v(TAG, "Considering default browser match " + info); 5639 } 5640 defaultBrowserMatch = info; 5641 } 5642 } 5643 } 5644 if (defaultBrowserMatch != null 5645 && defaultBrowserMatch.priority >= maxMatchPrio 5646 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5647 { 5648 if (debug) { 5649 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5650 } 5651 result.add(defaultBrowserMatch); 5652 } else { 5653 result.addAll(matchAllList); 5654 } 5655 } 5656 5657 // If there is nothing selected, add all candidates and remove the ones that the user 5658 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5659 if (result.size() == 0) { 5660 result.addAll(candidates); 5661 result.removeAll(neverList); 5662 } 5663 } 5664 } 5665 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5666 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5667 result.size()); 5668 for (ResolveInfo info : result) { 5669 Slog.v(TAG, " + " + info.activityInfo); 5670 } 5671 } 5672 return result; 5673 } 5674 5675 // Returns a packed value as a long: 5676 // 5677 // high 'int'-sized word: link status: undefined/ask/never/always. 5678 // low 'int'-sized word: relative priority among 'always' results. 5679 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5680 long result = ps.getDomainVerificationStatusForUser(userId); 5681 // if none available, get the master status 5682 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5683 if (ps.getIntentFilterVerificationInfo() != null) { 5684 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5685 } 5686 } 5687 return result; 5688 } 5689 5690 private ResolveInfo querySkipCurrentProfileIntents( 5691 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5692 int flags, int sourceUserId) { 5693 if (matchingFilters != null) { 5694 int size = matchingFilters.size(); 5695 for (int i = 0; i < size; i ++) { 5696 CrossProfileIntentFilter filter = matchingFilters.get(i); 5697 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5698 // Checking if there are activities in the target user that can handle the 5699 // intent. 5700 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5701 resolvedType, flags, sourceUserId); 5702 if (resolveInfo != null) { 5703 return resolveInfo; 5704 } 5705 } 5706 } 5707 } 5708 return null; 5709 } 5710 5711 // Return matching ResolveInfo in target user if any. 5712 private ResolveInfo queryCrossProfileIntents( 5713 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5714 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5715 if (matchingFilters != null) { 5716 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5717 // match the same intent. For performance reasons, it is better not to 5718 // run queryIntent twice for the same userId 5719 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5720 int size = matchingFilters.size(); 5721 for (int i = 0; i < size; i++) { 5722 CrossProfileIntentFilter filter = matchingFilters.get(i); 5723 int targetUserId = filter.getTargetUserId(); 5724 boolean skipCurrentProfile = 5725 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5726 boolean skipCurrentProfileIfNoMatchFound = 5727 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5728 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5729 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5730 // Checking if there are activities in the target user that can handle the 5731 // intent. 5732 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5733 resolvedType, flags, sourceUserId); 5734 if (resolveInfo != null) return resolveInfo; 5735 alreadyTriedUserIds.put(targetUserId, true); 5736 } 5737 } 5738 } 5739 return null; 5740 } 5741 5742 /** 5743 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5744 * will forward the intent to the filter's target user. 5745 * Otherwise, returns null. 5746 */ 5747 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5748 String resolvedType, int flags, int sourceUserId) { 5749 int targetUserId = filter.getTargetUserId(); 5750 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5751 resolvedType, flags, targetUserId); 5752 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5753 // If all the matches in the target profile are suspended, return null. 5754 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5755 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5756 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5757 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5758 targetUserId); 5759 } 5760 } 5761 } 5762 return null; 5763 } 5764 5765 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5766 int sourceUserId, int targetUserId) { 5767 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5768 long ident = Binder.clearCallingIdentity(); 5769 boolean targetIsProfile; 5770 try { 5771 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5772 } finally { 5773 Binder.restoreCallingIdentity(ident); 5774 } 5775 String className; 5776 if (targetIsProfile) { 5777 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5778 } else { 5779 className = FORWARD_INTENT_TO_PARENT; 5780 } 5781 ComponentName forwardingActivityComponentName = new ComponentName( 5782 mAndroidApplication.packageName, className); 5783 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5784 sourceUserId); 5785 if (!targetIsProfile) { 5786 forwardingActivityInfo.showUserIcon = targetUserId; 5787 forwardingResolveInfo.noResourceId = true; 5788 } 5789 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5790 forwardingResolveInfo.priority = 0; 5791 forwardingResolveInfo.preferredOrder = 0; 5792 forwardingResolveInfo.match = 0; 5793 forwardingResolveInfo.isDefault = true; 5794 forwardingResolveInfo.filter = filter; 5795 forwardingResolveInfo.targetUserId = targetUserId; 5796 return forwardingResolveInfo; 5797 } 5798 5799 @Override 5800 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5801 Intent[] specifics, String[] specificTypes, Intent intent, 5802 String resolvedType, int flags, int userId) { 5803 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5804 specificTypes, intent, resolvedType, flags, userId)); 5805 } 5806 5807 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5808 Intent[] specifics, String[] specificTypes, Intent intent, 5809 String resolvedType, int flags, int userId) { 5810 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5811 flags = updateFlagsForResolve(flags, userId, intent); 5812 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5813 false /* requireFullPermission */, false /* checkShell */, 5814 "query intent activity options"); 5815 final String resultsAction = intent.getAction(); 5816 5817 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5818 | PackageManager.GET_RESOLVED_FILTER, userId); 5819 5820 if (DEBUG_INTENT_MATCHING) { 5821 Log.v(TAG, "Query " + intent + ": " + results); 5822 } 5823 5824 int specificsPos = 0; 5825 int N; 5826 5827 // todo: note that the algorithm used here is O(N^2). This 5828 // isn't a problem in our current environment, but if we start running 5829 // into situations where we have more than 5 or 10 matches then this 5830 // should probably be changed to something smarter... 5831 5832 // First we go through and resolve each of the specific items 5833 // that were supplied, taking care of removing any corresponding 5834 // duplicate items in the generic resolve list. 5835 if (specifics != null) { 5836 for (int i=0; i<specifics.length; i++) { 5837 final Intent sintent = specifics[i]; 5838 if (sintent == null) { 5839 continue; 5840 } 5841 5842 if (DEBUG_INTENT_MATCHING) { 5843 Log.v(TAG, "Specific #" + i + ": " + sintent); 5844 } 5845 5846 String action = sintent.getAction(); 5847 if (resultsAction != null && resultsAction.equals(action)) { 5848 // If this action was explicitly requested, then don't 5849 // remove things that have it. 5850 action = null; 5851 } 5852 5853 ResolveInfo ri = null; 5854 ActivityInfo ai = null; 5855 5856 ComponentName comp = sintent.getComponent(); 5857 if (comp == null) { 5858 ri = resolveIntent( 5859 sintent, 5860 specificTypes != null ? specificTypes[i] : null, 5861 flags, userId); 5862 if (ri == null) { 5863 continue; 5864 } 5865 if (ri == mResolveInfo) { 5866 // ACK! Must do something better with this. 5867 } 5868 ai = ri.activityInfo; 5869 comp = new ComponentName(ai.applicationInfo.packageName, 5870 ai.name); 5871 } else { 5872 ai = getActivityInfo(comp, flags, userId); 5873 if (ai == null) { 5874 continue; 5875 } 5876 } 5877 5878 // Look for any generic query activities that are duplicates 5879 // of this specific one, and remove them from the results. 5880 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5881 N = results.size(); 5882 int j; 5883 for (j=specificsPos; j<N; j++) { 5884 ResolveInfo sri = results.get(j); 5885 if ((sri.activityInfo.name.equals(comp.getClassName()) 5886 && sri.activityInfo.applicationInfo.packageName.equals( 5887 comp.getPackageName())) 5888 || (action != null && sri.filter.matchAction(action))) { 5889 results.remove(j); 5890 if (DEBUG_INTENT_MATCHING) Log.v( 5891 TAG, "Removing duplicate item from " + j 5892 + " due to specific " + specificsPos); 5893 if (ri == null) { 5894 ri = sri; 5895 } 5896 j--; 5897 N--; 5898 } 5899 } 5900 5901 // Add this specific item to its proper place. 5902 if (ri == null) { 5903 ri = new ResolveInfo(); 5904 ri.activityInfo = ai; 5905 } 5906 results.add(specificsPos, ri); 5907 ri.specificIndex = i; 5908 specificsPos++; 5909 } 5910 } 5911 5912 // Now we go through the remaining generic results and remove any 5913 // duplicate actions that are found here. 5914 N = results.size(); 5915 for (int i=specificsPos; i<N-1; i++) { 5916 final ResolveInfo rii = results.get(i); 5917 if (rii.filter == null) { 5918 continue; 5919 } 5920 5921 // Iterate over all of the actions of this result's intent 5922 // filter... typically this should be just one. 5923 final Iterator<String> it = rii.filter.actionsIterator(); 5924 if (it == null) { 5925 continue; 5926 } 5927 while (it.hasNext()) { 5928 final String action = it.next(); 5929 if (resultsAction != null && resultsAction.equals(action)) { 5930 // If this action was explicitly requested, then don't 5931 // remove things that have it. 5932 continue; 5933 } 5934 for (int j=i+1; j<N; j++) { 5935 final ResolveInfo rij = results.get(j); 5936 if (rij.filter != null && rij.filter.hasAction(action)) { 5937 results.remove(j); 5938 if (DEBUG_INTENT_MATCHING) Log.v( 5939 TAG, "Removing duplicate item from " + j 5940 + " due to action " + action + " at " + i); 5941 j--; 5942 N--; 5943 } 5944 } 5945 } 5946 5947 // If the caller didn't request filter information, drop it now 5948 // so we don't have to marshall/unmarshall it. 5949 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5950 rii.filter = null; 5951 } 5952 } 5953 5954 // Filter out the caller activity if so requested. 5955 if (caller != null) { 5956 N = results.size(); 5957 for (int i=0; i<N; i++) { 5958 ActivityInfo ainfo = results.get(i).activityInfo; 5959 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5960 && caller.getClassName().equals(ainfo.name)) { 5961 results.remove(i); 5962 break; 5963 } 5964 } 5965 } 5966 5967 // If the caller didn't request filter information, 5968 // drop them now so we don't have to 5969 // marshall/unmarshall it. 5970 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5971 N = results.size(); 5972 for (int i=0; i<N; i++) { 5973 results.get(i).filter = null; 5974 } 5975 } 5976 5977 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5978 return results; 5979 } 5980 5981 @Override 5982 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5983 String resolvedType, int flags, int userId) { 5984 return new ParceledListSlice<>( 5985 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5986 } 5987 5988 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5989 String resolvedType, int flags, int userId) { 5990 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5991 flags = updateFlagsForResolve(flags, userId, intent); 5992 ComponentName comp = intent.getComponent(); 5993 if (comp == null) { 5994 if (intent.getSelector() != null) { 5995 intent = intent.getSelector(); 5996 comp = intent.getComponent(); 5997 } 5998 } 5999 if (comp != null) { 6000 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6001 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6002 if (ai != null) { 6003 ResolveInfo ri = new ResolveInfo(); 6004 ri.activityInfo = ai; 6005 list.add(ri); 6006 } 6007 return list; 6008 } 6009 6010 // reader 6011 synchronized (mPackages) { 6012 String pkgName = intent.getPackage(); 6013 if (pkgName == null) { 6014 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6015 } 6016 final PackageParser.Package pkg = mPackages.get(pkgName); 6017 if (pkg != null) { 6018 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6019 userId); 6020 } 6021 return Collections.emptyList(); 6022 } 6023 } 6024 6025 @Override 6026 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6027 if (!sUserManager.exists(userId)) return null; 6028 flags = updateFlagsForResolve(flags, userId, intent); 6029 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6030 if (query != null) { 6031 if (query.size() >= 1) { 6032 // If there is more than one service with the same priority, 6033 // just arbitrarily pick the first one. 6034 return query.get(0); 6035 } 6036 } 6037 return null; 6038 } 6039 6040 @Override 6041 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6042 String resolvedType, int flags, int userId) { 6043 return new ParceledListSlice<>( 6044 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6045 } 6046 6047 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6048 String resolvedType, int flags, int userId) { 6049 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6050 flags = updateFlagsForResolve(flags, userId, intent); 6051 ComponentName comp = intent.getComponent(); 6052 if (comp == null) { 6053 if (intent.getSelector() != null) { 6054 intent = intent.getSelector(); 6055 comp = intent.getComponent(); 6056 } 6057 } 6058 if (comp != null) { 6059 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6060 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6061 if (si != null) { 6062 final ResolveInfo ri = new ResolveInfo(); 6063 ri.serviceInfo = si; 6064 list.add(ri); 6065 } 6066 return list; 6067 } 6068 6069 // reader 6070 synchronized (mPackages) { 6071 String pkgName = intent.getPackage(); 6072 if (pkgName == null) { 6073 return mServices.queryIntent(intent, resolvedType, flags, userId); 6074 } 6075 final PackageParser.Package pkg = mPackages.get(pkgName); 6076 if (pkg != null) { 6077 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6078 userId); 6079 } 6080 return Collections.emptyList(); 6081 } 6082 } 6083 6084 @Override 6085 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6086 String resolvedType, int flags, int userId) { 6087 return new ParceledListSlice<>( 6088 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6089 } 6090 6091 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6092 Intent intent, String resolvedType, int flags, int userId) { 6093 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6094 flags = updateFlagsForResolve(flags, userId, intent); 6095 ComponentName comp = intent.getComponent(); 6096 if (comp == null) { 6097 if (intent.getSelector() != null) { 6098 intent = intent.getSelector(); 6099 comp = intent.getComponent(); 6100 } 6101 } 6102 if (comp != null) { 6103 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6104 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6105 if (pi != null) { 6106 final ResolveInfo ri = new ResolveInfo(); 6107 ri.providerInfo = pi; 6108 list.add(ri); 6109 } 6110 return list; 6111 } 6112 6113 // reader 6114 synchronized (mPackages) { 6115 String pkgName = intent.getPackage(); 6116 if (pkgName == null) { 6117 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6118 } 6119 final PackageParser.Package pkg = mPackages.get(pkgName); 6120 if (pkg != null) { 6121 return mProviders.queryIntentForPackage( 6122 intent, resolvedType, flags, pkg.providers, userId); 6123 } 6124 return Collections.emptyList(); 6125 } 6126 } 6127 6128 @Override 6129 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6130 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6131 flags = updateFlagsForPackage(flags, userId, null); 6132 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6133 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6134 true /* requireFullPermission */, false /* checkShell */, 6135 "get installed packages"); 6136 6137 // writer 6138 synchronized (mPackages) { 6139 ArrayList<PackageInfo> list; 6140 if (listUninstalled) { 6141 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6142 for (PackageSetting ps : mSettings.mPackages.values()) { 6143 final PackageInfo pi; 6144 if (ps.pkg != null) { 6145 pi = generatePackageInfo(ps, flags, userId); 6146 } else { 6147 pi = generatePackageInfo(ps, flags, userId); 6148 } 6149 if (pi != null) { 6150 list.add(pi); 6151 } 6152 } 6153 } else { 6154 list = new ArrayList<PackageInfo>(mPackages.size()); 6155 for (PackageParser.Package p : mPackages.values()) { 6156 final PackageInfo pi = 6157 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6158 if (pi != null) { 6159 list.add(pi); 6160 } 6161 } 6162 } 6163 6164 return new ParceledListSlice<PackageInfo>(list); 6165 } 6166 } 6167 6168 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6169 String[] permissions, boolean[] tmp, int flags, int userId) { 6170 int numMatch = 0; 6171 final PermissionsState permissionsState = ps.getPermissionsState(); 6172 for (int i=0; i<permissions.length; i++) { 6173 final String permission = permissions[i]; 6174 if (permissionsState.hasPermission(permission, userId)) { 6175 tmp[i] = true; 6176 numMatch++; 6177 } else { 6178 tmp[i] = false; 6179 } 6180 } 6181 if (numMatch == 0) { 6182 return; 6183 } 6184 final PackageInfo pi; 6185 if (ps.pkg != null) { 6186 pi = generatePackageInfo(ps, flags, userId); 6187 } else { 6188 pi = generatePackageInfo(ps, flags, userId); 6189 } 6190 // The above might return null in cases of uninstalled apps or install-state 6191 // skew across users/profiles. 6192 if (pi != null) { 6193 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6194 if (numMatch == permissions.length) { 6195 pi.requestedPermissions = permissions; 6196 } else { 6197 pi.requestedPermissions = new String[numMatch]; 6198 numMatch = 0; 6199 for (int i=0; i<permissions.length; i++) { 6200 if (tmp[i]) { 6201 pi.requestedPermissions[numMatch] = permissions[i]; 6202 numMatch++; 6203 } 6204 } 6205 } 6206 } 6207 list.add(pi); 6208 } 6209 } 6210 6211 @Override 6212 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6213 String[] permissions, int flags, int userId) { 6214 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6215 flags = updateFlagsForPackage(flags, userId, permissions); 6216 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6217 6218 // writer 6219 synchronized (mPackages) { 6220 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6221 boolean[] tmpBools = new boolean[permissions.length]; 6222 if (listUninstalled) { 6223 for (PackageSetting ps : mSettings.mPackages.values()) { 6224 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6225 } 6226 } else { 6227 for (PackageParser.Package pkg : mPackages.values()) { 6228 PackageSetting ps = (PackageSetting)pkg.mExtras; 6229 if (ps != null) { 6230 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6231 userId); 6232 } 6233 } 6234 } 6235 6236 return new ParceledListSlice<PackageInfo>(list); 6237 } 6238 } 6239 6240 @Override 6241 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6242 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6243 flags = updateFlagsForApplication(flags, userId, null); 6244 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6245 6246 // writer 6247 synchronized (mPackages) { 6248 ArrayList<ApplicationInfo> list; 6249 if (listUninstalled) { 6250 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6251 for (PackageSetting ps : mSettings.mPackages.values()) { 6252 ApplicationInfo ai; 6253 if (ps.pkg != null) { 6254 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6255 ps.readUserState(userId), userId); 6256 } else { 6257 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6258 } 6259 if (ai != null) { 6260 list.add(ai); 6261 } 6262 } 6263 } else { 6264 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6265 for (PackageParser.Package p : mPackages.values()) { 6266 if (p.mExtras != null) { 6267 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6268 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6269 if (ai != null) { 6270 list.add(ai); 6271 } 6272 } 6273 } 6274 } 6275 6276 return new ParceledListSlice<ApplicationInfo>(list); 6277 } 6278 } 6279 6280 @Override 6281 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6282 if (DISABLE_EPHEMERAL_APPS) { 6283 return null; 6284 } 6285 6286 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6287 "getEphemeralApplications"); 6288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6289 true /* requireFullPermission */, false /* checkShell */, 6290 "getEphemeralApplications"); 6291 synchronized (mPackages) { 6292 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6293 .getEphemeralApplicationsLPw(userId); 6294 if (ephemeralApps != null) { 6295 return new ParceledListSlice<>(ephemeralApps); 6296 } 6297 } 6298 return null; 6299 } 6300 6301 @Override 6302 public boolean isEphemeralApplication(String packageName, int userId) { 6303 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6304 true /* requireFullPermission */, false /* checkShell */, 6305 "isEphemeral"); 6306 if (DISABLE_EPHEMERAL_APPS) { 6307 return false; 6308 } 6309 6310 if (!isCallerSameApp(packageName)) { 6311 return false; 6312 } 6313 synchronized (mPackages) { 6314 PackageParser.Package pkg = mPackages.get(packageName); 6315 if (pkg != null) { 6316 return pkg.applicationInfo.isEphemeralApp(); 6317 } 6318 } 6319 return false; 6320 } 6321 6322 @Override 6323 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6324 if (DISABLE_EPHEMERAL_APPS) { 6325 return null; 6326 } 6327 6328 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6329 true /* requireFullPermission */, false /* checkShell */, 6330 "getCookie"); 6331 if (!isCallerSameApp(packageName)) { 6332 return null; 6333 } 6334 synchronized (mPackages) { 6335 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6336 packageName, userId); 6337 } 6338 } 6339 6340 @Override 6341 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6342 if (DISABLE_EPHEMERAL_APPS) { 6343 return true; 6344 } 6345 6346 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6347 true /* requireFullPermission */, true /* checkShell */, 6348 "setCookie"); 6349 if (!isCallerSameApp(packageName)) { 6350 return false; 6351 } 6352 synchronized (mPackages) { 6353 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6354 packageName, cookie, userId); 6355 } 6356 } 6357 6358 @Override 6359 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6360 if (DISABLE_EPHEMERAL_APPS) { 6361 return null; 6362 } 6363 6364 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6365 "getEphemeralApplicationIcon"); 6366 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6367 true /* requireFullPermission */, false /* checkShell */, 6368 "getEphemeralApplicationIcon"); 6369 synchronized (mPackages) { 6370 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6371 packageName, userId); 6372 } 6373 } 6374 6375 private boolean isCallerSameApp(String packageName) { 6376 PackageParser.Package pkg = mPackages.get(packageName); 6377 return pkg != null 6378 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6379 } 6380 6381 @Override 6382 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6383 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6384 } 6385 6386 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6387 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6388 6389 // reader 6390 synchronized (mPackages) { 6391 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6392 final int userId = UserHandle.getCallingUserId(); 6393 while (i.hasNext()) { 6394 final PackageParser.Package p = i.next(); 6395 if (p.applicationInfo == null) continue; 6396 6397 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6398 && !p.applicationInfo.isDirectBootAware(); 6399 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6400 && p.applicationInfo.isDirectBootAware(); 6401 6402 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6403 && (!mSafeMode || isSystemApp(p)) 6404 && (matchesUnaware || matchesAware)) { 6405 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6406 if (ps != null) { 6407 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6408 ps.readUserState(userId), userId); 6409 if (ai != null) { 6410 finalList.add(ai); 6411 } 6412 } 6413 } 6414 } 6415 } 6416 6417 return finalList; 6418 } 6419 6420 @Override 6421 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6422 if (!sUserManager.exists(userId)) return null; 6423 flags = updateFlagsForComponent(flags, userId, name); 6424 // reader 6425 synchronized (mPackages) { 6426 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6427 PackageSetting ps = provider != null 6428 ? mSettings.mPackages.get(provider.owner.packageName) 6429 : null; 6430 return ps != null 6431 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6432 ? PackageParser.generateProviderInfo(provider, flags, 6433 ps.readUserState(userId), userId) 6434 : null; 6435 } 6436 } 6437 6438 /** 6439 * @deprecated 6440 */ 6441 @Deprecated 6442 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6443 // reader 6444 synchronized (mPackages) { 6445 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6446 .entrySet().iterator(); 6447 final int userId = UserHandle.getCallingUserId(); 6448 while (i.hasNext()) { 6449 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6450 PackageParser.Provider p = entry.getValue(); 6451 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6452 6453 if (ps != null && p.syncable 6454 && (!mSafeMode || (p.info.applicationInfo.flags 6455 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6456 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6457 ps.readUserState(userId), userId); 6458 if (info != null) { 6459 outNames.add(entry.getKey()); 6460 outInfo.add(info); 6461 } 6462 } 6463 } 6464 } 6465 } 6466 6467 @Override 6468 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6469 int uid, int flags) { 6470 final int userId = processName != null ? UserHandle.getUserId(uid) 6471 : UserHandle.getCallingUserId(); 6472 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6473 flags = updateFlagsForComponent(flags, userId, processName); 6474 6475 ArrayList<ProviderInfo> finalList = null; 6476 // reader 6477 synchronized (mPackages) { 6478 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6479 while (i.hasNext()) { 6480 final PackageParser.Provider p = i.next(); 6481 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6482 if (ps != null && p.info.authority != null 6483 && (processName == null 6484 || (p.info.processName.equals(processName) 6485 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6486 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6487 if (finalList == null) { 6488 finalList = new ArrayList<ProviderInfo>(3); 6489 } 6490 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6491 ps.readUserState(userId), userId); 6492 if (info != null) { 6493 finalList.add(info); 6494 } 6495 } 6496 } 6497 } 6498 6499 if (finalList != null) { 6500 Collections.sort(finalList, mProviderInitOrderSorter); 6501 return new ParceledListSlice<ProviderInfo>(finalList); 6502 } 6503 6504 return ParceledListSlice.emptyList(); 6505 } 6506 6507 @Override 6508 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6509 // reader 6510 synchronized (mPackages) { 6511 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6512 return PackageParser.generateInstrumentationInfo(i, flags); 6513 } 6514 } 6515 6516 @Override 6517 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6518 String targetPackage, int flags) { 6519 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6520 } 6521 6522 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6523 int flags) { 6524 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6525 6526 // reader 6527 synchronized (mPackages) { 6528 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6529 while (i.hasNext()) { 6530 final PackageParser.Instrumentation p = i.next(); 6531 if (targetPackage == null 6532 || targetPackage.equals(p.info.targetPackage)) { 6533 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6534 flags); 6535 if (ii != null) { 6536 finalList.add(ii); 6537 } 6538 } 6539 } 6540 } 6541 6542 return finalList; 6543 } 6544 6545 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6546 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6547 if (overlays == null) { 6548 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6549 return; 6550 } 6551 for (PackageParser.Package opkg : overlays.values()) { 6552 // Not much to do if idmap fails: we already logged the error 6553 // and we certainly don't want to abort installation of pkg simply 6554 // because an overlay didn't fit properly. For these reasons, 6555 // ignore the return value of createIdmapForPackagePairLI. 6556 createIdmapForPackagePairLI(pkg, opkg); 6557 } 6558 } 6559 6560 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6561 PackageParser.Package opkg) { 6562 if (!opkg.mTrustedOverlay) { 6563 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6564 opkg.baseCodePath + ": overlay not trusted"); 6565 return false; 6566 } 6567 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6568 if (overlaySet == null) { 6569 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6570 opkg.baseCodePath + " but target package has no known overlays"); 6571 return false; 6572 } 6573 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6574 // TODO: generate idmap for split APKs 6575 try { 6576 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6577 } catch (InstallerException e) { 6578 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6579 + opkg.baseCodePath); 6580 return false; 6581 } 6582 PackageParser.Package[] overlayArray = 6583 overlaySet.values().toArray(new PackageParser.Package[0]); 6584 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6585 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6586 return p1.mOverlayPriority - p2.mOverlayPriority; 6587 } 6588 }; 6589 Arrays.sort(overlayArray, cmp); 6590 6591 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6592 int i = 0; 6593 for (PackageParser.Package p : overlayArray) { 6594 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6595 } 6596 return true; 6597 } 6598 6599 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6600 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6601 try { 6602 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6603 } finally { 6604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6605 } 6606 } 6607 6608 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6609 final File[] files = dir.listFiles(); 6610 if (ArrayUtils.isEmpty(files)) { 6611 Log.d(TAG, "No files in app dir " + dir); 6612 return; 6613 } 6614 6615 if (DEBUG_PACKAGE_SCANNING) { 6616 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6617 + " flags=0x" + Integer.toHexString(parseFlags)); 6618 } 6619 6620 for (File file : files) { 6621 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6622 && !PackageInstallerService.isStageName(file.getName()); 6623 if (!isPackage) { 6624 // Ignore entries which are not packages 6625 continue; 6626 } 6627 try { 6628 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6629 scanFlags, currentTime, null); 6630 } catch (PackageManagerException e) { 6631 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6632 6633 // Delete invalid userdata apps 6634 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6635 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6636 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6637 removeCodePathLI(file); 6638 } 6639 } 6640 } 6641 } 6642 6643 private static File getSettingsProblemFile() { 6644 File dataDir = Environment.getDataDirectory(); 6645 File systemDir = new File(dataDir, "system"); 6646 File fname = new File(systemDir, "uiderrors.txt"); 6647 return fname; 6648 } 6649 6650 static void reportSettingsProblem(int priority, String msg) { 6651 logCriticalInfo(priority, msg); 6652 } 6653 6654 static void logCriticalInfo(int priority, String msg) { 6655 Slog.println(priority, TAG, msg); 6656 EventLogTags.writePmCriticalInfo(msg); 6657 try { 6658 File fname = getSettingsProblemFile(); 6659 FileOutputStream out = new FileOutputStream(fname, true); 6660 PrintWriter pw = new FastPrintWriter(out); 6661 SimpleDateFormat formatter = new SimpleDateFormat(); 6662 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6663 pw.println(dateString + ": " + msg); 6664 pw.close(); 6665 FileUtils.setPermissions( 6666 fname.toString(), 6667 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6668 -1, -1); 6669 } catch (java.io.IOException e) { 6670 } 6671 } 6672 6673 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6674 final int policyFlags) throws PackageManagerException { 6675 if (ps != null 6676 && ps.codePath.equals(srcFile) 6677 && ps.timeStamp == srcFile.lastModified() 6678 && !isCompatSignatureUpdateNeeded(pkg) 6679 && !isRecoverSignatureUpdateNeeded(pkg)) { 6680 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6681 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6682 ArraySet<PublicKey> signingKs; 6683 synchronized (mPackages) { 6684 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6685 } 6686 if (ps.signatures.mSignatures != null 6687 && ps.signatures.mSignatures.length != 0 6688 && signingKs != null) { 6689 // Optimization: reuse the existing cached certificates 6690 // if the package appears to be unchanged. 6691 pkg.mSignatures = ps.signatures.mSignatures; 6692 pkg.mSigningKeys = signingKs; 6693 return; 6694 } 6695 6696 Slog.w(TAG, "PackageSetting for " + ps.name 6697 + " is missing signatures. Collecting certs again to recover them."); 6698 } else { 6699 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6700 } 6701 6702 try { 6703 PackageParser.collectCertificates(pkg, policyFlags); 6704 } catch (PackageParserException e) { 6705 throw PackageManagerException.from(e); 6706 } 6707 } 6708 6709 /** 6710 * Traces a package scan. 6711 * @see #scanPackageLI(File, int, int, long, UserHandle) 6712 */ 6713 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6714 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6716 try { 6717 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6718 } finally { 6719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6720 } 6721 } 6722 6723 /** 6724 * Scans a package and returns the newly parsed package. 6725 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6726 */ 6727 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6728 long currentTime, UserHandle user) throws PackageManagerException { 6729 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6730 PackageParser pp = new PackageParser(); 6731 pp.setSeparateProcesses(mSeparateProcesses); 6732 pp.setOnlyCoreApps(mOnlyCore); 6733 pp.setDisplayMetrics(mMetrics); 6734 6735 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6736 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6737 } 6738 6739 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6740 final PackageParser.Package pkg; 6741 try { 6742 pkg = pp.parsePackage(scanFile, parseFlags); 6743 } catch (PackageParserException e) { 6744 throw PackageManagerException.from(e); 6745 } finally { 6746 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6747 } 6748 6749 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6750 } 6751 6752 /** 6753 * Scans a package and returns the newly parsed package. 6754 * @throws PackageManagerException on a parse error. 6755 */ 6756 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6757 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6758 throws PackageManagerException { 6759 // If the package has children and this is the first dive in the function 6760 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6761 // packages (parent and children) would be successfully scanned before the 6762 // actual scan since scanning mutates internal state and we want to atomically 6763 // install the package and its children. 6764 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6765 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6766 scanFlags |= SCAN_CHECK_ONLY; 6767 } 6768 } else { 6769 scanFlags &= ~SCAN_CHECK_ONLY; 6770 } 6771 6772 // Scan the parent 6773 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6774 scanFlags, currentTime, user); 6775 6776 // Scan the children 6777 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6778 for (int i = 0; i < childCount; i++) { 6779 PackageParser.Package childPackage = pkg.childPackages.get(i); 6780 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6781 currentTime, user); 6782 } 6783 6784 6785 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6786 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6787 } 6788 6789 return scannedPkg; 6790 } 6791 6792 /** 6793 * Scans a package and returns the newly parsed package. 6794 * @throws PackageManagerException on a parse error. 6795 */ 6796 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6797 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6798 throws PackageManagerException { 6799 PackageSetting ps = null; 6800 PackageSetting updatedPkg; 6801 // reader 6802 synchronized (mPackages) { 6803 // Look to see if we already know about this package. 6804 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6805 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6806 // This package has been renamed to its original name. Let's 6807 // use that. 6808 ps = mSettings.peekPackageLPr(oldName); 6809 } 6810 // If there was no original package, see one for the real package name. 6811 if (ps == null) { 6812 ps = mSettings.peekPackageLPr(pkg.packageName); 6813 } 6814 // Check to see if this package could be hiding/updating a system 6815 // package. Must look for it either under the original or real 6816 // package name depending on our state. 6817 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6818 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6819 6820 // If this is a package we don't know about on the system partition, we 6821 // may need to remove disabled child packages on the system partition 6822 // or may need to not add child packages if the parent apk is updated 6823 // on the data partition and no longer defines this child package. 6824 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6825 // If this is a parent package for an updated system app and this system 6826 // app got an OTA update which no longer defines some of the child packages 6827 // we have to prune them from the disabled system packages. 6828 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6829 if (disabledPs != null) { 6830 final int scannedChildCount = (pkg.childPackages != null) 6831 ? pkg.childPackages.size() : 0; 6832 final int disabledChildCount = disabledPs.childPackageNames != null 6833 ? disabledPs.childPackageNames.size() : 0; 6834 for (int i = 0; i < disabledChildCount; i++) { 6835 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6836 boolean disabledPackageAvailable = false; 6837 for (int j = 0; j < scannedChildCount; j++) { 6838 PackageParser.Package childPkg = pkg.childPackages.get(j); 6839 if (childPkg.packageName.equals(disabledChildPackageName)) { 6840 disabledPackageAvailable = true; 6841 break; 6842 } 6843 } 6844 if (!disabledPackageAvailable) { 6845 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6846 } 6847 } 6848 } 6849 } 6850 } 6851 6852 boolean updatedPkgBetter = false; 6853 // First check if this is a system package that may involve an update 6854 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6855 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6856 // it needs to drop FLAG_PRIVILEGED. 6857 if (locationIsPrivileged(scanFile)) { 6858 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6859 } else { 6860 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6861 } 6862 6863 if (ps != null && !ps.codePath.equals(scanFile)) { 6864 // The path has changed from what was last scanned... check the 6865 // version of the new path against what we have stored to determine 6866 // what to do. 6867 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6868 if (pkg.mVersionCode <= ps.versionCode) { 6869 // The system package has been updated and the code path does not match 6870 // Ignore entry. Skip it. 6871 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6872 + " ignored: updated version " + ps.versionCode 6873 + " better than this " + pkg.mVersionCode); 6874 if (!updatedPkg.codePath.equals(scanFile)) { 6875 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6876 + ps.name + " changing from " + updatedPkg.codePathString 6877 + " to " + scanFile); 6878 updatedPkg.codePath = scanFile; 6879 updatedPkg.codePathString = scanFile.toString(); 6880 updatedPkg.resourcePath = scanFile; 6881 updatedPkg.resourcePathString = scanFile.toString(); 6882 } 6883 updatedPkg.pkg = pkg; 6884 updatedPkg.versionCode = pkg.mVersionCode; 6885 6886 // Update the disabled system child packages to point to the package too. 6887 final int childCount = updatedPkg.childPackageNames != null 6888 ? updatedPkg.childPackageNames.size() : 0; 6889 for (int i = 0; i < childCount; i++) { 6890 String childPackageName = updatedPkg.childPackageNames.get(i); 6891 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6892 childPackageName); 6893 if (updatedChildPkg != null) { 6894 updatedChildPkg.pkg = pkg; 6895 updatedChildPkg.versionCode = pkg.mVersionCode; 6896 } 6897 } 6898 6899 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6900 + scanFile + " ignored: updated version " + ps.versionCode 6901 + " better than this " + pkg.mVersionCode); 6902 } else { 6903 // The current app on the system partition is better than 6904 // what we have updated to on the data partition; switch 6905 // back to the system partition version. 6906 // At this point, its safely assumed that package installation for 6907 // apps in system partition will go through. If not there won't be a working 6908 // version of the app 6909 // writer 6910 synchronized (mPackages) { 6911 // Just remove the loaded entries from package lists. 6912 mPackages.remove(ps.name); 6913 } 6914 6915 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6916 + " reverting from " + ps.codePathString 6917 + ": new version " + pkg.mVersionCode 6918 + " better than installed " + ps.versionCode); 6919 6920 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6921 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6922 synchronized (mInstallLock) { 6923 args.cleanUpResourcesLI(); 6924 } 6925 synchronized (mPackages) { 6926 mSettings.enableSystemPackageLPw(ps.name); 6927 } 6928 updatedPkgBetter = true; 6929 } 6930 } 6931 } 6932 6933 if (updatedPkg != null) { 6934 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6935 // initially 6936 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6937 6938 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6939 // flag set initially 6940 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6941 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6942 } 6943 } 6944 6945 // Verify certificates against what was last scanned 6946 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6947 6948 /* 6949 * A new system app appeared, but we already had a non-system one of the 6950 * same name installed earlier. 6951 */ 6952 boolean shouldHideSystemApp = false; 6953 if (updatedPkg == null && ps != null 6954 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6955 /* 6956 * Check to make sure the signatures match first. If they don't, 6957 * wipe the installed application and its data. 6958 */ 6959 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6960 != PackageManager.SIGNATURE_MATCH) { 6961 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6962 + " signatures don't match existing userdata copy; removing"); 6963 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6964 "scanPackageInternalLI")) { 6965 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6966 } 6967 ps = null; 6968 } else { 6969 /* 6970 * If the newly-added system app is an older version than the 6971 * already installed version, hide it. It will be scanned later 6972 * and re-added like an update. 6973 */ 6974 if (pkg.mVersionCode <= ps.versionCode) { 6975 shouldHideSystemApp = true; 6976 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6977 + " but new version " + pkg.mVersionCode + " better than installed " 6978 + ps.versionCode + "; hiding system"); 6979 } else { 6980 /* 6981 * The newly found system app is a newer version that the 6982 * one previously installed. Simply remove the 6983 * already-installed application and replace it with our own 6984 * while keeping the application data. 6985 */ 6986 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6987 + " reverting from " + ps.codePathString + ": new version " 6988 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6989 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6990 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6991 synchronized (mInstallLock) { 6992 args.cleanUpResourcesLI(); 6993 } 6994 } 6995 } 6996 } 6997 6998 // The apk is forward locked (not public) if its code and resources 6999 // are kept in different files. (except for app in either system or 7000 // vendor path). 7001 // TODO grab this value from PackageSettings 7002 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7003 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7004 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7005 } 7006 } 7007 7008 // TODO: extend to support forward-locked splits 7009 String resourcePath = null; 7010 String baseResourcePath = null; 7011 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7012 if (ps != null && ps.resourcePathString != null) { 7013 resourcePath = ps.resourcePathString; 7014 baseResourcePath = ps.resourcePathString; 7015 } else { 7016 // Should not happen at all. Just log an error. 7017 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7018 } 7019 } else { 7020 resourcePath = pkg.codePath; 7021 baseResourcePath = pkg.baseCodePath; 7022 } 7023 7024 // Set application objects path explicitly. 7025 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7026 pkg.setApplicationInfoCodePath(pkg.codePath); 7027 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7028 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7029 pkg.setApplicationInfoResourcePath(resourcePath); 7030 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7031 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7032 7033 // Note that we invoke the following method only if we are about to unpack an application 7034 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7035 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7036 7037 /* 7038 * If the system app should be overridden by a previously installed 7039 * data, hide the system app now and let the /data/app scan pick it up 7040 * again. 7041 */ 7042 if (shouldHideSystemApp) { 7043 synchronized (mPackages) { 7044 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7045 } 7046 } 7047 7048 return scannedPkg; 7049 } 7050 7051 private static String fixProcessName(String defProcessName, 7052 String processName, int uid) { 7053 if (processName == null) { 7054 return defProcessName; 7055 } 7056 return processName; 7057 } 7058 7059 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7060 throws PackageManagerException { 7061 if (pkgSetting.signatures.mSignatures != null) { 7062 // Already existing package. Make sure signatures match 7063 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7064 == PackageManager.SIGNATURE_MATCH; 7065 if (!match) { 7066 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7067 == PackageManager.SIGNATURE_MATCH; 7068 } 7069 if (!match) { 7070 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7071 == PackageManager.SIGNATURE_MATCH; 7072 } 7073 if (!match) { 7074 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7075 + pkg.packageName + " signatures do not match the " 7076 + "previously installed version; ignoring!"); 7077 } 7078 } 7079 7080 // Check for shared user signatures 7081 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7082 // Already existing package. Make sure signatures match 7083 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7084 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7085 if (!match) { 7086 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7087 == PackageManager.SIGNATURE_MATCH; 7088 } 7089 if (!match) { 7090 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7091 == PackageManager.SIGNATURE_MATCH; 7092 } 7093 if (!match) { 7094 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7095 "Package " + pkg.packageName 7096 + " has no signatures that match those in shared user " 7097 + pkgSetting.sharedUser.name + "; ignoring!"); 7098 } 7099 } 7100 } 7101 7102 /** 7103 * Enforces that only the system UID or root's UID can call a method exposed 7104 * via Binder. 7105 * 7106 * @param message used as message if SecurityException is thrown 7107 * @throws SecurityException if the caller is not system or root 7108 */ 7109 private static final void enforceSystemOrRoot(String message) { 7110 final int uid = Binder.getCallingUid(); 7111 if (uid != Process.SYSTEM_UID && uid != 0) { 7112 throw new SecurityException(message); 7113 } 7114 } 7115 7116 @Override 7117 public void performFstrimIfNeeded() { 7118 enforceSystemOrRoot("Only the system can request fstrim"); 7119 7120 // Before everything else, see whether we need to fstrim. 7121 try { 7122 IMountService ms = PackageHelper.getMountService(); 7123 if (ms != null) { 7124 final boolean isUpgrade = isUpgrade(); 7125 boolean doTrim = isUpgrade; 7126 if (doTrim) { 7127 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7128 } else { 7129 final long interval = android.provider.Settings.Global.getLong( 7130 mContext.getContentResolver(), 7131 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7132 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7133 if (interval > 0) { 7134 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7135 if (timeSinceLast > interval) { 7136 doTrim = true; 7137 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7138 + "; running immediately"); 7139 } 7140 } 7141 } 7142 if (doTrim) { 7143 if (!isFirstBoot()) { 7144 try { 7145 ActivityManagerNative.getDefault().showBootMessage( 7146 mContext.getResources().getString( 7147 R.string.android_upgrading_fstrim), true); 7148 } catch (RemoteException e) { 7149 } 7150 } 7151 ms.runMaintenance(); 7152 } 7153 } else { 7154 Slog.e(TAG, "Mount service unavailable!"); 7155 } 7156 } catch (RemoteException e) { 7157 // Can't happen; MountService is local 7158 } 7159 } 7160 7161 @Override 7162 public void updatePackagesIfNeeded() { 7163 enforceSystemOrRoot("Only the system can request package update"); 7164 7165 // We need to re-extract after an OTA. 7166 boolean causeUpgrade = isUpgrade(); 7167 7168 // First boot or factory reset. 7169 // Note: we also handle devices that are upgrading to N right now as if it is their 7170 // first boot, as they do not have profile data. 7171 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7172 7173 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7174 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7175 7176 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7177 return; 7178 } 7179 7180 List<PackageParser.Package> pkgs; 7181 synchronized (mPackages) { 7182 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7183 } 7184 7185 int curr = 0; 7186 int total = pkgs.size(); 7187 for (PackageParser.Package pkg : pkgs) { 7188 curr++; 7189 7190 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7191 if (DEBUG_DEXOPT) { 7192 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7193 } 7194 continue; 7195 } 7196 7197 if (DEBUG_DEXOPT) { 7198 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7199 } 7200 7201 if (!isFirstBoot()) { 7202 try { 7203 ActivityManagerNative.getDefault().showBootMessage( 7204 mContext.getResources().getString(R.string.android_upgrading_apk, 7205 curr, total), true); 7206 } catch (RemoteException e) { 7207 } 7208 } 7209 7210 performDexOpt(pkg.packageName, 7211 null /* instructionSet */, 7212 false /* checkProfiles */, 7213 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7214 false /* force */); 7215 } 7216 } 7217 7218 @Override 7219 public void notifyPackageUse(String packageName, int reason) { 7220 synchronized (mPackages) { 7221 PackageParser.Package p = mPackages.get(packageName); 7222 if (p == null) { 7223 return; 7224 } 7225 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7226 } 7227 } 7228 7229 // TODO: this is not used nor needed. Delete it. 7230 @Override 7231 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7232 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7233 getFullCompilerFilter(), false /* force */); 7234 } 7235 7236 @Override 7237 public boolean performDexOpt(String packageName, String instructionSet, 7238 boolean checkProfiles, int compileReason, boolean force) { 7239 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7240 getCompilerFilterForReason(compileReason), force); 7241 } 7242 7243 @Override 7244 public boolean performDexOptMode(String packageName, String instructionSet, 7245 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7246 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7247 targetCompilerFilter, force); 7248 } 7249 7250 private boolean performDexOptTraced(String packageName, String instructionSet, 7251 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7252 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7253 try { 7254 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7255 targetCompilerFilter, force); 7256 } finally { 7257 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7258 } 7259 } 7260 7261 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7262 // if the package can now be considered up to date for the given filter. 7263 private boolean performDexOptInternal(String packageName, String instructionSet, 7264 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7265 PackageParser.Package p; 7266 final String targetInstructionSet; 7267 synchronized (mPackages) { 7268 p = mPackages.get(packageName); 7269 if (p == null) { 7270 return false; 7271 } 7272 mPackageUsage.write(false); 7273 7274 targetInstructionSet = instructionSet != null ? instructionSet : 7275 getPrimaryInstructionSet(p.applicationInfo); 7276 } 7277 long callingId = Binder.clearCallingIdentity(); 7278 try { 7279 synchronized (mInstallLock) { 7280 final String[] instructionSets = new String[] { targetInstructionSet }; 7281 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7282 checkProfiles, targetCompilerFilter, force); 7283 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7284 } 7285 } finally { 7286 Binder.restoreCallingIdentity(callingId); 7287 } 7288 } 7289 7290 public ArraySet<String> getOptimizablePackages() { 7291 ArraySet<String> pkgs = new ArraySet<String>(); 7292 synchronized (mPackages) { 7293 for (PackageParser.Package p : mPackages.values()) { 7294 if (PackageDexOptimizer.canOptimizePackage(p)) { 7295 pkgs.add(p.packageName); 7296 } 7297 } 7298 } 7299 return pkgs; 7300 } 7301 7302 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7303 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7304 boolean force) { 7305 // Select the dex optimizer based on the force parameter. 7306 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7307 // allocate an object here. 7308 PackageDexOptimizer pdo = force 7309 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7310 : mPackageDexOptimizer; 7311 7312 // Optimize all dependencies first. Note: we ignore the return value and march on 7313 // on errors. 7314 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7315 if (!deps.isEmpty()) { 7316 for (PackageParser.Package depPackage : deps) { 7317 // TODO: Analyze and investigate if we (should) profile libraries. 7318 // Currently this will do a full compilation of the library by default. 7319 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7320 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7321 } 7322 } 7323 7324 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7325 } 7326 7327 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7328 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7329 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7330 Set<String> collectedNames = new HashSet<>(); 7331 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7332 7333 retValue.remove(p); 7334 7335 return retValue; 7336 } else { 7337 return Collections.emptyList(); 7338 } 7339 } 7340 7341 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7342 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7343 if (!collectedNames.contains(p.packageName)) { 7344 collectedNames.add(p.packageName); 7345 collected.add(p); 7346 7347 if (p.usesLibraries != null) { 7348 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7349 } 7350 if (p.usesOptionalLibraries != null) { 7351 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7352 collectedNames); 7353 } 7354 } 7355 } 7356 7357 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7358 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7359 for (String libName : libs) { 7360 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7361 if (libPkg != null) { 7362 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7363 } 7364 } 7365 } 7366 7367 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7368 synchronized (mPackages) { 7369 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7370 if (lib != null && lib.apk != null) { 7371 return mPackages.get(lib.apk); 7372 } 7373 } 7374 return null; 7375 } 7376 7377 public void shutdown() { 7378 mPackageUsage.write(true); 7379 } 7380 7381 @Override 7382 public void forceDexOpt(String packageName) { 7383 enforceSystemOrRoot("forceDexOpt"); 7384 7385 PackageParser.Package pkg; 7386 synchronized (mPackages) { 7387 pkg = mPackages.get(packageName); 7388 if (pkg == null) { 7389 throw new IllegalArgumentException("Unknown package: " + packageName); 7390 } 7391 } 7392 7393 synchronized (mInstallLock) { 7394 final String[] instructionSets = new String[] { 7395 getPrimaryInstructionSet(pkg.applicationInfo) }; 7396 7397 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7398 7399 // Whoever is calling forceDexOpt wants a fully compiled package. 7400 // Don't use profiles since that may cause compilation to be skipped. 7401 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7402 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7403 true /* force */); 7404 7405 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7406 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7407 throw new IllegalStateException("Failed to dexopt: " + res); 7408 } 7409 } 7410 } 7411 7412 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7413 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7414 Slog.w(TAG, "Unable to update from " + oldPkg.name 7415 + " to " + newPkg.packageName 7416 + ": old package not in system partition"); 7417 return false; 7418 } else if (mPackages.get(oldPkg.name) != null) { 7419 Slog.w(TAG, "Unable to update from " + oldPkg.name 7420 + " to " + newPkg.packageName 7421 + ": old package still exists"); 7422 return false; 7423 } 7424 return true; 7425 } 7426 7427 void removeCodePathLI(File codePath) { 7428 if (codePath.isDirectory()) { 7429 try { 7430 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7431 } catch (InstallerException e) { 7432 Slog.w(TAG, "Failed to remove code path", e); 7433 } 7434 } else { 7435 codePath.delete(); 7436 } 7437 } 7438 7439 private int[] resolveUserIds(int userId) { 7440 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7441 } 7442 7443 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7444 if (pkg == null) { 7445 Slog.wtf(TAG, "Package was null!", new Throwable()); 7446 return; 7447 } 7448 clearAppDataLeafLIF(pkg, userId, flags); 7449 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7450 for (int i = 0; i < childCount; i++) { 7451 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7452 } 7453 } 7454 7455 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7456 final PackageSetting ps; 7457 synchronized (mPackages) { 7458 ps = mSettings.mPackages.get(pkg.packageName); 7459 } 7460 for (int realUserId : resolveUserIds(userId)) { 7461 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7462 try { 7463 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7464 ceDataInode); 7465 } catch (InstallerException e) { 7466 Slog.w(TAG, String.valueOf(e)); 7467 } 7468 } 7469 } 7470 7471 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7472 if (pkg == null) { 7473 Slog.wtf(TAG, "Package was null!", new Throwable()); 7474 return; 7475 } 7476 destroyAppDataLeafLIF(pkg, userId, flags); 7477 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7478 for (int i = 0; i < childCount; i++) { 7479 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7480 } 7481 } 7482 7483 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7484 final PackageSetting ps; 7485 synchronized (mPackages) { 7486 ps = mSettings.mPackages.get(pkg.packageName); 7487 } 7488 for (int realUserId : resolveUserIds(userId)) { 7489 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7490 try { 7491 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7492 ceDataInode); 7493 } catch (InstallerException e) { 7494 Slog.w(TAG, String.valueOf(e)); 7495 } 7496 } 7497 } 7498 7499 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7500 if (pkg == null) { 7501 Slog.wtf(TAG, "Package was null!", new Throwable()); 7502 return; 7503 } 7504 destroyAppProfilesLeafLIF(pkg); 7505 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7506 for (int i = 0; i < childCount; i++) { 7507 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7508 } 7509 } 7510 7511 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7512 try { 7513 mInstaller.destroyAppProfiles(pkg.packageName); 7514 } catch (InstallerException e) { 7515 Slog.w(TAG, String.valueOf(e)); 7516 } 7517 } 7518 7519 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7520 if (pkg == null) { 7521 Slog.wtf(TAG, "Package was null!", new Throwable()); 7522 return; 7523 } 7524 clearAppProfilesLeafLIF(pkg); 7525 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7526 for (int i = 0; i < childCount; i++) { 7527 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7528 } 7529 } 7530 7531 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7532 try { 7533 mInstaller.clearAppProfiles(pkg.packageName); 7534 } catch (InstallerException e) { 7535 Slog.w(TAG, String.valueOf(e)); 7536 } 7537 } 7538 7539 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7540 long lastUpdateTime) { 7541 // Set parent install/update time 7542 PackageSetting ps = (PackageSetting) pkg.mExtras; 7543 if (ps != null) { 7544 ps.firstInstallTime = firstInstallTime; 7545 ps.lastUpdateTime = lastUpdateTime; 7546 } 7547 // Set children install/update time 7548 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7549 for (int i = 0; i < childCount; i++) { 7550 PackageParser.Package childPkg = pkg.childPackages.get(i); 7551 ps = (PackageSetting) childPkg.mExtras; 7552 if (ps != null) { 7553 ps.firstInstallTime = firstInstallTime; 7554 ps.lastUpdateTime = lastUpdateTime; 7555 } 7556 } 7557 } 7558 7559 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7560 PackageParser.Package changingLib) { 7561 if (file.path != null) { 7562 usesLibraryFiles.add(file.path); 7563 return; 7564 } 7565 PackageParser.Package p = mPackages.get(file.apk); 7566 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7567 // If we are doing this while in the middle of updating a library apk, 7568 // then we need to make sure to use that new apk for determining the 7569 // dependencies here. (We haven't yet finished committing the new apk 7570 // to the package manager state.) 7571 if (p == null || p.packageName.equals(changingLib.packageName)) { 7572 p = changingLib; 7573 } 7574 } 7575 if (p != null) { 7576 usesLibraryFiles.addAll(p.getAllCodePaths()); 7577 } 7578 } 7579 7580 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7581 PackageParser.Package changingLib) throws PackageManagerException { 7582 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7583 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7584 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7585 for (int i=0; i<N; i++) { 7586 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7587 if (file == null) { 7588 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7589 "Package " + pkg.packageName + " requires unavailable shared library " 7590 + pkg.usesLibraries.get(i) + "; failing!"); 7591 } 7592 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7593 } 7594 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7595 for (int i=0; i<N; i++) { 7596 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7597 if (file == null) { 7598 Slog.w(TAG, "Package " + pkg.packageName 7599 + " desires unavailable shared library " 7600 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7601 } else { 7602 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7603 } 7604 } 7605 N = usesLibraryFiles.size(); 7606 if (N > 0) { 7607 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7608 } else { 7609 pkg.usesLibraryFiles = null; 7610 } 7611 } 7612 } 7613 7614 private static boolean hasString(List<String> list, List<String> which) { 7615 if (list == null) { 7616 return false; 7617 } 7618 for (int i=list.size()-1; i>=0; i--) { 7619 for (int j=which.size()-1; j>=0; j--) { 7620 if (which.get(j).equals(list.get(i))) { 7621 return true; 7622 } 7623 } 7624 } 7625 return false; 7626 } 7627 7628 private void updateAllSharedLibrariesLPw() { 7629 for (PackageParser.Package pkg : mPackages.values()) { 7630 try { 7631 updateSharedLibrariesLPw(pkg, null); 7632 } catch (PackageManagerException e) { 7633 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7634 } 7635 } 7636 } 7637 7638 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7639 PackageParser.Package changingPkg) { 7640 ArrayList<PackageParser.Package> res = null; 7641 for (PackageParser.Package pkg : mPackages.values()) { 7642 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7643 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7644 if (res == null) { 7645 res = new ArrayList<PackageParser.Package>(); 7646 } 7647 res.add(pkg); 7648 try { 7649 updateSharedLibrariesLPw(pkg, changingPkg); 7650 } catch (PackageManagerException e) { 7651 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7652 } 7653 } 7654 } 7655 return res; 7656 } 7657 7658 /** 7659 * Derive the value of the {@code cpuAbiOverride} based on the provided 7660 * value and an optional stored value from the package settings. 7661 */ 7662 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7663 String cpuAbiOverride = null; 7664 7665 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7666 cpuAbiOverride = null; 7667 } else if (abiOverride != null) { 7668 cpuAbiOverride = abiOverride; 7669 } else if (settings != null) { 7670 cpuAbiOverride = settings.cpuAbiOverrideString; 7671 } 7672 7673 return cpuAbiOverride; 7674 } 7675 7676 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7677 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7678 throws PackageManagerException { 7679 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7680 // If the package has children and this is the first dive in the function 7681 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7682 // whether all packages (parent and children) would be successfully scanned 7683 // before the actual scan since scanning mutates internal state and we want 7684 // to atomically install the package and its children. 7685 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7686 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7687 scanFlags |= SCAN_CHECK_ONLY; 7688 } 7689 } else { 7690 scanFlags &= ~SCAN_CHECK_ONLY; 7691 } 7692 7693 final PackageParser.Package scannedPkg; 7694 try { 7695 // Scan the parent 7696 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7697 // Scan the children 7698 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7699 for (int i = 0; i < childCount; i++) { 7700 PackageParser.Package childPkg = pkg.childPackages.get(i); 7701 scanPackageLI(childPkg, policyFlags, 7702 scanFlags, currentTime, user); 7703 } 7704 } finally { 7705 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7706 } 7707 7708 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7709 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7710 } 7711 7712 return scannedPkg; 7713 } 7714 7715 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7716 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7717 boolean success = false; 7718 try { 7719 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7720 currentTime, user); 7721 success = true; 7722 return res; 7723 } finally { 7724 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7725 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7726 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7727 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7728 destroyAppProfilesLIF(pkg); 7729 } 7730 } 7731 } 7732 7733 /** 7734 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7735 */ 7736 private static boolean apkHasCode(String fileName) { 7737 StrictJarFile jarFile = null; 7738 try { 7739 jarFile = new StrictJarFile(fileName, 7740 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7741 return jarFile.findEntry("classes.dex") != null; 7742 } catch (IOException ignore) { 7743 } finally { 7744 try { 7745 jarFile.close(); 7746 } catch (IOException ignore) {} 7747 } 7748 return false; 7749 } 7750 7751 /** 7752 * Enforces code policy for the package. This ensures that if an APK has 7753 * declared hasCode="true" in its manifest that the APK actually contains 7754 * code. 7755 * 7756 * @throws PackageManagerException If bytecode could not be found when it should exist 7757 */ 7758 private static void enforceCodePolicy(PackageParser.Package pkg) 7759 throws PackageManagerException { 7760 final boolean shouldHaveCode = 7761 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7762 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7763 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7764 "Package " + pkg.baseCodePath + " code is missing"); 7765 } 7766 7767 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7768 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7769 final boolean splitShouldHaveCode = 7770 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7771 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7772 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7773 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7774 } 7775 } 7776 } 7777 } 7778 7779 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7780 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7781 throws PackageManagerException { 7782 final File scanFile = new File(pkg.codePath); 7783 if (pkg.applicationInfo.getCodePath() == null || 7784 pkg.applicationInfo.getResourcePath() == null) { 7785 // Bail out. The resource and code paths haven't been set. 7786 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7787 "Code and resource paths haven't been set correctly"); 7788 } 7789 7790 // Apply policy 7791 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7792 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7793 if (pkg.applicationInfo.isDirectBootAware()) { 7794 // we're direct boot aware; set for all components 7795 for (PackageParser.Service s : pkg.services) { 7796 s.info.encryptionAware = s.info.directBootAware = true; 7797 } 7798 for (PackageParser.Provider p : pkg.providers) { 7799 p.info.encryptionAware = p.info.directBootAware = true; 7800 } 7801 for (PackageParser.Activity a : pkg.activities) { 7802 a.info.encryptionAware = a.info.directBootAware = true; 7803 } 7804 for (PackageParser.Activity r : pkg.receivers) { 7805 r.info.encryptionAware = r.info.directBootAware = true; 7806 } 7807 } 7808 } else { 7809 // Only allow system apps to be flagged as core apps. 7810 pkg.coreApp = false; 7811 // clear flags not applicable to regular apps 7812 pkg.applicationInfo.privateFlags &= 7813 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7814 pkg.applicationInfo.privateFlags &= 7815 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7816 } 7817 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7818 7819 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7820 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7821 } 7822 7823 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7824 enforceCodePolicy(pkg); 7825 } 7826 7827 if (mCustomResolverComponentName != null && 7828 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7829 setUpCustomResolverActivity(pkg); 7830 } 7831 7832 if (pkg.packageName.equals("android")) { 7833 synchronized (mPackages) { 7834 if (mAndroidApplication != null) { 7835 Slog.w(TAG, "*************************************************"); 7836 Slog.w(TAG, "Core android package being redefined. Skipping."); 7837 Slog.w(TAG, " file=" + scanFile); 7838 Slog.w(TAG, "*************************************************"); 7839 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7840 "Core android package being redefined. Skipping."); 7841 } 7842 7843 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7844 // Set up information for our fall-back user intent resolution activity. 7845 mPlatformPackage = pkg; 7846 pkg.mVersionCode = mSdkVersion; 7847 mAndroidApplication = pkg.applicationInfo; 7848 7849 if (!mResolverReplaced) { 7850 mResolveActivity.applicationInfo = mAndroidApplication; 7851 mResolveActivity.name = ResolverActivity.class.getName(); 7852 mResolveActivity.packageName = mAndroidApplication.packageName; 7853 mResolveActivity.processName = "system:ui"; 7854 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7855 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7856 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7857 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7858 mResolveActivity.exported = true; 7859 mResolveActivity.enabled = true; 7860 mResolveInfo.activityInfo = mResolveActivity; 7861 mResolveInfo.priority = 0; 7862 mResolveInfo.preferredOrder = 0; 7863 mResolveInfo.match = 0; 7864 mResolveComponentName = new ComponentName( 7865 mAndroidApplication.packageName, mResolveActivity.name); 7866 } 7867 } 7868 } 7869 } 7870 7871 if (DEBUG_PACKAGE_SCANNING) { 7872 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7873 Log.d(TAG, "Scanning package " + pkg.packageName); 7874 } 7875 7876 synchronized (mPackages) { 7877 if (mPackages.containsKey(pkg.packageName) 7878 || mSharedLibraries.containsKey(pkg.packageName)) { 7879 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7880 "Application package " + pkg.packageName 7881 + " already installed. Skipping duplicate."); 7882 } 7883 7884 // If we're only installing presumed-existing packages, require that the 7885 // scanned APK is both already known and at the path previously established 7886 // for it. Previously unknown packages we pick up normally, but if we have an 7887 // a priori expectation about this package's install presence, enforce it. 7888 // With a singular exception for new system packages. When an OTA contains 7889 // a new system package, we allow the codepath to change from a system location 7890 // to the user-installed location. If we don't allow this change, any newer, 7891 // user-installed version of the application will be ignored. 7892 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7893 if (mExpectingBetter.containsKey(pkg.packageName)) { 7894 logCriticalInfo(Log.WARN, 7895 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7896 } else { 7897 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7898 if (known != null) { 7899 if (DEBUG_PACKAGE_SCANNING) { 7900 Log.d(TAG, "Examining " + pkg.codePath 7901 + " and requiring known paths " + known.codePathString 7902 + " & " + known.resourcePathString); 7903 } 7904 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7905 || !pkg.applicationInfo.getResourcePath().equals( 7906 known.resourcePathString)) { 7907 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7908 "Application package " + pkg.packageName 7909 + " found at " + pkg.applicationInfo.getCodePath() 7910 + " but expected at " + known.codePathString 7911 + "; ignoring."); 7912 } 7913 } 7914 } 7915 } 7916 } 7917 7918 // Initialize package source and resource directories 7919 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7920 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7921 7922 SharedUserSetting suid = null; 7923 PackageSetting pkgSetting = null; 7924 7925 if (!isSystemApp(pkg)) { 7926 // Only system apps can use these features. 7927 pkg.mOriginalPackages = null; 7928 pkg.mRealPackage = null; 7929 pkg.mAdoptPermissions = null; 7930 } 7931 7932 // Getting the package setting may have a side-effect, so if we 7933 // are only checking if scan would succeed, stash a copy of the 7934 // old setting to restore at the end. 7935 PackageSetting nonMutatedPs = null; 7936 7937 // writer 7938 synchronized (mPackages) { 7939 if (pkg.mSharedUserId != null) { 7940 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7941 if (suid == null) { 7942 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7943 "Creating application package " + pkg.packageName 7944 + " for shared user failed"); 7945 } 7946 if (DEBUG_PACKAGE_SCANNING) { 7947 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7948 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7949 + "): packages=" + suid.packages); 7950 } 7951 } 7952 7953 // Check if we are renaming from an original package name. 7954 PackageSetting origPackage = null; 7955 String realName = null; 7956 if (pkg.mOriginalPackages != null) { 7957 // This package may need to be renamed to a previously 7958 // installed name. Let's check on that... 7959 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7960 if (pkg.mOriginalPackages.contains(renamed)) { 7961 // This package had originally been installed as the 7962 // original name, and we have already taken care of 7963 // transitioning to the new one. Just update the new 7964 // one to continue using the old name. 7965 realName = pkg.mRealPackage; 7966 if (!pkg.packageName.equals(renamed)) { 7967 // Callers into this function may have already taken 7968 // care of renaming the package; only do it here if 7969 // it is not already done. 7970 pkg.setPackageName(renamed); 7971 } 7972 7973 } else { 7974 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7975 if ((origPackage = mSettings.peekPackageLPr( 7976 pkg.mOriginalPackages.get(i))) != null) { 7977 // We do have the package already installed under its 7978 // original name... should we use it? 7979 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7980 // New package is not compatible with original. 7981 origPackage = null; 7982 continue; 7983 } else if (origPackage.sharedUser != null) { 7984 // Make sure uid is compatible between packages. 7985 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7986 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7987 + " to " + pkg.packageName + ": old uid " 7988 + origPackage.sharedUser.name 7989 + " differs from " + pkg.mSharedUserId); 7990 origPackage = null; 7991 continue; 7992 } 7993 // TODO: Add case when shared user id is added [b/28144775] 7994 } else { 7995 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7996 + pkg.packageName + " to old name " + origPackage.name); 7997 } 7998 break; 7999 } 8000 } 8001 } 8002 } 8003 8004 if (mTransferedPackages.contains(pkg.packageName)) { 8005 Slog.w(TAG, "Package " + pkg.packageName 8006 + " was transferred to another, but its .apk remains"); 8007 } 8008 8009 // See comments in nonMutatedPs declaration 8010 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8011 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8012 if (foundPs != null) { 8013 nonMutatedPs = new PackageSetting(foundPs); 8014 } 8015 } 8016 8017 // Just create the setting, don't add it yet. For already existing packages 8018 // the PkgSetting exists already and doesn't have to be created. 8019 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8020 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8021 pkg.applicationInfo.primaryCpuAbi, 8022 pkg.applicationInfo.secondaryCpuAbi, 8023 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8024 user, false); 8025 if (pkgSetting == null) { 8026 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8027 "Creating application package " + pkg.packageName + " failed"); 8028 } 8029 8030 if (pkgSetting.origPackage != null) { 8031 // If we are first transitioning from an original package, 8032 // fix up the new package's name now. We need to do this after 8033 // looking up the package under its new name, so getPackageLP 8034 // can take care of fiddling things correctly. 8035 pkg.setPackageName(origPackage.name); 8036 8037 // File a report about this. 8038 String msg = "New package " + pkgSetting.realName 8039 + " renamed to replace old package " + pkgSetting.name; 8040 reportSettingsProblem(Log.WARN, msg); 8041 8042 // Make a note of it. 8043 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8044 mTransferedPackages.add(origPackage.name); 8045 } 8046 8047 // No longer need to retain this. 8048 pkgSetting.origPackage = null; 8049 } 8050 8051 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8052 // Make a note of it. 8053 mTransferedPackages.add(pkg.packageName); 8054 } 8055 8056 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8058 } 8059 8060 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8061 // Check all shared libraries and map to their actual file path. 8062 // We only do this here for apps not on a system dir, because those 8063 // are the only ones that can fail an install due to this. We 8064 // will take care of the system apps by updating all of their 8065 // library paths after the scan is done. 8066 updateSharedLibrariesLPw(pkg, null); 8067 } 8068 8069 if (mFoundPolicyFile) { 8070 SELinuxMMAC.assignSeinfoValue(pkg); 8071 } 8072 8073 pkg.applicationInfo.uid = pkgSetting.appId; 8074 pkg.mExtras = pkgSetting; 8075 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8076 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8077 // We just determined the app is signed correctly, so bring 8078 // over the latest parsed certs. 8079 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8080 } else { 8081 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8082 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8083 "Package " + pkg.packageName + " upgrade keys do not match the " 8084 + "previously installed version"); 8085 } else { 8086 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8087 String msg = "System package " + pkg.packageName 8088 + " signature changed; retaining data."; 8089 reportSettingsProblem(Log.WARN, msg); 8090 } 8091 } 8092 } else { 8093 try { 8094 verifySignaturesLP(pkgSetting, pkg); 8095 // We just determined the app is signed correctly, so bring 8096 // over the latest parsed certs. 8097 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8098 } catch (PackageManagerException e) { 8099 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8100 throw e; 8101 } 8102 // The signature has changed, but this package is in the system 8103 // image... let's recover! 8104 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8105 // However... if this package is part of a shared user, but it 8106 // doesn't match the signature of the shared user, let's fail. 8107 // What this means is that you can't change the signatures 8108 // associated with an overall shared user, which doesn't seem all 8109 // that unreasonable. 8110 if (pkgSetting.sharedUser != null) { 8111 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8112 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8113 throw new PackageManagerException( 8114 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8115 "Signature mismatch for shared user: " 8116 + pkgSetting.sharedUser); 8117 } 8118 } 8119 // File a report about this. 8120 String msg = "System package " + pkg.packageName 8121 + " signature changed; retaining data."; 8122 reportSettingsProblem(Log.WARN, msg); 8123 } 8124 } 8125 // Verify that this new package doesn't have any content providers 8126 // that conflict with existing packages. Only do this if the 8127 // package isn't already installed, since we don't want to break 8128 // things that are installed. 8129 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8130 final int N = pkg.providers.size(); 8131 int i; 8132 for (i=0; i<N; i++) { 8133 PackageParser.Provider p = pkg.providers.get(i); 8134 if (p.info.authority != null) { 8135 String names[] = p.info.authority.split(";"); 8136 for (int j = 0; j < names.length; j++) { 8137 if (mProvidersByAuthority.containsKey(names[j])) { 8138 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8139 final String otherPackageName = 8140 ((other != null && other.getComponentName() != null) ? 8141 other.getComponentName().getPackageName() : "?"); 8142 throw new PackageManagerException( 8143 INSTALL_FAILED_CONFLICTING_PROVIDER, 8144 "Can't install because provider name " + names[j] 8145 + " (in package " + pkg.applicationInfo.packageName 8146 + ") is already used by " + otherPackageName); 8147 } 8148 } 8149 } 8150 } 8151 } 8152 8153 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8154 // This package wants to adopt ownership of permissions from 8155 // another package. 8156 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8157 final String origName = pkg.mAdoptPermissions.get(i); 8158 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8159 if (orig != null) { 8160 if (verifyPackageUpdateLPr(orig, pkg)) { 8161 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8162 + pkg.packageName); 8163 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8164 } 8165 } 8166 } 8167 } 8168 } 8169 8170 final String pkgName = pkg.packageName; 8171 8172 final long scanFileTime = scanFile.lastModified(); 8173 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8174 pkg.applicationInfo.processName = fixProcessName( 8175 pkg.applicationInfo.packageName, 8176 pkg.applicationInfo.processName, 8177 pkg.applicationInfo.uid); 8178 8179 if (pkg != mPlatformPackage) { 8180 // Get all of our default paths setup 8181 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8182 } 8183 8184 final String path = scanFile.getPath(); 8185 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8186 8187 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8188 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8189 8190 // Some system apps still use directory structure for native libraries 8191 // in which case we might end up not detecting abi solely based on apk 8192 // structure. Try to detect abi based on directory structure. 8193 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8194 pkg.applicationInfo.primaryCpuAbi == null) { 8195 setBundledAppAbisAndRoots(pkg, pkgSetting); 8196 setNativeLibraryPaths(pkg); 8197 } 8198 8199 } else { 8200 if ((scanFlags & SCAN_MOVE) != 0) { 8201 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8202 // but we already have this packages package info in the PackageSetting. We just 8203 // use that and derive the native library path based on the new codepath. 8204 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8205 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8206 } 8207 8208 // Set native library paths again. For moves, the path will be updated based on the 8209 // ABIs we've determined above. For non-moves, the path will be updated based on the 8210 // ABIs we determined during compilation, but the path will depend on the final 8211 // package path (after the rename away from the stage path). 8212 setNativeLibraryPaths(pkg); 8213 } 8214 8215 // This is a special case for the "system" package, where the ABI is 8216 // dictated by the zygote configuration (and init.rc). We should keep track 8217 // of this ABI so that we can deal with "normal" applications that run under 8218 // the same UID correctly. 8219 if (mPlatformPackage == pkg) { 8220 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8221 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8222 } 8223 8224 // If there's a mismatch between the abi-override in the package setting 8225 // and the abiOverride specified for the install. Warn about this because we 8226 // would've already compiled the app without taking the package setting into 8227 // account. 8228 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8229 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8230 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8231 " for package " + pkg.packageName); 8232 } 8233 } 8234 8235 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8236 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8237 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8238 8239 // Copy the derived override back to the parsed package, so that we can 8240 // update the package settings accordingly. 8241 pkg.cpuAbiOverride = cpuAbiOverride; 8242 8243 if (DEBUG_ABI_SELECTION) { 8244 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8245 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8246 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8247 } 8248 8249 // Push the derived path down into PackageSettings so we know what to 8250 // clean up at uninstall time. 8251 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8252 8253 if (DEBUG_ABI_SELECTION) { 8254 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8255 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8256 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8257 } 8258 8259 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8260 // We don't do this here during boot because we can do it all 8261 // at once after scanning all existing packages. 8262 // 8263 // We also do this *before* we perform dexopt on this package, so that 8264 // we can avoid redundant dexopts, and also to make sure we've got the 8265 // code and package path correct. 8266 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8267 pkg, true /* boot complete */); 8268 } 8269 8270 if (mFactoryTest && pkg.requestedPermissions.contains( 8271 android.Manifest.permission.FACTORY_TEST)) { 8272 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8273 } 8274 8275 ArrayList<PackageParser.Package> clientLibPkgs = null; 8276 8277 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8278 if (nonMutatedPs != null) { 8279 synchronized (mPackages) { 8280 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8281 } 8282 } 8283 return pkg; 8284 } 8285 8286 // Only privileged apps and updated privileged apps can add child packages. 8287 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8288 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8289 throw new PackageManagerException("Only privileged apps and updated " 8290 + "privileged apps can add child packages. Ignoring package " 8291 + pkg.packageName); 8292 } 8293 final int childCount = pkg.childPackages.size(); 8294 for (int i = 0; i < childCount; i++) { 8295 PackageParser.Package childPkg = pkg.childPackages.get(i); 8296 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8297 childPkg.packageName)) { 8298 throw new PackageManagerException("Cannot override a child package of " 8299 + "another disabled system app. Ignoring package " + pkg.packageName); 8300 } 8301 } 8302 } 8303 8304 // writer 8305 synchronized (mPackages) { 8306 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8307 // Only system apps can add new shared libraries. 8308 if (pkg.libraryNames != null) { 8309 for (int i=0; i<pkg.libraryNames.size(); i++) { 8310 String name = pkg.libraryNames.get(i); 8311 boolean allowed = false; 8312 if (pkg.isUpdatedSystemApp()) { 8313 // New library entries can only be added through the 8314 // system image. This is important to get rid of a lot 8315 // of nasty edge cases: for example if we allowed a non- 8316 // system update of the app to add a library, then uninstalling 8317 // the update would make the library go away, and assumptions 8318 // we made such as through app install filtering would now 8319 // have allowed apps on the device which aren't compatible 8320 // with it. Better to just have the restriction here, be 8321 // conservative, and create many fewer cases that can negatively 8322 // impact the user experience. 8323 final PackageSetting sysPs = mSettings 8324 .getDisabledSystemPkgLPr(pkg.packageName); 8325 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8326 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8327 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8328 allowed = true; 8329 break; 8330 } 8331 } 8332 } 8333 } else { 8334 allowed = true; 8335 } 8336 if (allowed) { 8337 if (!mSharedLibraries.containsKey(name)) { 8338 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8339 } else if (!name.equals(pkg.packageName)) { 8340 Slog.w(TAG, "Package " + pkg.packageName + " library " 8341 + name + " already exists; skipping"); 8342 } 8343 } else { 8344 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8345 + name + " that is not declared on system image; skipping"); 8346 } 8347 } 8348 if ((scanFlags & SCAN_BOOTING) == 0) { 8349 // If we are not booting, we need to update any applications 8350 // that are clients of our shared library. If we are booting, 8351 // this will all be done once the scan is complete. 8352 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8353 } 8354 } 8355 } 8356 } 8357 8358 if ((scanFlags & SCAN_BOOTING) != 0) { 8359 // No apps can run during boot scan, so they don't need to be frozen 8360 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8361 // Caller asked to not kill app, so it's probably not frozen 8362 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8363 // Caller asked us to ignore frozen check for some reason; they 8364 // probably didn't know the package name 8365 } else { 8366 // We're doing major surgery on this package, so it better be frozen 8367 // right now to keep it from launching 8368 checkPackageFrozen(pkgName); 8369 } 8370 8371 // Also need to kill any apps that are dependent on the library. 8372 if (clientLibPkgs != null) { 8373 for (int i=0; i<clientLibPkgs.size(); i++) { 8374 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8375 killApplication(clientPkg.applicationInfo.packageName, 8376 clientPkg.applicationInfo.uid, "update lib"); 8377 } 8378 } 8379 8380 // Make sure we're not adding any bogus keyset info 8381 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8382 ksms.assertScannedPackageValid(pkg); 8383 8384 // writer 8385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8386 8387 boolean createIdmapFailed = false; 8388 synchronized (mPackages) { 8389 // We don't expect installation to fail beyond this point 8390 8391 // Add the new setting to mSettings 8392 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8393 // Add the new setting to mPackages 8394 mPackages.put(pkg.applicationInfo.packageName, pkg); 8395 // Make sure we don't accidentally delete its data. 8396 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8397 while (iter.hasNext()) { 8398 PackageCleanItem item = iter.next(); 8399 if (pkgName.equals(item.packageName)) { 8400 iter.remove(); 8401 } 8402 } 8403 8404 // Take care of first install / last update times. 8405 if (currentTime != 0) { 8406 if (pkgSetting.firstInstallTime == 0) { 8407 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8408 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8409 pkgSetting.lastUpdateTime = currentTime; 8410 } 8411 } else if (pkgSetting.firstInstallTime == 0) { 8412 // We need *something*. Take time time stamp of the file. 8413 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8414 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8415 if (scanFileTime != pkgSetting.timeStamp) { 8416 // A package on the system image has changed; consider this 8417 // to be an update. 8418 pkgSetting.lastUpdateTime = scanFileTime; 8419 } 8420 } 8421 8422 // Add the package's KeySets to the global KeySetManagerService 8423 ksms.addScannedPackageLPw(pkg); 8424 8425 int N = pkg.providers.size(); 8426 StringBuilder r = null; 8427 int i; 8428 for (i=0; i<N; i++) { 8429 PackageParser.Provider p = pkg.providers.get(i); 8430 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8431 p.info.processName, pkg.applicationInfo.uid); 8432 mProviders.addProvider(p); 8433 p.syncable = p.info.isSyncable; 8434 if (p.info.authority != null) { 8435 String names[] = p.info.authority.split(";"); 8436 p.info.authority = null; 8437 for (int j = 0; j < names.length; j++) { 8438 if (j == 1 && p.syncable) { 8439 // We only want the first authority for a provider to possibly be 8440 // syncable, so if we already added this provider using a different 8441 // authority clear the syncable flag. We copy the provider before 8442 // changing it because the mProviders object contains a reference 8443 // to a provider that we don't want to change. 8444 // Only do this for the second authority since the resulting provider 8445 // object can be the same for all future authorities for this provider. 8446 p = new PackageParser.Provider(p); 8447 p.syncable = false; 8448 } 8449 if (!mProvidersByAuthority.containsKey(names[j])) { 8450 mProvidersByAuthority.put(names[j], p); 8451 if (p.info.authority == null) { 8452 p.info.authority = names[j]; 8453 } else { 8454 p.info.authority = p.info.authority + ";" + names[j]; 8455 } 8456 if (DEBUG_PACKAGE_SCANNING) { 8457 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8458 Log.d(TAG, "Registered content provider: " + names[j] 8459 + ", className = " + p.info.name + ", isSyncable = " 8460 + p.info.isSyncable); 8461 } 8462 } else { 8463 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8464 Slog.w(TAG, "Skipping provider name " + names[j] + 8465 " (in package " + pkg.applicationInfo.packageName + 8466 "): name already used by " 8467 + ((other != null && other.getComponentName() != null) 8468 ? other.getComponentName().getPackageName() : "?")); 8469 } 8470 } 8471 } 8472 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8473 if (r == null) { 8474 r = new StringBuilder(256); 8475 } else { 8476 r.append(' '); 8477 } 8478 r.append(p.info.name); 8479 } 8480 } 8481 if (r != null) { 8482 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8483 } 8484 8485 N = pkg.services.size(); 8486 r = null; 8487 for (i=0; i<N; i++) { 8488 PackageParser.Service s = pkg.services.get(i); 8489 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8490 s.info.processName, pkg.applicationInfo.uid); 8491 mServices.addService(s); 8492 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8493 if (r == null) { 8494 r = new StringBuilder(256); 8495 } else { 8496 r.append(' '); 8497 } 8498 r.append(s.info.name); 8499 } 8500 } 8501 if (r != null) { 8502 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8503 } 8504 8505 N = pkg.receivers.size(); 8506 r = null; 8507 for (i=0; i<N; i++) { 8508 PackageParser.Activity a = pkg.receivers.get(i); 8509 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8510 a.info.processName, pkg.applicationInfo.uid); 8511 mReceivers.addActivity(a, "receiver"); 8512 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8513 if (r == null) { 8514 r = new StringBuilder(256); 8515 } else { 8516 r.append(' '); 8517 } 8518 r.append(a.info.name); 8519 } 8520 } 8521 if (r != null) { 8522 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8523 } 8524 8525 N = pkg.activities.size(); 8526 r = null; 8527 for (i=0; i<N; i++) { 8528 PackageParser.Activity a = pkg.activities.get(i); 8529 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8530 a.info.processName, pkg.applicationInfo.uid); 8531 mActivities.addActivity(a, "activity"); 8532 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8533 if (r == null) { 8534 r = new StringBuilder(256); 8535 } else { 8536 r.append(' '); 8537 } 8538 r.append(a.info.name); 8539 } 8540 } 8541 if (r != null) { 8542 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8543 } 8544 8545 N = pkg.permissionGroups.size(); 8546 r = null; 8547 for (i=0; i<N; i++) { 8548 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8549 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8550 if (cur == null) { 8551 mPermissionGroups.put(pg.info.name, pg); 8552 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8553 if (r == null) { 8554 r = new StringBuilder(256); 8555 } else { 8556 r.append(' '); 8557 } 8558 r.append(pg.info.name); 8559 } 8560 } else { 8561 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8562 + pg.info.packageName + " ignored: original from " 8563 + cur.info.packageName); 8564 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8565 if (r == null) { 8566 r = new StringBuilder(256); 8567 } else { 8568 r.append(' '); 8569 } 8570 r.append("DUP:"); 8571 r.append(pg.info.name); 8572 } 8573 } 8574 } 8575 if (r != null) { 8576 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8577 } 8578 8579 N = pkg.permissions.size(); 8580 r = null; 8581 for (i=0; i<N; i++) { 8582 PackageParser.Permission p = pkg.permissions.get(i); 8583 8584 // Assume by default that we did not install this permission into the system. 8585 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8586 8587 // Now that permission groups have a special meaning, we ignore permission 8588 // groups for legacy apps to prevent unexpected behavior. In particular, 8589 // permissions for one app being granted to someone just becase they happen 8590 // to be in a group defined by another app (before this had no implications). 8591 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8592 p.group = mPermissionGroups.get(p.info.group); 8593 // Warn for a permission in an unknown group. 8594 if (p.info.group != null && p.group == null) { 8595 Slog.w(TAG, "Permission " + p.info.name + " from package " 8596 + p.info.packageName + " in an unknown group " + p.info.group); 8597 } 8598 } 8599 8600 ArrayMap<String, BasePermission> permissionMap = 8601 p.tree ? mSettings.mPermissionTrees 8602 : mSettings.mPermissions; 8603 BasePermission bp = permissionMap.get(p.info.name); 8604 8605 // Allow system apps to redefine non-system permissions 8606 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8607 final boolean currentOwnerIsSystem = (bp.perm != null 8608 && isSystemApp(bp.perm.owner)); 8609 if (isSystemApp(p.owner)) { 8610 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8611 // It's a built-in permission and no owner, take ownership now 8612 bp.packageSetting = pkgSetting; 8613 bp.perm = p; 8614 bp.uid = pkg.applicationInfo.uid; 8615 bp.sourcePackage = p.info.packageName; 8616 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8617 } else if (!currentOwnerIsSystem) { 8618 String msg = "New decl " + p.owner + " of permission " 8619 + p.info.name + " is system; overriding " + bp.sourcePackage; 8620 reportSettingsProblem(Log.WARN, msg); 8621 bp = null; 8622 } 8623 } 8624 } 8625 8626 if (bp == null) { 8627 bp = new BasePermission(p.info.name, p.info.packageName, 8628 BasePermission.TYPE_NORMAL); 8629 permissionMap.put(p.info.name, bp); 8630 } 8631 8632 if (bp.perm == null) { 8633 if (bp.sourcePackage == null 8634 || bp.sourcePackage.equals(p.info.packageName)) { 8635 BasePermission tree = findPermissionTreeLP(p.info.name); 8636 if (tree == null 8637 || tree.sourcePackage.equals(p.info.packageName)) { 8638 bp.packageSetting = pkgSetting; 8639 bp.perm = p; 8640 bp.uid = pkg.applicationInfo.uid; 8641 bp.sourcePackage = p.info.packageName; 8642 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8643 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8644 if (r == null) { 8645 r = new StringBuilder(256); 8646 } else { 8647 r.append(' '); 8648 } 8649 r.append(p.info.name); 8650 } 8651 } else { 8652 Slog.w(TAG, "Permission " + p.info.name + " from package " 8653 + p.info.packageName + " ignored: base tree " 8654 + tree.name + " is from package " 8655 + tree.sourcePackage); 8656 } 8657 } else { 8658 Slog.w(TAG, "Permission " + p.info.name + " from package " 8659 + p.info.packageName + " ignored: original from " 8660 + bp.sourcePackage); 8661 } 8662 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8663 if (r == null) { 8664 r = new StringBuilder(256); 8665 } else { 8666 r.append(' '); 8667 } 8668 r.append("DUP:"); 8669 r.append(p.info.name); 8670 } 8671 if (bp.perm == p) { 8672 bp.protectionLevel = p.info.protectionLevel; 8673 } 8674 } 8675 8676 if (r != null) { 8677 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8678 } 8679 8680 N = pkg.instrumentation.size(); 8681 r = null; 8682 for (i=0; i<N; i++) { 8683 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8684 a.info.packageName = pkg.applicationInfo.packageName; 8685 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8686 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8687 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8688 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8689 a.info.dataDir = pkg.applicationInfo.dataDir; 8690 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8691 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8692 8693 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8694 // need other information about the application, like the ABI and what not ? 8695 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8696 mInstrumentation.put(a.getComponentName(), a); 8697 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8698 if (r == null) { 8699 r = new StringBuilder(256); 8700 } else { 8701 r.append(' '); 8702 } 8703 r.append(a.info.name); 8704 } 8705 } 8706 if (r != null) { 8707 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8708 } 8709 8710 if (pkg.protectedBroadcasts != null) { 8711 N = pkg.protectedBroadcasts.size(); 8712 for (i=0; i<N; i++) { 8713 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8714 } 8715 } 8716 8717 pkgSetting.setTimeStamp(scanFileTime); 8718 8719 // Create idmap files for pairs of (packages, overlay packages). 8720 // Note: "android", ie framework-res.apk, is handled by native layers. 8721 if (pkg.mOverlayTarget != null) { 8722 // This is an overlay package. 8723 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8724 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8725 mOverlays.put(pkg.mOverlayTarget, 8726 new ArrayMap<String, PackageParser.Package>()); 8727 } 8728 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8729 map.put(pkg.packageName, pkg); 8730 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8731 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8732 createIdmapFailed = true; 8733 } 8734 } 8735 } else if (mOverlays.containsKey(pkg.packageName) && 8736 !pkg.packageName.equals("android")) { 8737 // This is a regular package, with one or more known overlay packages. 8738 createIdmapsForPackageLI(pkg); 8739 } 8740 } 8741 8742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8743 8744 if (createIdmapFailed) { 8745 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8746 "scanPackageLI failed to createIdmap"); 8747 } 8748 return pkg; 8749 } 8750 8751 /** 8752 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8753 * is derived purely on the basis of the contents of {@code scanFile} and 8754 * {@code cpuAbiOverride}. 8755 * 8756 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8757 */ 8758 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8759 String cpuAbiOverride, boolean extractLibs) 8760 throws PackageManagerException { 8761 // TODO: We can probably be smarter about this stuff. For installed apps, 8762 // we can calculate this information at install time once and for all. For 8763 // system apps, we can probably assume that this information doesn't change 8764 // after the first boot scan. As things stand, we do lots of unnecessary work. 8765 8766 // Give ourselves some initial paths; we'll come back for another 8767 // pass once we've determined ABI below. 8768 setNativeLibraryPaths(pkg); 8769 8770 // We would never need to extract libs for forward-locked and external packages, 8771 // since the container service will do it for us. We shouldn't attempt to 8772 // extract libs from system app when it was not updated. 8773 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8774 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8775 extractLibs = false; 8776 } 8777 8778 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8779 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8780 8781 NativeLibraryHelper.Handle handle = null; 8782 try { 8783 handle = NativeLibraryHelper.Handle.create(pkg); 8784 // TODO(multiArch): This can be null for apps that didn't go through the 8785 // usual installation process. We can calculate it again, like we 8786 // do during install time. 8787 // 8788 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8789 // unnecessary. 8790 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8791 8792 // Null out the abis so that they can be recalculated. 8793 pkg.applicationInfo.primaryCpuAbi = null; 8794 pkg.applicationInfo.secondaryCpuAbi = null; 8795 if (isMultiArch(pkg.applicationInfo)) { 8796 // Warn if we've set an abiOverride for multi-lib packages.. 8797 // By definition, we need to copy both 32 and 64 bit libraries for 8798 // such packages. 8799 if (pkg.cpuAbiOverride != null 8800 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8801 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8802 } 8803 8804 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8805 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8806 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8807 if (extractLibs) { 8808 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8809 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8810 useIsaSpecificSubdirs); 8811 } else { 8812 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8813 } 8814 } 8815 8816 maybeThrowExceptionForMultiArchCopy( 8817 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8818 8819 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8820 if (extractLibs) { 8821 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8822 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8823 useIsaSpecificSubdirs); 8824 } else { 8825 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8826 } 8827 } 8828 8829 maybeThrowExceptionForMultiArchCopy( 8830 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8831 8832 if (abi64 >= 0) { 8833 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8834 } 8835 8836 if (abi32 >= 0) { 8837 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8838 if (abi64 >= 0) { 8839 if (pkg.use32bitAbi) { 8840 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8841 pkg.applicationInfo.primaryCpuAbi = abi; 8842 } else { 8843 pkg.applicationInfo.secondaryCpuAbi = abi; 8844 } 8845 } else { 8846 pkg.applicationInfo.primaryCpuAbi = abi; 8847 } 8848 } 8849 8850 } else { 8851 String[] abiList = (cpuAbiOverride != null) ? 8852 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8853 8854 // Enable gross and lame hacks for apps that are built with old 8855 // SDK tools. We must scan their APKs for renderscript bitcode and 8856 // not launch them if it's present. Don't bother checking on devices 8857 // that don't have 64 bit support. 8858 boolean needsRenderScriptOverride = false; 8859 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8860 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8861 abiList = Build.SUPPORTED_32_BIT_ABIS; 8862 needsRenderScriptOverride = true; 8863 } 8864 8865 final int copyRet; 8866 if (extractLibs) { 8867 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8868 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8869 } else { 8870 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8871 } 8872 8873 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8874 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8875 "Error unpackaging native libs for app, errorCode=" + copyRet); 8876 } 8877 8878 if (copyRet >= 0) { 8879 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8880 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8881 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8882 } else if (needsRenderScriptOverride) { 8883 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8884 } 8885 } 8886 } catch (IOException ioe) { 8887 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8888 } finally { 8889 IoUtils.closeQuietly(handle); 8890 } 8891 8892 // Now that we've calculated the ABIs and determined if it's an internal app, 8893 // we will go ahead and populate the nativeLibraryPath. 8894 setNativeLibraryPaths(pkg); 8895 } 8896 8897 /** 8898 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8899 * i.e, so that all packages can be run inside a single process if required. 8900 * 8901 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8902 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8903 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8904 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8905 * updating a package that belongs to a shared user. 8906 * 8907 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8908 * adds unnecessary complexity. 8909 */ 8910 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8911 PackageParser.Package scannedPackage, boolean bootComplete) { 8912 String requiredInstructionSet = null; 8913 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8914 requiredInstructionSet = VMRuntime.getInstructionSet( 8915 scannedPackage.applicationInfo.primaryCpuAbi); 8916 } 8917 8918 PackageSetting requirer = null; 8919 for (PackageSetting ps : packagesForUser) { 8920 // If packagesForUser contains scannedPackage, we skip it. This will happen 8921 // when scannedPackage is an update of an existing package. Without this check, 8922 // we will never be able to change the ABI of any package belonging to a shared 8923 // user, even if it's compatible with other packages. 8924 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8925 if (ps.primaryCpuAbiString == null) { 8926 continue; 8927 } 8928 8929 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8930 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8931 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8932 // this but there's not much we can do. 8933 String errorMessage = "Instruction set mismatch, " 8934 + ((requirer == null) ? "[caller]" : requirer) 8935 + " requires " + requiredInstructionSet + " whereas " + ps 8936 + " requires " + instructionSet; 8937 Slog.w(TAG, errorMessage); 8938 } 8939 8940 if (requiredInstructionSet == null) { 8941 requiredInstructionSet = instructionSet; 8942 requirer = ps; 8943 } 8944 } 8945 } 8946 8947 if (requiredInstructionSet != null) { 8948 String adjustedAbi; 8949 if (requirer != null) { 8950 // requirer != null implies that either scannedPackage was null or that scannedPackage 8951 // did not require an ABI, in which case we have to adjust scannedPackage to match 8952 // the ABI of the set (which is the same as requirer's ABI) 8953 adjustedAbi = requirer.primaryCpuAbiString; 8954 if (scannedPackage != null) { 8955 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8956 } 8957 } else { 8958 // requirer == null implies that we're updating all ABIs in the set to 8959 // match scannedPackage. 8960 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8961 } 8962 8963 for (PackageSetting ps : packagesForUser) { 8964 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8965 if (ps.primaryCpuAbiString != null) { 8966 continue; 8967 } 8968 8969 ps.primaryCpuAbiString = adjustedAbi; 8970 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8971 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8972 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8973 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8974 + " (requirer=" 8975 + (requirer == null ? "null" : requirer.pkg.packageName) 8976 + ", scannedPackage=" 8977 + (scannedPackage != null ? scannedPackage.packageName : "null") 8978 + ")"); 8979 try { 8980 mInstaller.rmdex(ps.codePathString, 8981 getDexCodeInstructionSet(getPreferredInstructionSet())); 8982 } catch (InstallerException ignored) { 8983 } 8984 } 8985 } 8986 } 8987 } 8988 } 8989 8990 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8991 synchronized (mPackages) { 8992 mResolverReplaced = true; 8993 // Set up information for custom user intent resolution activity. 8994 mResolveActivity.applicationInfo = pkg.applicationInfo; 8995 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8996 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8997 mResolveActivity.processName = pkg.applicationInfo.packageName; 8998 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8999 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9000 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9001 mResolveActivity.theme = 0; 9002 mResolveActivity.exported = true; 9003 mResolveActivity.enabled = true; 9004 mResolveInfo.activityInfo = mResolveActivity; 9005 mResolveInfo.priority = 0; 9006 mResolveInfo.preferredOrder = 0; 9007 mResolveInfo.match = 0; 9008 mResolveComponentName = mCustomResolverComponentName; 9009 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9010 mResolveComponentName); 9011 } 9012 } 9013 9014 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9015 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9016 9017 // Set up information for ephemeral installer activity 9018 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9019 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9020 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9021 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9022 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9023 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9024 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9025 mEphemeralInstallerActivity.theme = 0; 9026 mEphemeralInstallerActivity.exported = true; 9027 mEphemeralInstallerActivity.enabled = true; 9028 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9029 mEphemeralInstallerInfo.priority = 0; 9030 mEphemeralInstallerInfo.preferredOrder = 0; 9031 mEphemeralInstallerInfo.match = 0; 9032 9033 if (DEBUG_EPHEMERAL) { 9034 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9035 } 9036 } 9037 9038 private static String calculateBundledApkRoot(final String codePathString) { 9039 final File codePath = new File(codePathString); 9040 final File codeRoot; 9041 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9042 codeRoot = Environment.getRootDirectory(); 9043 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9044 codeRoot = Environment.getOemDirectory(); 9045 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9046 codeRoot = Environment.getVendorDirectory(); 9047 } else { 9048 // Unrecognized code path; take its top real segment as the apk root: 9049 // e.g. /something/app/blah.apk => /something 9050 try { 9051 File f = codePath.getCanonicalFile(); 9052 File parent = f.getParentFile(); // non-null because codePath is a file 9053 File tmp; 9054 while ((tmp = parent.getParentFile()) != null) { 9055 f = parent; 9056 parent = tmp; 9057 } 9058 codeRoot = f; 9059 Slog.w(TAG, "Unrecognized code path " 9060 + codePath + " - using " + codeRoot); 9061 } catch (IOException e) { 9062 // Can't canonicalize the code path -- shenanigans? 9063 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9064 return Environment.getRootDirectory().getPath(); 9065 } 9066 } 9067 return codeRoot.getPath(); 9068 } 9069 9070 /** 9071 * Derive and set the location of native libraries for the given package, 9072 * which varies depending on where and how the package was installed. 9073 */ 9074 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9075 final ApplicationInfo info = pkg.applicationInfo; 9076 final String codePath = pkg.codePath; 9077 final File codeFile = new File(codePath); 9078 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9079 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9080 9081 info.nativeLibraryRootDir = null; 9082 info.nativeLibraryRootRequiresIsa = false; 9083 info.nativeLibraryDir = null; 9084 info.secondaryNativeLibraryDir = null; 9085 9086 if (isApkFile(codeFile)) { 9087 // Monolithic install 9088 if (bundledApp) { 9089 // If "/system/lib64/apkname" exists, assume that is the per-package 9090 // native library directory to use; otherwise use "/system/lib/apkname". 9091 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9092 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9093 getPrimaryInstructionSet(info)); 9094 9095 // This is a bundled system app so choose the path based on the ABI. 9096 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9097 // is just the default path. 9098 final String apkName = deriveCodePathName(codePath); 9099 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9100 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9101 apkName).getAbsolutePath(); 9102 9103 if (info.secondaryCpuAbi != null) { 9104 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9105 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9106 secondaryLibDir, apkName).getAbsolutePath(); 9107 } 9108 } else if (asecApp) { 9109 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9110 .getAbsolutePath(); 9111 } else { 9112 final String apkName = deriveCodePathName(codePath); 9113 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9114 .getAbsolutePath(); 9115 } 9116 9117 info.nativeLibraryRootRequiresIsa = false; 9118 info.nativeLibraryDir = info.nativeLibraryRootDir; 9119 } else { 9120 // Cluster install 9121 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9122 info.nativeLibraryRootRequiresIsa = true; 9123 9124 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9125 getPrimaryInstructionSet(info)).getAbsolutePath(); 9126 9127 if (info.secondaryCpuAbi != null) { 9128 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9129 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9130 } 9131 } 9132 } 9133 9134 /** 9135 * Calculate the abis and roots for a bundled app. These can uniquely 9136 * be determined from the contents of the system partition, i.e whether 9137 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9138 * of this information, and instead assume that the system was built 9139 * sensibly. 9140 */ 9141 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9142 PackageSetting pkgSetting) { 9143 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9144 9145 // If "/system/lib64/apkname" exists, assume that is the per-package 9146 // native library directory to use; otherwise use "/system/lib/apkname". 9147 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9148 setBundledAppAbi(pkg, apkRoot, apkName); 9149 // pkgSetting might be null during rescan following uninstall of updates 9150 // to a bundled app, so accommodate that possibility. The settings in 9151 // that case will be established later from the parsed package. 9152 // 9153 // If the settings aren't null, sync them up with what we've just derived. 9154 // note that apkRoot isn't stored in the package settings. 9155 if (pkgSetting != null) { 9156 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9157 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9158 } 9159 } 9160 9161 /** 9162 * Deduces the ABI of a bundled app and sets the relevant fields on the 9163 * parsed pkg object. 9164 * 9165 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9166 * under which system libraries are installed. 9167 * @param apkName the name of the installed package. 9168 */ 9169 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9170 final File codeFile = new File(pkg.codePath); 9171 9172 final boolean has64BitLibs; 9173 final boolean has32BitLibs; 9174 if (isApkFile(codeFile)) { 9175 // Monolithic install 9176 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9177 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9178 } else { 9179 // Cluster install 9180 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9181 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9182 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9183 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9184 has64BitLibs = (new File(rootDir, isa)).exists(); 9185 } else { 9186 has64BitLibs = false; 9187 } 9188 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9189 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9190 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9191 has32BitLibs = (new File(rootDir, isa)).exists(); 9192 } else { 9193 has32BitLibs = false; 9194 } 9195 } 9196 9197 if (has64BitLibs && !has32BitLibs) { 9198 // The package has 64 bit libs, but not 32 bit libs. Its primary 9199 // ABI should be 64 bit. We can safely assume here that the bundled 9200 // native libraries correspond to the most preferred ABI in the list. 9201 9202 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9203 pkg.applicationInfo.secondaryCpuAbi = null; 9204 } else if (has32BitLibs && !has64BitLibs) { 9205 // The package has 32 bit libs but not 64 bit libs. Its primary 9206 // ABI should be 32 bit. 9207 9208 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9209 pkg.applicationInfo.secondaryCpuAbi = null; 9210 } else if (has32BitLibs && has64BitLibs) { 9211 // The application has both 64 and 32 bit bundled libraries. We check 9212 // here that the app declares multiArch support, and warn if it doesn't. 9213 // 9214 // We will be lenient here and record both ABIs. The primary will be the 9215 // ABI that's higher on the list, i.e, a device that's configured to prefer 9216 // 64 bit apps will see a 64 bit primary ABI, 9217 9218 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9219 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9220 } 9221 9222 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9223 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9224 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9225 } else { 9226 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9227 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9228 } 9229 } else { 9230 pkg.applicationInfo.primaryCpuAbi = null; 9231 pkg.applicationInfo.secondaryCpuAbi = null; 9232 } 9233 } 9234 9235 private void killApplication(String pkgName, int appId, String reason) { 9236 // Request the ActivityManager to kill the process(only for existing packages) 9237 // so that we do not end up in a confused state while the user is still using the older 9238 // version of the application while the new one gets installed. 9239 final long token = Binder.clearCallingIdentity(); 9240 try { 9241 IActivityManager am = ActivityManagerNative.getDefault(); 9242 if (am != null) { 9243 try { 9244 am.killApplicationWithAppId(pkgName, appId, reason); 9245 } catch (RemoteException e) { 9246 } 9247 } 9248 } finally { 9249 Binder.restoreCallingIdentity(token); 9250 } 9251 } 9252 9253 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9254 // Remove the parent package setting 9255 PackageSetting ps = (PackageSetting) pkg.mExtras; 9256 if (ps != null) { 9257 removePackageLI(ps, chatty); 9258 } 9259 // Remove the child package setting 9260 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9261 for (int i = 0; i < childCount; i++) { 9262 PackageParser.Package childPkg = pkg.childPackages.get(i); 9263 ps = (PackageSetting) childPkg.mExtras; 9264 if (ps != null) { 9265 removePackageLI(ps, chatty); 9266 } 9267 } 9268 } 9269 9270 void removePackageLI(PackageSetting ps, boolean chatty) { 9271 if (DEBUG_INSTALL) { 9272 if (chatty) 9273 Log.d(TAG, "Removing package " + ps.name); 9274 } 9275 9276 // writer 9277 synchronized (mPackages) { 9278 mPackages.remove(ps.name); 9279 final PackageParser.Package pkg = ps.pkg; 9280 if (pkg != null) { 9281 cleanPackageDataStructuresLILPw(pkg, chatty); 9282 } 9283 } 9284 } 9285 9286 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9287 if (DEBUG_INSTALL) { 9288 if (chatty) 9289 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9290 } 9291 9292 // writer 9293 synchronized (mPackages) { 9294 // Remove the parent package 9295 mPackages.remove(pkg.applicationInfo.packageName); 9296 cleanPackageDataStructuresLILPw(pkg, chatty); 9297 9298 // Remove the child packages 9299 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9300 for (int i = 0; i < childCount; i++) { 9301 PackageParser.Package childPkg = pkg.childPackages.get(i); 9302 mPackages.remove(childPkg.applicationInfo.packageName); 9303 cleanPackageDataStructuresLILPw(childPkg, chatty); 9304 } 9305 } 9306 } 9307 9308 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9309 int N = pkg.providers.size(); 9310 StringBuilder r = null; 9311 int i; 9312 for (i=0; i<N; i++) { 9313 PackageParser.Provider p = pkg.providers.get(i); 9314 mProviders.removeProvider(p); 9315 if (p.info.authority == null) { 9316 9317 /* There was another ContentProvider with this authority when 9318 * this app was installed so this authority is null, 9319 * Ignore it as we don't have to unregister the provider. 9320 */ 9321 continue; 9322 } 9323 String names[] = p.info.authority.split(";"); 9324 for (int j = 0; j < names.length; j++) { 9325 if (mProvidersByAuthority.get(names[j]) == p) { 9326 mProvidersByAuthority.remove(names[j]); 9327 if (DEBUG_REMOVE) { 9328 if (chatty) 9329 Log.d(TAG, "Unregistered content provider: " + names[j] 9330 + ", className = " + p.info.name + ", isSyncable = " 9331 + p.info.isSyncable); 9332 } 9333 } 9334 } 9335 if (DEBUG_REMOVE && chatty) { 9336 if (r == null) { 9337 r = new StringBuilder(256); 9338 } else { 9339 r.append(' '); 9340 } 9341 r.append(p.info.name); 9342 } 9343 } 9344 if (r != null) { 9345 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9346 } 9347 9348 N = pkg.services.size(); 9349 r = null; 9350 for (i=0; i<N; i++) { 9351 PackageParser.Service s = pkg.services.get(i); 9352 mServices.removeService(s); 9353 if (chatty) { 9354 if (r == null) { 9355 r = new StringBuilder(256); 9356 } else { 9357 r.append(' '); 9358 } 9359 r.append(s.info.name); 9360 } 9361 } 9362 if (r != null) { 9363 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9364 } 9365 9366 N = pkg.receivers.size(); 9367 r = null; 9368 for (i=0; i<N; i++) { 9369 PackageParser.Activity a = pkg.receivers.get(i); 9370 mReceivers.removeActivity(a, "receiver"); 9371 if (DEBUG_REMOVE && chatty) { 9372 if (r == null) { 9373 r = new StringBuilder(256); 9374 } else { 9375 r.append(' '); 9376 } 9377 r.append(a.info.name); 9378 } 9379 } 9380 if (r != null) { 9381 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9382 } 9383 9384 N = pkg.activities.size(); 9385 r = null; 9386 for (i=0; i<N; i++) { 9387 PackageParser.Activity a = pkg.activities.get(i); 9388 mActivities.removeActivity(a, "activity"); 9389 if (DEBUG_REMOVE && chatty) { 9390 if (r == null) { 9391 r = new StringBuilder(256); 9392 } else { 9393 r.append(' '); 9394 } 9395 r.append(a.info.name); 9396 } 9397 } 9398 if (r != null) { 9399 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9400 } 9401 9402 N = pkg.permissions.size(); 9403 r = null; 9404 for (i=0; i<N; i++) { 9405 PackageParser.Permission p = pkg.permissions.get(i); 9406 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9407 if (bp == null) { 9408 bp = mSettings.mPermissionTrees.get(p.info.name); 9409 } 9410 if (bp != null && bp.perm == p) { 9411 bp.perm = null; 9412 if (DEBUG_REMOVE && chatty) { 9413 if (r == null) { 9414 r = new StringBuilder(256); 9415 } else { 9416 r.append(' '); 9417 } 9418 r.append(p.info.name); 9419 } 9420 } 9421 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9422 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9423 if (appOpPkgs != null) { 9424 appOpPkgs.remove(pkg.packageName); 9425 } 9426 } 9427 } 9428 if (r != null) { 9429 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9430 } 9431 9432 N = pkg.requestedPermissions.size(); 9433 r = null; 9434 for (i=0; i<N; i++) { 9435 String perm = pkg.requestedPermissions.get(i); 9436 BasePermission bp = mSettings.mPermissions.get(perm); 9437 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9438 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9439 if (appOpPkgs != null) { 9440 appOpPkgs.remove(pkg.packageName); 9441 if (appOpPkgs.isEmpty()) { 9442 mAppOpPermissionPackages.remove(perm); 9443 } 9444 } 9445 } 9446 } 9447 if (r != null) { 9448 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9449 } 9450 9451 N = pkg.instrumentation.size(); 9452 r = null; 9453 for (i=0; i<N; i++) { 9454 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9455 mInstrumentation.remove(a.getComponentName()); 9456 if (DEBUG_REMOVE && chatty) { 9457 if (r == null) { 9458 r = new StringBuilder(256); 9459 } else { 9460 r.append(' '); 9461 } 9462 r.append(a.info.name); 9463 } 9464 } 9465 if (r != null) { 9466 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9467 } 9468 9469 r = null; 9470 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9471 // Only system apps can hold shared libraries. 9472 if (pkg.libraryNames != null) { 9473 for (i=0; i<pkg.libraryNames.size(); i++) { 9474 String name = pkg.libraryNames.get(i); 9475 SharedLibraryEntry cur = mSharedLibraries.get(name); 9476 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9477 mSharedLibraries.remove(name); 9478 if (DEBUG_REMOVE && chatty) { 9479 if (r == null) { 9480 r = new StringBuilder(256); 9481 } else { 9482 r.append(' '); 9483 } 9484 r.append(name); 9485 } 9486 } 9487 } 9488 } 9489 } 9490 if (r != null) { 9491 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9492 } 9493 } 9494 9495 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9496 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9497 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9498 return true; 9499 } 9500 } 9501 return false; 9502 } 9503 9504 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9505 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9506 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9507 9508 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9509 // Update the parent permissions 9510 updatePermissionsLPw(pkg.packageName, pkg, flags); 9511 // Update the child permissions 9512 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9513 for (int i = 0; i < childCount; i++) { 9514 PackageParser.Package childPkg = pkg.childPackages.get(i); 9515 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9516 } 9517 } 9518 9519 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9520 int flags) { 9521 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9522 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9523 } 9524 9525 private void updatePermissionsLPw(String changingPkg, 9526 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9527 // Make sure there are no dangling permission trees. 9528 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9529 while (it.hasNext()) { 9530 final BasePermission bp = it.next(); 9531 if (bp.packageSetting == null) { 9532 // We may not yet have parsed the package, so just see if 9533 // we still know about its settings. 9534 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9535 } 9536 if (bp.packageSetting == null) { 9537 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9538 + " from package " + bp.sourcePackage); 9539 it.remove(); 9540 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9541 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9542 Slog.i(TAG, "Removing old permission tree: " + bp.name 9543 + " from package " + bp.sourcePackage); 9544 flags |= UPDATE_PERMISSIONS_ALL; 9545 it.remove(); 9546 } 9547 } 9548 } 9549 9550 // Make sure all dynamic permissions have been assigned to a package, 9551 // and make sure there are no dangling permissions. 9552 it = mSettings.mPermissions.values().iterator(); 9553 while (it.hasNext()) { 9554 final BasePermission bp = it.next(); 9555 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9556 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9557 + bp.name + " pkg=" + bp.sourcePackage 9558 + " info=" + bp.pendingInfo); 9559 if (bp.packageSetting == null && bp.pendingInfo != null) { 9560 final BasePermission tree = findPermissionTreeLP(bp.name); 9561 if (tree != null && tree.perm != null) { 9562 bp.packageSetting = tree.packageSetting; 9563 bp.perm = new PackageParser.Permission(tree.perm.owner, 9564 new PermissionInfo(bp.pendingInfo)); 9565 bp.perm.info.packageName = tree.perm.info.packageName; 9566 bp.perm.info.name = bp.name; 9567 bp.uid = tree.uid; 9568 } 9569 } 9570 } 9571 if (bp.packageSetting == null) { 9572 // We may not yet have parsed the package, so just see if 9573 // we still know about its settings. 9574 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9575 } 9576 if (bp.packageSetting == null) { 9577 Slog.w(TAG, "Removing dangling permission: " + bp.name 9578 + " from package " + bp.sourcePackage); 9579 it.remove(); 9580 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9581 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9582 Slog.i(TAG, "Removing old permission: " + bp.name 9583 + " from package " + bp.sourcePackage); 9584 flags |= UPDATE_PERMISSIONS_ALL; 9585 it.remove(); 9586 } 9587 } 9588 } 9589 9590 // Now update the permissions for all packages, in particular 9591 // replace the granted permissions of the system packages. 9592 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9593 for (PackageParser.Package pkg : mPackages.values()) { 9594 if (pkg != pkgInfo) { 9595 // Only replace for packages on requested volume 9596 final String volumeUuid = getVolumeUuidForPackage(pkg); 9597 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9598 && Objects.equals(replaceVolumeUuid, volumeUuid); 9599 grantPermissionsLPw(pkg, replace, changingPkg); 9600 } 9601 } 9602 } 9603 9604 if (pkgInfo != null) { 9605 // Only replace for packages on requested volume 9606 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9607 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9608 && Objects.equals(replaceVolumeUuid, volumeUuid); 9609 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9610 } 9611 } 9612 9613 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9614 String packageOfInterest) { 9615 // IMPORTANT: There are two types of permissions: install and runtime. 9616 // Install time permissions are granted when the app is installed to 9617 // all device users and users added in the future. Runtime permissions 9618 // are granted at runtime explicitly to specific users. Normal and signature 9619 // protected permissions are install time permissions. Dangerous permissions 9620 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9621 // otherwise they are runtime permissions. This function does not manage 9622 // runtime permissions except for the case an app targeting Lollipop MR1 9623 // being upgraded to target a newer SDK, in which case dangerous permissions 9624 // are transformed from install time to runtime ones. 9625 9626 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9627 if (ps == null) { 9628 return; 9629 } 9630 9631 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9632 9633 PermissionsState permissionsState = ps.getPermissionsState(); 9634 PermissionsState origPermissions = permissionsState; 9635 9636 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9637 9638 boolean runtimePermissionsRevoked = false; 9639 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9640 9641 boolean changedInstallPermission = false; 9642 9643 if (replace) { 9644 ps.installPermissionsFixed = false; 9645 if (!ps.isSharedUser()) { 9646 origPermissions = new PermissionsState(permissionsState); 9647 permissionsState.reset(); 9648 } else { 9649 // We need to know only about runtime permission changes since the 9650 // calling code always writes the install permissions state but 9651 // the runtime ones are written only if changed. The only cases of 9652 // changed runtime permissions here are promotion of an install to 9653 // runtime and revocation of a runtime from a shared user. 9654 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9655 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9656 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9657 runtimePermissionsRevoked = true; 9658 } 9659 } 9660 } 9661 9662 permissionsState.setGlobalGids(mGlobalGids); 9663 9664 final int N = pkg.requestedPermissions.size(); 9665 for (int i=0; i<N; i++) { 9666 final String name = pkg.requestedPermissions.get(i); 9667 final BasePermission bp = mSettings.mPermissions.get(name); 9668 9669 if (DEBUG_INSTALL) { 9670 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9671 } 9672 9673 if (bp == null || bp.packageSetting == null) { 9674 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9675 Slog.w(TAG, "Unknown permission " + name 9676 + " in package " + pkg.packageName); 9677 } 9678 continue; 9679 } 9680 9681 final String perm = bp.name; 9682 boolean allowedSig = false; 9683 int grant = GRANT_DENIED; 9684 9685 // Keep track of app op permissions. 9686 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9687 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9688 if (pkgs == null) { 9689 pkgs = new ArraySet<>(); 9690 mAppOpPermissionPackages.put(bp.name, pkgs); 9691 } 9692 pkgs.add(pkg.packageName); 9693 } 9694 9695 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9696 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9697 >= Build.VERSION_CODES.M; 9698 switch (level) { 9699 case PermissionInfo.PROTECTION_NORMAL: { 9700 // For all apps normal permissions are install time ones. 9701 grant = GRANT_INSTALL; 9702 } break; 9703 9704 case PermissionInfo.PROTECTION_DANGEROUS: { 9705 // If a permission review is required for legacy apps we represent 9706 // their permissions as always granted runtime ones since we need 9707 // to keep the review required permission flag per user while an 9708 // install permission's state is shared across all users. 9709 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9710 // For legacy apps dangerous permissions are install time ones. 9711 grant = GRANT_INSTALL; 9712 } else if (origPermissions.hasInstallPermission(bp.name)) { 9713 // For legacy apps that became modern, install becomes runtime. 9714 grant = GRANT_UPGRADE; 9715 } else if (mPromoteSystemApps 9716 && isSystemApp(ps) 9717 && mExistingSystemPackages.contains(ps.name)) { 9718 // For legacy system apps, install becomes runtime. 9719 // We cannot check hasInstallPermission() for system apps since those 9720 // permissions were granted implicitly and not persisted pre-M. 9721 grant = GRANT_UPGRADE; 9722 } else { 9723 // For modern apps keep runtime permissions unchanged. 9724 grant = GRANT_RUNTIME; 9725 } 9726 } break; 9727 9728 case PermissionInfo.PROTECTION_SIGNATURE: { 9729 // For all apps signature permissions are install time ones. 9730 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9731 if (allowedSig) { 9732 grant = GRANT_INSTALL; 9733 } 9734 } break; 9735 } 9736 9737 if (DEBUG_INSTALL) { 9738 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9739 } 9740 9741 if (grant != GRANT_DENIED) { 9742 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9743 // If this is an existing, non-system package, then 9744 // we can't add any new permissions to it. 9745 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9746 // Except... if this is a permission that was added 9747 // to the platform (note: need to only do this when 9748 // updating the platform). 9749 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9750 grant = GRANT_DENIED; 9751 } 9752 } 9753 } 9754 9755 switch (grant) { 9756 case GRANT_INSTALL: { 9757 // Revoke this as runtime permission to handle the case of 9758 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9759 for (int userId : UserManagerService.getInstance().getUserIds()) { 9760 if (origPermissions.getRuntimePermissionState( 9761 bp.name, userId) != null) { 9762 // Revoke the runtime permission and clear the flags. 9763 origPermissions.revokeRuntimePermission(bp, userId); 9764 origPermissions.updatePermissionFlags(bp, userId, 9765 PackageManager.MASK_PERMISSION_FLAGS, 0); 9766 // If we revoked a permission permission, we have to write. 9767 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9768 changedRuntimePermissionUserIds, userId); 9769 } 9770 } 9771 // Grant an install permission. 9772 if (permissionsState.grantInstallPermission(bp) != 9773 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9774 changedInstallPermission = true; 9775 } 9776 } break; 9777 9778 case GRANT_RUNTIME: { 9779 // Grant previously granted runtime permissions. 9780 for (int userId : UserManagerService.getInstance().getUserIds()) { 9781 PermissionState permissionState = origPermissions 9782 .getRuntimePermissionState(bp.name, userId); 9783 int flags = permissionState != null 9784 ? permissionState.getFlags() : 0; 9785 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9786 if (permissionsState.grantRuntimePermission(bp, userId) == 9787 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9788 // If we cannot put the permission as it was, we have to write. 9789 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9790 changedRuntimePermissionUserIds, userId); 9791 } 9792 // If the app supports runtime permissions no need for a review. 9793 if (Build.PERMISSIONS_REVIEW_REQUIRED 9794 && appSupportsRuntimePermissions 9795 && (flags & PackageManager 9796 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9797 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9798 // Since we changed the flags, we have to write. 9799 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9800 changedRuntimePermissionUserIds, userId); 9801 } 9802 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9803 && !appSupportsRuntimePermissions) { 9804 // For legacy apps that need a permission review, every new 9805 // runtime permission is granted but it is pending a review. 9806 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9807 permissionsState.grantRuntimePermission(bp, userId); 9808 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9809 // We changed the permission and flags, hence have to write. 9810 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9811 changedRuntimePermissionUserIds, userId); 9812 } 9813 } 9814 // Propagate the permission flags. 9815 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9816 } 9817 } break; 9818 9819 case GRANT_UPGRADE: { 9820 // Grant runtime permissions for a previously held install permission. 9821 PermissionState permissionState = origPermissions 9822 .getInstallPermissionState(bp.name); 9823 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9824 9825 if (origPermissions.revokeInstallPermission(bp) 9826 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9827 // We will be transferring the permission flags, so clear them. 9828 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9829 PackageManager.MASK_PERMISSION_FLAGS, 0); 9830 changedInstallPermission = true; 9831 } 9832 9833 // If the permission is not to be promoted to runtime we ignore it and 9834 // also its other flags as they are not applicable to install permissions. 9835 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9836 for (int userId : currentUserIds) { 9837 if (permissionsState.grantRuntimePermission(bp, userId) != 9838 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9839 // Transfer the permission flags. 9840 permissionsState.updatePermissionFlags(bp, userId, 9841 flags, flags); 9842 // If we granted the permission, we have to write. 9843 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9844 changedRuntimePermissionUserIds, userId); 9845 } 9846 } 9847 } 9848 } break; 9849 9850 default: { 9851 if (packageOfInterest == null 9852 || packageOfInterest.equals(pkg.packageName)) { 9853 Slog.w(TAG, "Not granting permission " + perm 9854 + " to package " + pkg.packageName 9855 + " because it was previously installed without"); 9856 } 9857 } break; 9858 } 9859 } else { 9860 if (permissionsState.revokeInstallPermission(bp) != 9861 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9862 // Also drop the permission flags. 9863 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9864 PackageManager.MASK_PERMISSION_FLAGS, 0); 9865 changedInstallPermission = true; 9866 Slog.i(TAG, "Un-granting permission " + perm 9867 + " from package " + pkg.packageName 9868 + " (protectionLevel=" + bp.protectionLevel 9869 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9870 + ")"); 9871 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9872 // Don't print warning for app op permissions, since it is fine for them 9873 // not to be granted, there is a UI for the user to decide. 9874 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9875 Slog.w(TAG, "Not granting permission " + perm 9876 + " to package " + pkg.packageName 9877 + " (protectionLevel=" + bp.protectionLevel 9878 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9879 + ")"); 9880 } 9881 } 9882 } 9883 } 9884 9885 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9886 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9887 // This is the first that we have heard about this package, so the 9888 // permissions we have now selected are fixed until explicitly 9889 // changed. 9890 ps.installPermissionsFixed = true; 9891 } 9892 9893 // Persist the runtime permissions state for users with changes. If permissions 9894 // were revoked because no app in the shared user declares them we have to 9895 // write synchronously to avoid losing runtime permissions state. 9896 for (int userId : changedRuntimePermissionUserIds) { 9897 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9898 } 9899 9900 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9901 } 9902 9903 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9904 boolean allowed = false; 9905 final int NP = PackageParser.NEW_PERMISSIONS.length; 9906 for (int ip=0; ip<NP; ip++) { 9907 final PackageParser.NewPermissionInfo npi 9908 = PackageParser.NEW_PERMISSIONS[ip]; 9909 if (npi.name.equals(perm) 9910 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9911 allowed = true; 9912 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9913 + pkg.packageName); 9914 break; 9915 } 9916 } 9917 return allowed; 9918 } 9919 9920 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9921 BasePermission bp, PermissionsState origPermissions) { 9922 boolean allowed; 9923 allowed = (compareSignatures( 9924 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9925 == PackageManager.SIGNATURE_MATCH) 9926 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9927 == PackageManager.SIGNATURE_MATCH); 9928 if (!allowed && (bp.protectionLevel 9929 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9930 if (isSystemApp(pkg)) { 9931 // For updated system applications, a system permission 9932 // is granted only if it had been defined by the original application. 9933 if (pkg.isUpdatedSystemApp()) { 9934 final PackageSetting sysPs = mSettings 9935 .getDisabledSystemPkgLPr(pkg.packageName); 9936 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9937 // If the original was granted this permission, we take 9938 // that grant decision as read and propagate it to the 9939 // update. 9940 if (sysPs.isPrivileged()) { 9941 allowed = true; 9942 } 9943 } else { 9944 // The system apk may have been updated with an older 9945 // version of the one on the data partition, but which 9946 // granted a new system permission that it didn't have 9947 // before. In this case we do want to allow the app to 9948 // now get the new permission if the ancestral apk is 9949 // privileged to get it. 9950 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9951 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9952 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9953 allowed = true; 9954 break; 9955 } 9956 } 9957 } 9958 // Also if a privileged parent package on the system image or any of 9959 // its children requested a privileged permission, the updated child 9960 // packages can also get the permission. 9961 if (pkg.parentPackage != null) { 9962 final PackageSetting disabledSysParentPs = mSettings 9963 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9964 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9965 && disabledSysParentPs.isPrivileged()) { 9966 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9967 allowed = true; 9968 } else if (disabledSysParentPs.pkg.childPackages != null) { 9969 final int count = disabledSysParentPs.pkg.childPackages.size(); 9970 for (int i = 0; i < count; i++) { 9971 PackageParser.Package disabledSysChildPkg = 9972 disabledSysParentPs.pkg.childPackages.get(i); 9973 if (isPackageRequestingPermission(disabledSysChildPkg, 9974 perm)) { 9975 allowed = true; 9976 break; 9977 } 9978 } 9979 } 9980 } 9981 } 9982 } 9983 } else { 9984 allowed = isPrivilegedApp(pkg); 9985 } 9986 } 9987 } 9988 if (!allowed) { 9989 if (!allowed && (bp.protectionLevel 9990 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9991 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9992 // If this was a previously normal/dangerous permission that got moved 9993 // to a system permission as part of the runtime permission redesign, then 9994 // we still want to blindly grant it to old apps. 9995 allowed = true; 9996 } 9997 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9998 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9999 // If this permission is to be granted to the system installer and 10000 // this app is an installer, then it gets the permission. 10001 allowed = true; 10002 } 10003 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10004 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10005 // If this permission is to be granted to the system verifier and 10006 // this app is a verifier, then it gets the permission. 10007 allowed = true; 10008 } 10009 if (!allowed && (bp.protectionLevel 10010 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10011 && isSystemApp(pkg)) { 10012 // Any pre-installed system app is allowed to get this permission. 10013 allowed = true; 10014 } 10015 if (!allowed && (bp.protectionLevel 10016 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10017 // For development permissions, a development permission 10018 // is granted only if it was already granted. 10019 allowed = origPermissions.hasInstallPermission(perm); 10020 } 10021 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10022 && pkg.packageName.equals(mSetupWizardPackage)) { 10023 // If this permission is to be granted to the system setup wizard and 10024 // this app is a setup wizard, then it gets the permission. 10025 allowed = true; 10026 } 10027 } 10028 return allowed; 10029 } 10030 10031 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10032 final int permCount = pkg.requestedPermissions.size(); 10033 for (int j = 0; j < permCount; j++) { 10034 String requestedPermission = pkg.requestedPermissions.get(j); 10035 if (permission.equals(requestedPermission)) { 10036 return true; 10037 } 10038 } 10039 return false; 10040 } 10041 10042 final class ActivityIntentResolver 10043 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10044 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10045 boolean defaultOnly, int userId) { 10046 if (!sUserManager.exists(userId)) return null; 10047 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10048 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10049 } 10050 10051 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10052 int userId) { 10053 if (!sUserManager.exists(userId)) return null; 10054 mFlags = flags; 10055 return super.queryIntent(intent, resolvedType, 10056 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10057 } 10058 10059 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10060 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10061 if (!sUserManager.exists(userId)) return null; 10062 if (packageActivities == null) { 10063 return null; 10064 } 10065 mFlags = flags; 10066 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10067 final int N = packageActivities.size(); 10068 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10069 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10070 10071 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10072 for (int i = 0; i < N; ++i) { 10073 intentFilters = packageActivities.get(i).intents; 10074 if (intentFilters != null && intentFilters.size() > 0) { 10075 PackageParser.ActivityIntentInfo[] array = 10076 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10077 intentFilters.toArray(array); 10078 listCut.add(array); 10079 } 10080 } 10081 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10082 } 10083 10084 /** 10085 * Finds a privileged activity that matches the specified activity names. 10086 */ 10087 private PackageParser.Activity findMatchingActivity( 10088 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10089 for (PackageParser.Activity sysActivity : activityList) { 10090 if (sysActivity.info.name.equals(activityInfo.name)) { 10091 return sysActivity; 10092 } 10093 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10094 return sysActivity; 10095 } 10096 if (sysActivity.info.targetActivity != null) { 10097 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10098 return sysActivity; 10099 } 10100 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10101 return sysActivity; 10102 } 10103 } 10104 } 10105 return null; 10106 } 10107 10108 public class IterGenerator<E> { 10109 public Iterator<E> generate(ActivityIntentInfo info) { 10110 return null; 10111 } 10112 } 10113 10114 public class ActionIterGenerator extends IterGenerator<String> { 10115 @Override 10116 public Iterator<String> generate(ActivityIntentInfo info) { 10117 return info.actionsIterator(); 10118 } 10119 } 10120 10121 public class CategoriesIterGenerator extends IterGenerator<String> { 10122 @Override 10123 public Iterator<String> generate(ActivityIntentInfo info) { 10124 return info.categoriesIterator(); 10125 } 10126 } 10127 10128 public class SchemesIterGenerator extends IterGenerator<String> { 10129 @Override 10130 public Iterator<String> generate(ActivityIntentInfo info) { 10131 return info.schemesIterator(); 10132 } 10133 } 10134 10135 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10136 @Override 10137 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10138 return info.authoritiesIterator(); 10139 } 10140 } 10141 10142 /** 10143 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10144 * MODIFIED. Do not pass in a list that should not be changed. 10145 */ 10146 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10147 IterGenerator<T> generator, Iterator<T> searchIterator) { 10148 // loop through the set of actions; every one must be found in the intent filter 10149 while (searchIterator.hasNext()) { 10150 // we must have at least one filter in the list to consider a match 10151 if (intentList.size() == 0) { 10152 break; 10153 } 10154 10155 final T searchAction = searchIterator.next(); 10156 10157 // loop through the set of intent filters 10158 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10159 while (intentIter.hasNext()) { 10160 final ActivityIntentInfo intentInfo = intentIter.next(); 10161 boolean selectionFound = false; 10162 10163 // loop through the intent filter's selection criteria; at least one 10164 // of them must match the searched criteria 10165 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10166 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10167 final T intentSelection = intentSelectionIter.next(); 10168 if (intentSelection != null && intentSelection.equals(searchAction)) { 10169 selectionFound = true; 10170 break; 10171 } 10172 } 10173 10174 // the selection criteria wasn't found in this filter's set; this filter 10175 // is not a potential match 10176 if (!selectionFound) { 10177 intentIter.remove(); 10178 } 10179 } 10180 } 10181 } 10182 10183 private boolean isProtectedAction(ActivityIntentInfo filter) { 10184 final Iterator<String> actionsIter = filter.actionsIterator(); 10185 while (actionsIter != null && actionsIter.hasNext()) { 10186 final String filterAction = actionsIter.next(); 10187 if (PROTECTED_ACTIONS.contains(filterAction)) { 10188 return true; 10189 } 10190 } 10191 return false; 10192 } 10193 10194 /** 10195 * Adjusts the priority of the given intent filter according to policy. 10196 * <p> 10197 * <ul> 10198 * <li>The priority for non privileged applications is capped to '0'</li> 10199 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10200 * <li>The priority for unbundled updates to privileged applications is capped to the 10201 * priority defined on the system partition</li> 10202 * </ul> 10203 * <p> 10204 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10205 * allowed to obtain any priority on any action. 10206 */ 10207 private void adjustPriority( 10208 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10209 // nothing to do; priority is fine as-is 10210 if (intent.getPriority() <= 0) { 10211 return; 10212 } 10213 10214 final ActivityInfo activityInfo = intent.activity.info; 10215 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10216 10217 final boolean privilegedApp = 10218 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10219 if (!privilegedApp) { 10220 // non-privileged applications can never define a priority >0 10221 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10222 + " package: " + applicationInfo.packageName 10223 + " activity: " + intent.activity.className 10224 + " origPrio: " + intent.getPriority()); 10225 intent.setPriority(0); 10226 return; 10227 } 10228 10229 if (systemActivities == null) { 10230 // the system package is not disabled; we're parsing the system partition 10231 if (isProtectedAction(intent)) { 10232 if (mDeferProtectedFilters) { 10233 // We can't deal with these just yet. No component should ever obtain a 10234 // >0 priority for a protected actions, with ONE exception -- the setup 10235 // wizard. The setup wizard, however, cannot be known until we're able to 10236 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10237 // until all intent filters have been processed. Chicken, meet egg. 10238 // Let the filter temporarily have a high priority and rectify the 10239 // priorities after all system packages have been scanned. 10240 mProtectedFilters.add(intent); 10241 if (DEBUG_FILTERS) { 10242 Slog.i(TAG, "Protected action; save for later;" 10243 + " package: " + applicationInfo.packageName 10244 + " activity: " + intent.activity.className 10245 + " origPrio: " + intent.getPriority()); 10246 } 10247 return; 10248 } else { 10249 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10250 Slog.i(TAG, "No setup wizard;" 10251 + " All protected intents capped to priority 0"); 10252 } 10253 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10254 if (DEBUG_FILTERS) { 10255 Slog.i(TAG, "Found setup wizard;" 10256 + " allow priority " + intent.getPriority() + ";" 10257 + " package: " + intent.activity.info.packageName 10258 + " activity: " + intent.activity.className 10259 + " priority: " + intent.getPriority()); 10260 } 10261 // setup wizard gets whatever it wants 10262 return; 10263 } 10264 Slog.w(TAG, "Protected action; cap priority to 0;" 10265 + " package: " + intent.activity.info.packageName 10266 + " activity: " + intent.activity.className 10267 + " origPrio: " + intent.getPriority()); 10268 intent.setPriority(0); 10269 return; 10270 } 10271 } 10272 // privileged apps on the system image get whatever priority they request 10273 return; 10274 } 10275 10276 // privileged app unbundled update ... try to find the same activity 10277 final PackageParser.Activity foundActivity = 10278 findMatchingActivity(systemActivities, activityInfo); 10279 if (foundActivity == null) { 10280 // this is a new activity; it cannot obtain >0 priority 10281 if (DEBUG_FILTERS) { 10282 Slog.i(TAG, "New activity; cap priority to 0;" 10283 + " package: " + applicationInfo.packageName 10284 + " activity: " + intent.activity.className 10285 + " origPrio: " + intent.getPriority()); 10286 } 10287 intent.setPriority(0); 10288 return; 10289 } 10290 10291 // found activity, now check for filter equivalence 10292 10293 // a shallow copy is enough; we modify the list, not its contents 10294 final List<ActivityIntentInfo> intentListCopy = 10295 new ArrayList<>(foundActivity.intents); 10296 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10297 10298 // find matching action subsets 10299 final Iterator<String> actionsIterator = intent.actionsIterator(); 10300 if (actionsIterator != null) { 10301 getIntentListSubset( 10302 intentListCopy, new ActionIterGenerator(), actionsIterator); 10303 if (intentListCopy.size() == 0) { 10304 // no more intents to match; we're not equivalent 10305 if (DEBUG_FILTERS) { 10306 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10307 + " package: " + applicationInfo.packageName 10308 + " activity: " + intent.activity.className 10309 + " origPrio: " + intent.getPriority()); 10310 } 10311 intent.setPriority(0); 10312 return; 10313 } 10314 } 10315 10316 // find matching category subsets 10317 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10318 if (categoriesIterator != null) { 10319 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10320 categoriesIterator); 10321 if (intentListCopy.size() == 0) { 10322 // no more intents to match; we're not equivalent 10323 if (DEBUG_FILTERS) { 10324 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10325 + " package: " + applicationInfo.packageName 10326 + " activity: " + intent.activity.className 10327 + " origPrio: " + intent.getPriority()); 10328 } 10329 intent.setPriority(0); 10330 return; 10331 } 10332 } 10333 10334 // find matching schemes subsets 10335 final Iterator<String> schemesIterator = intent.schemesIterator(); 10336 if (schemesIterator != null) { 10337 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10338 schemesIterator); 10339 if (intentListCopy.size() == 0) { 10340 // no more intents to match; we're not equivalent 10341 if (DEBUG_FILTERS) { 10342 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10343 + " package: " + applicationInfo.packageName 10344 + " activity: " + intent.activity.className 10345 + " origPrio: " + intent.getPriority()); 10346 } 10347 intent.setPriority(0); 10348 return; 10349 } 10350 } 10351 10352 // find matching authorities subsets 10353 final Iterator<IntentFilter.AuthorityEntry> 10354 authoritiesIterator = intent.authoritiesIterator(); 10355 if (authoritiesIterator != null) { 10356 getIntentListSubset(intentListCopy, 10357 new AuthoritiesIterGenerator(), 10358 authoritiesIterator); 10359 if (intentListCopy.size() == 0) { 10360 // no more intents to match; we're not equivalent 10361 if (DEBUG_FILTERS) { 10362 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10363 + " package: " + applicationInfo.packageName 10364 + " activity: " + intent.activity.className 10365 + " origPrio: " + intent.getPriority()); 10366 } 10367 intent.setPriority(0); 10368 return; 10369 } 10370 } 10371 10372 // we found matching filter(s); app gets the max priority of all intents 10373 int cappedPriority = 0; 10374 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10375 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10376 } 10377 if (intent.getPriority() > cappedPriority) { 10378 if (DEBUG_FILTERS) { 10379 Slog.i(TAG, "Found matching filter(s);" 10380 + " cap priority to " + cappedPriority + ";" 10381 + " package: " + applicationInfo.packageName 10382 + " activity: " + intent.activity.className 10383 + " origPrio: " + intent.getPriority()); 10384 } 10385 intent.setPriority(cappedPriority); 10386 return; 10387 } 10388 // all this for nothing; the requested priority was <= what was on the system 10389 } 10390 10391 public final void addActivity(PackageParser.Activity a, String type) { 10392 mActivities.put(a.getComponentName(), a); 10393 if (DEBUG_SHOW_INFO) 10394 Log.v( 10395 TAG, " " + type + " " + 10396 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10397 if (DEBUG_SHOW_INFO) 10398 Log.v(TAG, " Class=" + a.info.name); 10399 final int NI = a.intents.size(); 10400 for (int j=0; j<NI; j++) { 10401 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10402 if ("activity".equals(type)) { 10403 final PackageSetting ps = 10404 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10405 final List<PackageParser.Activity> systemActivities = 10406 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10407 adjustPriority(systemActivities, intent); 10408 } 10409 if (DEBUG_SHOW_INFO) { 10410 Log.v(TAG, " IntentFilter:"); 10411 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10412 } 10413 if (!intent.debugCheck()) { 10414 Log.w(TAG, "==> For Activity " + a.info.name); 10415 } 10416 addFilter(intent); 10417 } 10418 } 10419 10420 public final void removeActivity(PackageParser.Activity a, String type) { 10421 mActivities.remove(a.getComponentName()); 10422 if (DEBUG_SHOW_INFO) { 10423 Log.v(TAG, " " + type + " " 10424 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10425 : a.info.name) + ":"); 10426 Log.v(TAG, " Class=" + a.info.name); 10427 } 10428 final int NI = a.intents.size(); 10429 for (int j=0; j<NI; j++) { 10430 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10431 if (DEBUG_SHOW_INFO) { 10432 Log.v(TAG, " IntentFilter:"); 10433 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10434 } 10435 removeFilter(intent); 10436 } 10437 } 10438 10439 @Override 10440 protected boolean allowFilterResult( 10441 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10442 ActivityInfo filterAi = filter.activity.info; 10443 for (int i=dest.size()-1; i>=0; i--) { 10444 ActivityInfo destAi = dest.get(i).activityInfo; 10445 if (destAi.name == filterAi.name 10446 && destAi.packageName == filterAi.packageName) { 10447 return false; 10448 } 10449 } 10450 return true; 10451 } 10452 10453 @Override 10454 protected ActivityIntentInfo[] newArray(int size) { 10455 return new ActivityIntentInfo[size]; 10456 } 10457 10458 @Override 10459 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10460 if (!sUserManager.exists(userId)) return true; 10461 PackageParser.Package p = filter.activity.owner; 10462 if (p != null) { 10463 PackageSetting ps = (PackageSetting)p.mExtras; 10464 if (ps != null) { 10465 // System apps are never considered stopped for purposes of 10466 // filtering, because there may be no way for the user to 10467 // actually re-launch them. 10468 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10469 && ps.getStopped(userId); 10470 } 10471 } 10472 return false; 10473 } 10474 10475 @Override 10476 protected boolean isPackageForFilter(String packageName, 10477 PackageParser.ActivityIntentInfo info) { 10478 return packageName.equals(info.activity.owner.packageName); 10479 } 10480 10481 @Override 10482 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10483 int match, int userId) { 10484 if (!sUserManager.exists(userId)) return null; 10485 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10486 return null; 10487 } 10488 final PackageParser.Activity activity = info.activity; 10489 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10490 if (ps == null) { 10491 return null; 10492 } 10493 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10494 ps.readUserState(userId), userId); 10495 if (ai == null) { 10496 return null; 10497 } 10498 final ResolveInfo res = new ResolveInfo(); 10499 res.activityInfo = ai; 10500 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10501 res.filter = info; 10502 } 10503 if (info != null) { 10504 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10505 } 10506 res.priority = info.getPriority(); 10507 res.preferredOrder = activity.owner.mPreferredOrder; 10508 //System.out.println("Result: " + res.activityInfo.className + 10509 // " = " + res.priority); 10510 res.match = match; 10511 res.isDefault = info.hasDefault; 10512 res.labelRes = info.labelRes; 10513 res.nonLocalizedLabel = info.nonLocalizedLabel; 10514 if (userNeedsBadging(userId)) { 10515 res.noResourceId = true; 10516 } else { 10517 res.icon = info.icon; 10518 } 10519 res.iconResourceId = info.icon; 10520 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10521 return res; 10522 } 10523 10524 @Override 10525 protected void sortResults(List<ResolveInfo> results) { 10526 Collections.sort(results, mResolvePrioritySorter); 10527 } 10528 10529 @Override 10530 protected void dumpFilter(PrintWriter out, String prefix, 10531 PackageParser.ActivityIntentInfo filter) { 10532 out.print(prefix); out.print( 10533 Integer.toHexString(System.identityHashCode(filter.activity))); 10534 out.print(' '); 10535 filter.activity.printComponentShortName(out); 10536 out.print(" filter "); 10537 out.println(Integer.toHexString(System.identityHashCode(filter))); 10538 } 10539 10540 @Override 10541 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10542 return filter.activity; 10543 } 10544 10545 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10546 PackageParser.Activity activity = (PackageParser.Activity)label; 10547 out.print(prefix); out.print( 10548 Integer.toHexString(System.identityHashCode(activity))); 10549 out.print(' '); 10550 activity.printComponentShortName(out); 10551 if (count > 1) { 10552 out.print(" ("); out.print(count); out.print(" filters)"); 10553 } 10554 out.println(); 10555 } 10556 10557 // Keys are String (activity class name), values are Activity. 10558 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10559 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10560 private int mFlags; 10561 } 10562 10563 private final class ServiceIntentResolver 10564 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10565 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10566 boolean defaultOnly, int userId) { 10567 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10568 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10569 } 10570 10571 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10572 int userId) { 10573 if (!sUserManager.exists(userId)) return null; 10574 mFlags = flags; 10575 return super.queryIntent(intent, resolvedType, 10576 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10577 } 10578 10579 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10580 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10581 if (!sUserManager.exists(userId)) return null; 10582 if (packageServices == null) { 10583 return null; 10584 } 10585 mFlags = flags; 10586 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10587 final int N = packageServices.size(); 10588 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10589 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10590 10591 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10592 for (int i = 0; i < N; ++i) { 10593 intentFilters = packageServices.get(i).intents; 10594 if (intentFilters != null && intentFilters.size() > 0) { 10595 PackageParser.ServiceIntentInfo[] array = 10596 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10597 intentFilters.toArray(array); 10598 listCut.add(array); 10599 } 10600 } 10601 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10602 } 10603 10604 public final void addService(PackageParser.Service s) { 10605 mServices.put(s.getComponentName(), s); 10606 if (DEBUG_SHOW_INFO) { 10607 Log.v(TAG, " " 10608 + (s.info.nonLocalizedLabel != null 10609 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10610 Log.v(TAG, " Class=" + s.info.name); 10611 } 10612 final int NI = s.intents.size(); 10613 int j; 10614 for (j=0; j<NI; j++) { 10615 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10616 if (DEBUG_SHOW_INFO) { 10617 Log.v(TAG, " IntentFilter:"); 10618 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10619 } 10620 if (!intent.debugCheck()) { 10621 Log.w(TAG, "==> For Service " + s.info.name); 10622 } 10623 addFilter(intent); 10624 } 10625 } 10626 10627 public final void removeService(PackageParser.Service s) { 10628 mServices.remove(s.getComponentName()); 10629 if (DEBUG_SHOW_INFO) { 10630 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10631 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10632 Log.v(TAG, " Class=" + s.info.name); 10633 } 10634 final int NI = s.intents.size(); 10635 int j; 10636 for (j=0; j<NI; j++) { 10637 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10638 if (DEBUG_SHOW_INFO) { 10639 Log.v(TAG, " IntentFilter:"); 10640 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10641 } 10642 removeFilter(intent); 10643 } 10644 } 10645 10646 @Override 10647 protected boolean allowFilterResult( 10648 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10649 ServiceInfo filterSi = filter.service.info; 10650 for (int i=dest.size()-1; i>=0; i--) { 10651 ServiceInfo destAi = dest.get(i).serviceInfo; 10652 if (destAi.name == filterSi.name 10653 && destAi.packageName == filterSi.packageName) { 10654 return false; 10655 } 10656 } 10657 return true; 10658 } 10659 10660 @Override 10661 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10662 return new PackageParser.ServiceIntentInfo[size]; 10663 } 10664 10665 @Override 10666 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10667 if (!sUserManager.exists(userId)) return true; 10668 PackageParser.Package p = filter.service.owner; 10669 if (p != null) { 10670 PackageSetting ps = (PackageSetting)p.mExtras; 10671 if (ps != null) { 10672 // System apps are never considered stopped for purposes of 10673 // filtering, because there may be no way for the user to 10674 // actually re-launch them. 10675 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10676 && ps.getStopped(userId); 10677 } 10678 } 10679 return false; 10680 } 10681 10682 @Override 10683 protected boolean isPackageForFilter(String packageName, 10684 PackageParser.ServiceIntentInfo info) { 10685 return packageName.equals(info.service.owner.packageName); 10686 } 10687 10688 @Override 10689 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10690 int match, int userId) { 10691 if (!sUserManager.exists(userId)) return null; 10692 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10693 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10694 return null; 10695 } 10696 final PackageParser.Service service = info.service; 10697 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10698 if (ps == null) { 10699 return null; 10700 } 10701 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10702 ps.readUserState(userId), userId); 10703 if (si == null) { 10704 return null; 10705 } 10706 final ResolveInfo res = new ResolveInfo(); 10707 res.serviceInfo = si; 10708 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10709 res.filter = filter; 10710 } 10711 res.priority = info.getPriority(); 10712 res.preferredOrder = service.owner.mPreferredOrder; 10713 res.match = match; 10714 res.isDefault = info.hasDefault; 10715 res.labelRes = info.labelRes; 10716 res.nonLocalizedLabel = info.nonLocalizedLabel; 10717 res.icon = info.icon; 10718 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10719 return res; 10720 } 10721 10722 @Override 10723 protected void sortResults(List<ResolveInfo> results) { 10724 Collections.sort(results, mResolvePrioritySorter); 10725 } 10726 10727 @Override 10728 protected void dumpFilter(PrintWriter out, String prefix, 10729 PackageParser.ServiceIntentInfo filter) { 10730 out.print(prefix); out.print( 10731 Integer.toHexString(System.identityHashCode(filter.service))); 10732 out.print(' '); 10733 filter.service.printComponentShortName(out); 10734 out.print(" filter "); 10735 out.println(Integer.toHexString(System.identityHashCode(filter))); 10736 } 10737 10738 @Override 10739 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10740 return filter.service; 10741 } 10742 10743 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10744 PackageParser.Service service = (PackageParser.Service)label; 10745 out.print(prefix); out.print( 10746 Integer.toHexString(System.identityHashCode(service))); 10747 out.print(' '); 10748 service.printComponentShortName(out); 10749 if (count > 1) { 10750 out.print(" ("); out.print(count); out.print(" filters)"); 10751 } 10752 out.println(); 10753 } 10754 10755// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10756// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10757// final List<ResolveInfo> retList = Lists.newArrayList(); 10758// while (i.hasNext()) { 10759// final ResolveInfo resolveInfo = (ResolveInfo) i; 10760// if (isEnabledLP(resolveInfo.serviceInfo)) { 10761// retList.add(resolveInfo); 10762// } 10763// } 10764// return retList; 10765// } 10766 10767 // Keys are String (activity class name), values are Activity. 10768 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10769 = new ArrayMap<ComponentName, PackageParser.Service>(); 10770 private int mFlags; 10771 }; 10772 10773 private final class ProviderIntentResolver 10774 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10775 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10776 boolean defaultOnly, int userId) { 10777 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10778 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10779 } 10780 10781 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10782 int userId) { 10783 if (!sUserManager.exists(userId)) 10784 return null; 10785 mFlags = flags; 10786 return super.queryIntent(intent, resolvedType, 10787 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10788 } 10789 10790 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10791 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10792 if (!sUserManager.exists(userId)) 10793 return null; 10794 if (packageProviders == null) { 10795 return null; 10796 } 10797 mFlags = flags; 10798 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10799 final int N = packageProviders.size(); 10800 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10801 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10802 10803 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10804 for (int i = 0; i < N; ++i) { 10805 intentFilters = packageProviders.get(i).intents; 10806 if (intentFilters != null && intentFilters.size() > 0) { 10807 PackageParser.ProviderIntentInfo[] array = 10808 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10809 intentFilters.toArray(array); 10810 listCut.add(array); 10811 } 10812 } 10813 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10814 } 10815 10816 public final void addProvider(PackageParser.Provider p) { 10817 if (mProviders.containsKey(p.getComponentName())) { 10818 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10819 return; 10820 } 10821 10822 mProviders.put(p.getComponentName(), p); 10823 if (DEBUG_SHOW_INFO) { 10824 Log.v(TAG, " " 10825 + (p.info.nonLocalizedLabel != null 10826 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10827 Log.v(TAG, " Class=" + p.info.name); 10828 } 10829 final int NI = p.intents.size(); 10830 int j; 10831 for (j = 0; j < NI; j++) { 10832 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10833 if (DEBUG_SHOW_INFO) { 10834 Log.v(TAG, " IntentFilter:"); 10835 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10836 } 10837 if (!intent.debugCheck()) { 10838 Log.w(TAG, "==> For Provider " + p.info.name); 10839 } 10840 addFilter(intent); 10841 } 10842 } 10843 10844 public final void removeProvider(PackageParser.Provider p) { 10845 mProviders.remove(p.getComponentName()); 10846 if (DEBUG_SHOW_INFO) { 10847 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10848 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10849 Log.v(TAG, " Class=" + p.info.name); 10850 } 10851 final int NI = p.intents.size(); 10852 int j; 10853 for (j = 0; j < NI; j++) { 10854 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10855 if (DEBUG_SHOW_INFO) { 10856 Log.v(TAG, " IntentFilter:"); 10857 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10858 } 10859 removeFilter(intent); 10860 } 10861 } 10862 10863 @Override 10864 protected boolean allowFilterResult( 10865 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10866 ProviderInfo filterPi = filter.provider.info; 10867 for (int i = dest.size() - 1; i >= 0; i--) { 10868 ProviderInfo destPi = dest.get(i).providerInfo; 10869 if (destPi.name == filterPi.name 10870 && destPi.packageName == filterPi.packageName) { 10871 return false; 10872 } 10873 } 10874 return true; 10875 } 10876 10877 @Override 10878 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10879 return new PackageParser.ProviderIntentInfo[size]; 10880 } 10881 10882 @Override 10883 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10884 if (!sUserManager.exists(userId)) 10885 return true; 10886 PackageParser.Package p = filter.provider.owner; 10887 if (p != null) { 10888 PackageSetting ps = (PackageSetting) p.mExtras; 10889 if (ps != null) { 10890 // System apps are never considered stopped for purposes of 10891 // filtering, because there may be no way for the user to 10892 // actually re-launch them. 10893 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10894 && ps.getStopped(userId); 10895 } 10896 } 10897 return false; 10898 } 10899 10900 @Override 10901 protected boolean isPackageForFilter(String packageName, 10902 PackageParser.ProviderIntentInfo info) { 10903 return packageName.equals(info.provider.owner.packageName); 10904 } 10905 10906 @Override 10907 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10908 int match, int userId) { 10909 if (!sUserManager.exists(userId)) 10910 return null; 10911 final PackageParser.ProviderIntentInfo info = filter; 10912 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10913 return null; 10914 } 10915 final PackageParser.Provider provider = info.provider; 10916 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10917 if (ps == null) { 10918 return null; 10919 } 10920 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10921 ps.readUserState(userId), userId); 10922 if (pi == null) { 10923 return null; 10924 } 10925 final ResolveInfo res = new ResolveInfo(); 10926 res.providerInfo = pi; 10927 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10928 res.filter = filter; 10929 } 10930 res.priority = info.getPriority(); 10931 res.preferredOrder = provider.owner.mPreferredOrder; 10932 res.match = match; 10933 res.isDefault = info.hasDefault; 10934 res.labelRes = info.labelRes; 10935 res.nonLocalizedLabel = info.nonLocalizedLabel; 10936 res.icon = info.icon; 10937 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10938 return res; 10939 } 10940 10941 @Override 10942 protected void sortResults(List<ResolveInfo> results) { 10943 Collections.sort(results, mResolvePrioritySorter); 10944 } 10945 10946 @Override 10947 protected void dumpFilter(PrintWriter out, String prefix, 10948 PackageParser.ProviderIntentInfo filter) { 10949 out.print(prefix); 10950 out.print( 10951 Integer.toHexString(System.identityHashCode(filter.provider))); 10952 out.print(' '); 10953 filter.provider.printComponentShortName(out); 10954 out.print(" filter "); 10955 out.println(Integer.toHexString(System.identityHashCode(filter))); 10956 } 10957 10958 @Override 10959 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10960 return filter.provider; 10961 } 10962 10963 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10964 PackageParser.Provider provider = (PackageParser.Provider)label; 10965 out.print(prefix); out.print( 10966 Integer.toHexString(System.identityHashCode(provider))); 10967 out.print(' '); 10968 provider.printComponentShortName(out); 10969 if (count > 1) { 10970 out.print(" ("); out.print(count); out.print(" filters)"); 10971 } 10972 out.println(); 10973 } 10974 10975 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10976 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10977 private int mFlags; 10978 } 10979 10980 private static final class EphemeralIntentResolver 10981 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10982 @Override 10983 protected EphemeralResolveIntentInfo[] newArray(int size) { 10984 return new EphemeralResolveIntentInfo[size]; 10985 } 10986 10987 @Override 10988 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10989 return true; 10990 } 10991 10992 @Override 10993 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10994 int userId) { 10995 if (!sUserManager.exists(userId)) { 10996 return null; 10997 } 10998 return info.getEphemeralResolveInfo(); 10999 } 11000 } 11001 11002 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11003 new Comparator<ResolveInfo>() { 11004 public int compare(ResolveInfo r1, ResolveInfo r2) { 11005 int v1 = r1.priority; 11006 int v2 = r2.priority; 11007 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11008 if (v1 != v2) { 11009 return (v1 > v2) ? -1 : 1; 11010 } 11011 v1 = r1.preferredOrder; 11012 v2 = r2.preferredOrder; 11013 if (v1 != v2) { 11014 return (v1 > v2) ? -1 : 1; 11015 } 11016 if (r1.isDefault != r2.isDefault) { 11017 return r1.isDefault ? -1 : 1; 11018 } 11019 v1 = r1.match; 11020 v2 = r2.match; 11021 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11022 if (v1 != v2) { 11023 return (v1 > v2) ? -1 : 1; 11024 } 11025 if (r1.system != r2.system) { 11026 return r1.system ? -1 : 1; 11027 } 11028 if (r1.activityInfo != null) { 11029 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11030 } 11031 if (r1.serviceInfo != null) { 11032 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11033 } 11034 if (r1.providerInfo != null) { 11035 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11036 } 11037 return 0; 11038 } 11039 }; 11040 11041 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11042 new Comparator<ProviderInfo>() { 11043 public int compare(ProviderInfo p1, ProviderInfo p2) { 11044 final int v1 = p1.initOrder; 11045 final int v2 = p2.initOrder; 11046 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11047 } 11048 }; 11049 11050 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11051 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11052 final int[] userIds) { 11053 mHandler.post(new Runnable() { 11054 @Override 11055 public void run() { 11056 try { 11057 final IActivityManager am = ActivityManagerNative.getDefault(); 11058 if (am == null) return; 11059 final int[] resolvedUserIds; 11060 if (userIds == null) { 11061 resolvedUserIds = am.getRunningUserIds(); 11062 } else { 11063 resolvedUserIds = userIds; 11064 } 11065 for (int id : resolvedUserIds) { 11066 final Intent intent = new Intent(action, 11067 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11068 if (extras != null) { 11069 intent.putExtras(extras); 11070 } 11071 if (targetPkg != null) { 11072 intent.setPackage(targetPkg); 11073 } 11074 // Modify the UID when posting to other users 11075 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11076 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11077 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11078 intent.putExtra(Intent.EXTRA_UID, uid); 11079 } 11080 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11081 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11082 if (DEBUG_BROADCASTS) { 11083 RuntimeException here = new RuntimeException("here"); 11084 here.fillInStackTrace(); 11085 Slog.d(TAG, "Sending to user " + id + ": " 11086 + intent.toShortString(false, true, false, false) 11087 + " " + intent.getExtras(), here); 11088 } 11089 am.broadcastIntent(null, intent, null, finishedReceiver, 11090 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11091 null, finishedReceiver != null, false, id); 11092 } 11093 } catch (RemoteException ex) { 11094 } 11095 } 11096 }); 11097 } 11098 11099 /** 11100 * Check if the external storage media is available. This is true if there 11101 * is a mounted external storage medium or if the external storage is 11102 * emulated. 11103 */ 11104 private boolean isExternalMediaAvailable() { 11105 return mMediaMounted || Environment.isExternalStorageEmulated(); 11106 } 11107 11108 @Override 11109 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11110 // writer 11111 synchronized (mPackages) { 11112 if (!isExternalMediaAvailable()) { 11113 // If the external storage is no longer mounted at this point, 11114 // the caller may not have been able to delete all of this 11115 // packages files and can not delete any more. Bail. 11116 return null; 11117 } 11118 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11119 if (lastPackage != null) { 11120 pkgs.remove(lastPackage); 11121 } 11122 if (pkgs.size() > 0) { 11123 return pkgs.get(0); 11124 } 11125 } 11126 return null; 11127 } 11128 11129 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11130 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11131 userId, andCode ? 1 : 0, packageName); 11132 if (mSystemReady) { 11133 msg.sendToTarget(); 11134 } else { 11135 if (mPostSystemReadyMessages == null) { 11136 mPostSystemReadyMessages = new ArrayList<>(); 11137 } 11138 mPostSystemReadyMessages.add(msg); 11139 } 11140 } 11141 11142 void startCleaningPackages() { 11143 // reader 11144 if (!isExternalMediaAvailable()) { 11145 return; 11146 } 11147 synchronized (mPackages) { 11148 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11149 return; 11150 } 11151 } 11152 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11153 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11154 IActivityManager am = ActivityManagerNative.getDefault(); 11155 if (am != null) { 11156 try { 11157 am.startService(null, intent, null, mContext.getOpPackageName(), 11158 UserHandle.USER_SYSTEM); 11159 } catch (RemoteException e) { 11160 } 11161 } 11162 } 11163 11164 @Override 11165 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11166 int installFlags, String installerPackageName, int userId) { 11167 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11168 11169 final int callingUid = Binder.getCallingUid(); 11170 enforceCrossUserPermission(callingUid, userId, 11171 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11172 11173 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11174 try { 11175 if (observer != null) { 11176 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11177 } 11178 } catch (RemoteException re) { 11179 } 11180 return; 11181 } 11182 11183 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11184 installFlags |= PackageManager.INSTALL_FROM_ADB; 11185 11186 } else { 11187 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11188 // about installerPackageName. 11189 11190 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11191 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11192 } 11193 11194 UserHandle user; 11195 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11196 user = UserHandle.ALL; 11197 } else { 11198 user = new UserHandle(userId); 11199 } 11200 11201 // Only system components can circumvent runtime permissions when installing. 11202 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11203 && mContext.checkCallingOrSelfPermission(Manifest.permission 11204 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11205 throw new SecurityException("You need the " 11206 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11207 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11208 } 11209 11210 final File originFile = new File(originPath); 11211 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11212 11213 final Message msg = mHandler.obtainMessage(INIT_COPY); 11214 final VerificationInfo verificationInfo = new VerificationInfo( 11215 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11216 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11217 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11218 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11219 null /*certificates*/); 11220 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11221 msg.obj = params; 11222 11223 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11224 System.identityHashCode(msg.obj)); 11225 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11226 System.identityHashCode(msg.obj)); 11227 11228 mHandler.sendMessage(msg); 11229 } 11230 11231 void installStage(String packageName, File stagedDir, String stagedCid, 11232 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11233 String installerPackageName, int installerUid, UserHandle user, 11234 Certificate[][] certificates) { 11235 if (DEBUG_EPHEMERAL) { 11236 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11237 Slog.d(TAG, "Ephemeral install of " + packageName); 11238 } 11239 } 11240 final VerificationInfo verificationInfo = new VerificationInfo( 11241 sessionParams.originatingUri, sessionParams.referrerUri, 11242 sessionParams.originatingUid, installerUid); 11243 11244 final OriginInfo origin; 11245 if (stagedDir != null) { 11246 origin = OriginInfo.fromStagedFile(stagedDir); 11247 } else { 11248 origin = OriginInfo.fromStagedContainer(stagedCid); 11249 } 11250 11251 final Message msg = mHandler.obtainMessage(INIT_COPY); 11252 final InstallParams params = new InstallParams(origin, null, observer, 11253 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11254 verificationInfo, user, sessionParams.abiOverride, 11255 sessionParams.grantedRuntimePermissions, certificates); 11256 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11257 msg.obj = params; 11258 11259 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11260 System.identityHashCode(msg.obj)); 11261 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11262 System.identityHashCode(msg.obj)); 11263 11264 mHandler.sendMessage(msg); 11265 } 11266 11267 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11268 int userId) { 11269 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11270 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11271 } 11272 11273 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11274 int appId, int userId) { 11275 Bundle extras = new Bundle(1); 11276 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11277 11278 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11279 packageName, extras, 0, null, null, new int[] {userId}); 11280 try { 11281 IActivityManager am = ActivityManagerNative.getDefault(); 11282 if (isSystem && am.isUserRunning(userId, 0)) { 11283 // The just-installed/enabled app is bundled on the system, so presumed 11284 // to be able to run automatically without needing an explicit launch. 11285 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11286 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11287 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11288 .setPackage(packageName); 11289 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11290 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11291 } 11292 } catch (RemoteException e) { 11293 // shouldn't happen 11294 Slog.w(TAG, "Unable to bootstrap installed package", e); 11295 } 11296 } 11297 11298 @Override 11299 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11300 int userId) { 11301 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11302 PackageSetting pkgSetting; 11303 final int uid = Binder.getCallingUid(); 11304 enforceCrossUserPermission(uid, userId, 11305 true /* requireFullPermission */, true /* checkShell */, 11306 "setApplicationHiddenSetting for user " + userId); 11307 11308 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11309 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11310 return false; 11311 } 11312 11313 long callingId = Binder.clearCallingIdentity(); 11314 try { 11315 boolean sendAdded = false; 11316 boolean sendRemoved = false; 11317 // writer 11318 synchronized (mPackages) { 11319 pkgSetting = mSettings.mPackages.get(packageName); 11320 if (pkgSetting == null) { 11321 return false; 11322 } 11323 if (pkgSetting.getHidden(userId) != hidden) { 11324 pkgSetting.setHidden(hidden, userId); 11325 mSettings.writePackageRestrictionsLPr(userId); 11326 if (hidden) { 11327 sendRemoved = true; 11328 } else { 11329 sendAdded = true; 11330 } 11331 } 11332 } 11333 if (sendAdded) { 11334 sendPackageAddedForUser(packageName, pkgSetting, userId); 11335 return true; 11336 } 11337 if (sendRemoved) { 11338 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11339 "hiding pkg"); 11340 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11341 return true; 11342 } 11343 } finally { 11344 Binder.restoreCallingIdentity(callingId); 11345 } 11346 return false; 11347 } 11348 11349 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11350 int userId) { 11351 final PackageRemovedInfo info = new PackageRemovedInfo(); 11352 info.removedPackage = packageName; 11353 info.removedUsers = new int[] {userId}; 11354 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11355 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11356 } 11357 11358 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11359 if (pkgList.length > 0) { 11360 Bundle extras = new Bundle(1); 11361 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11362 11363 sendPackageBroadcast( 11364 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11365 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11366 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11367 new int[] {userId}); 11368 } 11369 } 11370 11371 /** 11372 * Returns true if application is not found or there was an error. Otherwise it returns 11373 * the hidden state of the package for the given user. 11374 */ 11375 @Override 11376 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11377 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11378 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11379 true /* requireFullPermission */, false /* checkShell */, 11380 "getApplicationHidden for user " + userId); 11381 PackageSetting pkgSetting; 11382 long callingId = Binder.clearCallingIdentity(); 11383 try { 11384 // writer 11385 synchronized (mPackages) { 11386 pkgSetting = mSettings.mPackages.get(packageName); 11387 if (pkgSetting == null) { 11388 return true; 11389 } 11390 return pkgSetting.getHidden(userId); 11391 } 11392 } finally { 11393 Binder.restoreCallingIdentity(callingId); 11394 } 11395 } 11396 11397 /** 11398 * @hide 11399 */ 11400 @Override 11401 public int installExistingPackageAsUser(String packageName, int userId) { 11402 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11403 null); 11404 PackageSetting pkgSetting; 11405 final int uid = Binder.getCallingUid(); 11406 enforceCrossUserPermission(uid, userId, 11407 true /* requireFullPermission */, true /* checkShell */, 11408 "installExistingPackage for user " + userId); 11409 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11410 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11411 } 11412 11413 long callingId = Binder.clearCallingIdentity(); 11414 try { 11415 boolean installed = false; 11416 11417 // writer 11418 synchronized (mPackages) { 11419 pkgSetting = mSettings.mPackages.get(packageName); 11420 if (pkgSetting == null) { 11421 return PackageManager.INSTALL_FAILED_INVALID_URI; 11422 } 11423 if (!pkgSetting.getInstalled(userId)) { 11424 pkgSetting.setInstalled(true, userId); 11425 pkgSetting.setHidden(false, userId); 11426 mSettings.writePackageRestrictionsLPr(userId); 11427 installed = true; 11428 } 11429 } 11430 11431 if (installed) { 11432 if (pkgSetting.pkg != null) { 11433 synchronized (mInstallLock) { 11434 // We don't need to freeze for a brand new install 11435 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11436 } 11437 } 11438 sendPackageAddedForUser(packageName, pkgSetting, userId); 11439 } 11440 } finally { 11441 Binder.restoreCallingIdentity(callingId); 11442 } 11443 11444 return PackageManager.INSTALL_SUCCEEDED; 11445 } 11446 11447 boolean isUserRestricted(int userId, String restrictionKey) { 11448 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11449 if (restrictions.getBoolean(restrictionKey, false)) { 11450 Log.w(TAG, "User is restricted: " + restrictionKey); 11451 return true; 11452 } 11453 return false; 11454 } 11455 11456 @Override 11457 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11458 int userId) { 11459 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11460 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11461 true /* requireFullPermission */, true /* checkShell */, 11462 "setPackagesSuspended for user " + userId); 11463 11464 if (ArrayUtils.isEmpty(packageNames)) { 11465 return packageNames; 11466 } 11467 11468 // List of package names for whom the suspended state has changed. 11469 List<String> changedPackages = new ArrayList<>(packageNames.length); 11470 // List of package names for whom the suspended state is not set as requested in this 11471 // method. 11472 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11473 for (int i = 0; i < packageNames.length; i++) { 11474 String packageName = packageNames[i]; 11475 long callingId = Binder.clearCallingIdentity(); 11476 try { 11477 boolean changed = false; 11478 final int appId; 11479 synchronized (mPackages) { 11480 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11481 if (pkgSetting == null) { 11482 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11483 + "\". Skipping suspending/un-suspending."); 11484 unactionedPackages.add(packageName); 11485 continue; 11486 } 11487 appId = pkgSetting.appId; 11488 if (pkgSetting.getSuspended(userId) != suspended) { 11489 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11490 unactionedPackages.add(packageName); 11491 continue; 11492 } 11493 pkgSetting.setSuspended(suspended, userId); 11494 mSettings.writePackageRestrictionsLPr(userId); 11495 changed = true; 11496 changedPackages.add(packageName); 11497 } 11498 } 11499 11500 if (changed && suspended) { 11501 killApplication(packageName, UserHandle.getUid(userId, appId), 11502 "suspending package"); 11503 } 11504 } finally { 11505 Binder.restoreCallingIdentity(callingId); 11506 } 11507 } 11508 11509 if (!changedPackages.isEmpty()) { 11510 sendPackagesSuspendedForUser(changedPackages.toArray( 11511 new String[changedPackages.size()]), userId, suspended); 11512 } 11513 11514 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11515 } 11516 11517 @Override 11518 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11519 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11520 true /* requireFullPermission */, false /* checkShell */, 11521 "isPackageSuspendedForUser for user " + userId); 11522 synchronized (mPackages) { 11523 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11524 if (pkgSetting == null) { 11525 throw new IllegalArgumentException("Unknown target package: " + packageName); 11526 } 11527 return pkgSetting.getSuspended(userId); 11528 } 11529 } 11530 11531 /** 11532 * TODO: cache and disallow blocking the active dialer. 11533 * 11534 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11535 */ 11536 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11537 if (isPackageDeviceAdmin(packageName, userId)) { 11538 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11539 + "\": has an active device admin"); 11540 return false; 11541 } 11542 11543 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11544 if (packageName.equals(activeLauncherPackageName)) { 11545 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11546 + "\": contains the active launcher"); 11547 return false; 11548 } 11549 11550 if (packageName.equals(mRequiredInstallerPackage)) { 11551 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11552 + "\": required for package installation"); 11553 return false; 11554 } 11555 11556 if (packageName.equals(mRequiredVerifierPackage)) { 11557 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11558 + "\": required for package verification"); 11559 return false; 11560 } 11561 11562 final PackageParser.Package pkg = mPackages.get(packageName); 11563 if (pkg != null && isPrivilegedApp(pkg)) { 11564 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11565 + "\": is a privileged app"); 11566 return false; 11567 } 11568 11569 return true; 11570 } 11571 11572 private String getActiveLauncherPackageName(int userId) { 11573 Intent intent = new Intent(Intent.ACTION_MAIN); 11574 intent.addCategory(Intent.CATEGORY_HOME); 11575 ResolveInfo resolveInfo = resolveIntent( 11576 intent, 11577 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11578 PackageManager.MATCH_DEFAULT_ONLY, 11579 userId); 11580 11581 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11582 } 11583 11584 @Override 11585 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11586 mContext.enforceCallingOrSelfPermission( 11587 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11588 "Only package verification agents can verify applications"); 11589 11590 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11591 final PackageVerificationResponse response = new PackageVerificationResponse( 11592 verificationCode, Binder.getCallingUid()); 11593 msg.arg1 = id; 11594 msg.obj = response; 11595 mHandler.sendMessage(msg); 11596 } 11597 11598 @Override 11599 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11600 long millisecondsToDelay) { 11601 mContext.enforceCallingOrSelfPermission( 11602 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11603 "Only package verification agents can extend verification timeouts"); 11604 11605 final PackageVerificationState state = mPendingVerification.get(id); 11606 final PackageVerificationResponse response = new PackageVerificationResponse( 11607 verificationCodeAtTimeout, Binder.getCallingUid()); 11608 11609 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11610 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11611 } 11612 if (millisecondsToDelay < 0) { 11613 millisecondsToDelay = 0; 11614 } 11615 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11616 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11617 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11618 } 11619 11620 if ((state != null) && !state.timeoutExtended()) { 11621 state.extendTimeout(); 11622 11623 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11624 msg.arg1 = id; 11625 msg.obj = response; 11626 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11627 } 11628 } 11629 11630 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11631 int verificationCode, UserHandle user) { 11632 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11633 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11634 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11635 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11636 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11637 11638 mContext.sendBroadcastAsUser(intent, user, 11639 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11640 } 11641 11642 private ComponentName matchComponentForVerifier(String packageName, 11643 List<ResolveInfo> receivers) { 11644 ActivityInfo targetReceiver = null; 11645 11646 final int NR = receivers.size(); 11647 for (int i = 0; i < NR; i++) { 11648 final ResolveInfo info = receivers.get(i); 11649 if (info.activityInfo == null) { 11650 continue; 11651 } 11652 11653 if (packageName.equals(info.activityInfo.packageName)) { 11654 targetReceiver = info.activityInfo; 11655 break; 11656 } 11657 } 11658 11659 if (targetReceiver == null) { 11660 return null; 11661 } 11662 11663 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11664 } 11665 11666 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11667 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11668 if (pkgInfo.verifiers.length == 0) { 11669 return null; 11670 } 11671 11672 final int N = pkgInfo.verifiers.length; 11673 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11674 for (int i = 0; i < N; i++) { 11675 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11676 11677 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11678 receivers); 11679 if (comp == null) { 11680 continue; 11681 } 11682 11683 final int verifierUid = getUidForVerifier(verifierInfo); 11684 if (verifierUid == -1) { 11685 continue; 11686 } 11687 11688 if (DEBUG_VERIFY) { 11689 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11690 + " with the correct signature"); 11691 } 11692 sufficientVerifiers.add(comp); 11693 verificationState.addSufficientVerifier(verifierUid); 11694 } 11695 11696 return sufficientVerifiers; 11697 } 11698 11699 private int getUidForVerifier(VerifierInfo verifierInfo) { 11700 synchronized (mPackages) { 11701 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11702 if (pkg == null) { 11703 return -1; 11704 } else if (pkg.mSignatures.length != 1) { 11705 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11706 + " has more than one signature; ignoring"); 11707 return -1; 11708 } 11709 11710 /* 11711 * If the public key of the package's signature does not match 11712 * our expected public key, then this is a different package and 11713 * we should skip. 11714 */ 11715 11716 final byte[] expectedPublicKey; 11717 try { 11718 final Signature verifierSig = pkg.mSignatures[0]; 11719 final PublicKey publicKey = verifierSig.getPublicKey(); 11720 expectedPublicKey = publicKey.getEncoded(); 11721 } catch (CertificateException e) { 11722 return -1; 11723 } 11724 11725 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11726 11727 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11728 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11729 + " does not have the expected public key; ignoring"); 11730 return -1; 11731 } 11732 11733 return pkg.applicationInfo.uid; 11734 } 11735 } 11736 11737 @Override 11738 public void finishPackageInstall(int token, boolean didLaunch) { 11739 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11740 11741 if (DEBUG_INSTALL) { 11742 Slog.v(TAG, "BM finishing package install for " + token); 11743 } 11744 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11745 11746 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11747 mHandler.sendMessage(msg); 11748 } 11749 11750 /** 11751 * Get the verification agent timeout. 11752 * 11753 * @return verification timeout in milliseconds 11754 */ 11755 private long getVerificationTimeout() { 11756 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11757 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11758 DEFAULT_VERIFICATION_TIMEOUT); 11759 } 11760 11761 /** 11762 * Get the default verification agent response code. 11763 * 11764 * @return default verification response code 11765 */ 11766 private int getDefaultVerificationResponse() { 11767 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11768 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11769 DEFAULT_VERIFICATION_RESPONSE); 11770 } 11771 11772 /** 11773 * Check whether or not package verification has been enabled. 11774 * 11775 * @return true if verification should be performed 11776 */ 11777 private boolean isVerificationEnabled(int userId, int installFlags) { 11778 if (!DEFAULT_VERIFY_ENABLE) { 11779 return false; 11780 } 11781 // Ephemeral apps don't get the full verification treatment 11782 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11783 if (DEBUG_EPHEMERAL) { 11784 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11785 } 11786 return false; 11787 } 11788 11789 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11790 11791 // Check if installing from ADB 11792 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11793 // Do not run verification in a test harness environment 11794 if (ActivityManager.isRunningInTestHarness()) { 11795 return false; 11796 } 11797 if (ensureVerifyAppsEnabled) { 11798 return true; 11799 } 11800 // Check if the developer does not want package verification for ADB installs 11801 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11802 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11803 return false; 11804 } 11805 } 11806 11807 if (ensureVerifyAppsEnabled) { 11808 return true; 11809 } 11810 11811 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11812 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11813 } 11814 11815 @Override 11816 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11817 throws RemoteException { 11818 mContext.enforceCallingOrSelfPermission( 11819 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11820 "Only intentfilter verification agents can verify applications"); 11821 11822 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11823 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11824 Binder.getCallingUid(), verificationCode, failedDomains); 11825 msg.arg1 = id; 11826 msg.obj = response; 11827 mHandler.sendMessage(msg); 11828 } 11829 11830 @Override 11831 public int getIntentVerificationStatus(String packageName, int userId) { 11832 synchronized (mPackages) { 11833 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11834 } 11835 } 11836 11837 @Override 11838 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11839 mContext.enforceCallingOrSelfPermission( 11840 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11841 11842 boolean result = false; 11843 synchronized (mPackages) { 11844 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11845 } 11846 if (result) { 11847 scheduleWritePackageRestrictionsLocked(userId); 11848 } 11849 return result; 11850 } 11851 11852 @Override 11853 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11854 String packageName) { 11855 synchronized (mPackages) { 11856 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11857 } 11858 } 11859 11860 @Override 11861 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11862 if (TextUtils.isEmpty(packageName)) { 11863 return ParceledListSlice.emptyList(); 11864 } 11865 synchronized (mPackages) { 11866 PackageParser.Package pkg = mPackages.get(packageName); 11867 if (pkg == null || pkg.activities == null) { 11868 return ParceledListSlice.emptyList(); 11869 } 11870 final int count = pkg.activities.size(); 11871 ArrayList<IntentFilter> result = new ArrayList<>(); 11872 for (int n=0; n<count; n++) { 11873 PackageParser.Activity activity = pkg.activities.get(n); 11874 if (activity.intents != null && activity.intents.size() > 0) { 11875 result.addAll(activity.intents); 11876 } 11877 } 11878 return new ParceledListSlice<>(result); 11879 } 11880 } 11881 11882 @Override 11883 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11884 mContext.enforceCallingOrSelfPermission( 11885 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11886 11887 synchronized (mPackages) { 11888 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11889 if (packageName != null) { 11890 result |= updateIntentVerificationStatus(packageName, 11891 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11892 userId); 11893 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11894 packageName, userId); 11895 } 11896 return result; 11897 } 11898 } 11899 11900 @Override 11901 public String getDefaultBrowserPackageName(int userId) { 11902 synchronized (mPackages) { 11903 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11904 } 11905 } 11906 11907 /** 11908 * Get the "allow unknown sources" setting. 11909 * 11910 * @return the current "allow unknown sources" setting 11911 */ 11912 private int getUnknownSourcesSettings() { 11913 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11914 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11915 -1); 11916 } 11917 11918 @Override 11919 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11920 final int uid = Binder.getCallingUid(); 11921 // writer 11922 synchronized (mPackages) { 11923 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11924 if (targetPackageSetting == null) { 11925 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11926 } 11927 11928 PackageSetting installerPackageSetting; 11929 if (installerPackageName != null) { 11930 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11931 if (installerPackageSetting == null) { 11932 throw new IllegalArgumentException("Unknown installer package: " 11933 + installerPackageName); 11934 } 11935 } else { 11936 installerPackageSetting = null; 11937 } 11938 11939 Signature[] callerSignature; 11940 Object obj = mSettings.getUserIdLPr(uid); 11941 if (obj != null) { 11942 if (obj instanceof SharedUserSetting) { 11943 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11944 } else if (obj instanceof PackageSetting) { 11945 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11946 } else { 11947 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11948 } 11949 } else { 11950 throw new SecurityException("Unknown calling UID: " + uid); 11951 } 11952 11953 // Verify: can't set installerPackageName to a package that is 11954 // not signed with the same cert as the caller. 11955 if (installerPackageSetting != null) { 11956 if (compareSignatures(callerSignature, 11957 installerPackageSetting.signatures.mSignatures) 11958 != PackageManager.SIGNATURE_MATCH) { 11959 throw new SecurityException( 11960 "Caller does not have same cert as new installer package " 11961 + installerPackageName); 11962 } 11963 } 11964 11965 // Verify: if target already has an installer package, it must 11966 // be signed with the same cert as the caller. 11967 if (targetPackageSetting.installerPackageName != null) { 11968 PackageSetting setting = mSettings.mPackages.get( 11969 targetPackageSetting.installerPackageName); 11970 // If the currently set package isn't valid, then it's always 11971 // okay to change it. 11972 if (setting != null) { 11973 if (compareSignatures(callerSignature, 11974 setting.signatures.mSignatures) 11975 != PackageManager.SIGNATURE_MATCH) { 11976 throw new SecurityException( 11977 "Caller does not have same cert as old installer package " 11978 + targetPackageSetting.installerPackageName); 11979 } 11980 } 11981 } 11982 11983 // Okay! 11984 targetPackageSetting.installerPackageName = installerPackageName; 11985 if (installerPackageName != null) { 11986 mSettings.mInstallerPackages.add(installerPackageName); 11987 } 11988 scheduleWriteSettingsLocked(); 11989 } 11990 } 11991 11992 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11993 // Queue up an async operation since the package installation may take a little while. 11994 mHandler.post(new Runnable() { 11995 public void run() { 11996 mHandler.removeCallbacks(this); 11997 // Result object to be returned 11998 PackageInstalledInfo res = new PackageInstalledInfo(); 11999 res.setReturnCode(currentStatus); 12000 res.uid = -1; 12001 res.pkg = null; 12002 res.removedInfo = null; 12003 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12004 args.doPreInstall(res.returnCode); 12005 synchronized (mInstallLock) { 12006 installPackageTracedLI(args, res); 12007 } 12008 args.doPostInstall(res.returnCode, res.uid); 12009 } 12010 12011 // A restore should be performed at this point if (a) the install 12012 // succeeded, (b) the operation is not an update, and (c) the new 12013 // package has not opted out of backup participation. 12014 final boolean update = res.removedInfo != null 12015 && res.removedInfo.removedPackage != null; 12016 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12017 boolean doRestore = !update 12018 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12019 12020 // Set up the post-install work request bookkeeping. This will be used 12021 // and cleaned up by the post-install event handling regardless of whether 12022 // there's a restore pass performed. Token values are >= 1. 12023 int token; 12024 if (mNextInstallToken < 0) mNextInstallToken = 1; 12025 token = mNextInstallToken++; 12026 12027 PostInstallData data = new PostInstallData(args, res); 12028 mRunningInstalls.put(token, data); 12029 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12030 12031 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12032 // Pass responsibility to the Backup Manager. It will perform a 12033 // restore if appropriate, then pass responsibility back to the 12034 // Package Manager to run the post-install observer callbacks 12035 // and broadcasts. 12036 IBackupManager bm = IBackupManager.Stub.asInterface( 12037 ServiceManager.getService(Context.BACKUP_SERVICE)); 12038 if (bm != null) { 12039 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12040 + " to BM for possible restore"); 12041 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12042 try { 12043 // TODO: http://b/22388012 12044 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12045 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12046 } else { 12047 doRestore = false; 12048 } 12049 } catch (RemoteException e) { 12050 // can't happen; the backup manager is local 12051 } catch (Exception e) { 12052 Slog.e(TAG, "Exception trying to enqueue restore", e); 12053 doRestore = false; 12054 } 12055 } else { 12056 Slog.e(TAG, "Backup Manager not found!"); 12057 doRestore = false; 12058 } 12059 } 12060 12061 if (!doRestore) { 12062 // No restore possible, or the Backup Manager was mysteriously not 12063 // available -- just fire the post-install work request directly. 12064 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12065 12066 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12067 12068 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12069 mHandler.sendMessage(msg); 12070 } 12071 } 12072 }); 12073 } 12074 12075 /** 12076 * Callback from PackageSettings whenever an app is first transitioned out of the 12077 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12078 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12079 * here whether the app is the target of an ongoing install, and only send the 12080 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12081 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12082 * handling. 12083 */ 12084 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12085 // Serialize this with the rest of the install-process message chain. In the 12086 // restore-at-install case, this Runnable will necessarily run before the 12087 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12088 // are coherent. In the non-restore case, the app has already completed install 12089 // and been launched through some other means, so it is not in a problematic 12090 // state for observers to see the FIRST_LAUNCH signal. 12091 mHandler.post(new Runnable() { 12092 @Override 12093 public void run() { 12094 for (int i = 0; i < mRunningInstalls.size(); i++) { 12095 final PostInstallData data = mRunningInstalls.valueAt(i); 12096 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12097 // right package; but is it for the right user? 12098 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12099 if (userId == data.res.newUsers[uIndex]) { 12100 if (DEBUG_BACKUP) { 12101 Slog.i(TAG, "Package " + pkgName 12102 + " being restored so deferring FIRST_LAUNCH"); 12103 } 12104 return; 12105 } 12106 } 12107 } 12108 } 12109 // didn't find it, so not being restored 12110 if (DEBUG_BACKUP) { 12111 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12112 } 12113 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12114 } 12115 }); 12116 } 12117 12118 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12119 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12120 installerPkg, null, userIds); 12121 } 12122 12123 private abstract class HandlerParams { 12124 private static final int MAX_RETRIES = 4; 12125 12126 /** 12127 * Number of times startCopy() has been attempted and had a non-fatal 12128 * error. 12129 */ 12130 private int mRetries = 0; 12131 12132 /** User handle for the user requesting the information or installation. */ 12133 private final UserHandle mUser; 12134 String traceMethod; 12135 int traceCookie; 12136 12137 HandlerParams(UserHandle user) { 12138 mUser = user; 12139 } 12140 12141 UserHandle getUser() { 12142 return mUser; 12143 } 12144 12145 HandlerParams setTraceMethod(String traceMethod) { 12146 this.traceMethod = traceMethod; 12147 return this; 12148 } 12149 12150 HandlerParams setTraceCookie(int traceCookie) { 12151 this.traceCookie = traceCookie; 12152 return this; 12153 } 12154 12155 final boolean startCopy() { 12156 boolean res; 12157 try { 12158 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12159 12160 if (++mRetries > MAX_RETRIES) { 12161 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12162 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12163 handleServiceError(); 12164 return false; 12165 } else { 12166 handleStartCopy(); 12167 res = true; 12168 } 12169 } catch (RemoteException e) { 12170 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12171 mHandler.sendEmptyMessage(MCS_RECONNECT); 12172 res = false; 12173 } 12174 handleReturnCode(); 12175 return res; 12176 } 12177 12178 final void serviceError() { 12179 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12180 handleServiceError(); 12181 handleReturnCode(); 12182 } 12183 12184 abstract void handleStartCopy() throws RemoteException; 12185 abstract void handleServiceError(); 12186 abstract void handleReturnCode(); 12187 } 12188 12189 class MeasureParams extends HandlerParams { 12190 private final PackageStats mStats; 12191 private boolean mSuccess; 12192 12193 private final IPackageStatsObserver mObserver; 12194 12195 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12196 super(new UserHandle(stats.userHandle)); 12197 mObserver = observer; 12198 mStats = stats; 12199 } 12200 12201 @Override 12202 public String toString() { 12203 return "MeasureParams{" 12204 + Integer.toHexString(System.identityHashCode(this)) 12205 + " " + mStats.packageName + "}"; 12206 } 12207 12208 @Override 12209 void handleStartCopy() throws RemoteException { 12210 synchronized (mInstallLock) { 12211 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12212 } 12213 12214 if (mSuccess) { 12215 final boolean mounted; 12216 if (Environment.isExternalStorageEmulated()) { 12217 mounted = true; 12218 } else { 12219 final String status = Environment.getExternalStorageState(); 12220 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12221 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12222 } 12223 12224 if (mounted) { 12225 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12226 12227 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12228 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12229 12230 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12231 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12232 12233 // Always subtract cache size, since it's a subdirectory 12234 mStats.externalDataSize -= mStats.externalCacheSize; 12235 12236 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12237 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12238 12239 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12240 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12241 } 12242 } 12243 } 12244 12245 @Override 12246 void handleReturnCode() { 12247 if (mObserver != null) { 12248 try { 12249 mObserver.onGetStatsCompleted(mStats, mSuccess); 12250 } catch (RemoteException e) { 12251 Slog.i(TAG, "Observer no longer exists."); 12252 } 12253 } 12254 } 12255 12256 @Override 12257 void handleServiceError() { 12258 Slog.e(TAG, "Could not measure application " + mStats.packageName 12259 + " external storage"); 12260 } 12261 } 12262 12263 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12264 throws RemoteException { 12265 long result = 0; 12266 for (File path : paths) { 12267 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12268 } 12269 return result; 12270 } 12271 12272 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12273 for (File path : paths) { 12274 try { 12275 mcs.clearDirectory(path.getAbsolutePath()); 12276 } catch (RemoteException e) { 12277 } 12278 } 12279 } 12280 12281 static class OriginInfo { 12282 /** 12283 * Location where install is coming from, before it has been 12284 * copied/renamed into place. This could be a single monolithic APK 12285 * file, or a cluster directory. This location may be untrusted. 12286 */ 12287 final File file; 12288 final String cid; 12289 12290 /** 12291 * Flag indicating that {@link #file} or {@link #cid} has already been 12292 * staged, meaning downstream users don't need to defensively copy the 12293 * contents. 12294 */ 12295 final boolean staged; 12296 12297 /** 12298 * Flag indicating that {@link #file} or {@link #cid} is an already 12299 * installed app that is being moved. 12300 */ 12301 final boolean existing; 12302 12303 final String resolvedPath; 12304 final File resolvedFile; 12305 12306 static OriginInfo fromNothing() { 12307 return new OriginInfo(null, null, false, false); 12308 } 12309 12310 static OriginInfo fromUntrustedFile(File file) { 12311 return new OriginInfo(file, null, false, false); 12312 } 12313 12314 static OriginInfo fromExistingFile(File file) { 12315 return new OriginInfo(file, null, false, true); 12316 } 12317 12318 static OriginInfo fromStagedFile(File file) { 12319 return new OriginInfo(file, null, true, false); 12320 } 12321 12322 static OriginInfo fromStagedContainer(String cid) { 12323 return new OriginInfo(null, cid, true, false); 12324 } 12325 12326 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12327 this.file = file; 12328 this.cid = cid; 12329 this.staged = staged; 12330 this.existing = existing; 12331 12332 if (cid != null) { 12333 resolvedPath = PackageHelper.getSdDir(cid); 12334 resolvedFile = new File(resolvedPath); 12335 } else if (file != null) { 12336 resolvedPath = file.getAbsolutePath(); 12337 resolvedFile = file; 12338 } else { 12339 resolvedPath = null; 12340 resolvedFile = null; 12341 } 12342 } 12343 } 12344 12345 static class MoveInfo { 12346 final int moveId; 12347 final String fromUuid; 12348 final String toUuid; 12349 final String packageName; 12350 final String dataAppName; 12351 final int appId; 12352 final String seinfo; 12353 final int targetSdkVersion; 12354 12355 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12356 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12357 this.moveId = moveId; 12358 this.fromUuid = fromUuid; 12359 this.toUuid = toUuid; 12360 this.packageName = packageName; 12361 this.dataAppName = dataAppName; 12362 this.appId = appId; 12363 this.seinfo = seinfo; 12364 this.targetSdkVersion = targetSdkVersion; 12365 } 12366 } 12367 12368 static class VerificationInfo { 12369 /** A constant used to indicate that a uid value is not present. */ 12370 public static final int NO_UID = -1; 12371 12372 /** URI referencing where the package was downloaded from. */ 12373 final Uri originatingUri; 12374 12375 /** HTTP referrer URI associated with the originatingURI. */ 12376 final Uri referrer; 12377 12378 /** UID of the application that the install request originated from. */ 12379 final int originatingUid; 12380 12381 /** UID of application requesting the install */ 12382 final int installerUid; 12383 12384 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12385 this.originatingUri = originatingUri; 12386 this.referrer = referrer; 12387 this.originatingUid = originatingUid; 12388 this.installerUid = installerUid; 12389 } 12390 } 12391 12392 class InstallParams extends HandlerParams { 12393 final OriginInfo origin; 12394 final MoveInfo move; 12395 final IPackageInstallObserver2 observer; 12396 int installFlags; 12397 final String installerPackageName; 12398 final String volumeUuid; 12399 private InstallArgs mArgs; 12400 private int mRet; 12401 final String packageAbiOverride; 12402 final String[] grantedRuntimePermissions; 12403 final VerificationInfo verificationInfo; 12404 final Certificate[][] certificates; 12405 12406 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12407 int installFlags, String installerPackageName, String volumeUuid, 12408 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12409 String[] grantedPermissions, Certificate[][] certificates) { 12410 super(user); 12411 this.origin = origin; 12412 this.move = move; 12413 this.observer = observer; 12414 this.installFlags = installFlags; 12415 this.installerPackageName = installerPackageName; 12416 this.volumeUuid = volumeUuid; 12417 this.verificationInfo = verificationInfo; 12418 this.packageAbiOverride = packageAbiOverride; 12419 this.grantedRuntimePermissions = grantedPermissions; 12420 this.certificates = certificates; 12421 } 12422 12423 @Override 12424 public String toString() { 12425 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12426 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12427 } 12428 12429 private int installLocationPolicy(PackageInfoLite pkgLite) { 12430 String packageName = pkgLite.packageName; 12431 int installLocation = pkgLite.installLocation; 12432 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12433 // reader 12434 synchronized (mPackages) { 12435 // Currently installed package which the new package is attempting to replace or 12436 // null if no such package is installed. 12437 PackageParser.Package installedPkg = mPackages.get(packageName); 12438 // Package which currently owns the data which the new package will own if installed. 12439 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12440 // will be null whereas dataOwnerPkg will contain information about the package 12441 // which was uninstalled while keeping its data. 12442 PackageParser.Package dataOwnerPkg = installedPkg; 12443 if (dataOwnerPkg == null) { 12444 PackageSetting ps = mSettings.mPackages.get(packageName); 12445 if (ps != null) { 12446 dataOwnerPkg = ps.pkg; 12447 } 12448 } 12449 12450 if (dataOwnerPkg != null) { 12451 // If installed, the package will get access to data left on the device by its 12452 // predecessor. As a security measure, this is permited only if this is not a 12453 // version downgrade or if the predecessor package is marked as debuggable and 12454 // a downgrade is explicitly requested. 12455 // 12456 // On debuggable platform builds, downgrades are permitted even for 12457 // non-debuggable packages to make testing easier. Debuggable platform builds do 12458 // not offer security guarantees and thus it's OK to disable some security 12459 // mechanisms to make debugging/testing easier on those builds. However, even on 12460 // debuggable builds downgrades of packages are permitted only if requested via 12461 // installFlags. This is because we aim to keep the behavior of debuggable 12462 // platform builds as close as possible to the behavior of non-debuggable 12463 // platform builds. 12464 final boolean downgradeRequested = 12465 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12466 final boolean packageDebuggable = 12467 (dataOwnerPkg.applicationInfo.flags 12468 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12469 final boolean downgradePermitted = 12470 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12471 if (!downgradePermitted) { 12472 try { 12473 checkDowngrade(dataOwnerPkg, pkgLite); 12474 } catch (PackageManagerException e) { 12475 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12476 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12477 } 12478 } 12479 } 12480 12481 if (installedPkg != null) { 12482 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12483 // Check for updated system application. 12484 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12485 if (onSd) { 12486 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12487 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12488 } 12489 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12490 } else { 12491 if (onSd) { 12492 // Install flag overrides everything. 12493 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12494 } 12495 // If current upgrade specifies particular preference 12496 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12497 // Application explicitly specified internal. 12498 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12499 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12500 // App explictly prefers external. Let policy decide 12501 } else { 12502 // Prefer previous location 12503 if (isExternal(installedPkg)) { 12504 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12505 } 12506 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12507 } 12508 } 12509 } else { 12510 // Invalid install. Return error code 12511 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12512 } 12513 } 12514 } 12515 // All the special cases have been taken care of. 12516 // Return result based on recommended install location. 12517 if (onSd) { 12518 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12519 } 12520 return pkgLite.recommendedInstallLocation; 12521 } 12522 12523 /* 12524 * Invoke remote method to get package information and install 12525 * location values. Override install location based on default 12526 * policy if needed and then create install arguments based 12527 * on the install location. 12528 */ 12529 public void handleStartCopy() throws RemoteException { 12530 int ret = PackageManager.INSTALL_SUCCEEDED; 12531 12532 // If we're already staged, we've firmly committed to an install location 12533 if (origin.staged) { 12534 if (origin.file != null) { 12535 installFlags |= PackageManager.INSTALL_INTERNAL; 12536 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12537 } else if (origin.cid != null) { 12538 installFlags |= PackageManager.INSTALL_EXTERNAL; 12539 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12540 } else { 12541 throw new IllegalStateException("Invalid stage location"); 12542 } 12543 } 12544 12545 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12546 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12547 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12548 PackageInfoLite pkgLite = null; 12549 12550 if (onInt && onSd) { 12551 // Check if both bits are set. 12552 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12553 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12554 } else if (onSd && ephemeral) { 12555 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12556 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12557 } else { 12558 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12559 packageAbiOverride); 12560 12561 if (DEBUG_EPHEMERAL && ephemeral) { 12562 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12563 } 12564 12565 /* 12566 * If we have too little free space, try to free cache 12567 * before giving up. 12568 */ 12569 if (!origin.staged && pkgLite.recommendedInstallLocation 12570 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12571 // TODO: focus freeing disk space on the target device 12572 final StorageManager storage = StorageManager.from(mContext); 12573 final long lowThreshold = storage.getStorageLowBytes( 12574 Environment.getDataDirectory()); 12575 12576 final long sizeBytes = mContainerService.calculateInstalledSize( 12577 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12578 12579 try { 12580 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12581 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12582 installFlags, packageAbiOverride); 12583 } catch (InstallerException e) { 12584 Slog.w(TAG, "Failed to free cache", e); 12585 } 12586 12587 /* 12588 * The cache free must have deleted the file we 12589 * downloaded to install. 12590 * 12591 * TODO: fix the "freeCache" call to not delete 12592 * the file we care about. 12593 */ 12594 if (pkgLite.recommendedInstallLocation 12595 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12596 pkgLite.recommendedInstallLocation 12597 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12598 } 12599 } 12600 } 12601 12602 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12603 int loc = pkgLite.recommendedInstallLocation; 12604 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12605 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12606 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12607 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12608 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12609 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12610 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12611 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12612 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12613 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12614 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12615 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12616 } else { 12617 // Override with defaults if needed. 12618 loc = installLocationPolicy(pkgLite); 12619 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12620 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12621 } else if (!onSd && !onInt) { 12622 // Override install location with flags 12623 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12624 // Set the flag to install on external media. 12625 installFlags |= PackageManager.INSTALL_EXTERNAL; 12626 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12627 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12628 if (DEBUG_EPHEMERAL) { 12629 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12630 } 12631 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12632 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12633 |PackageManager.INSTALL_INTERNAL); 12634 } else { 12635 // Make sure the flag for installing on external 12636 // media is unset 12637 installFlags |= PackageManager.INSTALL_INTERNAL; 12638 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12639 } 12640 } 12641 } 12642 } 12643 12644 final InstallArgs args = createInstallArgs(this); 12645 mArgs = args; 12646 12647 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12648 // TODO: http://b/22976637 12649 // Apps installed for "all" users use the device owner to verify the app 12650 UserHandle verifierUser = getUser(); 12651 if (verifierUser == UserHandle.ALL) { 12652 verifierUser = UserHandle.SYSTEM; 12653 } 12654 12655 /* 12656 * Determine if we have any installed package verifiers. If we 12657 * do, then we'll defer to them to verify the packages. 12658 */ 12659 final int requiredUid = mRequiredVerifierPackage == null ? -1 12660 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12661 verifierUser.getIdentifier()); 12662 if (!origin.existing && requiredUid != -1 12663 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12664 final Intent verification = new Intent( 12665 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12666 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12667 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12668 PACKAGE_MIME_TYPE); 12669 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12670 12671 // Query all live verifiers based on current user state 12672 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12673 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12674 12675 if (DEBUG_VERIFY) { 12676 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12677 + verification.toString() + " with " + pkgLite.verifiers.length 12678 + " optional verifiers"); 12679 } 12680 12681 final int verificationId = mPendingVerificationToken++; 12682 12683 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12684 12685 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12686 installerPackageName); 12687 12688 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12689 installFlags); 12690 12691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12692 pkgLite.packageName); 12693 12694 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12695 pkgLite.versionCode); 12696 12697 if (verificationInfo != null) { 12698 if (verificationInfo.originatingUri != null) { 12699 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12700 verificationInfo.originatingUri); 12701 } 12702 if (verificationInfo.referrer != null) { 12703 verification.putExtra(Intent.EXTRA_REFERRER, 12704 verificationInfo.referrer); 12705 } 12706 if (verificationInfo.originatingUid >= 0) { 12707 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12708 verificationInfo.originatingUid); 12709 } 12710 if (verificationInfo.installerUid >= 0) { 12711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12712 verificationInfo.installerUid); 12713 } 12714 } 12715 12716 final PackageVerificationState verificationState = new PackageVerificationState( 12717 requiredUid, args); 12718 12719 mPendingVerification.append(verificationId, verificationState); 12720 12721 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12722 receivers, verificationState); 12723 12724 /* 12725 * If any sufficient verifiers were listed in the package 12726 * manifest, attempt to ask them. 12727 */ 12728 if (sufficientVerifiers != null) { 12729 final int N = sufficientVerifiers.size(); 12730 if (N == 0) { 12731 Slog.i(TAG, "Additional verifiers required, but none installed."); 12732 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12733 } else { 12734 for (int i = 0; i < N; i++) { 12735 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12736 12737 final Intent sufficientIntent = new Intent(verification); 12738 sufficientIntent.setComponent(verifierComponent); 12739 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12740 } 12741 } 12742 } 12743 12744 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12745 mRequiredVerifierPackage, receivers); 12746 if (ret == PackageManager.INSTALL_SUCCEEDED 12747 && mRequiredVerifierPackage != null) { 12748 Trace.asyncTraceBegin( 12749 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12750 /* 12751 * Send the intent to the required verification agent, 12752 * but only start the verification timeout after the 12753 * target BroadcastReceivers have run. 12754 */ 12755 verification.setComponent(requiredVerifierComponent); 12756 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12757 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12758 new BroadcastReceiver() { 12759 @Override 12760 public void onReceive(Context context, Intent intent) { 12761 final Message msg = mHandler 12762 .obtainMessage(CHECK_PENDING_VERIFICATION); 12763 msg.arg1 = verificationId; 12764 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12765 } 12766 }, null, 0, null, null); 12767 12768 /* 12769 * We don't want the copy to proceed until verification 12770 * succeeds, so null out this field. 12771 */ 12772 mArgs = null; 12773 } 12774 } else { 12775 /* 12776 * No package verification is enabled, so immediately start 12777 * the remote call to initiate copy using temporary file. 12778 */ 12779 ret = args.copyApk(mContainerService, true); 12780 } 12781 } 12782 12783 mRet = ret; 12784 } 12785 12786 @Override 12787 void handleReturnCode() { 12788 // If mArgs is null, then MCS couldn't be reached. When it 12789 // reconnects, it will try again to install. At that point, this 12790 // will succeed. 12791 if (mArgs != null) { 12792 processPendingInstall(mArgs, mRet); 12793 } 12794 } 12795 12796 @Override 12797 void handleServiceError() { 12798 mArgs = createInstallArgs(this); 12799 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12800 } 12801 12802 public boolean isForwardLocked() { 12803 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12804 } 12805 } 12806 12807 /** 12808 * Used during creation of InstallArgs 12809 * 12810 * @param installFlags package installation flags 12811 * @return true if should be installed on external storage 12812 */ 12813 private static boolean installOnExternalAsec(int installFlags) { 12814 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12815 return false; 12816 } 12817 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12818 return true; 12819 } 12820 return false; 12821 } 12822 12823 /** 12824 * Used during creation of InstallArgs 12825 * 12826 * @param installFlags package installation flags 12827 * @return true if should be installed as forward locked 12828 */ 12829 private static boolean installForwardLocked(int installFlags) { 12830 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12831 } 12832 12833 private InstallArgs createInstallArgs(InstallParams params) { 12834 if (params.move != null) { 12835 return new MoveInstallArgs(params); 12836 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12837 return new AsecInstallArgs(params); 12838 } else { 12839 return new FileInstallArgs(params); 12840 } 12841 } 12842 12843 /** 12844 * Create args that describe an existing installed package. Typically used 12845 * when cleaning up old installs, or used as a move source. 12846 */ 12847 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12848 String resourcePath, String[] instructionSets) { 12849 final boolean isInAsec; 12850 if (installOnExternalAsec(installFlags)) { 12851 /* Apps on SD card are always in ASEC containers. */ 12852 isInAsec = true; 12853 } else if (installForwardLocked(installFlags) 12854 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12855 /* 12856 * Forward-locked apps are only in ASEC containers if they're the 12857 * new style 12858 */ 12859 isInAsec = true; 12860 } else { 12861 isInAsec = false; 12862 } 12863 12864 if (isInAsec) { 12865 return new AsecInstallArgs(codePath, instructionSets, 12866 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12867 } else { 12868 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12869 } 12870 } 12871 12872 static abstract class InstallArgs { 12873 /** @see InstallParams#origin */ 12874 final OriginInfo origin; 12875 /** @see InstallParams#move */ 12876 final MoveInfo move; 12877 12878 final IPackageInstallObserver2 observer; 12879 // Always refers to PackageManager flags only 12880 final int installFlags; 12881 final String installerPackageName; 12882 final String volumeUuid; 12883 final UserHandle user; 12884 final String abiOverride; 12885 final String[] installGrantPermissions; 12886 /** If non-null, drop an async trace when the install completes */ 12887 final String traceMethod; 12888 final int traceCookie; 12889 final Certificate[][] certificates; 12890 12891 // The list of instruction sets supported by this app. This is currently 12892 // only used during the rmdex() phase to clean up resources. We can get rid of this 12893 // if we move dex files under the common app path. 12894 /* nullable */ String[] instructionSets; 12895 12896 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12897 int installFlags, String installerPackageName, String volumeUuid, 12898 UserHandle user, String[] instructionSets, 12899 String abiOverride, String[] installGrantPermissions, 12900 String traceMethod, int traceCookie, Certificate[][] certificates) { 12901 this.origin = origin; 12902 this.move = move; 12903 this.installFlags = installFlags; 12904 this.observer = observer; 12905 this.installerPackageName = installerPackageName; 12906 this.volumeUuid = volumeUuid; 12907 this.user = user; 12908 this.instructionSets = instructionSets; 12909 this.abiOverride = abiOverride; 12910 this.installGrantPermissions = installGrantPermissions; 12911 this.traceMethod = traceMethod; 12912 this.traceCookie = traceCookie; 12913 this.certificates = certificates; 12914 } 12915 12916 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12917 abstract int doPreInstall(int status); 12918 12919 /** 12920 * Rename package into final resting place. All paths on the given 12921 * scanned package should be updated to reflect the rename. 12922 */ 12923 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12924 abstract int doPostInstall(int status, int uid); 12925 12926 /** @see PackageSettingBase#codePathString */ 12927 abstract String getCodePath(); 12928 /** @see PackageSettingBase#resourcePathString */ 12929 abstract String getResourcePath(); 12930 12931 // Need installer lock especially for dex file removal. 12932 abstract void cleanUpResourcesLI(); 12933 abstract boolean doPostDeleteLI(boolean delete); 12934 12935 /** 12936 * Called before the source arguments are copied. This is used mostly 12937 * for MoveParams when it needs to read the source file to put it in the 12938 * destination. 12939 */ 12940 int doPreCopy() { 12941 return PackageManager.INSTALL_SUCCEEDED; 12942 } 12943 12944 /** 12945 * Called after the source arguments are copied. This is used mostly for 12946 * MoveParams when it needs to read the source file to put it in the 12947 * destination. 12948 */ 12949 int doPostCopy(int uid) { 12950 return PackageManager.INSTALL_SUCCEEDED; 12951 } 12952 12953 protected boolean isFwdLocked() { 12954 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12955 } 12956 12957 protected boolean isExternalAsec() { 12958 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12959 } 12960 12961 protected boolean isEphemeral() { 12962 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12963 } 12964 12965 UserHandle getUser() { 12966 return user; 12967 } 12968 } 12969 12970 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12971 if (!allCodePaths.isEmpty()) { 12972 if (instructionSets == null) { 12973 throw new IllegalStateException("instructionSet == null"); 12974 } 12975 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12976 for (String codePath : allCodePaths) { 12977 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12978 try { 12979 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12980 } catch (InstallerException ignored) { 12981 } 12982 } 12983 } 12984 } 12985 } 12986 12987 /** 12988 * Logic to handle installation of non-ASEC applications, including copying 12989 * and renaming logic. 12990 */ 12991 class FileInstallArgs extends InstallArgs { 12992 private File codeFile; 12993 private File resourceFile; 12994 12995 // Example topology: 12996 // /data/app/com.example/base.apk 12997 // /data/app/com.example/split_foo.apk 12998 // /data/app/com.example/lib/arm/libfoo.so 12999 // /data/app/com.example/lib/arm64/libfoo.so 13000 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13001 13002 /** New install */ 13003 FileInstallArgs(InstallParams params) { 13004 super(params.origin, params.move, params.observer, params.installFlags, 13005 params.installerPackageName, params.volumeUuid, 13006 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13007 params.grantedRuntimePermissions, 13008 params.traceMethod, params.traceCookie, params.certificates); 13009 if (isFwdLocked()) { 13010 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13011 } 13012 } 13013 13014 /** Existing install */ 13015 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13016 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13017 null, null, null, 0, null /*certificates*/); 13018 this.codeFile = (codePath != null) ? new File(codePath) : null; 13019 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13020 } 13021 13022 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13023 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13024 try { 13025 return doCopyApk(imcs, temp); 13026 } finally { 13027 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13028 } 13029 } 13030 13031 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13032 if (origin.staged) { 13033 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13034 codeFile = origin.file; 13035 resourceFile = origin.file; 13036 return PackageManager.INSTALL_SUCCEEDED; 13037 } 13038 13039 try { 13040 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13041 final File tempDir = 13042 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13043 codeFile = tempDir; 13044 resourceFile = tempDir; 13045 } catch (IOException e) { 13046 Slog.w(TAG, "Failed to create copy file: " + e); 13047 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13048 } 13049 13050 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13051 @Override 13052 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13053 if (!FileUtils.isValidExtFilename(name)) { 13054 throw new IllegalArgumentException("Invalid filename: " + name); 13055 } 13056 try { 13057 final File file = new File(codeFile, name); 13058 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13059 O_RDWR | O_CREAT, 0644); 13060 Os.chmod(file.getAbsolutePath(), 0644); 13061 return new ParcelFileDescriptor(fd); 13062 } catch (ErrnoException e) { 13063 throw new RemoteException("Failed to open: " + e.getMessage()); 13064 } 13065 } 13066 }; 13067 13068 int ret = PackageManager.INSTALL_SUCCEEDED; 13069 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13070 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13071 Slog.e(TAG, "Failed to copy package"); 13072 return ret; 13073 } 13074 13075 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13076 NativeLibraryHelper.Handle handle = null; 13077 try { 13078 handle = NativeLibraryHelper.Handle.create(codeFile); 13079 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13080 abiOverride); 13081 } catch (IOException e) { 13082 Slog.e(TAG, "Copying native libraries failed", e); 13083 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13084 } finally { 13085 IoUtils.closeQuietly(handle); 13086 } 13087 13088 return ret; 13089 } 13090 13091 int doPreInstall(int status) { 13092 if (status != PackageManager.INSTALL_SUCCEEDED) { 13093 cleanUp(); 13094 } 13095 return status; 13096 } 13097 13098 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13099 if (status != PackageManager.INSTALL_SUCCEEDED) { 13100 cleanUp(); 13101 return false; 13102 } 13103 13104 final File targetDir = codeFile.getParentFile(); 13105 final File beforeCodeFile = codeFile; 13106 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13107 13108 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13109 try { 13110 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13111 } catch (ErrnoException e) { 13112 Slog.w(TAG, "Failed to rename", e); 13113 return false; 13114 } 13115 13116 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13117 Slog.w(TAG, "Failed to restorecon"); 13118 return false; 13119 } 13120 13121 // Reflect the rename internally 13122 codeFile = afterCodeFile; 13123 resourceFile = afterCodeFile; 13124 13125 // Reflect the rename in scanned details 13126 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13127 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13128 afterCodeFile, pkg.baseCodePath)); 13129 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13130 afterCodeFile, pkg.splitCodePaths)); 13131 13132 // Reflect the rename in app info 13133 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13134 pkg.setApplicationInfoCodePath(pkg.codePath); 13135 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13136 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13137 pkg.setApplicationInfoResourcePath(pkg.codePath); 13138 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13139 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13140 13141 return true; 13142 } 13143 13144 int doPostInstall(int status, int uid) { 13145 if (status != PackageManager.INSTALL_SUCCEEDED) { 13146 cleanUp(); 13147 } 13148 return status; 13149 } 13150 13151 @Override 13152 String getCodePath() { 13153 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13154 } 13155 13156 @Override 13157 String getResourcePath() { 13158 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13159 } 13160 13161 private boolean cleanUp() { 13162 if (codeFile == null || !codeFile.exists()) { 13163 return false; 13164 } 13165 13166 removeCodePathLI(codeFile); 13167 13168 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13169 resourceFile.delete(); 13170 } 13171 13172 return true; 13173 } 13174 13175 void cleanUpResourcesLI() { 13176 // Try enumerating all code paths before deleting 13177 List<String> allCodePaths = Collections.EMPTY_LIST; 13178 if (codeFile != null && codeFile.exists()) { 13179 try { 13180 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13181 allCodePaths = pkg.getAllCodePaths(); 13182 } catch (PackageParserException e) { 13183 // Ignored; we tried our best 13184 } 13185 } 13186 13187 cleanUp(); 13188 removeDexFiles(allCodePaths, instructionSets); 13189 } 13190 13191 boolean doPostDeleteLI(boolean delete) { 13192 // XXX err, shouldn't we respect the delete flag? 13193 cleanUpResourcesLI(); 13194 return true; 13195 } 13196 } 13197 13198 private boolean isAsecExternal(String cid) { 13199 final String asecPath = PackageHelper.getSdFilesystem(cid); 13200 return !asecPath.startsWith(mAsecInternalPath); 13201 } 13202 13203 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13204 PackageManagerException { 13205 if (copyRet < 0) { 13206 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13207 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13208 throw new PackageManagerException(copyRet, message); 13209 } 13210 } 13211 } 13212 13213 /** 13214 * Extract the MountService "container ID" from the full code path of an 13215 * .apk. 13216 */ 13217 static String cidFromCodePath(String fullCodePath) { 13218 int eidx = fullCodePath.lastIndexOf("/"); 13219 String subStr1 = fullCodePath.substring(0, eidx); 13220 int sidx = subStr1.lastIndexOf("/"); 13221 return subStr1.substring(sidx+1, eidx); 13222 } 13223 13224 /** 13225 * Logic to handle installation of ASEC applications, including copying and 13226 * renaming logic. 13227 */ 13228 class AsecInstallArgs extends InstallArgs { 13229 static final String RES_FILE_NAME = "pkg.apk"; 13230 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13231 13232 String cid; 13233 String packagePath; 13234 String resourcePath; 13235 13236 /** New install */ 13237 AsecInstallArgs(InstallParams params) { 13238 super(params.origin, params.move, params.observer, params.installFlags, 13239 params.installerPackageName, params.volumeUuid, 13240 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13241 params.grantedRuntimePermissions, 13242 params.traceMethod, params.traceCookie, params.certificates); 13243 } 13244 13245 /** Existing install */ 13246 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13247 boolean isExternal, boolean isForwardLocked) { 13248 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13249 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13250 instructionSets, null, null, null, 0, null /*certificates*/); 13251 // Hackily pretend we're still looking at a full code path 13252 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13253 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13254 } 13255 13256 // Extract cid from fullCodePath 13257 int eidx = fullCodePath.lastIndexOf("/"); 13258 String subStr1 = fullCodePath.substring(0, eidx); 13259 int sidx = subStr1.lastIndexOf("/"); 13260 cid = subStr1.substring(sidx+1, eidx); 13261 setMountPath(subStr1); 13262 } 13263 13264 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13265 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13266 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13267 instructionSets, null, null, null, 0, null /*certificates*/); 13268 this.cid = cid; 13269 setMountPath(PackageHelper.getSdDir(cid)); 13270 } 13271 13272 void createCopyFile() { 13273 cid = mInstallerService.allocateExternalStageCidLegacy(); 13274 } 13275 13276 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13277 if (origin.staged && origin.cid != null) { 13278 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13279 cid = origin.cid; 13280 setMountPath(PackageHelper.getSdDir(cid)); 13281 return PackageManager.INSTALL_SUCCEEDED; 13282 } 13283 13284 if (temp) { 13285 createCopyFile(); 13286 } else { 13287 /* 13288 * Pre-emptively destroy the container since it's destroyed if 13289 * copying fails due to it existing anyway. 13290 */ 13291 PackageHelper.destroySdDir(cid); 13292 } 13293 13294 final String newMountPath = imcs.copyPackageToContainer( 13295 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13296 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13297 13298 if (newMountPath != null) { 13299 setMountPath(newMountPath); 13300 return PackageManager.INSTALL_SUCCEEDED; 13301 } else { 13302 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13303 } 13304 } 13305 13306 @Override 13307 String getCodePath() { 13308 return packagePath; 13309 } 13310 13311 @Override 13312 String getResourcePath() { 13313 return resourcePath; 13314 } 13315 13316 int doPreInstall(int status) { 13317 if (status != PackageManager.INSTALL_SUCCEEDED) { 13318 // Destroy container 13319 PackageHelper.destroySdDir(cid); 13320 } else { 13321 boolean mounted = PackageHelper.isContainerMounted(cid); 13322 if (!mounted) { 13323 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13324 Process.SYSTEM_UID); 13325 if (newMountPath != null) { 13326 setMountPath(newMountPath); 13327 } else { 13328 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13329 } 13330 } 13331 } 13332 return status; 13333 } 13334 13335 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13336 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13337 String newMountPath = null; 13338 if (PackageHelper.isContainerMounted(cid)) { 13339 // Unmount the container 13340 if (!PackageHelper.unMountSdDir(cid)) { 13341 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13342 return false; 13343 } 13344 } 13345 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13346 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13347 " which might be stale. Will try to clean up."); 13348 // Clean up the stale container and proceed to recreate. 13349 if (!PackageHelper.destroySdDir(newCacheId)) { 13350 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13351 return false; 13352 } 13353 // Successfully cleaned up stale container. Try to rename again. 13354 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13355 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13356 + " inspite of cleaning it up."); 13357 return false; 13358 } 13359 } 13360 if (!PackageHelper.isContainerMounted(newCacheId)) { 13361 Slog.w(TAG, "Mounting container " + newCacheId); 13362 newMountPath = PackageHelper.mountSdDir(newCacheId, 13363 getEncryptKey(), Process.SYSTEM_UID); 13364 } else { 13365 newMountPath = PackageHelper.getSdDir(newCacheId); 13366 } 13367 if (newMountPath == null) { 13368 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13369 return false; 13370 } 13371 Log.i(TAG, "Succesfully renamed " + cid + 13372 " to " + newCacheId + 13373 " at new path: " + newMountPath); 13374 cid = newCacheId; 13375 13376 final File beforeCodeFile = new File(packagePath); 13377 setMountPath(newMountPath); 13378 final File afterCodeFile = new File(packagePath); 13379 13380 // Reflect the rename in scanned details 13381 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13382 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13383 afterCodeFile, pkg.baseCodePath)); 13384 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13385 afterCodeFile, pkg.splitCodePaths)); 13386 13387 // Reflect the rename in app info 13388 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13389 pkg.setApplicationInfoCodePath(pkg.codePath); 13390 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13391 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13392 pkg.setApplicationInfoResourcePath(pkg.codePath); 13393 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13394 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13395 13396 return true; 13397 } 13398 13399 private void setMountPath(String mountPath) { 13400 final File mountFile = new File(mountPath); 13401 13402 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13403 if (monolithicFile.exists()) { 13404 packagePath = monolithicFile.getAbsolutePath(); 13405 if (isFwdLocked()) { 13406 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13407 } else { 13408 resourcePath = packagePath; 13409 } 13410 } else { 13411 packagePath = mountFile.getAbsolutePath(); 13412 resourcePath = packagePath; 13413 } 13414 } 13415 13416 int doPostInstall(int status, int uid) { 13417 if (status != PackageManager.INSTALL_SUCCEEDED) { 13418 cleanUp(); 13419 } else { 13420 final int groupOwner; 13421 final String protectedFile; 13422 if (isFwdLocked()) { 13423 groupOwner = UserHandle.getSharedAppGid(uid); 13424 protectedFile = RES_FILE_NAME; 13425 } else { 13426 groupOwner = -1; 13427 protectedFile = null; 13428 } 13429 13430 if (uid < Process.FIRST_APPLICATION_UID 13431 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13432 Slog.e(TAG, "Failed to finalize " + cid); 13433 PackageHelper.destroySdDir(cid); 13434 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13435 } 13436 13437 boolean mounted = PackageHelper.isContainerMounted(cid); 13438 if (!mounted) { 13439 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13440 } 13441 } 13442 return status; 13443 } 13444 13445 private void cleanUp() { 13446 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13447 13448 // Destroy secure container 13449 PackageHelper.destroySdDir(cid); 13450 } 13451 13452 private List<String> getAllCodePaths() { 13453 final File codeFile = new File(getCodePath()); 13454 if (codeFile != null && codeFile.exists()) { 13455 try { 13456 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13457 return pkg.getAllCodePaths(); 13458 } catch (PackageParserException e) { 13459 // Ignored; we tried our best 13460 } 13461 } 13462 return Collections.EMPTY_LIST; 13463 } 13464 13465 void cleanUpResourcesLI() { 13466 // Enumerate all code paths before deleting 13467 cleanUpResourcesLI(getAllCodePaths()); 13468 } 13469 13470 private void cleanUpResourcesLI(List<String> allCodePaths) { 13471 cleanUp(); 13472 removeDexFiles(allCodePaths, instructionSets); 13473 } 13474 13475 String getPackageName() { 13476 return getAsecPackageName(cid); 13477 } 13478 13479 boolean doPostDeleteLI(boolean delete) { 13480 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13481 final List<String> allCodePaths = getAllCodePaths(); 13482 boolean mounted = PackageHelper.isContainerMounted(cid); 13483 if (mounted) { 13484 // Unmount first 13485 if (PackageHelper.unMountSdDir(cid)) { 13486 mounted = false; 13487 } 13488 } 13489 if (!mounted && delete) { 13490 cleanUpResourcesLI(allCodePaths); 13491 } 13492 return !mounted; 13493 } 13494 13495 @Override 13496 int doPreCopy() { 13497 if (isFwdLocked()) { 13498 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13499 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13500 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13501 } 13502 } 13503 13504 return PackageManager.INSTALL_SUCCEEDED; 13505 } 13506 13507 @Override 13508 int doPostCopy(int uid) { 13509 if (isFwdLocked()) { 13510 if (uid < Process.FIRST_APPLICATION_UID 13511 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13512 RES_FILE_NAME)) { 13513 Slog.e(TAG, "Failed to finalize " + cid); 13514 PackageHelper.destroySdDir(cid); 13515 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13516 } 13517 } 13518 13519 return PackageManager.INSTALL_SUCCEEDED; 13520 } 13521 } 13522 13523 /** 13524 * Logic to handle movement of existing installed applications. 13525 */ 13526 class MoveInstallArgs extends InstallArgs { 13527 private File codeFile; 13528 private File resourceFile; 13529 13530 /** New install */ 13531 MoveInstallArgs(InstallParams params) { 13532 super(params.origin, params.move, params.observer, params.installFlags, 13533 params.installerPackageName, params.volumeUuid, 13534 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13535 params.grantedRuntimePermissions, 13536 params.traceMethod, params.traceCookie, params.certificates); 13537 } 13538 13539 int copyApk(IMediaContainerService imcs, boolean temp) { 13540 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13541 + move.fromUuid + " to " + move.toUuid); 13542 synchronized (mInstaller) { 13543 try { 13544 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13545 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13546 } catch (InstallerException e) { 13547 Slog.w(TAG, "Failed to move app", e); 13548 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13549 } 13550 } 13551 13552 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13553 resourceFile = codeFile; 13554 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13555 13556 return PackageManager.INSTALL_SUCCEEDED; 13557 } 13558 13559 int doPreInstall(int status) { 13560 if (status != PackageManager.INSTALL_SUCCEEDED) { 13561 cleanUp(move.toUuid); 13562 } 13563 return status; 13564 } 13565 13566 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13567 if (status != PackageManager.INSTALL_SUCCEEDED) { 13568 cleanUp(move.toUuid); 13569 return false; 13570 } 13571 13572 // Reflect the move in app info 13573 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13574 pkg.setApplicationInfoCodePath(pkg.codePath); 13575 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13576 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13577 pkg.setApplicationInfoResourcePath(pkg.codePath); 13578 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13579 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13580 13581 return true; 13582 } 13583 13584 int doPostInstall(int status, int uid) { 13585 if (status == PackageManager.INSTALL_SUCCEEDED) { 13586 cleanUp(move.fromUuid); 13587 } else { 13588 cleanUp(move.toUuid); 13589 } 13590 return status; 13591 } 13592 13593 @Override 13594 String getCodePath() { 13595 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13596 } 13597 13598 @Override 13599 String getResourcePath() { 13600 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13601 } 13602 13603 private boolean cleanUp(String volumeUuid) { 13604 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13605 move.dataAppName); 13606 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13607 final int[] userIds = sUserManager.getUserIds(); 13608 synchronized (mInstallLock) { 13609 // Clean up both app data and code 13610 // All package moves are frozen until finished 13611 for (int userId : userIds) { 13612 try { 13613 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13614 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13615 } catch (InstallerException e) { 13616 Slog.w(TAG, String.valueOf(e)); 13617 } 13618 } 13619 removeCodePathLI(codeFile); 13620 } 13621 return true; 13622 } 13623 13624 void cleanUpResourcesLI() { 13625 throw new UnsupportedOperationException(); 13626 } 13627 13628 boolean doPostDeleteLI(boolean delete) { 13629 throw new UnsupportedOperationException(); 13630 } 13631 } 13632 13633 static String getAsecPackageName(String packageCid) { 13634 int idx = packageCid.lastIndexOf("-"); 13635 if (idx == -1) { 13636 return packageCid; 13637 } 13638 return packageCid.substring(0, idx); 13639 } 13640 13641 // Utility method used to create code paths based on package name and available index. 13642 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13643 String idxStr = ""; 13644 int idx = 1; 13645 // Fall back to default value of idx=1 if prefix is not 13646 // part of oldCodePath 13647 if (oldCodePath != null) { 13648 String subStr = oldCodePath; 13649 // Drop the suffix right away 13650 if (suffix != null && subStr.endsWith(suffix)) { 13651 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13652 } 13653 // If oldCodePath already contains prefix find out the 13654 // ending index to either increment or decrement. 13655 int sidx = subStr.lastIndexOf(prefix); 13656 if (sidx != -1) { 13657 subStr = subStr.substring(sidx + prefix.length()); 13658 if (subStr != null) { 13659 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13660 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13661 } 13662 try { 13663 idx = Integer.parseInt(subStr); 13664 if (idx <= 1) { 13665 idx++; 13666 } else { 13667 idx--; 13668 } 13669 } catch(NumberFormatException e) { 13670 } 13671 } 13672 } 13673 } 13674 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13675 return prefix + idxStr; 13676 } 13677 13678 private File getNextCodePath(File targetDir, String packageName) { 13679 int suffix = 1; 13680 File result; 13681 do { 13682 result = new File(targetDir, packageName + "-" + suffix); 13683 suffix++; 13684 } while (result.exists()); 13685 return result; 13686 } 13687 13688 // Utility method that returns the relative package path with respect 13689 // to the installation directory. Like say for /data/data/com.test-1.apk 13690 // string com.test-1 is returned. 13691 static String deriveCodePathName(String codePath) { 13692 if (codePath == null) { 13693 return null; 13694 } 13695 final File codeFile = new File(codePath); 13696 final String name = codeFile.getName(); 13697 if (codeFile.isDirectory()) { 13698 return name; 13699 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13700 final int lastDot = name.lastIndexOf('.'); 13701 return name.substring(0, lastDot); 13702 } else { 13703 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13704 return null; 13705 } 13706 } 13707 13708 static class PackageInstalledInfo { 13709 String name; 13710 int uid; 13711 // The set of users that originally had this package installed. 13712 int[] origUsers; 13713 // The set of users that now have this package installed. 13714 int[] newUsers; 13715 PackageParser.Package pkg; 13716 int returnCode; 13717 String returnMsg; 13718 PackageRemovedInfo removedInfo; 13719 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13720 13721 public void setError(int code, String msg) { 13722 setReturnCode(code); 13723 setReturnMessage(msg); 13724 Slog.w(TAG, msg); 13725 } 13726 13727 public void setError(String msg, PackageParserException e) { 13728 setReturnCode(e.error); 13729 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13730 Slog.w(TAG, msg, e); 13731 } 13732 13733 public void setError(String msg, PackageManagerException e) { 13734 returnCode = e.error; 13735 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13736 Slog.w(TAG, msg, e); 13737 } 13738 13739 public void setReturnCode(int returnCode) { 13740 this.returnCode = returnCode; 13741 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13742 for (int i = 0; i < childCount; i++) { 13743 addedChildPackages.valueAt(i).returnCode = returnCode; 13744 } 13745 } 13746 13747 private void setReturnMessage(String returnMsg) { 13748 this.returnMsg = returnMsg; 13749 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13750 for (int i = 0; i < childCount; i++) { 13751 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13752 } 13753 } 13754 13755 // In some error cases we want to convey more info back to the observer 13756 String origPackage; 13757 String origPermission; 13758 } 13759 13760 /* 13761 * Install a non-existing package. 13762 */ 13763 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13764 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13765 PackageInstalledInfo res) { 13766 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13767 13768 // Remember this for later, in case we need to rollback this install 13769 String pkgName = pkg.packageName; 13770 13771 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13772 13773 synchronized(mPackages) { 13774 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13775 // A package with the same name is already installed, though 13776 // it has been renamed to an older name. The package we 13777 // are trying to install should be installed as an update to 13778 // the existing one, but that has not been requested, so bail. 13779 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13780 + " without first uninstalling package running as " 13781 + mSettings.mRenamedPackages.get(pkgName)); 13782 return; 13783 } 13784 if (mPackages.containsKey(pkgName)) { 13785 // Don't allow installation over an existing package with the same name. 13786 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13787 + " without first uninstalling."); 13788 return; 13789 } 13790 } 13791 13792 try { 13793 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13794 System.currentTimeMillis(), user); 13795 13796 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13797 13798 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13799 prepareAppDataAfterInstallLIF(newPackage); 13800 13801 } else { 13802 // Remove package from internal structures, but keep around any 13803 // data that might have already existed 13804 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13805 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13806 } 13807 } catch (PackageManagerException e) { 13808 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13809 } 13810 13811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13812 } 13813 13814 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13815 // Can't rotate keys during boot or if sharedUser. 13816 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13817 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13818 return false; 13819 } 13820 // app is using upgradeKeySets; make sure all are valid 13821 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13822 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13823 for (int i = 0; i < upgradeKeySets.length; i++) { 13824 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13825 Slog.wtf(TAG, "Package " 13826 + (oldPs.name != null ? oldPs.name : "<null>") 13827 + " contains upgrade-key-set reference to unknown key-set: " 13828 + upgradeKeySets[i] 13829 + " reverting to signatures check."); 13830 return false; 13831 } 13832 } 13833 return true; 13834 } 13835 13836 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13837 // Upgrade keysets are being used. Determine if new package has a superset of the 13838 // required keys. 13839 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13840 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13841 for (int i = 0; i < upgradeKeySets.length; i++) { 13842 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13843 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13844 return true; 13845 } 13846 } 13847 return false; 13848 } 13849 13850 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13851 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13852 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13853 13854 final PackageParser.Package oldPackage; 13855 final String pkgName = pkg.packageName; 13856 final int[] allUsers; 13857 13858 // First find the old package info and check signatures 13859 synchronized(mPackages) { 13860 oldPackage = mPackages.get(pkgName); 13861 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13862 if (isEphemeral && !oldIsEphemeral) { 13863 // can't downgrade from full to ephemeral 13864 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13865 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13866 return; 13867 } 13868 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13869 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13870 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13871 if (!checkUpgradeKeySetLP(ps, pkg)) { 13872 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13873 "New package not signed by keys specified by upgrade-keysets: " 13874 + pkgName); 13875 return; 13876 } 13877 } else { 13878 // default to original signature matching 13879 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13880 != PackageManager.SIGNATURE_MATCH) { 13881 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13882 "New package has a different signature: " + pkgName); 13883 return; 13884 } 13885 } 13886 13887 // Check for shared user id changes 13888 String invalidPackageName = 13889 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13890 if (invalidPackageName != null) { 13891 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13892 "Package " + invalidPackageName + " tried to change user " 13893 + oldPackage.mSharedUserId); 13894 return; 13895 } 13896 13897 // In case of rollback, remember per-user/profile install state 13898 allUsers = sUserManager.getUserIds(); 13899 } 13900 13901 // Update what is removed 13902 res.removedInfo = new PackageRemovedInfo(); 13903 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13904 res.removedInfo.removedPackage = oldPackage.packageName; 13905 res.removedInfo.isUpdate = true; 13906 final int childCount = (oldPackage.childPackages != null) 13907 ? oldPackage.childPackages.size() : 0; 13908 for (int i = 0; i < childCount; i++) { 13909 boolean childPackageUpdated = false; 13910 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13911 if (res.addedChildPackages != null) { 13912 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13913 if (childRes != null) { 13914 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13915 childRes.removedInfo.removedPackage = childPkg.packageName; 13916 childRes.removedInfo.isUpdate = true; 13917 childPackageUpdated = true; 13918 } 13919 } 13920 if (!childPackageUpdated) { 13921 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13922 childRemovedRes.removedPackage = childPkg.packageName; 13923 childRemovedRes.isUpdate = false; 13924 childRemovedRes.dataRemoved = true; 13925 synchronized (mPackages) { 13926 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13927 if (childPs != null) { 13928 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13929 } 13930 } 13931 if (res.removedInfo.removedChildPackages == null) { 13932 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13933 } 13934 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13935 } 13936 } 13937 13938 boolean sysPkg = (isSystemApp(oldPackage)); 13939 if (sysPkg) { 13940 // Set the system/privileged flags as needed 13941 final boolean privileged = 13942 (oldPackage.applicationInfo.privateFlags 13943 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13944 final int systemPolicyFlags = policyFlags 13945 | PackageParser.PARSE_IS_SYSTEM 13946 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13947 13948 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13949 user, allUsers, installerPackageName, res); 13950 } else { 13951 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13952 user, allUsers, installerPackageName, res); 13953 } 13954 } 13955 13956 public List<String> getPreviousCodePaths(String packageName) { 13957 final PackageSetting ps = mSettings.mPackages.get(packageName); 13958 final List<String> result = new ArrayList<String>(); 13959 if (ps != null && ps.oldCodePaths != null) { 13960 result.addAll(ps.oldCodePaths); 13961 } 13962 return result; 13963 } 13964 13965 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13966 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13967 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13968 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13969 + deletedPackage); 13970 13971 String pkgName = deletedPackage.packageName; 13972 boolean deletedPkg = true; 13973 boolean addedPkg = false; 13974 boolean updatedSettings = false; 13975 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13976 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13977 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13978 13979 final long origUpdateTime = (pkg.mExtras != null) 13980 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13981 13982 // First delete the existing package while retaining the data directory 13983 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13984 res.removedInfo, true, pkg)) { 13985 // If the existing package wasn't successfully deleted 13986 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13987 deletedPkg = false; 13988 } else { 13989 // Successfully deleted the old package; proceed with replace. 13990 13991 // If deleted package lived in a container, give users a chance to 13992 // relinquish resources before killing. 13993 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13994 if (DEBUG_INSTALL) { 13995 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13996 } 13997 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13998 final ArrayList<String> pkgList = new ArrayList<String>(1); 13999 pkgList.add(deletedPackage.applicationInfo.packageName); 14000 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14001 } 14002 14003 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14004 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14005 clearAppProfilesLIF(pkg); 14006 14007 try { 14008 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14009 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14010 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14011 14012 // Update the in-memory copy of the previous code paths. 14013 PackageSetting ps = mSettings.mPackages.get(pkgName); 14014 if (!killApp) { 14015 if (ps.oldCodePaths == null) { 14016 ps.oldCodePaths = new ArraySet<>(); 14017 } 14018 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14019 if (deletedPackage.splitCodePaths != null) { 14020 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14021 } 14022 } else { 14023 ps.oldCodePaths = null; 14024 } 14025 if (ps.childPackageNames != null) { 14026 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14027 final String childPkgName = ps.childPackageNames.get(i); 14028 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14029 childPs.oldCodePaths = ps.oldCodePaths; 14030 } 14031 } 14032 prepareAppDataAfterInstallLIF(newPackage); 14033 addedPkg = true; 14034 } catch (PackageManagerException e) { 14035 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14036 } 14037 } 14038 14039 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14040 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14041 14042 // Revert all internal state mutations and added folders for the failed install 14043 if (addedPkg) { 14044 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14045 res.removedInfo, true, null); 14046 } 14047 14048 // Restore the old package 14049 if (deletedPkg) { 14050 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14051 File restoreFile = new File(deletedPackage.codePath); 14052 // Parse old package 14053 boolean oldExternal = isExternal(deletedPackage); 14054 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14055 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14056 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14057 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14058 try { 14059 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14060 null); 14061 } catch (PackageManagerException e) { 14062 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14063 + e.getMessage()); 14064 return; 14065 } 14066 14067 synchronized (mPackages) { 14068 // Ensure the installer package name up to date 14069 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14070 14071 // Update permissions for restored package 14072 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14073 14074 mSettings.writeLPr(); 14075 } 14076 14077 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14078 } 14079 } else { 14080 synchronized (mPackages) { 14081 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14082 if (ps != null) { 14083 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14084 if (res.removedInfo.removedChildPackages != null) { 14085 final int childCount = res.removedInfo.removedChildPackages.size(); 14086 // Iterate in reverse as we may modify the collection 14087 for (int i = childCount - 1; i >= 0; i--) { 14088 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14089 if (res.addedChildPackages.containsKey(childPackageName)) { 14090 res.removedInfo.removedChildPackages.removeAt(i); 14091 } else { 14092 PackageRemovedInfo childInfo = res.removedInfo 14093 .removedChildPackages.valueAt(i); 14094 childInfo.removedForAllUsers = mPackages.get( 14095 childInfo.removedPackage) == null; 14096 } 14097 } 14098 } 14099 } 14100 } 14101 } 14102 } 14103 14104 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14105 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14106 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14107 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14108 + ", old=" + deletedPackage); 14109 14110 final boolean disabledSystem; 14111 14112 // Remove existing system package 14113 removePackageLI(deletedPackage, true); 14114 14115 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14116 if (!disabledSystem) { 14117 // We didn't need to disable the .apk as a current system package, 14118 // which means we are replacing another update that is already 14119 // installed. We need to make sure to delete the older one's .apk. 14120 res.removedInfo.args = createInstallArgsForExisting(0, 14121 deletedPackage.applicationInfo.getCodePath(), 14122 deletedPackage.applicationInfo.getResourcePath(), 14123 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14124 } else { 14125 res.removedInfo.args = null; 14126 } 14127 14128 // Successfully disabled the old package. Now proceed with re-installation 14129 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14130 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14131 clearAppProfilesLIF(pkg); 14132 14133 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14134 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14135 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14136 14137 PackageParser.Package newPackage = null; 14138 try { 14139 // Add the package to the internal data structures 14140 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14141 14142 // Set the update and install times 14143 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14144 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14145 System.currentTimeMillis()); 14146 14147 // Update the package dynamic state if succeeded 14148 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14149 // Now that the install succeeded make sure we remove data 14150 // directories for any child package the update removed. 14151 final int deletedChildCount = (deletedPackage.childPackages != null) 14152 ? deletedPackage.childPackages.size() : 0; 14153 final int newChildCount = (newPackage.childPackages != null) 14154 ? newPackage.childPackages.size() : 0; 14155 for (int i = 0; i < deletedChildCount; i++) { 14156 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14157 boolean childPackageDeleted = true; 14158 for (int j = 0; j < newChildCount; j++) { 14159 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14160 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14161 childPackageDeleted = false; 14162 break; 14163 } 14164 } 14165 if (childPackageDeleted) { 14166 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14167 deletedChildPkg.packageName); 14168 if (ps != null && res.removedInfo.removedChildPackages != null) { 14169 PackageRemovedInfo removedChildRes = res.removedInfo 14170 .removedChildPackages.get(deletedChildPkg.packageName); 14171 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14172 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14173 } 14174 } 14175 } 14176 14177 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14178 prepareAppDataAfterInstallLIF(newPackage); 14179 } 14180 } catch (PackageManagerException e) { 14181 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14182 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14183 } 14184 14185 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14186 // Re installation failed. Restore old information 14187 // Remove new pkg information 14188 if (newPackage != null) { 14189 removeInstalledPackageLI(newPackage, true); 14190 } 14191 // Add back the old system package 14192 try { 14193 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14194 } catch (PackageManagerException e) { 14195 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14196 } 14197 14198 synchronized (mPackages) { 14199 if (disabledSystem) { 14200 enableSystemPackageLPw(deletedPackage); 14201 } 14202 14203 // Ensure the installer package name up to date 14204 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14205 14206 // Update permissions for restored package 14207 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14208 14209 mSettings.writeLPr(); 14210 } 14211 14212 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14213 + " after failed upgrade"); 14214 } 14215 } 14216 14217 /** 14218 * Checks whether the parent or any of the child packages have a change shared 14219 * user. For a package to be a valid update the shred users of the parent and 14220 * the children should match. We may later support changing child shared users. 14221 * @param oldPkg The updated package. 14222 * @param newPkg The update package. 14223 * @return The shared user that change between the versions. 14224 */ 14225 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14226 PackageParser.Package newPkg) { 14227 // Check parent shared user 14228 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14229 return newPkg.packageName; 14230 } 14231 // Check child shared users 14232 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14233 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14234 for (int i = 0; i < newChildCount; i++) { 14235 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14236 // If this child was present, did it have the same shared user? 14237 for (int j = 0; j < oldChildCount; j++) { 14238 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14239 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14240 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14241 return newChildPkg.packageName; 14242 } 14243 } 14244 } 14245 return null; 14246 } 14247 14248 private void removeNativeBinariesLI(PackageSetting ps) { 14249 // Remove the lib path for the parent package 14250 if (ps != null) { 14251 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14252 // Remove the lib path for the child packages 14253 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14254 for (int i = 0; i < childCount; i++) { 14255 PackageSetting childPs = null; 14256 synchronized (mPackages) { 14257 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14258 } 14259 if (childPs != null) { 14260 NativeLibraryHelper.removeNativeBinariesLI(childPs 14261 .legacyNativeLibraryPathString); 14262 } 14263 } 14264 } 14265 } 14266 14267 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14268 // Enable the parent package 14269 mSettings.enableSystemPackageLPw(pkg.packageName); 14270 // Enable the child packages 14271 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14272 for (int i = 0; i < childCount; i++) { 14273 PackageParser.Package childPkg = pkg.childPackages.get(i); 14274 mSettings.enableSystemPackageLPw(childPkg.packageName); 14275 } 14276 } 14277 14278 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14279 PackageParser.Package newPkg) { 14280 // Disable the parent package (parent always replaced) 14281 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14282 // Disable the child packages 14283 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14284 for (int i = 0; i < childCount; i++) { 14285 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14286 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14287 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14288 } 14289 return disabled; 14290 } 14291 14292 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14293 String installerPackageName) { 14294 // Enable the parent package 14295 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14296 // Enable the child packages 14297 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14298 for (int i = 0; i < childCount; i++) { 14299 PackageParser.Package childPkg = pkg.childPackages.get(i); 14300 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14301 } 14302 } 14303 14304 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14305 // Collect all used permissions in the UID 14306 ArraySet<String> usedPermissions = new ArraySet<>(); 14307 final int packageCount = su.packages.size(); 14308 for (int i = 0; i < packageCount; i++) { 14309 PackageSetting ps = su.packages.valueAt(i); 14310 if (ps.pkg == null) { 14311 continue; 14312 } 14313 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14314 for (int j = 0; j < requestedPermCount; j++) { 14315 String permission = ps.pkg.requestedPermissions.get(j); 14316 BasePermission bp = mSettings.mPermissions.get(permission); 14317 if (bp != null) { 14318 usedPermissions.add(permission); 14319 } 14320 } 14321 } 14322 14323 PermissionsState permissionsState = su.getPermissionsState(); 14324 // Prune install permissions 14325 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14326 final int installPermCount = installPermStates.size(); 14327 for (int i = installPermCount - 1; i >= 0; i--) { 14328 PermissionState permissionState = installPermStates.get(i); 14329 if (!usedPermissions.contains(permissionState.getName())) { 14330 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14331 if (bp != null) { 14332 permissionsState.revokeInstallPermission(bp); 14333 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14334 PackageManager.MASK_PERMISSION_FLAGS, 0); 14335 } 14336 } 14337 } 14338 14339 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14340 14341 // Prune runtime permissions 14342 for (int userId : allUserIds) { 14343 List<PermissionState> runtimePermStates = permissionsState 14344 .getRuntimePermissionStates(userId); 14345 final int runtimePermCount = runtimePermStates.size(); 14346 for (int i = runtimePermCount - 1; i >= 0; i--) { 14347 PermissionState permissionState = runtimePermStates.get(i); 14348 if (!usedPermissions.contains(permissionState.getName())) { 14349 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14350 if (bp != null) { 14351 permissionsState.revokeRuntimePermission(bp, userId); 14352 permissionsState.updatePermissionFlags(bp, userId, 14353 PackageManager.MASK_PERMISSION_FLAGS, 0); 14354 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14355 runtimePermissionChangedUserIds, userId); 14356 } 14357 } 14358 } 14359 } 14360 14361 return runtimePermissionChangedUserIds; 14362 } 14363 14364 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14365 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14366 // Update the parent package setting 14367 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14368 res, user); 14369 // Update the child packages setting 14370 final int childCount = (newPackage.childPackages != null) 14371 ? newPackage.childPackages.size() : 0; 14372 for (int i = 0; i < childCount; i++) { 14373 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14374 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14375 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14376 childRes.origUsers, childRes, user); 14377 } 14378 } 14379 14380 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14381 String installerPackageName, int[] allUsers, int[] installedForUsers, 14382 PackageInstalledInfo res, UserHandle user) { 14383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14384 14385 String pkgName = newPackage.packageName; 14386 synchronized (mPackages) { 14387 //write settings. the installStatus will be incomplete at this stage. 14388 //note that the new package setting would have already been 14389 //added to mPackages. It hasn't been persisted yet. 14390 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14391 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14392 mSettings.writeLPr(); 14393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14394 } 14395 14396 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14397 synchronized (mPackages) { 14398 updatePermissionsLPw(newPackage.packageName, newPackage, 14399 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14400 ? UPDATE_PERMISSIONS_ALL : 0)); 14401 // For system-bundled packages, we assume that installing an upgraded version 14402 // of the package implies that the user actually wants to run that new code, 14403 // so we enable the package. 14404 PackageSetting ps = mSettings.mPackages.get(pkgName); 14405 final int userId = user.getIdentifier(); 14406 if (ps != null) { 14407 if (isSystemApp(newPackage)) { 14408 if (DEBUG_INSTALL) { 14409 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14410 } 14411 // Enable system package for requested users 14412 if (res.origUsers != null) { 14413 for (int origUserId : res.origUsers) { 14414 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14415 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14416 origUserId, installerPackageName); 14417 } 14418 } 14419 } 14420 // Also convey the prior install/uninstall state 14421 if (allUsers != null && installedForUsers != null) { 14422 for (int currentUserId : allUsers) { 14423 final boolean installed = ArrayUtils.contains( 14424 installedForUsers, currentUserId); 14425 if (DEBUG_INSTALL) { 14426 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14427 } 14428 ps.setInstalled(installed, currentUserId); 14429 } 14430 // these install state changes will be persisted in the 14431 // upcoming call to mSettings.writeLPr(). 14432 } 14433 } 14434 // It's implied that when a user requests installation, they want the app to be 14435 // installed and enabled. 14436 if (userId != UserHandle.USER_ALL) { 14437 ps.setInstalled(true, userId); 14438 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14439 } 14440 } 14441 res.name = pkgName; 14442 res.uid = newPackage.applicationInfo.uid; 14443 res.pkg = newPackage; 14444 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14445 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14446 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14447 //to update install status 14448 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14449 mSettings.writeLPr(); 14450 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14451 } 14452 14453 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14454 } 14455 14456 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14457 try { 14458 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14459 installPackageLI(args, res); 14460 } finally { 14461 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14462 } 14463 } 14464 14465 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14466 final int installFlags = args.installFlags; 14467 final String installerPackageName = args.installerPackageName; 14468 final String volumeUuid = args.volumeUuid; 14469 final File tmpPackageFile = new File(args.getCodePath()); 14470 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14471 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14472 || (args.volumeUuid != null)); 14473 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14474 boolean replace = false; 14475 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14476 if (args.move != null) { 14477 // moving a complete application; perform an initial scan on the new install location 14478 scanFlags |= SCAN_INITIAL; 14479 } 14480 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14481 scanFlags |= SCAN_DONT_KILL_APP; 14482 } 14483 14484 // Result object to be returned 14485 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14486 14487 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14488 14489 // Sanity check 14490 if (ephemeral && (forwardLocked || onExternal)) { 14491 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14492 + " external=" + onExternal); 14493 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14494 return; 14495 } 14496 14497 // Retrieve PackageSettings and parse package 14498 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14499 | PackageParser.PARSE_ENFORCE_CODE 14500 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14501 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14502 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14503 PackageParser pp = new PackageParser(); 14504 pp.setSeparateProcesses(mSeparateProcesses); 14505 pp.setDisplayMetrics(mMetrics); 14506 14507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14508 final PackageParser.Package pkg; 14509 try { 14510 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14511 } catch (PackageParserException e) { 14512 res.setError("Failed parse during installPackageLI", e); 14513 return; 14514 } finally { 14515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14516 } 14517 14518 // If we are installing a clustered package add results for the children 14519 if (pkg.childPackages != null) { 14520 synchronized (mPackages) { 14521 final int childCount = pkg.childPackages.size(); 14522 for (int i = 0; i < childCount; i++) { 14523 PackageParser.Package childPkg = pkg.childPackages.get(i); 14524 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14525 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14526 childRes.pkg = childPkg; 14527 childRes.name = childPkg.packageName; 14528 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14529 if (childPs != null) { 14530 childRes.origUsers = childPs.queryInstalledUsers( 14531 sUserManager.getUserIds(), true); 14532 } 14533 if ((mPackages.containsKey(childPkg.packageName))) { 14534 childRes.removedInfo = new PackageRemovedInfo(); 14535 childRes.removedInfo.removedPackage = childPkg.packageName; 14536 } 14537 if (res.addedChildPackages == null) { 14538 res.addedChildPackages = new ArrayMap<>(); 14539 } 14540 res.addedChildPackages.put(childPkg.packageName, childRes); 14541 } 14542 } 14543 } 14544 14545 // If package doesn't declare API override, mark that we have an install 14546 // time CPU ABI override. 14547 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14548 pkg.cpuAbiOverride = args.abiOverride; 14549 } 14550 14551 String pkgName = res.name = pkg.packageName; 14552 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14553 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14554 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14555 return; 14556 } 14557 } 14558 14559 try { 14560 // either use what we've been given or parse directly from the APK 14561 if (args.certificates != null) { 14562 try { 14563 PackageParser.populateCertificates(pkg, args.certificates); 14564 } catch (PackageParserException e) { 14565 // there was something wrong with the certificates we were given; 14566 // try to pull them from the APK 14567 PackageParser.collectCertificates(pkg, parseFlags); 14568 } 14569 } else { 14570 PackageParser.collectCertificates(pkg, parseFlags); 14571 } 14572 } catch (PackageParserException e) { 14573 res.setError("Failed collect during installPackageLI", e); 14574 return; 14575 } 14576 14577 // Get rid of all references to package scan path via parser. 14578 pp = null; 14579 String oldCodePath = null; 14580 boolean systemApp = false; 14581 synchronized (mPackages) { 14582 // Check if installing already existing package 14583 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14584 String oldName = mSettings.mRenamedPackages.get(pkgName); 14585 if (pkg.mOriginalPackages != null 14586 && pkg.mOriginalPackages.contains(oldName) 14587 && mPackages.containsKey(oldName)) { 14588 // This package is derived from an original package, 14589 // and this device has been updating from that original 14590 // name. We must continue using the original name, so 14591 // rename the new package here. 14592 pkg.setPackageName(oldName); 14593 pkgName = pkg.packageName; 14594 replace = true; 14595 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14596 + oldName + " pkgName=" + pkgName); 14597 } else if (mPackages.containsKey(pkgName)) { 14598 // This package, under its official name, already exists 14599 // on the device; we should replace it. 14600 replace = true; 14601 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14602 } 14603 14604 // Child packages are installed through the parent package 14605 if (pkg.parentPackage != null) { 14606 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14607 "Package " + pkg.packageName + " is child of package " 14608 + pkg.parentPackage.parentPackage + ". Child packages " 14609 + "can be updated only through the parent package."); 14610 return; 14611 } 14612 14613 if (replace) { 14614 // Prevent apps opting out from runtime permissions 14615 PackageParser.Package oldPackage = mPackages.get(pkgName); 14616 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14617 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14618 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14619 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14620 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14621 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14622 + " doesn't support runtime permissions but the old" 14623 + " target SDK " + oldTargetSdk + " does."); 14624 return; 14625 } 14626 14627 // Prevent installing of child packages 14628 if (oldPackage.parentPackage != null) { 14629 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14630 "Package " + pkg.packageName + " is child of package " 14631 + oldPackage.parentPackage + ". Child packages " 14632 + "can be updated only through the parent package."); 14633 return; 14634 } 14635 } 14636 } 14637 14638 PackageSetting ps = mSettings.mPackages.get(pkgName); 14639 if (ps != null) { 14640 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14641 14642 // Quick sanity check that we're signed correctly if updating; 14643 // we'll check this again later when scanning, but we want to 14644 // bail early here before tripping over redefined permissions. 14645 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14646 if (!checkUpgradeKeySetLP(ps, pkg)) { 14647 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14648 + pkg.packageName + " upgrade keys do not match the " 14649 + "previously installed version"); 14650 return; 14651 } 14652 } else { 14653 try { 14654 verifySignaturesLP(ps, pkg); 14655 } catch (PackageManagerException e) { 14656 res.setError(e.error, e.getMessage()); 14657 return; 14658 } 14659 } 14660 14661 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14662 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14663 systemApp = (ps.pkg.applicationInfo.flags & 14664 ApplicationInfo.FLAG_SYSTEM) != 0; 14665 } 14666 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14667 } 14668 14669 // Check whether the newly-scanned package wants to define an already-defined perm 14670 int N = pkg.permissions.size(); 14671 for (int i = N-1; i >= 0; i--) { 14672 PackageParser.Permission perm = pkg.permissions.get(i); 14673 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14674 if (bp != null) { 14675 // If the defining package is signed with our cert, it's okay. This 14676 // also includes the "updating the same package" case, of course. 14677 // "updating same package" could also involve key-rotation. 14678 final boolean sigsOk; 14679 if (bp.sourcePackage.equals(pkg.packageName) 14680 && (bp.packageSetting instanceof PackageSetting) 14681 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14682 scanFlags))) { 14683 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14684 } else { 14685 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14686 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14687 } 14688 if (!sigsOk) { 14689 // If the owning package is the system itself, we log but allow 14690 // install to proceed; we fail the install on all other permission 14691 // redefinitions. 14692 if (!bp.sourcePackage.equals("android")) { 14693 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14694 + pkg.packageName + " attempting to redeclare permission " 14695 + perm.info.name + " already owned by " + bp.sourcePackage); 14696 res.origPermission = perm.info.name; 14697 res.origPackage = bp.sourcePackage; 14698 return; 14699 } else { 14700 Slog.w(TAG, "Package " + pkg.packageName 14701 + " attempting to redeclare system permission " 14702 + perm.info.name + "; ignoring new declaration"); 14703 pkg.permissions.remove(i); 14704 } 14705 } 14706 } 14707 } 14708 } 14709 14710 if (systemApp) { 14711 if (onExternal) { 14712 // Abort update; system app can't be replaced with app on sdcard 14713 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14714 "Cannot install updates to system apps on sdcard"); 14715 return; 14716 } else if (ephemeral) { 14717 // Abort update; system app can't be replaced with an ephemeral app 14718 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14719 "Cannot update a system app with an ephemeral app"); 14720 return; 14721 } 14722 } 14723 14724 if (args.move != null) { 14725 // We did an in-place move, so dex is ready to roll 14726 scanFlags |= SCAN_NO_DEX; 14727 scanFlags |= SCAN_MOVE; 14728 14729 synchronized (mPackages) { 14730 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14731 if (ps == null) { 14732 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14733 "Missing settings for moved package " + pkgName); 14734 } 14735 14736 // We moved the entire application as-is, so bring over the 14737 // previously derived ABI information. 14738 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14739 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14740 } 14741 14742 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14743 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14744 scanFlags |= SCAN_NO_DEX; 14745 14746 try { 14747 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14748 args.abiOverride : pkg.cpuAbiOverride); 14749 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14750 true /* extract libs */); 14751 } catch (PackageManagerException pme) { 14752 Slog.e(TAG, "Error deriving application ABI", pme); 14753 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14754 return; 14755 } 14756 14757 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14758 // Do not run PackageDexOptimizer through the local performDexOpt 14759 // method because `pkg` is not in `mPackages` yet. 14760 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14761 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14762 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14763 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14764 String msg = "Extracting package failed for " + pkgName; 14765 res.setError(INSTALL_FAILED_DEXOPT, msg); 14766 return; 14767 } 14768 14769 // Notify BackgroundDexOptService that the package has been changed. 14770 // If this is an update of a package which used to fail to compile, 14771 // BDOS will remove it from its blacklist. 14772 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14773 } 14774 14775 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14776 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14777 return; 14778 } 14779 14780 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14781 14782 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14783 "installPackageLI")) { 14784 if (replace) { 14785 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14786 installerPackageName, res); 14787 } else { 14788 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14789 args.user, installerPackageName, volumeUuid, res); 14790 } 14791 } 14792 synchronized (mPackages) { 14793 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14794 if (ps != null) { 14795 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14796 } 14797 14798 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14799 for (int i = 0; i < childCount; i++) { 14800 PackageParser.Package childPkg = pkg.childPackages.get(i); 14801 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14802 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14803 if (childPs != null) { 14804 childRes.newUsers = childPs.queryInstalledUsers( 14805 sUserManager.getUserIds(), true); 14806 } 14807 } 14808 } 14809 } 14810 14811 private void startIntentFilterVerifications(int userId, boolean replacing, 14812 PackageParser.Package pkg) { 14813 if (mIntentFilterVerifierComponent == null) { 14814 Slog.w(TAG, "No IntentFilter verification will not be done as " 14815 + "there is no IntentFilterVerifier available!"); 14816 return; 14817 } 14818 14819 final int verifierUid = getPackageUid( 14820 mIntentFilterVerifierComponent.getPackageName(), 14821 MATCH_DEBUG_TRIAGED_MISSING, 14822 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14823 14824 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14825 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14826 mHandler.sendMessage(msg); 14827 14828 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14829 for (int i = 0; i < childCount; i++) { 14830 PackageParser.Package childPkg = pkg.childPackages.get(i); 14831 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14832 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14833 mHandler.sendMessage(msg); 14834 } 14835 } 14836 14837 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14838 PackageParser.Package pkg) { 14839 int size = pkg.activities.size(); 14840 if (size == 0) { 14841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14842 "No activity, so no need to verify any IntentFilter!"); 14843 return; 14844 } 14845 14846 final boolean hasDomainURLs = hasDomainURLs(pkg); 14847 if (!hasDomainURLs) { 14848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14849 "No domain URLs, so no need to verify any IntentFilter!"); 14850 return; 14851 } 14852 14853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14854 + " if any IntentFilter from the " + size 14855 + " Activities needs verification ..."); 14856 14857 int count = 0; 14858 final String packageName = pkg.packageName; 14859 14860 synchronized (mPackages) { 14861 // If this is a new install and we see that we've already run verification for this 14862 // package, we have nothing to do: it means the state was restored from backup. 14863 if (!replacing) { 14864 IntentFilterVerificationInfo ivi = 14865 mSettings.getIntentFilterVerificationLPr(packageName); 14866 if (ivi != null) { 14867 if (DEBUG_DOMAIN_VERIFICATION) { 14868 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14869 + ivi.getStatusString()); 14870 } 14871 return; 14872 } 14873 } 14874 14875 // If any filters need to be verified, then all need to be. 14876 boolean needToVerify = false; 14877 for (PackageParser.Activity a : pkg.activities) { 14878 for (ActivityIntentInfo filter : a.intents) { 14879 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14880 if (DEBUG_DOMAIN_VERIFICATION) { 14881 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14882 } 14883 needToVerify = true; 14884 break; 14885 } 14886 } 14887 } 14888 14889 if (needToVerify) { 14890 final int verificationId = mIntentFilterVerificationToken++; 14891 for (PackageParser.Activity a : pkg.activities) { 14892 for (ActivityIntentInfo filter : a.intents) { 14893 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14894 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14895 "Verification needed for IntentFilter:" + filter.toString()); 14896 mIntentFilterVerifier.addOneIntentFilterVerification( 14897 verifierUid, userId, verificationId, filter, packageName); 14898 count++; 14899 } 14900 } 14901 } 14902 } 14903 } 14904 14905 if (count > 0) { 14906 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14907 + " IntentFilter verification" + (count > 1 ? "s" : "") 14908 + " for userId:" + userId); 14909 mIntentFilterVerifier.startVerifications(userId); 14910 } else { 14911 if (DEBUG_DOMAIN_VERIFICATION) { 14912 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14913 } 14914 } 14915 } 14916 14917 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14918 final ComponentName cn = filter.activity.getComponentName(); 14919 final String packageName = cn.getPackageName(); 14920 14921 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14922 packageName); 14923 if (ivi == null) { 14924 return true; 14925 } 14926 int status = ivi.getStatus(); 14927 switch (status) { 14928 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14929 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14930 return true; 14931 14932 default: 14933 // Nothing to do 14934 return false; 14935 } 14936 } 14937 14938 private static boolean isMultiArch(ApplicationInfo info) { 14939 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14940 } 14941 14942 private static boolean isExternal(PackageParser.Package pkg) { 14943 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14944 } 14945 14946 private static boolean isExternal(PackageSetting ps) { 14947 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14948 } 14949 14950 private static boolean isEphemeral(PackageParser.Package pkg) { 14951 return pkg.applicationInfo.isEphemeralApp(); 14952 } 14953 14954 private static boolean isEphemeral(PackageSetting ps) { 14955 return ps.pkg != null && isEphemeral(ps.pkg); 14956 } 14957 14958 private static boolean isSystemApp(PackageParser.Package pkg) { 14959 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14960 } 14961 14962 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14963 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14964 } 14965 14966 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14967 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14968 } 14969 14970 private static boolean isSystemApp(PackageSetting ps) { 14971 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14972 } 14973 14974 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14975 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14976 } 14977 14978 private int packageFlagsToInstallFlags(PackageSetting ps) { 14979 int installFlags = 0; 14980 if (isEphemeral(ps)) { 14981 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14982 } 14983 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14984 // This existing package was an external ASEC install when we have 14985 // the external flag without a UUID 14986 installFlags |= PackageManager.INSTALL_EXTERNAL; 14987 } 14988 if (ps.isForwardLocked()) { 14989 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14990 } 14991 return installFlags; 14992 } 14993 14994 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14995 if (isExternal(pkg)) { 14996 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14997 return StorageManager.UUID_PRIMARY_PHYSICAL; 14998 } else { 14999 return pkg.volumeUuid; 15000 } 15001 } else { 15002 return StorageManager.UUID_PRIVATE_INTERNAL; 15003 } 15004 } 15005 15006 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15007 if (isExternal(pkg)) { 15008 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15009 return mSettings.getExternalVersion(); 15010 } else { 15011 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15012 } 15013 } else { 15014 return mSettings.getInternalVersion(); 15015 } 15016 } 15017 15018 private void deleteTempPackageFiles() { 15019 final FilenameFilter filter = new FilenameFilter() { 15020 public boolean accept(File dir, String name) { 15021 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15022 } 15023 }; 15024 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15025 file.delete(); 15026 } 15027 } 15028 15029 @Override 15030 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15031 int flags) { 15032 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15033 flags); 15034 } 15035 15036 @Override 15037 public void deletePackage(final String packageName, 15038 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15039 mContext.enforceCallingOrSelfPermission( 15040 android.Manifest.permission.DELETE_PACKAGES, null); 15041 Preconditions.checkNotNull(packageName); 15042 Preconditions.checkNotNull(observer); 15043 final int uid = Binder.getCallingUid(); 15044 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15045 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15046 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15047 mContext.enforceCallingOrSelfPermission( 15048 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15049 "deletePackage for user " + userId); 15050 } 15051 15052 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15053 try { 15054 observer.onPackageDeleted(packageName, 15055 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15056 } catch (RemoteException re) { 15057 } 15058 return; 15059 } 15060 15061 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15062 try { 15063 observer.onPackageDeleted(packageName, 15064 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15065 } catch (RemoteException re) { 15066 } 15067 return; 15068 } 15069 15070 if (DEBUG_REMOVE) { 15071 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15072 + " deleteAllUsers: " + deleteAllUsers ); 15073 } 15074 // Queue up an async operation since the package deletion may take a little while. 15075 mHandler.post(new Runnable() { 15076 public void run() { 15077 mHandler.removeCallbacks(this); 15078 int returnCode; 15079 if (!deleteAllUsers) { 15080 returnCode = deletePackageX(packageName, userId, deleteFlags); 15081 } else { 15082 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15083 // If nobody is blocking uninstall, proceed with delete for all users 15084 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15085 returnCode = deletePackageX(packageName, userId, deleteFlags); 15086 } else { 15087 // Otherwise uninstall individually for users with blockUninstalls=false 15088 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15089 for (int userId : users) { 15090 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15091 returnCode = deletePackageX(packageName, userId, userFlags); 15092 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15093 Slog.w(TAG, "Package delete failed for user " + userId 15094 + ", returnCode " + returnCode); 15095 } 15096 } 15097 } 15098 // The app has only been marked uninstalled for certain users. 15099 // We still need to report that delete was blocked 15100 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15101 } 15102 } 15103 try { 15104 observer.onPackageDeleted(packageName, returnCode, null); 15105 } catch (RemoteException e) { 15106 Log.i(TAG, "Observer no longer exists."); 15107 } //end catch 15108 } //end run 15109 }); 15110 } 15111 15112 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15113 int[] result = EMPTY_INT_ARRAY; 15114 for (int userId : userIds) { 15115 if (getBlockUninstallForUser(packageName, userId)) { 15116 result = ArrayUtils.appendInt(result, userId); 15117 } 15118 } 15119 return result; 15120 } 15121 15122 @Override 15123 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15124 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15125 } 15126 15127 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15128 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15129 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15130 try { 15131 if (dpm != null) { 15132 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15133 /* callingUserOnly =*/ false); 15134 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15135 : deviceOwnerComponentName.getPackageName(); 15136 // Does the package contains the device owner? 15137 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15138 // this check is probably not needed, since DO should be registered as a device 15139 // admin on some user too. (Original bug for this: b/17657954) 15140 if (packageName.equals(deviceOwnerPackageName)) { 15141 return true; 15142 } 15143 // Does it contain a device admin for any user? 15144 int[] users; 15145 if (userId == UserHandle.USER_ALL) { 15146 users = sUserManager.getUserIds(); 15147 } else { 15148 users = new int[]{userId}; 15149 } 15150 for (int i = 0; i < users.length; ++i) { 15151 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15152 return true; 15153 } 15154 } 15155 } 15156 } catch (RemoteException e) { 15157 } 15158 return false; 15159 } 15160 15161 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15162 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15163 } 15164 15165 /** 15166 * This method is an internal method that could be get invoked either 15167 * to delete an installed package or to clean up a failed installation. 15168 * After deleting an installed package, a broadcast is sent to notify any 15169 * listeners that the package has been removed. For cleaning up a failed 15170 * installation, the broadcast is not necessary since the package's 15171 * installation wouldn't have sent the initial broadcast either 15172 * The key steps in deleting a package are 15173 * deleting the package information in internal structures like mPackages, 15174 * deleting the packages base directories through installd 15175 * updating mSettings to reflect current status 15176 * persisting settings for later use 15177 * sending a broadcast if necessary 15178 */ 15179 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15180 final PackageRemovedInfo info = new PackageRemovedInfo(); 15181 final boolean res; 15182 15183 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15184 ? UserHandle.ALL : new UserHandle(userId); 15185 15186 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15187 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15188 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15189 } 15190 15191 PackageSetting uninstalledPs = null; 15192 15193 // for the uninstall-updates case and restricted profiles, remember the per- 15194 // user handle installed state 15195 int[] allUsers; 15196 synchronized (mPackages) { 15197 uninstalledPs = mSettings.mPackages.get(packageName); 15198 if (uninstalledPs == null) { 15199 Slog.w(TAG, "Not removing non-existent package " + packageName); 15200 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15201 } 15202 allUsers = sUserManager.getUserIds(); 15203 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15204 } 15205 15206 synchronized (mInstallLock) { 15207 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15208 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15209 "deletePackageX")) { 15210 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15211 deleteFlags | REMOVE_CHATTY, info, true, null); 15212 } 15213 synchronized (mPackages) { 15214 if (res) { 15215 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15216 } 15217 } 15218 } 15219 15220 if (res) { 15221 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15222 info.sendPackageRemovedBroadcasts(killApp); 15223 info.sendSystemPackageUpdatedBroadcasts(); 15224 info.sendSystemPackageAppearedBroadcasts(); 15225 } 15226 // Force a gc here. 15227 Runtime.getRuntime().gc(); 15228 // Delete the resources here after sending the broadcast to let 15229 // other processes clean up before deleting resources. 15230 if (info.args != null) { 15231 synchronized (mInstallLock) { 15232 info.args.doPostDeleteLI(true); 15233 } 15234 } 15235 15236 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15237 } 15238 15239 class PackageRemovedInfo { 15240 String removedPackage; 15241 int uid = -1; 15242 int removedAppId = -1; 15243 int[] origUsers; 15244 int[] removedUsers = null; 15245 boolean isRemovedPackageSystemUpdate = false; 15246 boolean isUpdate; 15247 boolean dataRemoved; 15248 boolean removedForAllUsers; 15249 // Clean up resources deleted packages. 15250 InstallArgs args = null; 15251 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15252 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15253 15254 void sendPackageRemovedBroadcasts(boolean killApp) { 15255 sendPackageRemovedBroadcastInternal(killApp); 15256 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15257 for (int i = 0; i < childCount; i++) { 15258 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15259 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15260 } 15261 } 15262 15263 void sendSystemPackageUpdatedBroadcasts() { 15264 if (isRemovedPackageSystemUpdate) { 15265 sendSystemPackageUpdatedBroadcastsInternal(); 15266 final int childCount = (removedChildPackages != null) 15267 ? removedChildPackages.size() : 0; 15268 for (int i = 0; i < childCount; i++) { 15269 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15270 if (childInfo.isRemovedPackageSystemUpdate) { 15271 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15272 } 15273 } 15274 } 15275 } 15276 15277 void sendSystemPackageAppearedBroadcasts() { 15278 final int packageCount = (appearedChildPackages != null) 15279 ? appearedChildPackages.size() : 0; 15280 for (int i = 0; i < packageCount; i++) { 15281 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15282 for (int userId : installedInfo.newUsers) { 15283 sendPackageAddedForUser(installedInfo.name, true, 15284 UserHandle.getAppId(installedInfo.uid), userId); 15285 } 15286 } 15287 } 15288 15289 private void sendSystemPackageUpdatedBroadcastsInternal() { 15290 Bundle extras = new Bundle(2); 15291 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15292 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15293 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15294 extras, 0, null, null, null); 15295 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15296 extras, 0, null, null, null); 15297 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15298 null, 0, removedPackage, null, null); 15299 } 15300 15301 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15302 Bundle extras = new Bundle(2); 15303 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15304 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15305 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15306 if (isUpdate || isRemovedPackageSystemUpdate) { 15307 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15308 } 15309 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15310 if (removedPackage != null) { 15311 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15312 extras, 0, null, null, removedUsers); 15313 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15314 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15315 removedPackage, extras, 0, null, null, removedUsers); 15316 } 15317 } 15318 if (removedAppId >= 0) { 15319 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15320 removedUsers); 15321 } 15322 } 15323 } 15324 15325 /* 15326 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15327 * flag is not set, the data directory is removed as well. 15328 * make sure this flag is set for partially installed apps. If not its meaningless to 15329 * delete a partially installed application. 15330 */ 15331 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15332 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15333 String packageName = ps.name; 15334 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15335 // Retrieve object to delete permissions for shared user later on 15336 final PackageParser.Package deletedPkg; 15337 final PackageSetting deletedPs; 15338 // reader 15339 synchronized (mPackages) { 15340 deletedPkg = mPackages.get(packageName); 15341 deletedPs = mSettings.mPackages.get(packageName); 15342 if (outInfo != null) { 15343 outInfo.removedPackage = packageName; 15344 outInfo.removedUsers = deletedPs != null 15345 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15346 : null; 15347 } 15348 } 15349 15350 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15351 15352 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15353 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15354 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15355 destroyAppProfilesLIF(deletedPkg); 15356 if (outInfo != null) { 15357 outInfo.dataRemoved = true; 15358 } 15359 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15360 } 15361 15362 // writer 15363 synchronized (mPackages) { 15364 if (deletedPs != null) { 15365 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15366 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15367 clearDefaultBrowserIfNeeded(packageName); 15368 if (outInfo != null) { 15369 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15370 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15371 } 15372 updatePermissionsLPw(deletedPs.name, null, 0); 15373 if (deletedPs.sharedUser != null) { 15374 // Remove permissions associated with package. Since runtime 15375 // permissions are per user we have to kill the removed package 15376 // or packages running under the shared user of the removed 15377 // package if revoking the permissions requested only by the removed 15378 // package is successful and this causes a change in gids. 15379 for (int userId : UserManagerService.getInstance().getUserIds()) { 15380 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15381 userId); 15382 if (userIdToKill == UserHandle.USER_ALL 15383 || userIdToKill >= UserHandle.USER_SYSTEM) { 15384 // If gids changed for this user, kill all affected packages. 15385 mHandler.post(new Runnable() { 15386 @Override 15387 public void run() { 15388 // This has to happen with no lock held. 15389 killApplication(deletedPs.name, deletedPs.appId, 15390 KILL_APP_REASON_GIDS_CHANGED); 15391 } 15392 }); 15393 break; 15394 } 15395 } 15396 } 15397 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15398 } 15399 // make sure to preserve per-user disabled state if this removal was just 15400 // a downgrade of a system app to the factory package 15401 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15402 if (DEBUG_REMOVE) { 15403 Slog.d(TAG, "Propagating install state across downgrade"); 15404 } 15405 for (int userId : allUserHandles) { 15406 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15407 if (DEBUG_REMOVE) { 15408 Slog.d(TAG, " user " + userId + " => " + installed); 15409 } 15410 ps.setInstalled(installed, userId); 15411 } 15412 } 15413 } 15414 // can downgrade to reader 15415 if (writeSettings) { 15416 // Save settings now 15417 mSettings.writeLPr(); 15418 } 15419 } 15420 if (outInfo != null) { 15421 // A user ID was deleted here. Go through all users and remove it 15422 // from KeyStore. 15423 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15424 } 15425 } 15426 15427 static boolean locationIsPrivileged(File path) { 15428 try { 15429 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15430 .getCanonicalPath(); 15431 return path.getCanonicalPath().startsWith(privilegedAppDir); 15432 } catch (IOException e) { 15433 Slog.e(TAG, "Unable to access code path " + path); 15434 } 15435 return false; 15436 } 15437 15438 /* 15439 * Tries to delete system package. 15440 */ 15441 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15442 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15443 boolean writeSettings) { 15444 if (deletedPs.parentPackageName != null) { 15445 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15446 return false; 15447 } 15448 15449 final boolean applyUserRestrictions 15450 = (allUserHandles != null) && (outInfo.origUsers != null); 15451 final PackageSetting disabledPs; 15452 // Confirm if the system package has been updated 15453 // An updated system app can be deleted. This will also have to restore 15454 // the system pkg from system partition 15455 // reader 15456 synchronized (mPackages) { 15457 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15458 } 15459 15460 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15461 + " disabledPs=" + disabledPs); 15462 15463 if (disabledPs == null) { 15464 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15465 return false; 15466 } else if (DEBUG_REMOVE) { 15467 Slog.d(TAG, "Deleting system pkg from data partition"); 15468 } 15469 15470 if (DEBUG_REMOVE) { 15471 if (applyUserRestrictions) { 15472 Slog.d(TAG, "Remembering install states:"); 15473 for (int userId : allUserHandles) { 15474 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15475 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15476 } 15477 } 15478 } 15479 15480 // Delete the updated package 15481 outInfo.isRemovedPackageSystemUpdate = true; 15482 if (outInfo.removedChildPackages != null) { 15483 final int childCount = (deletedPs.childPackageNames != null) 15484 ? deletedPs.childPackageNames.size() : 0; 15485 for (int i = 0; i < childCount; i++) { 15486 String childPackageName = deletedPs.childPackageNames.get(i); 15487 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15488 .contains(childPackageName)) { 15489 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15490 childPackageName); 15491 if (childInfo != null) { 15492 childInfo.isRemovedPackageSystemUpdate = true; 15493 } 15494 } 15495 } 15496 } 15497 15498 if (disabledPs.versionCode < deletedPs.versionCode) { 15499 // Delete data for downgrades 15500 flags &= ~PackageManager.DELETE_KEEP_DATA; 15501 } else { 15502 // Preserve data by setting flag 15503 flags |= PackageManager.DELETE_KEEP_DATA; 15504 } 15505 15506 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15507 outInfo, writeSettings, disabledPs.pkg); 15508 if (!ret) { 15509 return false; 15510 } 15511 15512 // writer 15513 synchronized (mPackages) { 15514 // Reinstate the old system package 15515 enableSystemPackageLPw(disabledPs.pkg); 15516 // Remove any native libraries from the upgraded package. 15517 removeNativeBinariesLI(deletedPs); 15518 } 15519 15520 // Install the system package 15521 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15522 int parseFlags = mDefParseFlags 15523 | PackageParser.PARSE_MUST_BE_APK 15524 | PackageParser.PARSE_IS_SYSTEM 15525 | PackageParser.PARSE_IS_SYSTEM_DIR; 15526 if (locationIsPrivileged(disabledPs.codePath)) { 15527 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15528 } 15529 15530 final PackageParser.Package newPkg; 15531 try { 15532 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15533 } catch (PackageManagerException e) { 15534 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15535 + e.getMessage()); 15536 return false; 15537 } 15538 15539 prepareAppDataAfterInstallLIF(newPkg); 15540 15541 // writer 15542 synchronized (mPackages) { 15543 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15544 15545 // Propagate the permissions state as we do not want to drop on the floor 15546 // runtime permissions. The update permissions method below will take 15547 // care of removing obsolete permissions and grant install permissions. 15548 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15549 updatePermissionsLPw(newPkg.packageName, newPkg, 15550 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15551 15552 if (applyUserRestrictions) { 15553 if (DEBUG_REMOVE) { 15554 Slog.d(TAG, "Propagating install state across reinstall"); 15555 } 15556 for (int userId : allUserHandles) { 15557 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15558 if (DEBUG_REMOVE) { 15559 Slog.d(TAG, " user " + userId + " => " + installed); 15560 } 15561 ps.setInstalled(installed, userId); 15562 15563 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15564 } 15565 // Regardless of writeSettings we need to ensure that this restriction 15566 // state propagation is persisted 15567 mSettings.writeAllUsersPackageRestrictionsLPr(); 15568 } 15569 // can downgrade to reader here 15570 if (writeSettings) { 15571 mSettings.writeLPr(); 15572 } 15573 } 15574 return true; 15575 } 15576 15577 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15578 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15579 PackageRemovedInfo outInfo, boolean writeSettings, 15580 PackageParser.Package replacingPackage) { 15581 synchronized (mPackages) { 15582 if (outInfo != null) { 15583 outInfo.uid = ps.appId; 15584 } 15585 15586 if (outInfo != null && outInfo.removedChildPackages != null) { 15587 final int childCount = (ps.childPackageNames != null) 15588 ? ps.childPackageNames.size() : 0; 15589 for (int i = 0; i < childCount; i++) { 15590 String childPackageName = ps.childPackageNames.get(i); 15591 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15592 if (childPs == null) { 15593 return false; 15594 } 15595 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15596 childPackageName); 15597 if (childInfo != null) { 15598 childInfo.uid = childPs.appId; 15599 } 15600 } 15601 } 15602 } 15603 15604 // Delete package data from internal structures and also remove data if flag is set 15605 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15606 15607 // Delete the child packages data 15608 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15609 for (int i = 0; i < childCount; i++) { 15610 PackageSetting childPs; 15611 synchronized (mPackages) { 15612 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15613 } 15614 if (childPs != null) { 15615 PackageRemovedInfo childOutInfo = (outInfo != null 15616 && outInfo.removedChildPackages != null) 15617 ? outInfo.removedChildPackages.get(childPs.name) : null; 15618 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15619 && (replacingPackage != null 15620 && !replacingPackage.hasChildPackage(childPs.name)) 15621 ? flags & ~DELETE_KEEP_DATA : flags; 15622 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15623 deleteFlags, writeSettings); 15624 } 15625 } 15626 15627 // Delete application code and resources only for parent packages 15628 if (ps.parentPackageName == null) { 15629 if (deleteCodeAndResources && (outInfo != null)) { 15630 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15631 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15632 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15633 } 15634 } 15635 15636 return true; 15637 } 15638 15639 @Override 15640 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15641 int userId) { 15642 mContext.enforceCallingOrSelfPermission( 15643 android.Manifest.permission.DELETE_PACKAGES, null); 15644 synchronized (mPackages) { 15645 PackageSetting ps = mSettings.mPackages.get(packageName); 15646 if (ps == null) { 15647 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15648 return false; 15649 } 15650 if (!ps.getInstalled(userId)) { 15651 // Can't block uninstall for an app that is not installed or enabled. 15652 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15653 return false; 15654 } 15655 ps.setBlockUninstall(blockUninstall, userId); 15656 mSettings.writePackageRestrictionsLPr(userId); 15657 } 15658 return true; 15659 } 15660 15661 @Override 15662 public boolean getBlockUninstallForUser(String packageName, int userId) { 15663 synchronized (mPackages) { 15664 PackageSetting ps = mSettings.mPackages.get(packageName); 15665 if (ps == null) { 15666 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15667 return false; 15668 } 15669 return ps.getBlockUninstall(userId); 15670 } 15671 } 15672 15673 @Override 15674 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15675 int callingUid = Binder.getCallingUid(); 15676 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15677 throw new SecurityException( 15678 "setRequiredForSystemUser can only be run by the system or root"); 15679 } 15680 synchronized (mPackages) { 15681 PackageSetting ps = mSettings.mPackages.get(packageName); 15682 if (ps == null) { 15683 Log.w(TAG, "Package doesn't exist: " + packageName); 15684 return false; 15685 } 15686 if (systemUserApp) { 15687 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15688 } else { 15689 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15690 } 15691 mSettings.writeLPr(); 15692 } 15693 return true; 15694 } 15695 15696 /* 15697 * This method handles package deletion in general 15698 */ 15699 private boolean deletePackageLIF(String packageName, UserHandle user, 15700 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15701 PackageRemovedInfo outInfo, boolean writeSettings, 15702 PackageParser.Package replacingPackage) { 15703 if (packageName == null) { 15704 Slog.w(TAG, "Attempt to delete null packageName."); 15705 return false; 15706 } 15707 15708 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15709 15710 PackageSetting ps; 15711 15712 synchronized (mPackages) { 15713 ps = mSettings.mPackages.get(packageName); 15714 if (ps == null) { 15715 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15716 return false; 15717 } 15718 15719 if (ps.parentPackageName != null && (!isSystemApp(ps) 15720 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15721 if (DEBUG_REMOVE) { 15722 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15723 + ((user == null) ? UserHandle.USER_ALL : user)); 15724 } 15725 final int removedUserId = (user != null) ? user.getIdentifier() 15726 : UserHandle.USER_ALL; 15727 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15728 return false; 15729 } 15730 markPackageUninstalledForUserLPw(ps, user); 15731 scheduleWritePackageRestrictionsLocked(user); 15732 return true; 15733 } 15734 } 15735 15736 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15737 && user.getIdentifier() != UserHandle.USER_ALL)) { 15738 // The caller is asking that the package only be deleted for a single 15739 // user. To do this, we just mark its uninstalled state and delete 15740 // its data. If this is a system app, we only allow this to happen if 15741 // they have set the special DELETE_SYSTEM_APP which requests different 15742 // semantics than normal for uninstalling system apps. 15743 markPackageUninstalledForUserLPw(ps, user); 15744 15745 if (!isSystemApp(ps)) { 15746 // Do not uninstall the APK if an app should be cached 15747 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15748 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15749 // Other user still have this package installed, so all 15750 // we need to do is clear this user's data and save that 15751 // it is uninstalled. 15752 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15753 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15754 return false; 15755 } 15756 scheduleWritePackageRestrictionsLocked(user); 15757 return true; 15758 } else { 15759 // We need to set it back to 'installed' so the uninstall 15760 // broadcasts will be sent correctly. 15761 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15762 ps.setInstalled(true, user.getIdentifier()); 15763 } 15764 } else { 15765 // This is a system app, so we assume that the 15766 // other users still have this package installed, so all 15767 // we need to do is clear this user's data and save that 15768 // it is uninstalled. 15769 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15770 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15771 return false; 15772 } 15773 scheduleWritePackageRestrictionsLocked(user); 15774 return true; 15775 } 15776 } 15777 15778 // If we are deleting a composite package for all users, keep track 15779 // of result for each child. 15780 if (ps.childPackageNames != null && outInfo != null) { 15781 synchronized (mPackages) { 15782 final int childCount = ps.childPackageNames.size(); 15783 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15784 for (int i = 0; i < childCount; i++) { 15785 String childPackageName = ps.childPackageNames.get(i); 15786 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15787 childInfo.removedPackage = childPackageName; 15788 outInfo.removedChildPackages.put(childPackageName, childInfo); 15789 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15790 if (childPs != null) { 15791 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15792 } 15793 } 15794 } 15795 } 15796 15797 boolean ret = false; 15798 if (isSystemApp(ps)) { 15799 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15800 // When an updated system application is deleted we delete the existing resources 15801 // as well and fall back to existing code in system partition 15802 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15803 } else { 15804 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15805 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15806 outInfo, writeSettings, replacingPackage); 15807 } 15808 15809 // Take a note whether we deleted the package for all users 15810 if (outInfo != null) { 15811 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15812 if (outInfo.removedChildPackages != null) { 15813 synchronized (mPackages) { 15814 final int childCount = outInfo.removedChildPackages.size(); 15815 for (int i = 0; i < childCount; i++) { 15816 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15817 if (childInfo != null) { 15818 childInfo.removedForAllUsers = mPackages.get( 15819 childInfo.removedPackage) == null; 15820 } 15821 } 15822 } 15823 } 15824 // If we uninstalled an update to a system app there may be some 15825 // child packages that appeared as they are declared in the system 15826 // app but were not declared in the update. 15827 if (isSystemApp(ps)) { 15828 synchronized (mPackages) { 15829 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15830 final int childCount = (updatedPs.childPackageNames != null) 15831 ? updatedPs.childPackageNames.size() : 0; 15832 for (int i = 0; i < childCount; i++) { 15833 String childPackageName = updatedPs.childPackageNames.get(i); 15834 if (outInfo.removedChildPackages == null 15835 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15836 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15837 if (childPs == null) { 15838 continue; 15839 } 15840 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15841 installRes.name = childPackageName; 15842 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15843 installRes.pkg = mPackages.get(childPackageName); 15844 installRes.uid = childPs.pkg.applicationInfo.uid; 15845 if (outInfo.appearedChildPackages == null) { 15846 outInfo.appearedChildPackages = new ArrayMap<>(); 15847 } 15848 outInfo.appearedChildPackages.put(childPackageName, installRes); 15849 } 15850 } 15851 } 15852 } 15853 } 15854 15855 return ret; 15856 } 15857 15858 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15859 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15860 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15861 for (int nextUserId : userIds) { 15862 if (DEBUG_REMOVE) { 15863 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15864 } 15865 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15866 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15867 false /*hidden*/, false /*suspended*/, null, null, null, 15868 false /*blockUninstall*/, 15869 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15870 } 15871 } 15872 15873 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15874 PackageRemovedInfo outInfo) { 15875 final PackageParser.Package pkg; 15876 synchronized (mPackages) { 15877 pkg = mPackages.get(ps.name); 15878 } 15879 15880 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15881 : new int[] {userId}; 15882 for (int nextUserId : userIds) { 15883 if (DEBUG_REMOVE) { 15884 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15885 + nextUserId); 15886 } 15887 15888 destroyAppDataLIF(pkg, userId, 15889 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15890 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15891 schedulePackageCleaning(ps.name, nextUserId, false); 15892 synchronized (mPackages) { 15893 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15894 scheduleWritePackageRestrictionsLocked(nextUserId); 15895 } 15896 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15897 } 15898 } 15899 15900 if (outInfo != null) { 15901 outInfo.removedPackage = ps.name; 15902 outInfo.removedAppId = ps.appId; 15903 outInfo.removedUsers = userIds; 15904 } 15905 15906 return true; 15907 } 15908 15909 private final class ClearStorageConnection implements ServiceConnection { 15910 IMediaContainerService mContainerService; 15911 15912 @Override 15913 public void onServiceConnected(ComponentName name, IBinder service) { 15914 synchronized (this) { 15915 mContainerService = IMediaContainerService.Stub.asInterface(service); 15916 notifyAll(); 15917 } 15918 } 15919 15920 @Override 15921 public void onServiceDisconnected(ComponentName name) { 15922 } 15923 } 15924 15925 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15926 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15927 15928 final boolean mounted; 15929 if (Environment.isExternalStorageEmulated()) { 15930 mounted = true; 15931 } else { 15932 final String status = Environment.getExternalStorageState(); 15933 15934 mounted = status.equals(Environment.MEDIA_MOUNTED) 15935 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15936 } 15937 15938 if (!mounted) { 15939 return; 15940 } 15941 15942 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15943 int[] users; 15944 if (userId == UserHandle.USER_ALL) { 15945 users = sUserManager.getUserIds(); 15946 } else { 15947 users = new int[] { userId }; 15948 } 15949 final ClearStorageConnection conn = new ClearStorageConnection(); 15950 if (mContext.bindServiceAsUser( 15951 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15952 try { 15953 for (int curUser : users) { 15954 long timeout = SystemClock.uptimeMillis() + 5000; 15955 synchronized (conn) { 15956 long now = SystemClock.uptimeMillis(); 15957 while (conn.mContainerService == null && now < timeout) { 15958 try { 15959 conn.wait(timeout - now); 15960 } catch (InterruptedException e) { 15961 } 15962 } 15963 } 15964 if (conn.mContainerService == null) { 15965 return; 15966 } 15967 15968 final UserEnvironment userEnv = new UserEnvironment(curUser); 15969 clearDirectory(conn.mContainerService, 15970 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15971 if (allData) { 15972 clearDirectory(conn.mContainerService, 15973 userEnv.buildExternalStorageAppDataDirs(packageName)); 15974 clearDirectory(conn.mContainerService, 15975 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15976 } 15977 } 15978 } finally { 15979 mContext.unbindService(conn); 15980 } 15981 } 15982 } 15983 15984 @Override 15985 public void clearApplicationProfileData(String packageName) { 15986 enforceSystemOrRoot("Only the system can clear all profile data"); 15987 15988 final PackageParser.Package pkg; 15989 synchronized (mPackages) { 15990 pkg = mPackages.get(packageName); 15991 } 15992 15993 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15994 synchronized (mInstallLock) { 15995 clearAppProfilesLIF(pkg); 15996 } 15997 } 15998 } 15999 16000 @Override 16001 public void clearApplicationUserData(final String packageName, 16002 final IPackageDataObserver observer, final int userId) { 16003 mContext.enforceCallingOrSelfPermission( 16004 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16005 16006 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16007 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16008 16009 final DevicePolicyManagerInternal dpmi = LocalServices 16010 .getService(DevicePolicyManagerInternal.class); 16011 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16012 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16013 } 16014 // Queue up an async operation since the package deletion may take a little while. 16015 mHandler.post(new Runnable() { 16016 public void run() { 16017 mHandler.removeCallbacks(this); 16018 final boolean succeeded; 16019 try (PackageFreezer freezer = freezePackage(packageName, 16020 "clearApplicationUserData")) { 16021 synchronized (mInstallLock) { 16022 succeeded = clearApplicationUserDataLIF(packageName, userId); 16023 } 16024 clearExternalStorageDataSync(packageName, userId, true); 16025 } 16026 if (succeeded) { 16027 // invoke DeviceStorageMonitor's update method to clear any notifications 16028 DeviceStorageMonitorInternal dsm = LocalServices 16029 .getService(DeviceStorageMonitorInternal.class); 16030 if (dsm != null) { 16031 dsm.checkMemory(); 16032 } 16033 } 16034 if(observer != null) { 16035 try { 16036 observer.onRemoveCompleted(packageName, succeeded); 16037 } catch (RemoteException e) { 16038 Log.i(TAG, "Observer no longer exists."); 16039 } 16040 } //end if observer 16041 } //end run 16042 }); 16043 } 16044 16045 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16046 if (packageName == null) { 16047 Slog.w(TAG, "Attempt to delete null packageName."); 16048 return false; 16049 } 16050 16051 // Try finding details about the requested package 16052 PackageParser.Package pkg; 16053 synchronized (mPackages) { 16054 pkg = mPackages.get(packageName); 16055 if (pkg == null) { 16056 final PackageSetting ps = mSettings.mPackages.get(packageName); 16057 if (ps != null) { 16058 pkg = ps.pkg; 16059 } 16060 } 16061 16062 if (pkg == null) { 16063 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16064 return false; 16065 } 16066 16067 PackageSetting ps = (PackageSetting) pkg.mExtras; 16068 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16069 } 16070 16071 clearAppDataLIF(pkg, userId, 16072 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16073 16074 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16075 removeKeystoreDataIfNeeded(userId, appId); 16076 16077 final UserManager um = mContext.getSystemService(UserManager.class); 16078 final int flags; 16079 if (um.isUserUnlocked(userId)) { 16080 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16081 } else if (um.isUserRunning(userId)) { 16082 flags = StorageManager.FLAG_STORAGE_DE; 16083 } else { 16084 flags = 0; 16085 } 16086 prepareAppDataContentsLIF(pkg, userId, flags); 16087 16088 return true; 16089 } 16090 16091 /** 16092 * Reverts user permission state changes (permissions and flags) in 16093 * all packages for a given user. 16094 * 16095 * @param userId The device user for which to do a reset. 16096 */ 16097 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16098 final int packageCount = mPackages.size(); 16099 for (int i = 0; i < packageCount; i++) { 16100 PackageParser.Package pkg = mPackages.valueAt(i); 16101 PackageSetting ps = (PackageSetting) pkg.mExtras; 16102 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16103 } 16104 } 16105 16106 /** 16107 * Reverts user permission state changes (permissions and flags). 16108 * 16109 * @param ps The package for which to reset. 16110 * @param userId The device user for which to do a reset. 16111 */ 16112 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16113 final PackageSetting ps, final int userId) { 16114 if (ps.pkg == null) { 16115 return; 16116 } 16117 16118 // These are flags that can change base on user actions. 16119 final int userSettableMask = FLAG_PERMISSION_USER_SET 16120 | FLAG_PERMISSION_USER_FIXED 16121 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16122 | FLAG_PERMISSION_REVIEW_REQUIRED; 16123 16124 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16125 | FLAG_PERMISSION_POLICY_FIXED; 16126 16127 boolean writeInstallPermissions = false; 16128 boolean writeRuntimePermissions = false; 16129 16130 final int permissionCount = ps.pkg.requestedPermissions.size(); 16131 for (int i = 0; i < permissionCount; i++) { 16132 String permission = ps.pkg.requestedPermissions.get(i); 16133 16134 BasePermission bp = mSettings.mPermissions.get(permission); 16135 if (bp == null) { 16136 continue; 16137 } 16138 16139 // If shared user we just reset the state to which only this app contributed. 16140 if (ps.sharedUser != null) { 16141 boolean used = false; 16142 final int packageCount = ps.sharedUser.packages.size(); 16143 for (int j = 0; j < packageCount; j++) { 16144 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16145 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16146 && pkg.pkg.requestedPermissions.contains(permission)) { 16147 used = true; 16148 break; 16149 } 16150 } 16151 if (used) { 16152 continue; 16153 } 16154 } 16155 16156 PermissionsState permissionsState = ps.getPermissionsState(); 16157 16158 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16159 16160 // Always clear the user settable flags. 16161 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16162 bp.name) != null; 16163 // If permission review is enabled and this is a legacy app, mark the 16164 // permission as requiring a review as this is the initial state. 16165 int flags = 0; 16166 if (Build.PERMISSIONS_REVIEW_REQUIRED 16167 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16168 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16169 } 16170 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16171 if (hasInstallState) { 16172 writeInstallPermissions = true; 16173 } else { 16174 writeRuntimePermissions = true; 16175 } 16176 } 16177 16178 // Below is only runtime permission handling. 16179 if (!bp.isRuntime()) { 16180 continue; 16181 } 16182 16183 // Never clobber system or policy. 16184 if ((oldFlags & policyOrSystemFlags) != 0) { 16185 continue; 16186 } 16187 16188 // If this permission was granted by default, make sure it is. 16189 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16190 if (permissionsState.grantRuntimePermission(bp, userId) 16191 != PERMISSION_OPERATION_FAILURE) { 16192 writeRuntimePermissions = true; 16193 } 16194 // If permission review is enabled the permissions for a legacy apps 16195 // are represented as constantly granted runtime ones, so don't revoke. 16196 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16197 // Otherwise, reset the permission. 16198 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16199 switch (revokeResult) { 16200 case PERMISSION_OPERATION_SUCCESS: 16201 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16202 writeRuntimePermissions = true; 16203 final int appId = ps.appId; 16204 mHandler.post(new Runnable() { 16205 @Override 16206 public void run() { 16207 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16208 } 16209 }); 16210 } break; 16211 } 16212 } 16213 } 16214 16215 // Synchronously write as we are taking permissions away. 16216 if (writeRuntimePermissions) { 16217 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16218 } 16219 16220 // Synchronously write as we are taking permissions away. 16221 if (writeInstallPermissions) { 16222 mSettings.writeLPr(); 16223 } 16224 } 16225 16226 /** 16227 * Remove entries from the keystore daemon. Will only remove it if the 16228 * {@code appId} is valid. 16229 */ 16230 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16231 if (appId < 0) { 16232 return; 16233 } 16234 16235 final KeyStore keyStore = KeyStore.getInstance(); 16236 if (keyStore != null) { 16237 if (userId == UserHandle.USER_ALL) { 16238 for (final int individual : sUserManager.getUserIds()) { 16239 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16240 } 16241 } else { 16242 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16243 } 16244 } else { 16245 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16246 } 16247 } 16248 16249 @Override 16250 public void deleteApplicationCacheFiles(final String packageName, 16251 final IPackageDataObserver observer) { 16252 final int userId = UserHandle.getCallingUserId(); 16253 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16254 } 16255 16256 @Override 16257 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16258 final IPackageDataObserver observer) { 16259 mContext.enforceCallingOrSelfPermission( 16260 android.Manifest.permission.DELETE_CACHE_FILES, null); 16261 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16262 /* requireFullPermission= */ true, /* checkShell= */ false, 16263 "delete application cache files"); 16264 16265 final PackageParser.Package pkg; 16266 synchronized (mPackages) { 16267 pkg = mPackages.get(packageName); 16268 } 16269 16270 // Queue up an async operation since the package deletion may take a little while. 16271 mHandler.post(new Runnable() { 16272 public void run() { 16273 synchronized (mInstallLock) { 16274 final int flags = StorageManager.FLAG_STORAGE_DE 16275 | StorageManager.FLAG_STORAGE_CE; 16276 // We're only clearing cache files, so we don't care if the 16277 // app is unfrozen and still able to run 16278 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16279 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16280 } 16281 clearExternalStorageDataSync(packageName, userId, false); 16282 if (observer != null) { 16283 try { 16284 observer.onRemoveCompleted(packageName, true); 16285 } catch (RemoteException e) { 16286 Log.i(TAG, "Observer no longer exists."); 16287 } 16288 } 16289 } 16290 }); 16291 } 16292 16293 @Override 16294 public void getPackageSizeInfo(final String packageName, int userHandle, 16295 final IPackageStatsObserver observer) { 16296 mContext.enforceCallingOrSelfPermission( 16297 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16298 if (packageName == null) { 16299 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16300 } 16301 16302 PackageStats stats = new PackageStats(packageName, userHandle); 16303 16304 /* 16305 * Queue up an async operation since the package measurement may take a 16306 * little while. 16307 */ 16308 Message msg = mHandler.obtainMessage(INIT_COPY); 16309 msg.obj = new MeasureParams(stats, observer); 16310 mHandler.sendMessage(msg); 16311 } 16312 16313 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16314 final PackageSetting ps; 16315 synchronized (mPackages) { 16316 ps = mSettings.mPackages.get(packageName); 16317 if (ps == null) { 16318 Slog.w(TAG, "Failed to find settings for " + packageName); 16319 return false; 16320 } 16321 } 16322 try { 16323 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16324 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16325 ps.getCeDataInode(userId), ps.codePathString, stats); 16326 } catch (InstallerException e) { 16327 Slog.w(TAG, String.valueOf(e)); 16328 return false; 16329 } 16330 16331 // For now, ignore code size of packages on system partition 16332 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16333 stats.codeSize = 0; 16334 } 16335 16336 return true; 16337 } 16338 16339 private int getUidTargetSdkVersionLockedLPr(int uid) { 16340 Object obj = mSettings.getUserIdLPr(uid); 16341 if (obj instanceof SharedUserSetting) { 16342 final SharedUserSetting sus = (SharedUserSetting) obj; 16343 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16344 final Iterator<PackageSetting> it = sus.packages.iterator(); 16345 while (it.hasNext()) { 16346 final PackageSetting ps = it.next(); 16347 if (ps.pkg != null) { 16348 int v = ps.pkg.applicationInfo.targetSdkVersion; 16349 if (v < vers) vers = v; 16350 } 16351 } 16352 return vers; 16353 } else if (obj instanceof PackageSetting) { 16354 final PackageSetting ps = (PackageSetting) obj; 16355 if (ps.pkg != null) { 16356 return ps.pkg.applicationInfo.targetSdkVersion; 16357 } 16358 } 16359 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16360 } 16361 16362 @Override 16363 public void addPreferredActivity(IntentFilter filter, int match, 16364 ComponentName[] set, ComponentName activity, int userId) { 16365 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16366 "Adding preferred"); 16367 } 16368 16369 private void addPreferredActivityInternal(IntentFilter filter, int match, 16370 ComponentName[] set, ComponentName activity, boolean always, int userId, 16371 String opname) { 16372 // writer 16373 int callingUid = Binder.getCallingUid(); 16374 enforceCrossUserPermission(callingUid, userId, 16375 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16376 if (filter.countActions() == 0) { 16377 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16378 return; 16379 } 16380 synchronized (mPackages) { 16381 if (mContext.checkCallingOrSelfPermission( 16382 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16383 != PackageManager.PERMISSION_GRANTED) { 16384 if (getUidTargetSdkVersionLockedLPr(callingUid) 16385 < Build.VERSION_CODES.FROYO) { 16386 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16387 + callingUid); 16388 return; 16389 } 16390 mContext.enforceCallingOrSelfPermission( 16391 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16392 } 16393 16394 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16395 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16396 + userId + ":"); 16397 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16398 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16399 scheduleWritePackageRestrictionsLocked(userId); 16400 } 16401 } 16402 16403 @Override 16404 public void replacePreferredActivity(IntentFilter filter, int match, 16405 ComponentName[] set, ComponentName activity, int userId) { 16406 if (filter.countActions() != 1) { 16407 throw new IllegalArgumentException( 16408 "replacePreferredActivity expects filter to have only 1 action."); 16409 } 16410 if (filter.countDataAuthorities() != 0 16411 || filter.countDataPaths() != 0 16412 || filter.countDataSchemes() > 1 16413 || filter.countDataTypes() != 0) { 16414 throw new IllegalArgumentException( 16415 "replacePreferredActivity expects filter to have no data authorities, " + 16416 "paths, or types; and at most one scheme."); 16417 } 16418 16419 final int callingUid = Binder.getCallingUid(); 16420 enforceCrossUserPermission(callingUid, userId, 16421 true /* requireFullPermission */, false /* checkShell */, 16422 "replace preferred activity"); 16423 synchronized (mPackages) { 16424 if (mContext.checkCallingOrSelfPermission( 16425 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16426 != PackageManager.PERMISSION_GRANTED) { 16427 if (getUidTargetSdkVersionLockedLPr(callingUid) 16428 < Build.VERSION_CODES.FROYO) { 16429 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16430 + Binder.getCallingUid()); 16431 return; 16432 } 16433 mContext.enforceCallingOrSelfPermission( 16434 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16435 } 16436 16437 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16438 if (pir != null) { 16439 // Get all of the existing entries that exactly match this filter. 16440 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16441 if (existing != null && existing.size() == 1) { 16442 PreferredActivity cur = existing.get(0); 16443 if (DEBUG_PREFERRED) { 16444 Slog.i(TAG, "Checking replace of preferred:"); 16445 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16446 if (!cur.mPref.mAlways) { 16447 Slog.i(TAG, " -- CUR; not mAlways!"); 16448 } else { 16449 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16450 Slog.i(TAG, " -- CUR: mSet=" 16451 + Arrays.toString(cur.mPref.mSetComponents)); 16452 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16453 Slog.i(TAG, " -- NEW: mMatch=" 16454 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16455 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16456 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16457 } 16458 } 16459 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16460 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16461 && cur.mPref.sameSet(set)) { 16462 // Setting the preferred activity to what it happens to be already 16463 if (DEBUG_PREFERRED) { 16464 Slog.i(TAG, "Replacing with same preferred activity " 16465 + cur.mPref.mShortComponent + " for user " 16466 + userId + ":"); 16467 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16468 } 16469 return; 16470 } 16471 } 16472 16473 if (existing != null) { 16474 if (DEBUG_PREFERRED) { 16475 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16476 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16477 } 16478 for (int i = 0; i < existing.size(); i++) { 16479 PreferredActivity pa = existing.get(i); 16480 if (DEBUG_PREFERRED) { 16481 Slog.i(TAG, "Removing existing preferred activity " 16482 + pa.mPref.mComponent + ":"); 16483 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16484 } 16485 pir.removeFilter(pa); 16486 } 16487 } 16488 } 16489 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16490 "Replacing preferred"); 16491 } 16492 } 16493 16494 @Override 16495 public void clearPackagePreferredActivities(String packageName) { 16496 final int uid = Binder.getCallingUid(); 16497 // writer 16498 synchronized (mPackages) { 16499 PackageParser.Package pkg = mPackages.get(packageName); 16500 if (pkg == null || pkg.applicationInfo.uid != uid) { 16501 if (mContext.checkCallingOrSelfPermission( 16502 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16503 != PackageManager.PERMISSION_GRANTED) { 16504 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16505 < Build.VERSION_CODES.FROYO) { 16506 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16507 + Binder.getCallingUid()); 16508 return; 16509 } 16510 mContext.enforceCallingOrSelfPermission( 16511 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16512 } 16513 } 16514 16515 int user = UserHandle.getCallingUserId(); 16516 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16517 scheduleWritePackageRestrictionsLocked(user); 16518 } 16519 } 16520 } 16521 16522 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16523 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16524 ArrayList<PreferredActivity> removed = null; 16525 boolean changed = false; 16526 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16527 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16528 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16529 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16530 continue; 16531 } 16532 Iterator<PreferredActivity> it = pir.filterIterator(); 16533 while (it.hasNext()) { 16534 PreferredActivity pa = it.next(); 16535 // Mark entry for removal only if it matches the package name 16536 // and the entry is of type "always". 16537 if (packageName == null || 16538 (pa.mPref.mComponent.getPackageName().equals(packageName) 16539 && pa.mPref.mAlways)) { 16540 if (removed == null) { 16541 removed = new ArrayList<PreferredActivity>(); 16542 } 16543 removed.add(pa); 16544 } 16545 } 16546 if (removed != null) { 16547 for (int j=0; j<removed.size(); j++) { 16548 PreferredActivity pa = removed.get(j); 16549 pir.removeFilter(pa); 16550 } 16551 changed = true; 16552 } 16553 } 16554 return changed; 16555 } 16556 16557 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16558 private void clearIntentFilterVerificationsLPw(int userId) { 16559 final int packageCount = mPackages.size(); 16560 for (int i = 0; i < packageCount; i++) { 16561 PackageParser.Package pkg = mPackages.valueAt(i); 16562 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16563 } 16564 } 16565 16566 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16567 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16568 if (userId == UserHandle.USER_ALL) { 16569 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16570 sUserManager.getUserIds())) { 16571 for (int oneUserId : sUserManager.getUserIds()) { 16572 scheduleWritePackageRestrictionsLocked(oneUserId); 16573 } 16574 } 16575 } else { 16576 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16577 scheduleWritePackageRestrictionsLocked(userId); 16578 } 16579 } 16580 } 16581 16582 void clearDefaultBrowserIfNeeded(String packageName) { 16583 for (int oneUserId : sUserManager.getUserIds()) { 16584 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16585 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16586 if (packageName.equals(defaultBrowserPackageName)) { 16587 setDefaultBrowserPackageName(null, oneUserId); 16588 } 16589 } 16590 } 16591 16592 @Override 16593 public void resetApplicationPreferences(int userId) { 16594 mContext.enforceCallingOrSelfPermission( 16595 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16596 // writer 16597 synchronized (mPackages) { 16598 final long identity = Binder.clearCallingIdentity(); 16599 try { 16600 clearPackagePreferredActivitiesLPw(null, userId); 16601 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16602 // TODO: We have to reset the default SMS and Phone. This requires 16603 // significant refactoring to keep all default apps in the package 16604 // manager (cleaner but more work) or have the services provide 16605 // callbacks to the package manager to request a default app reset. 16606 applyFactoryDefaultBrowserLPw(userId); 16607 clearIntentFilterVerificationsLPw(userId); 16608 primeDomainVerificationsLPw(userId); 16609 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16610 scheduleWritePackageRestrictionsLocked(userId); 16611 } finally { 16612 Binder.restoreCallingIdentity(identity); 16613 } 16614 } 16615 } 16616 16617 @Override 16618 public int getPreferredActivities(List<IntentFilter> outFilters, 16619 List<ComponentName> outActivities, String packageName) { 16620 16621 int num = 0; 16622 final int userId = UserHandle.getCallingUserId(); 16623 // reader 16624 synchronized (mPackages) { 16625 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16626 if (pir != null) { 16627 final Iterator<PreferredActivity> it = pir.filterIterator(); 16628 while (it.hasNext()) { 16629 final PreferredActivity pa = it.next(); 16630 if (packageName == null 16631 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16632 && pa.mPref.mAlways)) { 16633 if (outFilters != null) { 16634 outFilters.add(new IntentFilter(pa)); 16635 } 16636 if (outActivities != null) { 16637 outActivities.add(pa.mPref.mComponent); 16638 } 16639 } 16640 } 16641 } 16642 } 16643 16644 return num; 16645 } 16646 16647 @Override 16648 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16649 int userId) { 16650 int callingUid = Binder.getCallingUid(); 16651 if (callingUid != Process.SYSTEM_UID) { 16652 throw new SecurityException( 16653 "addPersistentPreferredActivity can only be run by the system"); 16654 } 16655 if (filter.countActions() == 0) { 16656 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16657 return; 16658 } 16659 synchronized (mPackages) { 16660 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16661 ":"); 16662 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16663 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16664 new PersistentPreferredActivity(filter, activity)); 16665 scheduleWritePackageRestrictionsLocked(userId); 16666 } 16667 } 16668 16669 @Override 16670 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16671 int callingUid = Binder.getCallingUid(); 16672 if (callingUid != Process.SYSTEM_UID) { 16673 throw new SecurityException( 16674 "clearPackagePersistentPreferredActivities can only be run by the system"); 16675 } 16676 ArrayList<PersistentPreferredActivity> removed = null; 16677 boolean changed = false; 16678 synchronized (mPackages) { 16679 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16680 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16681 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16682 .valueAt(i); 16683 if (userId != thisUserId) { 16684 continue; 16685 } 16686 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16687 while (it.hasNext()) { 16688 PersistentPreferredActivity ppa = it.next(); 16689 // Mark entry for removal only if it matches the package name. 16690 if (ppa.mComponent.getPackageName().equals(packageName)) { 16691 if (removed == null) { 16692 removed = new ArrayList<PersistentPreferredActivity>(); 16693 } 16694 removed.add(ppa); 16695 } 16696 } 16697 if (removed != null) { 16698 for (int j=0; j<removed.size(); j++) { 16699 PersistentPreferredActivity ppa = removed.get(j); 16700 ppir.removeFilter(ppa); 16701 } 16702 changed = true; 16703 } 16704 } 16705 16706 if (changed) { 16707 scheduleWritePackageRestrictionsLocked(userId); 16708 } 16709 } 16710 } 16711 16712 /** 16713 * Common machinery for picking apart a restored XML blob and passing 16714 * it to a caller-supplied functor to be applied to the running system. 16715 */ 16716 private void restoreFromXml(XmlPullParser parser, int userId, 16717 String expectedStartTag, BlobXmlRestorer functor) 16718 throws IOException, XmlPullParserException { 16719 int type; 16720 while ((type = parser.next()) != XmlPullParser.START_TAG 16721 && type != XmlPullParser.END_DOCUMENT) { 16722 } 16723 if (type != XmlPullParser.START_TAG) { 16724 // oops didn't find a start tag?! 16725 if (DEBUG_BACKUP) { 16726 Slog.e(TAG, "Didn't find start tag during restore"); 16727 } 16728 return; 16729 } 16730Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16731 // this is supposed to be TAG_PREFERRED_BACKUP 16732 if (!expectedStartTag.equals(parser.getName())) { 16733 if (DEBUG_BACKUP) { 16734 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16735 } 16736 return; 16737 } 16738 16739 // skip interfering stuff, then we're aligned with the backing implementation 16740 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16741Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16742 functor.apply(parser, userId); 16743 } 16744 16745 private interface BlobXmlRestorer { 16746 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16747 } 16748 16749 /** 16750 * Non-Binder method, support for the backup/restore mechanism: write the 16751 * full set of preferred activities in its canonical XML format. Returns the 16752 * XML output as a byte array, or null if there is none. 16753 */ 16754 @Override 16755 public byte[] getPreferredActivityBackup(int userId) { 16756 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16757 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16758 } 16759 16760 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16761 try { 16762 final XmlSerializer serializer = new FastXmlSerializer(); 16763 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16764 serializer.startDocument(null, true); 16765 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16766 16767 synchronized (mPackages) { 16768 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16769 } 16770 16771 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16772 serializer.endDocument(); 16773 serializer.flush(); 16774 } catch (Exception e) { 16775 if (DEBUG_BACKUP) { 16776 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16777 } 16778 return null; 16779 } 16780 16781 return dataStream.toByteArray(); 16782 } 16783 16784 @Override 16785 public void restorePreferredActivities(byte[] backup, int userId) { 16786 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16787 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16788 } 16789 16790 try { 16791 final XmlPullParser parser = Xml.newPullParser(); 16792 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16793 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16794 new BlobXmlRestorer() { 16795 @Override 16796 public void apply(XmlPullParser parser, int userId) 16797 throws XmlPullParserException, IOException { 16798 synchronized (mPackages) { 16799 mSettings.readPreferredActivitiesLPw(parser, userId); 16800 } 16801 } 16802 } ); 16803 } catch (Exception e) { 16804 if (DEBUG_BACKUP) { 16805 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16806 } 16807 } 16808 } 16809 16810 /** 16811 * Non-Binder method, support for the backup/restore mechanism: write the 16812 * default browser (etc) settings in its canonical XML format. Returns the default 16813 * browser XML representation as a byte array, or null if there is none. 16814 */ 16815 @Override 16816 public byte[] getDefaultAppsBackup(int userId) { 16817 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16818 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16819 } 16820 16821 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16822 try { 16823 final XmlSerializer serializer = new FastXmlSerializer(); 16824 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16825 serializer.startDocument(null, true); 16826 serializer.startTag(null, TAG_DEFAULT_APPS); 16827 16828 synchronized (mPackages) { 16829 mSettings.writeDefaultAppsLPr(serializer, userId); 16830 } 16831 16832 serializer.endTag(null, TAG_DEFAULT_APPS); 16833 serializer.endDocument(); 16834 serializer.flush(); 16835 } catch (Exception e) { 16836 if (DEBUG_BACKUP) { 16837 Slog.e(TAG, "Unable to write default apps for backup", e); 16838 } 16839 return null; 16840 } 16841 16842 return dataStream.toByteArray(); 16843 } 16844 16845 @Override 16846 public void restoreDefaultApps(byte[] backup, int userId) { 16847 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16848 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16849 } 16850 16851 try { 16852 final XmlPullParser parser = Xml.newPullParser(); 16853 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16854 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16855 new BlobXmlRestorer() { 16856 @Override 16857 public void apply(XmlPullParser parser, int userId) 16858 throws XmlPullParserException, IOException { 16859 synchronized (mPackages) { 16860 mSettings.readDefaultAppsLPw(parser, userId); 16861 } 16862 } 16863 } ); 16864 } catch (Exception e) { 16865 if (DEBUG_BACKUP) { 16866 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16867 } 16868 } 16869 } 16870 16871 @Override 16872 public byte[] getIntentFilterVerificationBackup(int userId) { 16873 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16874 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16875 } 16876 16877 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16878 try { 16879 final XmlSerializer serializer = new FastXmlSerializer(); 16880 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16881 serializer.startDocument(null, true); 16882 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16883 16884 synchronized (mPackages) { 16885 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16886 } 16887 16888 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16889 serializer.endDocument(); 16890 serializer.flush(); 16891 } catch (Exception e) { 16892 if (DEBUG_BACKUP) { 16893 Slog.e(TAG, "Unable to write default apps for backup", e); 16894 } 16895 return null; 16896 } 16897 16898 return dataStream.toByteArray(); 16899 } 16900 16901 @Override 16902 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16904 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16905 } 16906 16907 try { 16908 final XmlPullParser parser = Xml.newPullParser(); 16909 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16910 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16911 new BlobXmlRestorer() { 16912 @Override 16913 public void apply(XmlPullParser parser, int userId) 16914 throws XmlPullParserException, IOException { 16915 synchronized (mPackages) { 16916 mSettings.readAllDomainVerificationsLPr(parser, userId); 16917 mSettings.writeLPr(); 16918 } 16919 } 16920 } ); 16921 } catch (Exception e) { 16922 if (DEBUG_BACKUP) { 16923 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16924 } 16925 } 16926 } 16927 16928 @Override 16929 public byte[] getPermissionGrantBackup(int userId) { 16930 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16931 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16932 } 16933 16934 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16935 try { 16936 final XmlSerializer serializer = new FastXmlSerializer(); 16937 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16938 serializer.startDocument(null, true); 16939 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16940 16941 synchronized (mPackages) { 16942 serializeRuntimePermissionGrantsLPr(serializer, userId); 16943 } 16944 16945 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16946 serializer.endDocument(); 16947 serializer.flush(); 16948 } catch (Exception e) { 16949 if (DEBUG_BACKUP) { 16950 Slog.e(TAG, "Unable to write default apps for backup", e); 16951 } 16952 return null; 16953 } 16954 16955 return dataStream.toByteArray(); 16956 } 16957 16958 @Override 16959 public void restorePermissionGrants(byte[] backup, int userId) { 16960 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16961 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16962 } 16963 16964 try { 16965 final XmlPullParser parser = Xml.newPullParser(); 16966 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16967 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16968 new BlobXmlRestorer() { 16969 @Override 16970 public void apply(XmlPullParser parser, int userId) 16971 throws XmlPullParserException, IOException { 16972 synchronized (mPackages) { 16973 processRestoredPermissionGrantsLPr(parser, userId); 16974 } 16975 } 16976 } ); 16977 } catch (Exception e) { 16978 if (DEBUG_BACKUP) { 16979 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16980 } 16981 } 16982 } 16983 16984 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16985 throws IOException { 16986 serializer.startTag(null, TAG_ALL_GRANTS); 16987 16988 final int N = mSettings.mPackages.size(); 16989 for (int i = 0; i < N; i++) { 16990 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16991 boolean pkgGrantsKnown = false; 16992 16993 PermissionsState packagePerms = ps.getPermissionsState(); 16994 16995 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16996 final int grantFlags = state.getFlags(); 16997 // only look at grants that are not system/policy fixed 16998 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16999 final boolean isGranted = state.isGranted(); 17000 // And only back up the user-twiddled state bits 17001 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17002 final String packageName = mSettings.mPackages.keyAt(i); 17003 if (!pkgGrantsKnown) { 17004 serializer.startTag(null, TAG_GRANT); 17005 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17006 pkgGrantsKnown = true; 17007 } 17008 17009 final boolean userSet = 17010 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17011 final boolean userFixed = 17012 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17013 final boolean revoke = 17014 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17015 17016 serializer.startTag(null, TAG_PERMISSION); 17017 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17018 if (isGranted) { 17019 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17020 } 17021 if (userSet) { 17022 serializer.attribute(null, ATTR_USER_SET, "true"); 17023 } 17024 if (userFixed) { 17025 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17026 } 17027 if (revoke) { 17028 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17029 } 17030 serializer.endTag(null, TAG_PERMISSION); 17031 } 17032 } 17033 } 17034 17035 if (pkgGrantsKnown) { 17036 serializer.endTag(null, TAG_GRANT); 17037 } 17038 } 17039 17040 serializer.endTag(null, TAG_ALL_GRANTS); 17041 } 17042 17043 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17044 throws XmlPullParserException, IOException { 17045 String pkgName = null; 17046 int outerDepth = parser.getDepth(); 17047 int type; 17048 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17049 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17050 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17051 continue; 17052 } 17053 17054 final String tagName = parser.getName(); 17055 if (tagName.equals(TAG_GRANT)) { 17056 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17057 if (DEBUG_BACKUP) { 17058 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17059 } 17060 } else if (tagName.equals(TAG_PERMISSION)) { 17061 17062 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17063 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17064 17065 int newFlagSet = 0; 17066 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17067 newFlagSet |= FLAG_PERMISSION_USER_SET; 17068 } 17069 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17070 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17071 } 17072 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17073 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17074 } 17075 if (DEBUG_BACKUP) { 17076 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17077 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17078 } 17079 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17080 if (ps != null) { 17081 // Already installed so we apply the grant immediately 17082 if (DEBUG_BACKUP) { 17083 Slog.v(TAG, " + already installed; applying"); 17084 } 17085 PermissionsState perms = ps.getPermissionsState(); 17086 BasePermission bp = mSettings.mPermissions.get(permName); 17087 if (bp != null) { 17088 if (isGranted) { 17089 perms.grantRuntimePermission(bp, userId); 17090 } 17091 if (newFlagSet != 0) { 17092 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17093 } 17094 } 17095 } else { 17096 // Need to wait for post-restore install to apply the grant 17097 if (DEBUG_BACKUP) { 17098 Slog.v(TAG, " - not yet installed; saving for later"); 17099 } 17100 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17101 isGranted, newFlagSet, userId); 17102 } 17103 } else { 17104 PackageManagerService.reportSettingsProblem(Log.WARN, 17105 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17106 XmlUtils.skipCurrentTag(parser); 17107 } 17108 } 17109 17110 scheduleWriteSettingsLocked(); 17111 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17112 } 17113 17114 @Override 17115 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17116 int sourceUserId, int targetUserId, int flags) { 17117 mContext.enforceCallingOrSelfPermission( 17118 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17119 int callingUid = Binder.getCallingUid(); 17120 enforceOwnerRights(ownerPackage, callingUid); 17121 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17122 if (intentFilter.countActions() == 0) { 17123 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17124 return; 17125 } 17126 synchronized (mPackages) { 17127 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17128 ownerPackage, targetUserId, flags); 17129 CrossProfileIntentResolver resolver = 17130 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17131 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17132 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17133 if (existing != null) { 17134 int size = existing.size(); 17135 for (int i = 0; i < size; i++) { 17136 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17137 return; 17138 } 17139 } 17140 } 17141 resolver.addFilter(newFilter); 17142 scheduleWritePackageRestrictionsLocked(sourceUserId); 17143 } 17144 } 17145 17146 @Override 17147 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17148 mContext.enforceCallingOrSelfPermission( 17149 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17150 int callingUid = Binder.getCallingUid(); 17151 enforceOwnerRights(ownerPackage, callingUid); 17152 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17153 synchronized (mPackages) { 17154 CrossProfileIntentResolver resolver = 17155 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17156 ArraySet<CrossProfileIntentFilter> set = 17157 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17158 for (CrossProfileIntentFilter filter : set) { 17159 if (filter.getOwnerPackage().equals(ownerPackage)) { 17160 resolver.removeFilter(filter); 17161 } 17162 } 17163 scheduleWritePackageRestrictionsLocked(sourceUserId); 17164 } 17165 } 17166 17167 // Enforcing that callingUid is owning pkg on userId 17168 private void enforceOwnerRights(String pkg, int callingUid) { 17169 // The system owns everything. 17170 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17171 return; 17172 } 17173 int callingUserId = UserHandle.getUserId(callingUid); 17174 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17175 if (pi == null) { 17176 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17177 + callingUserId); 17178 } 17179 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17180 throw new SecurityException("Calling uid " + callingUid 17181 + " does not own package " + pkg); 17182 } 17183 } 17184 17185 @Override 17186 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17187 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17188 } 17189 17190 private Intent getHomeIntent() { 17191 Intent intent = new Intent(Intent.ACTION_MAIN); 17192 intent.addCategory(Intent.CATEGORY_HOME); 17193 return intent; 17194 } 17195 17196 private IntentFilter getHomeFilter() { 17197 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17198 filter.addCategory(Intent.CATEGORY_HOME); 17199 filter.addCategory(Intent.CATEGORY_DEFAULT); 17200 return filter; 17201 } 17202 17203 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17204 int userId) { 17205 Intent intent = getHomeIntent(); 17206 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17207 PackageManager.GET_META_DATA, userId); 17208 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17209 true, false, false, userId); 17210 17211 allHomeCandidates.clear(); 17212 if (list != null) { 17213 for (ResolveInfo ri : list) { 17214 allHomeCandidates.add(ri); 17215 } 17216 } 17217 return (preferred == null || preferred.activityInfo == null) 17218 ? null 17219 : new ComponentName(preferred.activityInfo.packageName, 17220 preferred.activityInfo.name); 17221 } 17222 17223 @Override 17224 public void setHomeActivity(ComponentName comp, int userId) { 17225 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17226 getHomeActivitiesAsUser(homeActivities, userId); 17227 17228 boolean found = false; 17229 17230 final int size = homeActivities.size(); 17231 final ComponentName[] set = new ComponentName[size]; 17232 for (int i = 0; i < size; i++) { 17233 final ResolveInfo candidate = homeActivities.get(i); 17234 final ActivityInfo info = candidate.activityInfo; 17235 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17236 set[i] = activityName; 17237 if (!found && activityName.equals(comp)) { 17238 found = true; 17239 } 17240 } 17241 if (!found) { 17242 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17243 + userId); 17244 } 17245 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17246 set, comp, userId); 17247 } 17248 17249 private @Nullable String getSetupWizardPackageName() { 17250 final Intent intent = new Intent(Intent.ACTION_MAIN); 17251 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17252 17253 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17254 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17255 | MATCH_DISABLED_COMPONENTS, 17256 UserHandle.myUserId()); 17257 if (matches.size() == 1) { 17258 return matches.get(0).getComponentInfo().packageName; 17259 } else { 17260 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17261 + ": matches=" + matches); 17262 return null; 17263 } 17264 } 17265 17266 @Override 17267 public void setApplicationEnabledSetting(String appPackageName, 17268 int newState, int flags, int userId, String callingPackage) { 17269 if (!sUserManager.exists(userId)) return; 17270 if (callingPackage == null) { 17271 callingPackage = Integer.toString(Binder.getCallingUid()); 17272 } 17273 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17274 } 17275 17276 @Override 17277 public void setComponentEnabledSetting(ComponentName componentName, 17278 int newState, int flags, int userId) { 17279 if (!sUserManager.exists(userId)) return; 17280 setEnabledSetting(componentName.getPackageName(), 17281 componentName.getClassName(), newState, flags, userId, null); 17282 } 17283 17284 private void setEnabledSetting(final String packageName, String className, int newState, 17285 final int flags, int userId, String callingPackage) { 17286 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17287 || newState == COMPONENT_ENABLED_STATE_ENABLED 17288 || newState == COMPONENT_ENABLED_STATE_DISABLED 17289 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17290 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17291 throw new IllegalArgumentException("Invalid new component state: " 17292 + newState); 17293 } 17294 PackageSetting pkgSetting; 17295 final int uid = Binder.getCallingUid(); 17296 final int permission; 17297 if (uid == Process.SYSTEM_UID) { 17298 permission = PackageManager.PERMISSION_GRANTED; 17299 } else { 17300 permission = mContext.checkCallingOrSelfPermission( 17301 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17302 } 17303 enforceCrossUserPermission(uid, userId, 17304 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17305 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17306 boolean sendNow = false; 17307 boolean isApp = (className == null); 17308 String componentName = isApp ? packageName : className; 17309 int packageUid = -1; 17310 ArrayList<String> components; 17311 17312 // writer 17313 synchronized (mPackages) { 17314 pkgSetting = mSettings.mPackages.get(packageName); 17315 if (pkgSetting == null) { 17316 if (className == null) { 17317 throw new IllegalArgumentException("Unknown package: " + packageName); 17318 } 17319 throw new IllegalArgumentException( 17320 "Unknown component: " + packageName + "/" + className); 17321 } 17322 // Allow root and verify that userId is not being specified by a different user 17323 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17324 throw new SecurityException( 17325 "Permission Denial: attempt to change component state from pid=" 17326 + Binder.getCallingPid() 17327 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17328 } 17329 if (className == null) { 17330 // We're dealing with an application/package level state change 17331 if (pkgSetting.getEnabled(userId) == newState) { 17332 // Nothing to do 17333 return; 17334 } 17335 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17336 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17337 // Don't care about who enables an app. 17338 callingPackage = null; 17339 } 17340 pkgSetting.setEnabled(newState, userId, callingPackage); 17341 // pkgSetting.pkg.mSetEnabled = newState; 17342 } else { 17343 // We're dealing with a component level state change 17344 // First, verify that this is a valid class name. 17345 PackageParser.Package pkg = pkgSetting.pkg; 17346 if (pkg == null || !pkg.hasComponentClassName(className)) { 17347 if (pkg != null && 17348 pkg.applicationInfo.targetSdkVersion >= 17349 Build.VERSION_CODES.JELLY_BEAN) { 17350 throw new IllegalArgumentException("Component class " + className 17351 + " does not exist in " + packageName); 17352 } else { 17353 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17354 + className + " does not exist in " + packageName); 17355 } 17356 } 17357 switch (newState) { 17358 case COMPONENT_ENABLED_STATE_ENABLED: 17359 if (!pkgSetting.enableComponentLPw(className, userId)) { 17360 return; 17361 } 17362 break; 17363 case COMPONENT_ENABLED_STATE_DISABLED: 17364 if (!pkgSetting.disableComponentLPw(className, userId)) { 17365 return; 17366 } 17367 break; 17368 case COMPONENT_ENABLED_STATE_DEFAULT: 17369 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17370 return; 17371 } 17372 break; 17373 default: 17374 Slog.e(TAG, "Invalid new component state: " + newState); 17375 return; 17376 } 17377 } 17378 scheduleWritePackageRestrictionsLocked(userId); 17379 components = mPendingBroadcasts.get(userId, packageName); 17380 final boolean newPackage = components == null; 17381 if (newPackage) { 17382 components = new ArrayList<String>(); 17383 } 17384 if (!components.contains(componentName)) { 17385 components.add(componentName); 17386 } 17387 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17388 sendNow = true; 17389 // Purge entry from pending broadcast list if another one exists already 17390 // since we are sending one right away. 17391 mPendingBroadcasts.remove(userId, packageName); 17392 } else { 17393 if (newPackage) { 17394 mPendingBroadcasts.put(userId, packageName, components); 17395 } 17396 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17397 // Schedule a message 17398 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17399 } 17400 } 17401 } 17402 17403 long callingId = Binder.clearCallingIdentity(); 17404 try { 17405 if (sendNow) { 17406 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17407 sendPackageChangedBroadcast(packageName, 17408 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17409 } 17410 } finally { 17411 Binder.restoreCallingIdentity(callingId); 17412 } 17413 } 17414 17415 @Override 17416 public void flushPackageRestrictionsAsUser(int userId) { 17417 if (!sUserManager.exists(userId)) { 17418 return; 17419 } 17420 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17421 false /* checkShell */, "flushPackageRestrictions"); 17422 synchronized (mPackages) { 17423 mSettings.writePackageRestrictionsLPr(userId); 17424 mDirtyUsers.remove(userId); 17425 if (mDirtyUsers.isEmpty()) { 17426 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17427 } 17428 } 17429 } 17430 17431 private void sendPackageChangedBroadcast(String packageName, 17432 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17433 if (DEBUG_INSTALL) 17434 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17435 + componentNames); 17436 Bundle extras = new Bundle(4); 17437 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17438 String nameList[] = new String[componentNames.size()]; 17439 componentNames.toArray(nameList); 17440 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17441 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17442 extras.putInt(Intent.EXTRA_UID, packageUid); 17443 // If this is not reporting a change of the overall package, then only send it 17444 // to registered receivers. We don't want to launch a swath of apps for every 17445 // little component state change. 17446 final int flags = !componentNames.contains(packageName) 17447 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17448 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17449 new int[] {UserHandle.getUserId(packageUid)}); 17450 } 17451 17452 @Override 17453 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17454 if (!sUserManager.exists(userId)) return; 17455 final int uid = Binder.getCallingUid(); 17456 final int permission = mContext.checkCallingOrSelfPermission( 17457 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17458 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17459 enforceCrossUserPermission(uid, userId, 17460 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17461 // writer 17462 synchronized (mPackages) { 17463 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17464 allowedByPermission, uid, userId)) { 17465 scheduleWritePackageRestrictionsLocked(userId); 17466 } 17467 } 17468 } 17469 17470 @Override 17471 public String getInstallerPackageName(String packageName) { 17472 // reader 17473 synchronized (mPackages) { 17474 return mSettings.getInstallerPackageNameLPr(packageName); 17475 } 17476 } 17477 17478 @Override 17479 public int getApplicationEnabledSetting(String packageName, int userId) { 17480 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17481 int uid = Binder.getCallingUid(); 17482 enforceCrossUserPermission(uid, userId, 17483 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17484 // reader 17485 synchronized (mPackages) { 17486 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17487 } 17488 } 17489 17490 @Override 17491 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17492 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17493 int uid = Binder.getCallingUid(); 17494 enforceCrossUserPermission(uid, userId, 17495 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17496 // reader 17497 synchronized (mPackages) { 17498 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17499 } 17500 } 17501 17502 @Override 17503 public void enterSafeMode() { 17504 enforceSystemOrRoot("Only the system can request entering safe mode"); 17505 17506 if (!mSystemReady) { 17507 mSafeMode = true; 17508 } 17509 } 17510 17511 @Override 17512 public void systemReady() { 17513 mSystemReady = true; 17514 17515 // Read the compatibilty setting when the system is ready. 17516 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17517 mContext.getContentResolver(), 17518 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17519 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17520 if (DEBUG_SETTINGS) { 17521 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17522 } 17523 17524 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17525 17526 synchronized (mPackages) { 17527 // Verify that all of the preferred activity components actually 17528 // exist. It is possible for applications to be updated and at 17529 // that point remove a previously declared activity component that 17530 // had been set as a preferred activity. We try to clean this up 17531 // the next time we encounter that preferred activity, but it is 17532 // possible for the user flow to never be able to return to that 17533 // situation so here we do a sanity check to make sure we haven't 17534 // left any junk around. 17535 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17536 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17537 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17538 removed.clear(); 17539 for (PreferredActivity pa : pir.filterSet()) { 17540 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17541 removed.add(pa); 17542 } 17543 } 17544 if (removed.size() > 0) { 17545 for (int r=0; r<removed.size(); r++) { 17546 PreferredActivity pa = removed.get(r); 17547 Slog.w(TAG, "Removing dangling preferred activity: " 17548 + pa.mPref.mComponent); 17549 pir.removeFilter(pa); 17550 } 17551 mSettings.writePackageRestrictionsLPr( 17552 mSettings.mPreferredActivities.keyAt(i)); 17553 } 17554 } 17555 17556 for (int userId : UserManagerService.getInstance().getUserIds()) { 17557 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17558 grantPermissionsUserIds = ArrayUtils.appendInt( 17559 grantPermissionsUserIds, userId); 17560 } 17561 } 17562 } 17563 sUserManager.systemReady(); 17564 17565 // If we upgraded grant all default permissions before kicking off. 17566 for (int userId : grantPermissionsUserIds) { 17567 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17568 } 17569 17570 // Kick off any messages waiting for system ready 17571 if (mPostSystemReadyMessages != null) { 17572 for (Message msg : mPostSystemReadyMessages) { 17573 msg.sendToTarget(); 17574 } 17575 mPostSystemReadyMessages = null; 17576 } 17577 17578 // Watch for external volumes that come and go over time 17579 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17580 storage.registerListener(mStorageListener); 17581 17582 mInstallerService.systemReady(); 17583 mPackageDexOptimizer.systemReady(); 17584 17585 MountServiceInternal mountServiceInternal = LocalServices.getService( 17586 MountServiceInternal.class); 17587 mountServiceInternal.addExternalStoragePolicy( 17588 new MountServiceInternal.ExternalStorageMountPolicy() { 17589 @Override 17590 public int getMountMode(int uid, String packageName) { 17591 if (Process.isIsolated(uid)) { 17592 return Zygote.MOUNT_EXTERNAL_NONE; 17593 } 17594 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17595 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17596 } 17597 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17598 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17599 } 17600 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17601 return Zygote.MOUNT_EXTERNAL_READ; 17602 } 17603 return Zygote.MOUNT_EXTERNAL_WRITE; 17604 } 17605 17606 @Override 17607 public boolean hasExternalStorage(int uid, String packageName) { 17608 return true; 17609 } 17610 }); 17611 17612 // Now that we're mostly running, clean up stale users and apps 17613 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17614 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17615 } 17616 17617 @Override 17618 public boolean isSafeMode() { 17619 return mSafeMode; 17620 } 17621 17622 @Override 17623 public boolean hasSystemUidErrors() { 17624 return mHasSystemUidErrors; 17625 } 17626 17627 static String arrayToString(int[] array) { 17628 StringBuffer buf = new StringBuffer(128); 17629 buf.append('['); 17630 if (array != null) { 17631 for (int i=0; i<array.length; i++) { 17632 if (i > 0) buf.append(", "); 17633 buf.append(array[i]); 17634 } 17635 } 17636 buf.append(']'); 17637 return buf.toString(); 17638 } 17639 17640 static class DumpState { 17641 public static final int DUMP_LIBS = 1 << 0; 17642 public static final int DUMP_FEATURES = 1 << 1; 17643 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17644 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17645 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17646 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17647 public static final int DUMP_PERMISSIONS = 1 << 6; 17648 public static final int DUMP_PACKAGES = 1 << 7; 17649 public static final int DUMP_SHARED_USERS = 1 << 8; 17650 public static final int DUMP_MESSAGES = 1 << 9; 17651 public static final int DUMP_PROVIDERS = 1 << 10; 17652 public static final int DUMP_VERIFIERS = 1 << 11; 17653 public static final int DUMP_PREFERRED = 1 << 12; 17654 public static final int DUMP_PREFERRED_XML = 1 << 13; 17655 public static final int DUMP_KEYSETS = 1 << 14; 17656 public static final int DUMP_VERSION = 1 << 15; 17657 public static final int DUMP_INSTALLS = 1 << 16; 17658 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17659 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17660 public static final int DUMP_FROZEN = 1 << 19; 17661 17662 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17663 17664 private int mTypes; 17665 17666 private int mOptions; 17667 17668 private boolean mTitlePrinted; 17669 17670 private SharedUserSetting mSharedUser; 17671 17672 public boolean isDumping(int type) { 17673 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17674 return true; 17675 } 17676 17677 return (mTypes & type) != 0; 17678 } 17679 17680 public void setDump(int type) { 17681 mTypes |= type; 17682 } 17683 17684 public boolean isOptionEnabled(int option) { 17685 return (mOptions & option) != 0; 17686 } 17687 17688 public void setOptionEnabled(int option) { 17689 mOptions |= option; 17690 } 17691 17692 public boolean onTitlePrinted() { 17693 final boolean printed = mTitlePrinted; 17694 mTitlePrinted = true; 17695 return printed; 17696 } 17697 17698 public boolean getTitlePrinted() { 17699 return mTitlePrinted; 17700 } 17701 17702 public void setTitlePrinted(boolean enabled) { 17703 mTitlePrinted = enabled; 17704 } 17705 17706 public SharedUserSetting getSharedUser() { 17707 return mSharedUser; 17708 } 17709 17710 public void setSharedUser(SharedUserSetting user) { 17711 mSharedUser = user; 17712 } 17713 } 17714 17715 @Override 17716 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17717 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17718 (new PackageManagerShellCommand(this)).exec( 17719 this, in, out, err, args, resultReceiver); 17720 } 17721 17722 @Override 17723 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17724 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17725 != PackageManager.PERMISSION_GRANTED) { 17726 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17727 + Binder.getCallingPid() 17728 + ", uid=" + Binder.getCallingUid() 17729 + " without permission " 17730 + android.Manifest.permission.DUMP); 17731 return; 17732 } 17733 17734 DumpState dumpState = new DumpState(); 17735 boolean fullPreferred = false; 17736 boolean checkin = false; 17737 17738 String packageName = null; 17739 ArraySet<String> permissionNames = null; 17740 17741 int opti = 0; 17742 while (opti < args.length) { 17743 String opt = args[opti]; 17744 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17745 break; 17746 } 17747 opti++; 17748 17749 if ("-a".equals(opt)) { 17750 // Right now we only know how to print all. 17751 } else if ("-h".equals(opt)) { 17752 pw.println("Package manager dump options:"); 17753 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17754 pw.println(" --checkin: dump for a checkin"); 17755 pw.println(" -f: print details of intent filters"); 17756 pw.println(" -h: print this help"); 17757 pw.println(" cmd may be one of:"); 17758 pw.println(" l[ibraries]: list known shared libraries"); 17759 pw.println(" f[eatures]: list device features"); 17760 pw.println(" k[eysets]: print known keysets"); 17761 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17762 pw.println(" perm[issions]: dump permissions"); 17763 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17764 pw.println(" pref[erred]: print preferred package settings"); 17765 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17766 pw.println(" prov[iders]: dump content providers"); 17767 pw.println(" p[ackages]: dump installed packages"); 17768 pw.println(" s[hared-users]: dump shared user IDs"); 17769 pw.println(" m[essages]: print collected runtime messages"); 17770 pw.println(" v[erifiers]: print package verifier info"); 17771 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17772 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17773 pw.println(" version: print database version info"); 17774 pw.println(" write: write current settings now"); 17775 pw.println(" installs: details about install sessions"); 17776 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17777 pw.println(" <package.name>: info about given package"); 17778 return; 17779 } else if ("--checkin".equals(opt)) { 17780 checkin = true; 17781 } else if ("-f".equals(opt)) { 17782 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17783 } else { 17784 pw.println("Unknown argument: " + opt + "; use -h for help"); 17785 } 17786 } 17787 17788 // Is the caller requesting to dump a particular piece of data? 17789 if (opti < args.length) { 17790 String cmd = args[opti]; 17791 opti++; 17792 // Is this a package name? 17793 if ("android".equals(cmd) || cmd.contains(".")) { 17794 packageName = cmd; 17795 // When dumping a single package, we always dump all of its 17796 // filter information since the amount of data will be reasonable. 17797 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17798 } else if ("check-permission".equals(cmd)) { 17799 if (opti >= args.length) { 17800 pw.println("Error: check-permission missing permission argument"); 17801 return; 17802 } 17803 String perm = args[opti]; 17804 opti++; 17805 if (opti >= args.length) { 17806 pw.println("Error: check-permission missing package argument"); 17807 return; 17808 } 17809 String pkg = args[opti]; 17810 opti++; 17811 int user = UserHandle.getUserId(Binder.getCallingUid()); 17812 if (opti < args.length) { 17813 try { 17814 user = Integer.parseInt(args[opti]); 17815 } catch (NumberFormatException e) { 17816 pw.println("Error: check-permission user argument is not a number: " 17817 + args[opti]); 17818 return; 17819 } 17820 } 17821 pw.println(checkPermission(perm, pkg, user)); 17822 return; 17823 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17824 dumpState.setDump(DumpState.DUMP_LIBS); 17825 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17826 dumpState.setDump(DumpState.DUMP_FEATURES); 17827 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17828 if (opti >= args.length) { 17829 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17830 | DumpState.DUMP_SERVICE_RESOLVERS 17831 | DumpState.DUMP_RECEIVER_RESOLVERS 17832 | DumpState.DUMP_CONTENT_RESOLVERS); 17833 } else { 17834 while (opti < args.length) { 17835 String name = args[opti]; 17836 if ("a".equals(name) || "activity".equals(name)) { 17837 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17838 } else if ("s".equals(name) || "service".equals(name)) { 17839 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17840 } else if ("r".equals(name) || "receiver".equals(name)) { 17841 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17842 } else if ("c".equals(name) || "content".equals(name)) { 17843 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17844 } else { 17845 pw.println("Error: unknown resolver table type: " + name); 17846 return; 17847 } 17848 opti++; 17849 } 17850 } 17851 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17852 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17853 } else if ("permission".equals(cmd)) { 17854 if (opti >= args.length) { 17855 pw.println("Error: permission requires permission name"); 17856 return; 17857 } 17858 permissionNames = new ArraySet<>(); 17859 while (opti < args.length) { 17860 permissionNames.add(args[opti]); 17861 opti++; 17862 } 17863 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17864 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17865 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17866 dumpState.setDump(DumpState.DUMP_PREFERRED); 17867 } else if ("preferred-xml".equals(cmd)) { 17868 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17869 if (opti < args.length && "--full".equals(args[opti])) { 17870 fullPreferred = true; 17871 opti++; 17872 } 17873 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17874 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17875 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17876 dumpState.setDump(DumpState.DUMP_PACKAGES); 17877 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17878 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17879 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17880 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17881 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17882 dumpState.setDump(DumpState.DUMP_MESSAGES); 17883 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17884 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17885 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17886 || "intent-filter-verifiers".equals(cmd)) { 17887 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17888 } else if ("version".equals(cmd)) { 17889 dumpState.setDump(DumpState.DUMP_VERSION); 17890 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17891 dumpState.setDump(DumpState.DUMP_KEYSETS); 17892 } else if ("installs".equals(cmd)) { 17893 dumpState.setDump(DumpState.DUMP_INSTALLS); 17894 } else if ("frozen".equals(cmd)) { 17895 dumpState.setDump(DumpState.DUMP_FROZEN); 17896 } else if ("write".equals(cmd)) { 17897 synchronized (mPackages) { 17898 mSettings.writeLPr(); 17899 pw.println("Settings written."); 17900 return; 17901 } 17902 } 17903 } 17904 17905 if (checkin) { 17906 pw.println("vers,1"); 17907 } 17908 17909 // reader 17910 synchronized (mPackages) { 17911 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17912 if (!checkin) { 17913 if (dumpState.onTitlePrinted()) 17914 pw.println(); 17915 pw.println("Database versions:"); 17916 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17917 } 17918 } 17919 17920 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17921 if (!checkin) { 17922 if (dumpState.onTitlePrinted()) 17923 pw.println(); 17924 pw.println("Verifiers:"); 17925 pw.print(" Required: "); 17926 pw.print(mRequiredVerifierPackage); 17927 pw.print(" (uid="); 17928 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17929 UserHandle.USER_SYSTEM)); 17930 pw.println(")"); 17931 } else if (mRequiredVerifierPackage != null) { 17932 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17933 pw.print(","); 17934 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17935 UserHandle.USER_SYSTEM)); 17936 } 17937 } 17938 17939 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17940 packageName == null) { 17941 if (mIntentFilterVerifierComponent != null) { 17942 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17943 if (!checkin) { 17944 if (dumpState.onTitlePrinted()) 17945 pw.println(); 17946 pw.println("Intent Filter Verifier:"); 17947 pw.print(" Using: "); 17948 pw.print(verifierPackageName); 17949 pw.print(" (uid="); 17950 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17951 UserHandle.USER_SYSTEM)); 17952 pw.println(")"); 17953 } else if (verifierPackageName != null) { 17954 pw.print("ifv,"); pw.print(verifierPackageName); 17955 pw.print(","); 17956 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17957 UserHandle.USER_SYSTEM)); 17958 } 17959 } else { 17960 pw.println(); 17961 pw.println("No Intent Filter Verifier available!"); 17962 } 17963 } 17964 17965 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17966 boolean printedHeader = false; 17967 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17968 while (it.hasNext()) { 17969 String name = it.next(); 17970 SharedLibraryEntry ent = mSharedLibraries.get(name); 17971 if (!checkin) { 17972 if (!printedHeader) { 17973 if (dumpState.onTitlePrinted()) 17974 pw.println(); 17975 pw.println("Libraries:"); 17976 printedHeader = true; 17977 } 17978 pw.print(" "); 17979 } else { 17980 pw.print("lib,"); 17981 } 17982 pw.print(name); 17983 if (!checkin) { 17984 pw.print(" -> "); 17985 } 17986 if (ent.path != null) { 17987 if (!checkin) { 17988 pw.print("(jar) "); 17989 pw.print(ent.path); 17990 } else { 17991 pw.print(",jar,"); 17992 pw.print(ent.path); 17993 } 17994 } else { 17995 if (!checkin) { 17996 pw.print("(apk) "); 17997 pw.print(ent.apk); 17998 } else { 17999 pw.print(",apk,"); 18000 pw.print(ent.apk); 18001 } 18002 } 18003 pw.println(); 18004 } 18005 } 18006 18007 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18008 if (dumpState.onTitlePrinted()) 18009 pw.println(); 18010 if (!checkin) { 18011 pw.println("Features:"); 18012 } 18013 18014 for (FeatureInfo feat : mAvailableFeatures.values()) { 18015 if (checkin) { 18016 pw.print("feat,"); 18017 pw.print(feat.name); 18018 pw.print(","); 18019 pw.println(feat.version); 18020 } else { 18021 pw.print(" "); 18022 pw.print(feat.name); 18023 if (feat.version > 0) { 18024 pw.print(" version="); 18025 pw.print(feat.version); 18026 } 18027 pw.println(); 18028 } 18029 } 18030 } 18031 18032 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18033 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18034 : "Activity Resolver Table:", " ", packageName, 18035 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18036 dumpState.setTitlePrinted(true); 18037 } 18038 } 18039 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18040 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18041 : "Receiver Resolver Table:", " ", packageName, 18042 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18043 dumpState.setTitlePrinted(true); 18044 } 18045 } 18046 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18047 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18048 : "Service Resolver Table:", " ", packageName, 18049 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18050 dumpState.setTitlePrinted(true); 18051 } 18052 } 18053 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18054 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18055 : "Provider Resolver Table:", " ", packageName, 18056 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18057 dumpState.setTitlePrinted(true); 18058 } 18059 } 18060 18061 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18062 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18063 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18064 int user = mSettings.mPreferredActivities.keyAt(i); 18065 if (pir.dump(pw, 18066 dumpState.getTitlePrinted() 18067 ? "\nPreferred Activities User " + user + ":" 18068 : "Preferred Activities User " + user + ":", " ", 18069 packageName, true, false)) { 18070 dumpState.setTitlePrinted(true); 18071 } 18072 } 18073 } 18074 18075 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18076 pw.flush(); 18077 FileOutputStream fout = new FileOutputStream(fd); 18078 BufferedOutputStream str = new BufferedOutputStream(fout); 18079 XmlSerializer serializer = new FastXmlSerializer(); 18080 try { 18081 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18082 serializer.startDocument(null, true); 18083 serializer.setFeature( 18084 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18085 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18086 serializer.endDocument(); 18087 serializer.flush(); 18088 } catch (IllegalArgumentException e) { 18089 pw.println("Failed writing: " + e); 18090 } catch (IllegalStateException e) { 18091 pw.println("Failed writing: " + e); 18092 } catch (IOException e) { 18093 pw.println("Failed writing: " + e); 18094 } 18095 } 18096 18097 if (!checkin 18098 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18099 && packageName == null) { 18100 pw.println(); 18101 int count = mSettings.mPackages.size(); 18102 if (count == 0) { 18103 pw.println("No applications!"); 18104 pw.println(); 18105 } else { 18106 final String prefix = " "; 18107 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18108 if (allPackageSettings.size() == 0) { 18109 pw.println("No domain preferred apps!"); 18110 pw.println(); 18111 } else { 18112 pw.println("App verification status:"); 18113 pw.println(); 18114 count = 0; 18115 for (PackageSetting ps : allPackageSettings) { 18116 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18117 if (ivi == null || ivi.getPackageName() == null) continue; 18118 pw.println(prefix + "Package: " + ivi.getPackageName()); 18119 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18120 pw.println(prefix + "Status: " + ivi.getStatusString()); 18121 pw.println(); 18122 count++; 18123 } 18124 if (count == 0) { 18125 pw.println(prefix + "No app verification established."); 18126 pw.println(); 18127 } 18128 for (int userId : sUserManager.getUserIds()) { 18129 pw.println("App linkages for user " + userId + ":"); 18130 pw.println(); 18131 count = 0; 18132 for (PackageSetting ps : allPackageSettings) { 18133 final long status = ps.getDomainVerificationStatusForUser(userId); 18134 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18135 continue; 18136 } 18137 pw.println(prefix + "Package: " + ps.name); 18138 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18139 String statusStr = IntentFilterVerificationInfo. 18140 getStatusStringFromValue(status); 18141 pw.println(prefix + "Status: " + statusStr); 18142 pw.println(); 18143 count++; 18144 } 18145 if (count == 0) { 18146 pw.println(prefix + "No configured app linkages."); 18147 pw.println(); 18148 } 18149 } 18150 } 18151 } 18152 } 18153 18154 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18155 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18156 if (packageName == null && permissionNames == null) { 18157 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18158 if (iperm == 0) { 18159 if (dumpState.onTitlePrinted()) 18160 pw.println(); 18161 pw.println("AppOp Permissions:"); 18162 } 18163 pw.print(" AppOp Permission "); 18164 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18165 pw.println(":"); 18166 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18167 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18168 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18169 } 18170 } 18171 } 18172 } 18173 18174 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18175 boolean printedSomething = false; 18176 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18177 if (packageName != null && !packageName.equals(p.info.packageName)) { 18178 continue; 18179 } 18180 if (!printedSomething) { 18181 if (dumpState.onTitlePrinted()) 18182 pw.println(); 18183 pw.println("Registered ContentProviders:"); 18184 printedSomething = true; 18185 } 18186 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18187 pw.print(" "); pw.println(p.toString()); 18188 } 18189 printedSomething = false; 18190 for (Map.Entry<String, PackageParser.Provider> entry : 18191 mProvidersByAuthority.entrySet()) { 18192 PackageParser.Provider p = entry.getValue(); 18193 if (packageName != null && !packageName.equals(p.info.packageName)) { 18194 continue; 18195 } 18196 if (!printedSomething) { 18197 if (dumpState.onTitlePrinted()) 18198 pw.println(); 18199 pw.println("ContentProvider Authorities:"); 18200 printedSomething = true; 18201 } 18202 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18203 pw.print(" "); pw.println(p.toString()); 18204 if (p.info != null && p.info.applicationInfo != null) { 18205 final String appInfo = p.info.applicationInfo.toString(); 18206 pw.print(" applicationInfo="); pw.println(appInfo); 18207 } 18208 } 18209 } 18210 18211 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18212 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18213 } 18214 18215 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18216 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18217 } 18218 18219 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18220 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18221 } 18222 18223 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18224 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18225 } 18226 18227 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18228 // XXX should handle packageName != null by dumping only install data that 18229 // the given package is involved with. 18230 if (dumpState.onTitlePrinted()) pw.println(); 18231 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18232 } 18233 18234 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18235 // XXX should handle packageName != null by dumping only install data that 18236 // the given package is involved with. 18237 if (dumpState.onTitlePrinted()) pw.println(); 18238 18239 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18240 ipw.println(); 18241 ipw.println("Frozen packages:"); 18242 ipw.increaseIndent(); 18243 if (mFrozenPackages.size() == 0) { 18244 ipw.println("(none)"); 18245 } else { 18246 for (int i = 0; i < mFrozenPackages.size(); i++) { 18247 ipw.println(mFrozenPackages.valueAt(i)); 18248 } 18249 } 18250 ipw.decreaseIndent(); 18251 } 18252 18253 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18254 if (dumpState.onTitlePrinted()) pw.println(); 18255 mSettings.dumpReadMessagesLPr(pw, dumpState); 18256 18257 pw.println(); 18258 pw.println("Package warning messages:"); 18259 BufferedReader in = null; 18260 String line = null; 18261 try { 18262 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18263 while ((line = in.readLine()) != null) { 18264 if (line.contains("ignored: updated version")) continue; 18265 pw.println(line); 18266 } 18267 } catch (IOException ignored) { 18268 } finally { 18269 IoUtils.closeQuietly(in); 18270 } 18271 } 18272 18273 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18274 BufferedReader in = null; 18275 String line = null; 18276 try { 18277 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18278 while ((line = in.readLine()) != null) { 18279 if (line.contains("ignored: updated version")) continue; 18280 pw.print("msg,"); 18281 pw.println(line); 18282 } 18283 } catch (IOException ignored) { 18284 } finally { 18285 IoUtils.closeQuietly(in); 18286 } 18287 } 18288 } 18289 } 18290 18291 private String dumpDomainString(String packageName) { 18292 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18293 .getList(); 18294 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18295 18296 ArraySet<String> result = new ArraySet<>(); 18297 if (iviList.size() > 0) { 18298 for (IntentFilterVerificationInfo ivi : iviList) { 18299 for (String host : ivi.getDomains()) { 18300 result.add(host); 18301 } 18302 } 18303 } 18304 if (filters != null && filters.size() > 0) { 18305 for (IntentFilter filter : filters) { 18306 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18307 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18308 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18309 result.addAll(filter.getHostsList()); 18310 } 18311 } 18312 } 18313 18314 StringBuilder sb = new StringBuilder(result.size() * 16); 18315 for (String domain : result) { 18316 if (sb.length() > 0) sb.append(" "); 18317 sb.append(domain); 18318 } 18319 return sb.toString(); 18320 } 18321 18322 // ------- apps on sdcard specific code ------- 18323 static final boolean DEBUG_SD_INSTALL = false; 18324 18325 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18326 18327 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18328 18329 private boolean mMediaMounted = false; 18330 18331 static String getEncryptKey() { 18332 try { 18333 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18334 SD_ENCRYPTION_KEYSTORE_NAME); 18335 if (sdEncKey == null) { 18336 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18337 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18338 if (sdEncKey == null) { 18339 Slog.e(TAG, "Failed to create encryption keys"); 18340 return null; 18341 } 18342 } 18343 return sdEncKey; 18344 } catch (NoSuchAlgorithmException nsae) { 18345 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18346 return null; 18347 } catch (IOException ioe) { 18348 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18349 return null; 18350 } 18351 } 18352 18353 /* 18354 * Update media status on PackageManager. 18355 */ 18356 @Override 18357 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18358 int callingUid = Binder.getCallingUid(); 18359 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18360 throw new SecurityException("Media status can only be updated by the system"); 18361 } 18362 // reader; this apparently protects mMediaMounted, but should probably 18363 // be a different lock in that case. 18364 synchronized (mPackages) { 18365 Log.i(TAG, "Updating external media status from " 18366 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18367 + (mediaStatus ? "mounted" : "unmounted")); 18368 if (DEBUG_SD_INSTALL) 18369 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18370 + ", mMediaMounted=" + mMediaMounted); 18371 if (mediaStatus == mMediaMounted) { 18372 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18373 : 0, -1); 18374 mHandler.sendMessage(msg); 18375 return; 18376 } 18377 mMediaMounted = mediaStatus; 18378 } 18379 // Queue up an async operation since the package installation may take a 18380 // little while. 18381 mHandler.post(new Runnable() { 18382 public void run() { 18383 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18384 } 18385 }); 18386 } 18387 18388 /** 18389 * Called by MountService when the initial ASECs to scan are available. 18390 * Should block until all the ASEC containers are finished being scanned. 18391 */ 18392 public void scanAvailableAsecs() { 18393 updateExternalMediaStatusInner(true, false, false); 18394 } 18395 18396 /* 18397 * Collect information of applications on external media, map them against 18398 * existing containers and update information based on current mount status. 18399 * Please note that we always have to report status if reportStatus has been 18400 * set to true especially when unloading packages. 18401 */ 18402 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18403 boolean externalStorage) { 18404 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18405 int[] uidArr = EmptyArray.INT; 18406 18407 final String[] list = PackageHelper.getSecureContainerList(); 18408 if (ArrayUtils.isEmpty(list)) { 18409 Log.i(TAG, "No secure containers found"); 18410 } else { 18411 // Process list of secure containers and categorize them 18412 // as active or stale based on their package internal state. 18413 18414 // reader 18415 synchronized (mPackages) { 18416 for (String cid : list) { 18417 // Leave stages untouched for now; installer service owns them 18418 if (PackageInstallerService.isStageName(cid)) continue; 18419 18420 if (DEBUG_SD_INSTALL) 18421 Log.i(TAG, "Processing container " + cid); 18422 String pkgName = getAsecPackageName(cid); 18423 if (pkgName == null) { 18424 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18425 continue; 18426 } 18427 if (DEBUG_SD_INSTALL) 18428 Log.i(TAG, "Looking for pkg : " + pkgName); 18429 18430 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18431 if (ps == null) { 18432 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18433 continue; 18434 } 18435 18436 /* 18437 * Skip packages that are not external if we're unmounting 18438 * external storage. 18439 */ 18440 if (externalStorage && !isMounted && !isExternal(ps)) { 18441 continue; 18442 } 18443 18444 final AsecInstallArgs args = new AsecInstallArgs(cid, 18445 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18446 // The package status is changed only if the code path 18447 // matches between settings and the container id. 18448 if (ps.codePathString != null 18449 && ps.codePathString.startsWith(args.getCodePath())) { 18450 if (DEBUG_SD_INSTALL) { 18451 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18452 + " at code path: " + ps.codePathString); 18453 } 18454 18455 // We do have a valid package installed on sdcard 18456 processCids.put(args, ps.codePathString); 18457 final int uid = ps.appId; 18458 if (uid != -1) { 18459 uidArr = ArrayUtils.appendInt(uidArr, uid); 18460 } 18461 } else { 18462 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18463 + ps.codePathString); 18464 } 18465 } 18466 } 18467 18468 Arrays.sort(uidArr); 18469 } 18470 18471 // Process packages with valid entries. 18472 if (isMounted) { 18473 if (DEBUG_SD_INSTALL) 18474 Log.i(TAG, "Loading packages"); 18475 loadMediaPackages(processCids, uidArr, externalStorage); 18476 startCleaningPackages(); 18477 mInstallerService.onSecureContainersAvailable(); 18478 } else { 18479 if (DEBUG_SD_INSTALL) 18480 Log.i(TAG, "Unloading packages"); 18481 unloadMediaPackages(processCids, uidArr, reportStatus); 18482 } 18483 } 18484 18485 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18486 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18487 final int size = infos.size(); 18488 final String[] packageNames = new String[size]; 18489 final int[] packageUids = new int[size]; 18490 for (int i = 0; i < size; i++) { 18491 final ApplicationInfo info = infos.get(i); 18492 packageNames[i] = info.packageName; 18493 packageUids[i] = info.uid; 18494 } 18495 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18496 finishedReceiver); 18497 } 18498 18499 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18500 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18501 sendResourcesChangedBroadcast(mediaStatus, replacing, 18502 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18503 } 18504 18505 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18506 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18507 int size = pkgList.length; 18508 if (size > 0) { 18509 // Send broadcasts here 18510 Bundle extras = new Bundle(); 18511 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18512 if (uidArr != null) { 18513 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18514 } 18515 if (replacing) { 18516 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18517 } 18518 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18519 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18520 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18521 } 18522 } 18523 18524 /* 18525 * Look at potentially valid container ids from processCids If package 18526 * information doesn't match the one on record or package scanning fails, 18527 * the cid is added to list of removeCids. We currently don't delete stale 18528 * containers. 18529 */ 18530 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18531 boolean externalStorage) { 18532 ArrayList<String> pkgList = new ArrayList<String>(); 18533 Set<AsecInstallArgs> keys = processCids.keySet(); 18534 18535 for (AsecInstallArgs args : keys) { 18536 String codePath = processCids.get(args); 18537 if (DEBUG_SD_INSTALL) 18538 Log.i(TAG, "Loading container : " + args.cid); 18539 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18540 try { 18541 // Make sure there are no container errors first. 18542 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18543 Slog.e(TAG, "Failed to mount cid : " + args.cid 18544 + " when installing from sdcard"); 18545 continue; 18546 } 18547 // Check code path here. 18548 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18549 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18550 + " does not match one in settings " + codePath); 18551 continue; 18552 } 18553 // Parse package 18554 int parseFlags = mDefParseFlags; 18555 if (args.isExternalAsec()) { 18556 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18557 } 18558 if (args.isFwdLocked()) { 18559 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18560 } 18561 18562 synchronized (mInstallLock) { 18563 PackageParser.Package pkg = null; 18564 try { 18565 // Sadly we don't know the package name yet to freeze it 18566 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18567 SCAN_IGNORE_FROZEN, 0, null); 18568 } catch (PackageManagerException e) { 18569 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18570 } 18571 // Scan the package 18572 if (pkg != null) { 18573 /* 18574 * TODO why is the lock being held? doPostInstall is 18575 * called in other places without the lock. This needs 18576 * to be straightened out. 18577 */ 18578 // writer 18579 synchronized (mPackages) { 18580 retCode = PackageManager.INSTALL_SUCCEEDED; 18581 pkgList.add(pkg.packageName); 18582 // Post process args 18583 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18584 pkg.applicationInfo.uid); 18585 } 18586 } else { 18587 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18588 } 18589 } 18590 18591 } finally { 18592 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18593 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18594 } 18595 } 18596 } 18597 // writer 18598 synchronized (mPackages) { 18599 // If the platform SDK has changed since the last time we booted, 18600 // we need to re-grant app permission to catch any new ones that 18601 // appear. This is really a hack, and means that apps can in some 18602 // cases get permissions that the user didn't initially explicitly 18603 // allow... it would be nice to have some better way to handle 18604 // this situation. 18605 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18606 : mSettings.getInternalVersion(); 18607 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18608 : StorageManager.UUID_PRIVATE_INTERNAL; 18609 18610 int updateFlags = UPDATE_PERMISSIONS_ALL; 18611 if (ver.sdkVersion != mSdkVersion) { 18612 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18613 + mSdkVersion + "; regranting permissions for external"); 18614 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18615 } 18616 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18617 18618 // Yay, everything is now upgraded 18619 ver.forceCurrent(); 18620 18621 // can downgrade to reader 18622 // Persist settings 18623 mSettings.writeLPr(); 18624 } 18625 // Send a broadcast to let everyone know we are done processing 18626 if (pkgList.size() > 0) { 18627 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18628 } 18629 } 18630 18631 /* 18632 * Utility method to unload a list of specified containers 18633 */ 18634 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18635 // Just unmount all valid containers. 18636 for (AsecInstallArgs arg : cidArgs) { 18637 synchronized (mInstallLock) { 18638 arg.doPostDeleteLI(false); 18639 } 18640 } 18641 } 18642 18643 /* 18644 * Unload packages mounted on external media. This involves deleting package 18645 * data from internal structures, sending broadcasts about disabled packages, 18646 * gc'ing to free up references, unmounting all secure containers 18647 * corresponding to packages on external media, and posting a 18648 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18649 * that we always have to post this message if status has been requested no 18650 * matter what. 18651 */ 18652 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18653 final boolean reportStatus) { 18654 if (DEBUG_SD_INSTALL) 18655 Log.i(TAG, "unloading media packages"); 18656 ArrayList<String> pkgList = new ArrayList<String>(); 18657 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18658 final Set<AsecInstallArgs> keys = processCids.keySet(); 18659 for (AsecInstallArgs args : keys) { 18660 String pkgName = args.getPackageName(); 18661 if (DEBUG_SD_INSTALL) 18662 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18663 // Delete package internally 18664 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18665 synchronized (mInstallLock) { 18666 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18667 final boolean res; 18668 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18669 "unloadMediaPackages")) { 18670 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18671 null); 18672 } 18673 if (res) { 18674 pkgList.add(pkgName); 18675 } else { 18676 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18677 failedList.add(args); 18678 } 18679 } 18680 } 18681 18682 // reader 18683 synchronized (mPackages) { 18684 // We didn't update the settings after removing each package; 18685 // write them now for all packages. 18686 mSettings.writeLPr(); 18687 } 18688 18689 // We have to absolutely send UPDATED_MEDIA_STATUS only 18690 // after confirming that all the receivers processed the ordered 18691 // broadcast when packages get disabled, force a gc to clean things up. 18692 // and unload all the containers. 18693 if (pkgList.size() > 0) { 18694 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18695 new IIntentReceiver.Stub() { 18696 public void performReceive(Intent intent, int resultCode, String data, 18697 Bundle extras, boolean ordered, boolean sticky, 18698 int sendingUser) throws RemoteException { 18699 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18700 reportStatus ? 1 : 0, 1, keys); 18701 mHandler.sendMessage(msg); 18702 } 18703 }); 18704 } else { 18705 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18706 keys); 18707 mHandler.sendMessage(msg); 18708 } 18709 } 18710 18711 private void loadPrivatePackages(final VolumeInfo vol) { 18712 mHandler.post(new Runnable() { 18713 @Override 18714 public void run() { 18715 loadPrivatePackagesInner(vol); 18716 } 18717 }); 18718 } 18719 18720 private void loadPrivatePackagesInner(VolumeInfo vol) { 18721 final String volumeUuid = vol.fsUuid; 18722 if (TextUtils.isEmpty(volumeUuid)) { 18723 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18724 return; 18725 } 18726 18727 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18728 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18729 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18730 18731 final VersionInfo ver; 18732 final List<PackageSetting> packages; 18733 synchronized (mPackages) { 18734 ver = mSettings.findOrCreateVersion(volumeUuid); 18735 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18736 } 18737 18738 for (PackageSetting ps : packages) { 18739 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18740 synchronized (mInstallLock) { 18741 final PackageParser.Package pkg; 18742 try { 18743 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18744 loaded.add(pkg.applicationInfo); 18745 18746 } catch (PackageManagerException e) { 18747 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18748 } 18749 18750 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18751 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18752 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18753 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18754 } 18755 } 18756 } 18757 18758 // Reconcile app data for all started/unlocked users 18759 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18760 final UserManager um = mContext.getSystemService(UserManager.class); 18761 for (UserInfo user : um.getUsers()) { 18762 final int flags; 18763 if (um.isUserUnlocked(user.id)) { 18764 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18765 } else if (um.isUserRunning(user.id)) { 18766 flags = StorageManager.FLAG_STORAGE_DE; 18767 } else { 18768 continue; 18769 } 18770 18771 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18772 synchronized (mInstallLock) { 18773 reconcileAppsDataLI(volumeUuid, user.id, flags); 18774 } 18775 } 18776 18777 synchronized (mPackages) { 18778 int updateFlags = UPDATE_PERMISSIONS_ALL; 18779 if (ver.sdkVersion != mSdkVersion) { 18780 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18781 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18782 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18783 } 18784 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18785 18786 // Yay, everything is now upgraded 18787 ver.forceCurrent(); 18788 18789 mSettings.writeLPr(); 18790 } 18791 18792 for (PackageFreezer freezer : freezers) { 18793 freezer.close(); 18794 } 18795 18796 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18797 sendResourcesChangedBroadcast(true, false, loaded, null); 18798 } 18799 18800 private void unloadPrivatePackages(final VolumeInfo vol) { 18801 mHandler.post(new Runnable() { 18802 @Override 18803 public void run() { 18804 unloadPrivatePackagesInner(vol); 18805 } 18806 }); 18807 } 18808 18809 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18810 final String volumeUuid = vol.fsUuid; 18811 if (TextUtils.isEmpty(volumeUuid)) { 18812 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18813 return; 18814 } 18815 18816 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18817 synchronized (mInstallLock) { 18818 synchronized (mPackages) { 18819 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18820 for (PackageSetting ps : packages) { 18821 if (ps.pkg == null) continue; 18822 18823 final ApplicationInfo info = ps.pkg.applicationInfo; 18824 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18825 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18826 18827 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18828 "unloadPrivatePackagesInner")) { 18829 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18830 false, null)) { 18831 unloaded.add(info); 18832 } else { 18833 Slog.w(TAG, "Failed to unload " + ps.codePath); 18834 } 18835 } 18836 } 18837 18838 mSettings.writeLPr(); 18839 } 18840 } 18841 18842 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18843 sendResourcesChangedBroadcast(false, false, unloaded, null); 18844 } 18845 18846 /** 18847 * Prepare storage areas for given user on all mounted devices. 18848 */ 18849 void prepareUserData(int userId, int userSerial, int flags) { 18850 synchronized (mInstallLock) { 18851 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18852 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18853 final String volumeUuid = vol.getFsUuid(); 18854 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18855 } 18856 } 18857 } 18858 18859 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18860 boolean allowRecover) { 18861 // Prepare storage and verify that serial numbers are consistent; if 18862 // there's a mismatch we need to destroy to avoid leaking data 18863 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18864 try { 18865 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18866 18867 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18868 UserManagerService.enforceSerialNumber( 18869 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18870 } 18871 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18872 UserManagerService.enforceSerialNumber( 18873 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18874 } 18875 18876 synchronized (mInstallLock) { 18877 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18878 } 18879 } catch (Exception e) { 18880 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18881 + " because we failed to prepare: " + e); 18882 destroyUserDataLI(volumeUuid, userId, 18883 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18884 18885 if (allowRecover) { 18886 // Try one last time; if we fail again we're really in trouble 18887 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18888 } 18889 } 18890 } 18891 18892 /** 18893 * Destroy storage areas for given user on all mounted devices. 18894 */ 18895 void destroyUserData(int userId, int flags) { 18896 synchronized (mInstallLock) { 18897 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18898 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18899 final String volumeUuid = vol.getFsUuid(); 18900 destroyUserDataLI(volumeUuid, userId, flags); 18901 } 18902 } 18903 } 18904 18905 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18906 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18907 try { 18908 // Clean up app data, profile data, and media data 18909 mInstaller.destroyUserData(volumeUuid, userId, flags); 18910 18911 // Clean up system data 18912 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18913 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18914 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18915 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18916 } 18917 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18918 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18919 } 18920 } 18921 18922 // Data with special labels is now gone, so finish the job 18923 storage.destroyUserStorage(volumeUuid, userId, flags); 18924 18925 } catch (Exception e) { 18926 logCriticalInfo(Log.WARN, 18927 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18928 } 18929 } 18930 18931 /** 18932 * Examine all users present on given mounted volume, and destroy data 18933 * belonging to users that are no longer valid, or whose user ID has been 18934 * recycled. 18935 */ 18936 private void reconcileUsers(String volumeUuid) { 18937 final List<File> files = new ArrayList<>(); 18938 Collections.addAll(files, FileUtils 18939 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18940 Collections.addAll(files, FileUtils 18941 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18942 for (File file : files) { 18943 if (!file.isDirectory()) continue; 18944 18945 final int userId; 18946 final UserInfo info; 18947 try { 18948 userId = Integer.parseInt(file.getName()); 18949 info = sUserManager.getUserInfo(userId); 18950 } catch (NumberFormatException e) { 18951 Slog.w(TAG, "Invalid user directory " + file); 18952 continue; 18953 } 18954 18955 boolean destroyUser = false; 18956 if (info == null) { 18957 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18958 + " because no matching user was found"); 18959 destroyUser = true; 18960 } else if (!mOnlyCore) { 18961 try { 18962 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18963 } catch (IOException e) { 18964 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18965 + " because we failed to enforce serial number: " + e); 18966 destroyUser = true; 18967 } 18968 } 18969 18970 if (destroyUser) { 18971 synchronized (mInstallLock) { 18972 destroyUserDataLI(volumeUuid, userId, 18973 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18974 } 18975 } 18976 } 18977 } 18978 18979 private void assertPackageKnown(String volumeUuid, String packageName) 18980 throws PackageManagerException { 18981 synchronized (mPackages) { 18982 final PackageSetting ps = mSettings.mPackages.get(packageName); 18983 if (ps == null) { 18984 throw new PackageManagerException("Package " + packageName + " is unknown"); 18985 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18986 throw new PackageManagerException( 18987 "Package " + packageName + " found on unknown volume " + volumeUuid 18988 + "; expected volume " + ps.volumeUuid); 18989 } 18990 } 18991 } 18992 18993 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18994 throws PackageManagerException { 18995 synchronized (mPackages) { 18996 final PackageSetting ps = mSettings.mPackages.get(packageName); 18997 if (ps == null) { 18998 throw new PackageManagerException("Package " + packageName + " is unknown"); 18999 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19000 throw new PackageManagerException( 19001 "Package " + packageName + " found on unknown volume " + volumeUuid 19002 + "; expected volume " + ps.volumeUuid); 19003 } else if (!ps.getInstalled(userId)) { 19004 throw new PackageManagerException( 19005 "Package " + packageName + " not installed for user " + userId); 19006 } 19007 } 19008 } 19009 19010 /** 19011 * Examine all apps present on given mounted volume, and destroy apps that 19012 * aren't expected, either due to uninstallation or reinstallation on 19013 * another volume. 19014 */ 19015 private void reconcileApps(String volumeUuid) { 19016 final File[] files = FileUtils 19017 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19018 for (File file : files) { 19019 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19020 && !PackageInstallerService.isStageName(file.getName()); 19021 if (!isPackage) { 19022 // Ignore entries which are not packages 19023 continue; 19024 } 19025 19026 try { 19027 final PackageLite pkg = PackageParser.parsePackageLite(file, 19028 PackageParser.PARSE_MUST_BE_APK); 19029 assertPackageKnown(volumeUuid, pkg.packageName); 19030 19031 } catch (PackageParserException | PackageManagerException e) { 19032 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19033 synchronized (mInstallLock) { 19034 removeCodePathLI(file); 19035 } 19036 } 19037 } 19038 } 19039 19040 /** 19041 * Reconcile all app data for the given user. 19042 * <p> 19043 * Verifies that directories exist and that ownership and labeling is 19044 * correct for all installed apps on all mounted volumes. 19045 */ 19046 void reconcileAppsData(int userId, int flags) { 19047 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19048 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19049 final String volumeUuid = vol.getFsUuid(); 19050 synchronized (mInstallLock) { 19051 reconcileAppsDataLI(volumeUuid, userId, flags); 19052 } 19053 } 19054 } 19055 19056 /** 19057 * Reconcile all app data on given mounted volume. 19058 * <p> 19059 * Destroys app data that isn't expected, either due to uninstallation or 19060 * reinstallation on another volume. 19061 * <p> 19062 * Verifies that directories exist and that ownership and labeling is 19063 * correct for all installed apps. 19064 */ 19065 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19066 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19067 + Integer.toHexString(flags)); 19068 19069 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19070 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19071 19072 boolean restoreconNeeded = false; 19073 19074 // First look for stale data that doesn't belong, and check if things 19075 // have changed since we did our last restorecon 19076 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19077 if (!isUserKeyUnlocked(userId)) { 19078 throw new RuntimeException( 19079 "Yikes, someone asked us to reconcile CE storage while " + userId 19080 + " was still locked; this would have caused massive data loss!"); 19081 } 19082 19083 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19084 19085 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19086 for (File file : files) { 19087 final String packageName = file.getName(); 19088 try { 19089 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19090 } catch (PackageManagerException e) { 19091 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19092 try { 19093 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19094 StorageManager.FLAG_STORAGE_CE, 0); 19095 } catch (InstallerException e2) { 19096 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19097 } 19098 } 19099 } 19100 } 19101 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19102 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19103 19104 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19105 for (File file : files) { 19106 final String packageName = file.getName(); 19107 try { 19108 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19109 } catch (PackageManagerException e) { 19110 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19111 try { 19112 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19113 StorageManager.FLAG_STORAGE_DE, 0); 19114 } catch (InstallerException e2) { 19115 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19116 } 19117 } 19118 } 19119 } 19120 19121 // Ensure that data directories are ready to roll for all packages 19122 // installed for this volume and user 19123 final List<PackageSetting> packages; 19124 synchronized (mPackages) { 19125 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19126 } 19127 int preparedCount = 0; 19128 for (PackageSetting ps : packages) { 19129 final String packageName = ps.name; 19130 if (ps.pkg == null) { 19131 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19132 // TODO: might be due to legacy ASEC apps; we should circle back 19133 // and reconcile again once they're scanned 19134 continue; 19135 } 19136 19137 if (ps.getInstalled(userId)) { 19138 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19139 19140 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19141 // We may have just shuffled around app data directories, so 19142 // prepare them one more time 19143 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19144 } 19145 19146 preparedCount++; 19147 } 19148 } 19149 19150 if (restoreconNeeded) { 19151 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19152 SELinuxMMAC.setRestoreconDone(ceDir); 19153 } 19154 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19155 SELinuxMMAC.setRestoreconDone(deDir); 19156 } 19157 } 19158 19159 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19160 + " packages; restoreconNeeded was " + restoreconNeeded); 19161 } 19162 19163 /** 19164 * Prepare app data for the given app just after it was installed or 19165 * upgraded. This method carefully only touches users that it's installed 19166 * for, and it forces a restorecon to handle any seinfo changes. 19167 * <p> 19168 * Verifies that directories exist and that ownership and labeling is 19169 * correct for all installed apps. If there is an ownership mismatch, it 19170 * will try recovering system apps by wiping data; third-party app data is 19171 * left intact. 19172 * <p> 19173 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19174 */ 19175 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19176 final PackageSetting ps; 19177 synchronized (mPackages) { 19178 ps = mSettings.mPackages.get(pkg.packageName); 19179 mSettings.writeKernelMappingLPr(ps); 19180 } 19181 19182 final UserManager um = mContext.getSystemService(UserManager.class); 19183 for (UserInfo user : um.getUsers()) { 19184 final int flags; 19185 if (um.isUserUnlocked(user.id)) { 19186 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19187 } else if (um.isUserRunning(user.id)) { 19188 flags = StorageManager.FLAG_STORAGE_DE; 19189 } else { 19190 continue; 19191 } 19192 19193 if (ps.getInstalled(user.id)) { 19194 // Whenever an app changes, force a restorecon of its data 19195 // TODO: when user data is locked, mark that we're still dirty 19196 prepareAppDataLIF(pkg, user.id, flags, true); 19197 } 19198 } 19199 } 19200 19201 /** 19202 * Prepare app data for the given app. 19203 * <p> 19204 * Verifies that directories exist and that ownership and labeling is 19205 * correct for all installed apps. If there is an ownership mismatch, this 19206 * will try recovering system apps by wiping data; third-party app data is 19207 * left intact. 19208 */ 19209 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19210 boolean restoreconNeeded) { 19211 if (pkg == null) { 19212 Slog.wtf(TAG, "Package was null!", new Throwable()); 19213 return; 19214 } 19215 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19216 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19217 for (int i = 0; i < childCount; i++) { 19218 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19219 } 19220 } 19221 19222 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19223 boolean restoreconNeeded) { 19224 if (DEBUG_APP_DATA) { 19225 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19226 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19227 } 19228 19229 final String volumeUuid = pkg.volumeUuid; 19230 final String packageName = pkg.packageName; 19231 final ApplicationInfo app = pkg.applicationInfo; 19232 final int appId = UserHandle.getAppId(app.uid); 19233 19234 Preconditions.checkNotNull(app.seinfo); 19235 19236 try { 19237 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19238 appId, app.seinfo, app.targetSdkVersion); 19239 } catch (InstallerException e) { 19240 if (app.isSystemApp()) { 19241 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19242 + ", but trying to recover: " + e); 19243 destroyAppDataLeafLIF(pkg, userId, flags); 19244 try { 19245 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19246 appId, app.seinfo, app.targetSdkVersion); 19247 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19248 } catch (InstallerException e2) { 19249 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19250 } 19251 } else { 19252 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19253 } 19254 } 19255 19256 if (restoreconNeeded) { 19257 try { 19258 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19259 app.seinfo); 19260 } catch (InstallerException e) { 19261 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19262 } 19263 } 19264 19265 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19266 try { 19267 // CE storage is unlocked right now, so read out the inode and 19268 // remember for use later when it's locked 19269 // TODO: mark this structure as dirty so we persist it! 19270 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19271 StorageManager.FLAG_STORAGE_CE); 19272 synchronized (mPackages) { 19273 final PackageSetting ps = mSettings.mPackages.get(packageName); 19274 if (ps != null) { 19275 ps.setCeDataInode(ceDataInode, userId); 19276 } 19277 } 19278 } catch (InstallerException e) { 19279 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19280 } 19281 } 19282 19283 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19284 } 19285 19286 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19287 if (pkg == null) { 19288 Slog.wtf(TAG, "Package was null!", new Throwable()); 19289 return; 19290 } 19291 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19292 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19293 for (int i = 0; i < childCount; i++) { 19294 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19295 } 19296 } 19297 19298 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19299 final String volumeUuid = pkg.volumeUuid; 19300 final String packageName = pkg.packageName; 19301 final ApplicationInfo app = pkg.applicationInfo; 19302 19303 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19304 // Create a native library symlink only if we have native libraries 19305 // and if the native libraries are 32 bit libraries. We do not provide 19306 // this symlink for 64 bit libraries. 19307 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19308 final String nativeLibPath = app.nativeLibraryDir; 19309 try { 19310 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19311 nativeLibPath, userId); 19312 } catch (InstallerException e) { 19313 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19314 } 19315 } 19316 } 19317 } 19318 19319 /** 19320 * For system apps on non-FBE devices, this method migrates any existing 19321 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19322 * requested by the app. 19323 */ 19324 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19325 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19326 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19327 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19328 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19329 try { 19330 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19331 storageTarget); 19332 } catch (InstallerException e) { 19333 logCriticalInfo(Log.WARN, 19334 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19335 } 19336 return true; 19337 } else { 19338 return false; 19339 } 19340 } 19341 19342 public PackageFreezer freezePackage(String packageName, String killReason) { 19343 return new PackageFreezer(packageName, killReason); 19344 } 19345 19346 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19347 String killReason) { 19348 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19349 return new PackageFreezer(); 19350 } else { 19351 return freezePackage(packageName, killReason); 19352 } 19353 } 19354 19355 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19356 String killReason) { 19357 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19358 return new PackageFreezer(); 19359 } else { 19360 return freezePackage(packageName, killReason); 19361 } 19362 } 19363 19364 /** 19365 * Class that freezes and kills the given package upon creation, and 19366 * unfreezes it upon closing. This is typically used when doing surgery on 19367 * app code/data to prevent the app from running while you're working. 19368 */ 19369 private class PackageFreezer implements AutoCloseable { 19370 private final String mPackageName; 19371 private final PackageFreezer[] mChildren; 19372 19373 private final boolean mWeFroze; 19374 19375 private final AtomicBoolean mClosed = new AtomicBoolean(); 19376 private final CloseGuard mCloseGuard = CloseGuard.get(); 19377 19378 /** 19379 * Create and return a stub freezer that doesn't actually do anything, 19380 * typically used when someone requested 19381 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19382 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19383 */ 19384 public PackageFreezer() { 19385 mPackageName = null; 19386 mChildren = null; 19387 mWeFroze = false; 19388 mCloseGuard.open("close"); 19389 } 19390 19391 public PackageFreezer(String packageName, String killReason) { 19392 synchronized (mPackages) { 19393 mPackageName = packageName; 19394 mWeFroze = mFrozenPackages.add(mPackageName); 19395 19396 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19397 if (ps != null) { 19398 killApplication(ps.name, ps.appId, killReason); 19399 } 19400 19401 final PackageParser.Package p = mPackages.get(packageName); 19402 if (p != null && p.childPackages != null) { 19403 final int N = p.childPackages.size(); 19404 mChildren = new PackageFreezer[N]; 19405 for (int i = 0; i < N; i++) { 19406 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19407 killReason); 19408 } 19409 } else { 19410 mChildren = null; 19411 } 19412 } 19413 mCloseGuard.open("close"); 19414 } 19415 19416 @Override 19417 protected void finalize() throws Throwable { 19418 try { 19419 mCloseGuard.warnIfOpen(); 19420 close(); 19421 } finally { 19422 super.finalize(); 19423 } 19424 } 19425 19426 @Override 19427 public void close() { 19428 mCloseGuard.close(); 19429 if (mClosed.compareAndSet(false, true)) { 19430 synchronized (mPackages) { 19431 if (mWeFroze) { 19432 mFrozenPackages.remove(mPackageName); 19433 } 19434 19435 if (mChildren != null) { 19436 for (PackageFreezer freezer : mChildren) { 19437 freezer.close(); 19438 } 19439 } 19440 } 19441 } 19442 } 19443 } 19444 19445 /** 19446 * Verify that given package is currently frozen. 19447 */ 19448 private void checkPackageFrozen(String packageName) { 19449 synchronized (mPackages) { 19450 if (!mFrozenPackages.contains(packageName)) { 19451 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19452 } 19453 } 19454 } 19455 19456 @Override 19457 public int movePackage(final String packageName, final String volumeUuid) { 19458 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19459 19460 final int moveId = mNextMoveId.getAndIncrement(); 19461 mHandler.post(new Runnable() { 19462 @Override 19463 public void run() { 19464 try { 19465 movePackageInternal(packageName, volumeUuid, moveId); 19466 } catch (PackageManagerException e) { 19467 Slog.w(TAG, "Failed to move " + packageName, e); 19468 mMoveCallbacks.notifyStatusChanged(moveId, 19469 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19470 } 19471 } 19472 }); 19473 return moveId; 19474 } 19475 19476 private void movePackageInternal(final String packageName, final String volumeUuid, 19477 final int moveId) throws PackageManagerException { 19478 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19479 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19480 final PackageManager pm = mContext.getPackageManager(); 19481 19482 final boolean currentAsec; 19483 final String currentVolumeUuid; 19484 final File codeFile; 19485 final String installerPackageName; 19486 final String packageAbiOverride; 19487 final int appId; 19488 final String seinfo; 19489 final String label; 19490 final int targetSdkVersion; 19491 final PackageFreezer freezer; 19492 19493 // reader 19494 synchronized (mPackages) { 19495 final PackageParser.Package pkg = mPackages.get(packageName); 19496 final PackageSetting ps = mSettings.mPackages.get(packageName); 19497 if (pkg == null || ps == null) { 19498 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19499 } 19500 19501 if (pkg.applicationInfo.isSystemApp()) { 19502 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19503 "Cannot move system application"); 19504 } 19505 19506 if (pkg.applicationInfo.isExternalAsec()) { 19507 currentAsec = true; 19508 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19509 } else if (pkg.applicationInfo.isForwardLocked()) { 19510 currentAsec = true; 19511 currentVolumeUuid = "forward_locked"; 19512 } else { 19513 currentAsec = false; 19514 currentVolumeUuid = ps.volumeUuid; 19515 19516 final File probe = new File(pkg.codePath); 19517 final File probeOat = new File(probe, "oat"); 19518 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19519 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19520 "Move only supported for modern cluster style installs"); 19521 } 19522 } 19523 19524 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19525 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19526 "Package already moved to " + volumeUuid); 19527 } 19528 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19529 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19530 "Device admin cannot be moved"); 19531 } 19532 19533 if (mFrozenPackages.contains(packageName)) { 19534 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19535 "Failed to move already frozen package"); 19536 } 19537 19538 codeFile = new File(pkg.codePath); 19539 installerPackageName = ps.installerPackageName; 19540 packageAbiOverride = ps.cpuAbiOverrideString; 19541 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19542 seinfo = pkg.applicationInfo.seinfo; 19543 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19544 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19545 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19546 } 19547 19548 final Bundle extras = new Bundle(); 19549 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19550 extras.putString(Intent.EXTRA_TITLE, label); 19551 mMoveCallbacks.notifyCreated(moveId, extras); 19552 19553 int installFlags; 19554 final boolean moveCompleteApp; 19555 final File measurePath; 19556 19557 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19558 installFlags = INSTALL_INTERNAL; 19559 moveCompleteApp = !currentAsec; 19560 measurePath = Environment.getDataAppDirectory(volumeUuid); 19561 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19562 installFlags = INSTALL_EXTERNAL; 19563 moveCompleteApp = false; 19564 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19565 } else { 19566 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19567 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19568 || !volume.isMountedWritable()) { 19569 freezer.close(); 19570 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19571 "Move location not mounted private volume"); 19572 } 19573 19574 Preconditions.checkState(!currentAsec); 19575 19576 installFlags = INSTALL_INTERNAL; 19577 moveCompleteApp = true; 19578 measurePath = Environment.getDataAppDirectory(volumeUuid); 19579 } 19580 19581 final PackageStats stats = new PackageStats(null, -1); 19582 synchronized (mInstaller) { 19583 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19584 freezer.close(); 19585 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19586 "Failed to measure package size"); 19587 } 19588 } 19589 19590 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19591 + stats.dataSize); 19592 19593 final long startFreeBytes = measurePath.getFreeSpace(); 19594 final long sizeBytes; 19595 if (moveCompleteApp) { 19596 sizeBytes = stats.codeSize + stats.dataSize; 19597 } else { 19598 sizeBytes = stats.codeSize; 19599 } 19600 19601 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19602 freezer.close(); 19603 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19604 "Not enough free space to move"); 19605 } 19606 19607 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19608 19609 final CountDownLatch installedLatch = new CountDownLatch(1); 19610 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19611 @Override 19612 public void onUserActionRequired(Intent intent) throws RemoteException { 19613 throw new IllegalStateException(); 19614 } 19615 19616 @Override 19617 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19618 Bundle extras) throws RemoteException { 19619 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19620 + PackageManager.installStatusToString(returnCode, msg)); 19621 19622 installedLatch.countDown(); 19623 freezer.close(); 19624 19625 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19626 switch (status) { 19627 case PackageInstaller.STATUS_SUCCESS: 19628 mMoveCallbacks.notifyStatusChanged(moveId, 19629 PackageManager.MOVE_SUCCEEDED); 19630 break; 19631 case PackageInstaller.STATUS_FAILURE_STORAGE: 19632 mMoveCallbacks.notifyStatusChanged(moveId, 19633 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19634 break; 19635 default: 19636 mMoveCallbacks.notifyStatusChanged(moveId, 19637 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19638 break; 19639 } 19640 } 19641 }; 19642 19643 final MoveInfo move; 19644 if (moveCompleteApp) { 19645 // Kick off a thread to report progress estimates 19646 new Thread() { 19647 @Override 19648 public void run() { 19649 while (true) { 19650 try { 19651 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19652 break; 19653 } 19654 } catch (InterruptedException ignored) { 19655 } 19656 19657 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19658 final int progress = 10 + (int) MathUtils.constrain( 19659 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19660 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19661 } 19662 } 19663 }.start(); 19664 19665 final String dataAppName = codeFile.getName(); 19666 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19667 dataAppName, appId, seinfo, targetSdkVersion); 19668 } else { 19669 move = null; 19670 } 19671 19672 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19673 19674 final Message msg = mHandler.obtainMessage(INIT_COPY); 19675 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19676 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19677 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19678 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19679 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19680 msg.obj = params; 19681 19682 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19683 System.identityHashCode(msg.obj)); 19684 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19685 System.identityHashCode(msg.obj)); 19686 19687 mHandler.sendMessage(msg); 19688 } 19689 19690 @Override 19691 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19692 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19693 19694 final int realMoveId = mNextMoveId.getAndIncrement(); 19695 final Bundle extras = new Bundle(); 19696 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19697 mMoveCallbacks.notifyCreated(realMoveId, extras); 19698 19699 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19700 @Override 19701 public void onCreated(int moveId, Bundle extras) { 19702 // Ignored 19703 } 19704 19705 @Override 19706 public void onStatusChanged(int moveId, int status, long estMillis) { 19707 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19708 } 19709 }; 19710 19711 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19712 storage.setPrimaryStorageUuid(volumeUuid, callback); 19713 return realMoveId; 19714 } 19715 19716 @Override 19717 public int getMoveStatus(int moveId) { 19718 mContext.enforceCallingOrSelfPermission( 19719 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19720 return mMoveCallbacks.mLastStatus.get(moveId); 19721 } 19722 19723 @Override 19724 public void registerMoveCallback(IPackageMoveObserver callback) { 19725 mContext.enforceCallingOrSelfPermission( 19726 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19727 mMoveCallbacks.register(callback); 19728 } 19729 19730 @Override 19731 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19732 mContext.enforceCallingOrSelfPermission( 19733 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19734 mMoveCallbacks.unregister(callback); 19735 } 19736 19737 @Override 19738 public boolean setInstallLocation(int loc) { 19739 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19740 null); 19741 if (getInstallLocation() == loc) { 19742 return true; 19743 } 19744 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19745 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19746 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19747 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19748 return true; 19749 } 19750 return false; 19751 } 19752 19753 @Override 19754 public int getInstallLocation() { 19755 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19756 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19757 PackageHelper.APP_INSTALL_AUTO); 19758 } 19759 19760 /** Called by UserManagerService */ 19761 void cleanUpUser(UserManagerService userManager, int userHandle) { 19762 synchronized (mPackages) { 19763 mDirtyUsers.remove(userHandle); 19764 mUserNeedsBadging.delete(userHandle); 19765 mSettings.removeUserLPw(userHandle); 19766 mPendingBroadcasts.remove(userHandle); 19767 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19768 removeUnusedPackagesLPw(userManager, userHandle); 19769 } 19770 } 19771 19772 /** 19773 * We're removing userHandle and would like to remove any downloaded packages 19774 * that are no longer in use by any other user. 19775 * @param userHandle the user being removed 19776 */ 19777 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19778 final boolean DEBUG_CLEAN_APKS = false; 19779 int [] users = userManager.getUserIds(); 19780 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19781 while (psit.hasNext()) { 19782 PackageSetting ps = psit.next(); 19783 if (ps.pkg == null) { 19784 continue; 19785 } 19786 final String packageName = ps.pkg.packageName; 19787 // Skip over if system app 19788 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19789 continue; 19790 } 19791 if (DEBUG_CLEAN_APKS) { 19792 Slog.i(TAG, "Checking package " + packageName); 19793 } 19794 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19795 if (keep) { 19796 if (DEBUG_CLEAN_APKS) { 19797 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19798 } 19799 } else { 19800 for (int i = 0; i < users.length; i++) { 19801 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19802 keep = true; 19803 if (DEBUG_CLEAN_APKS) { 19804 Slog.i(TAG, " Keeping package " + packageName + " for user " 19805 + users[i]); 19806 } 19807 break; 19808 } 19809 } 19810 } 19811 if (!keep) { 19812 if (DEBUG_CLEAN_APKS) { 19813 Slog.i(TAG, " Removing package " + packageName); 19814 } 19815 mHandler.post(new Runnable() { 19816 public void run() { 19817 deletePackageX(packageName, userHandle, 0); 19818 } //end run 19819 }); 19820 } 19821 } 19822 } 19823 19824 /** Called by UserManagerService */ 19825 void createNewUser(int userHandle) { 19826 synchronized (mInstallLock) { 19827 mSettings.createNewUserLI(this, mInstaller, userHandle); 19828 } 19829 synchronized (mPackages) { 19830 applyFactoryDefaultBrowserLPw(userHandle); 19831 primeDomainVerificationsLPw(userHandle); 19832 } 19833 } 19834 19835 void newUserCreated(final int userHandle) { 19836 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19837 // If permission review for legacy apps is required, we represent 19838 // dagerous permissions for such apps as always granted runtime 19839 // permissions to keep per user flag state whether review is needed. 19840 // Hence, if a new user is added we have to propagate dangerous 19841 // permission grants for these legacy apps. 19842 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19843 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19844 | UPDATE_PERMISSIONS_REPLACE_ALL); 19845 } 19846 } 19847 19848 @Override 19849 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19850 mContext.enforceCallingOrSelfPermission( 19851 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19852 "Only package verification agents can read the verifier device identity"); 19853 19854 synchronized (mPackages) { 19855 return mSettings.getVerifierDeviceIdentityLPw(); 19856 } 19857 } 19858 19859 @Override 19860 public void setPermissionEnforced(String permission, boolean enforced) { 19861 // TODO: Now that we no longer change GID for storage, this should to away. 19862 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19863 "setPermissionEnforced"); 19864 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19865 synchronized (mPackages) { 19866 if (mSettings.mReadExternalStorageEnforced == null 19867 || mSettings.mReadExternalStorageEnforced != enforced) { 19868 mSettings.mReadExternalStorageEnforced = enforced; 19869 mSettings.writeLPr(); 19870 } 19871 } 19872 // kill any non-foreground processes so we restart them and 19873 // grant/revoke the GID. 19874 final IActivityManager am = ActivityManagerNative.getDefault(); 19875 if (am != null) { 19876 final long token = Binder.clearCallingIdentity(); 19877 try { 19878 am.killProcessesBelowForeground("setPermissionEnforcement"); 19879 } catch (RemoteException e) { 19880 } finally { 19881 Binder.restoreCallingIdentity(token); 19882 } 19883 } 19884 } else { 19885 throw new IllegalArgumentException("No selective enforcement for " + permission); 19886 } 19887 } 19888 19889 @Override 19890 @Deprecated 19891 public boolean isPermissionEnforced(String permission) { 19892 return true; 19893 } 19894 19895 @Override 19896 public boolean isStorageLow() { 19897 final long token = Binder.clearCallingIdentity(); 19898 try { 19899 final DeviceStorageMonitorInternal 19900 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19901 if (dsm != null) { 19902 return dsm.isMemoryLow(); 19903 } else { 19904 return false; 19905 } 19906 } finally { 19907 Binder.restoreCallingIdentity(token); 19908 } 19909 } 19910 19911 @Override 19912 public IPackageInstaller getPackageInstaller() { 19913 return mInstallerService; 19914 } 19915 19916 private boolean userNeedsBadging(int userId) { 19917 int index = mUserNeedsBadging.indexOfKey(userId); 19918 if (index < 0) { 19919 final UserInfo userInfo; 19920 final long token = Binder.clearCallingIdentity(); 19921 try { 19922 userInfo = sUserManager.getUserInfo(userId); 19923 } finally { 19924 Binder.restoreCallingIdentity(token); 19925 } 19926 final boolean b; 19927 if (userInfo != null && userInfo.isManagedProfile()) { 19928 b = true; 19929 } else { 19930 b = false; 19931 } 19932 mUserNeedsBadging.put(userId, b); 19933 return b; 19934 } 19935 return mUserNeedsBadging.valueAt(index); 19936 } 19937 19938 @Override 19939 public KeySet getKeySetByAlias(String packageName, String alias) { 19940 if (packageName == null || alias == null) { 19941 return null; 19942 } 19943 synchronized(mPackages) { 19944 final PackageParser.Package pkg = mPackages.get(packageName); 19945 if (pkg == null) { 19946 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19947 throw new IllegalArgumentException("Unknown package: " + packageName); 19948 } 19949 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19950 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19951 } 19952 } 19953 19954 @Override 19955 public KeySet getSigningKeySet(String packageName) { 19956 if (packageName == null) { 19957 return null; 19958 } 19959 synchronized(mPackages) { 19960 final PackageParser.Package pkg = mPackages.get(packageName); 19961 if (pkg == null) { 19962 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19963 throw new IllegalArgumentException("Unknown package: " + packageName); 19964 } 19965 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19966 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19967 throw new SecurityException("May not access signing KeySet of other apps."); 19968 } 19969 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19970 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19971 } 19972 } 19973 19974 @Override 19975 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19976 if (packageName == null || ks == null) { 19977 return false; 19978 } 19979 synchronized(mPackages) { 19980 final PackageParser.Package pkg = mPackages.get(packageName); 19981 if (pkg == null) { 19982 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19983 throw new IllegalArgumentException("Unknown package: " + packageName); 19984 } 19985 IBinder ksh = ks.getToken(); 19986 if (ksh instanceof KeySetHandle) { 19987 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19988 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19989 } 19990 return false; 19991 } 19992 } 19993 19994 @Override 19995 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19996 if (packageName == null || ks == null) { 19997 return false; 19998 } 19999 synchronized(mPackages) { 20000 final PackageParser.Package pkg = mPackages.get(packageName); 20001 if (pkg == null) { 20002 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20003 throw new IllegalArgumentException("Unknown package: " + packageName); 20004 } 20005 IBinder ksh = ks.getToken(); 20006 if (ksh instanceof KeySetHandle) { 20007 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20008 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20009 } 20010 return false; 20011 } 20012 } 20013 20014 private void deletePackageIfUnusedLPr(final String packageName) { 20015 PackageSetting ps = mSettings.mPackages.get(packageName); 20016 if (ps == null) { 20017 return; 20018 } 20019 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20020 // TODO Implement atomic delete if package is unused 20021 // It is currently possible that the package will be deleted even if it is installed 20022 // after this method returns. 20023 mHandler.post(new Runnable() { 20024 public void run() { 20025 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20026 } 20027 }); 20028 } 20029 } 20030 20031 /** 20032 * Check and throw if the given before/after packages would be considered a 20033 * downgrade. 20034 */ 20035 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20036 throws PackageManagerException { 20037 if (after.versionCode < before.mVersionCode) { 20038 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20039 "Update version code " + after.versionCode + " is older than current " 20040 + before.mVersionCode); 20041 } else if (after.versionCode == before.mVersionCode) { 20042 if (after.baseRevisionCode < before.baseRevisionCode) { 20043 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20044 "Update base revision code " + after.baseRevisionCode 20045 + " is older than current " + before.baseRevisionCode); 20046 } 20047 20048 if (!ArrayUtils.isEmpty(after.splitNames)) { 20049 for (int i = 0; i < after.splitNames.length; i++) { 20050 final String splitName = after.splitNames[i]; 20051 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20052 if (j != -1) { 20053 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20054 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20055 "Update split " + splitName + " revision code " 20056 + after.splitRevisionCodes[i] + " is older than current " 20057 + before.splitRevisionCodes[j]); 20058 } 20059 } 20060 } 20061 } 20062 } 20063 } 20064 20065 private static class MoveCallbacks extends Handler { 20066 private static final int MSG_CREATED = 1; 20067 private static final int MSG_STATUS_CHANGED = 2; 20068 20069 private final RemoteCallbackList<IPackageMoveObserver> 20070 mCallbacks = new RemoteCallbackList<>(); 20071 20072 private final SparseIntArray mLastStatus = new SparseIntArray(); 20073 20074 public MoveCallbacks(Looper looper) { 20075 super(looper); 20076 } 20077 20078 public void register(IPackageMoveObserver callback) { 20079 mCallbacks.register(callback); 20080 } 20081 20082 public void unregister(IPackageMoveObserver callback) { 20083 mCallbacks.unregister(callback); 20084 } 20085 20086 @Override 20087 public void handleMessage(Message msg) { 20088 final SomeArgs args = (SomeArgs) msg.obj; 20089 final int n = mCallbacks.beginBroadcast(); 20090 for (int i = 0; i < n; i++) { 20091 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20092 try { 20093 invokeCallback(callback, msg.what, args); 20094 } catch (RemoteException ignored) { 20095 } 20096 } 20097 mCallbacks.finishBroadcast(); 20098 args.recycle(); 20099 } 20100 20101 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20102 throws RemoteException { 20103 switch (what) { 20104 case MSG_CREATED: { 20105 callback.onCreated(args.argi1, (Bundle) args.arg2); 20106 break; 20107 } 20108 case MSG_STATUS_CHANGED: { 20109 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20110 break; 20111 } 20112 } 20113 } 20114 20115 private void notifyCreated(int moveId, Bundle extras) { 20116 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20117 20118 final SomeArgs args = SomeArgs.obtain(); 20119 args.argi1 = moveId; 20120 args.arg2 = extras; 20121 obtainMessage(MSG_CREATED, args).sendToTarget(); 20122 } 20123 20124 private void notifyStatusChanged(int moveId, int status) { 20125 notifyStatusChanged(moveId, status, -1); 20126 } 20127 20128 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20129 Slog.v(TAG, "Move " + moveId + " status " + status); 20130 20131 final SomeArgs args = SomeArgs.obtain(); 20132 args.argi1 = moveId; 20133 args.argi2 = status; 20134 args.arg3 = estMillis; 20135 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20136 20137 synchronized (mLastStatus) { 20138 mLastStatus.put(moveId, status); 20139 } 20140 } 20141 } 20142 20143 private final static class OnPermissionChangeListeners extends Handler { 20144 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20145 20146 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20147 new RemoteCallbackList<>(); 20148 20149 public OnPermissionChangeListeners(Looper looper) { 20150 super(looper); 20151 } 20152 20153 @Override 20154 public void handleMessage(Message msg) { 20155 switch (msg.what) { 20156 case MSG_ON_PERMISSIONS_CHANGED: { 20157 final int uid = msg.arg1; 20158 handleOnPermissionsChanged(uid); 20159 } break; 20160 } 20161 } 20162 20163 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20164 mPermissionListeners.register(listener); 20165 20166 } 20167 20168 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20169 mPermissionListeners.unregister(listener); 20170 } 20171 20172 public void onPermissionsChanged(int uid) { 20173 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20174 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20175 } 20176 } 20177 20178 private void handleOnPermissionsChanged(int uid) { 20179 final int count = mPermissionListeners.beginBroadcast(); 20180 try { 20181 for (int i = 0; i < count; i++) { 20182 IOnPermissionsChangeListener callback = mPermissionListeners 20183 .getBroadcastItem(i); 20184 try { 20185 callback.onPermissionsChanged(uid); 20186 } catch (RemoteException e) { 20187 Log.e(TAG, "Permission listener is dead", e); 20188 } 20189 } 20190 } finally { 20191 mPermissionListeners.finishBroadcast(); 20192 } 20193 } 20194 } 20195 20196 private class PackageManagerInternalImpl extends PackageManagerInternal { 20197 @Override 20198 public void setLocationPackagesProvider(PackagesProvider provider) { 20199 synchronized (mPackages) { 20200 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20201 } 20202 } 20203 20204 @Override 20205 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20206 synchronized (mPackages) { 20207 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20208 } 20209 } 20210 20211 @Override 20212 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20213 synchronized (mPackages) { 20214 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20215 } 20216 } 20217 20218 @Override 20219 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20220 synchronized (mPackages) { 20221 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20222 } 20223 } 20224 20225 @Override 20226 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20227 synchronized (mPackages) { 20228 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20229 } 20230 } 20231 20232 @Override 20233 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20234 synchronized (mPackages) { 20235 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20236 } 20237 } 20238 20239 @Override 20240 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20241 synchronized (mPackages) { 20242 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20243 packageName, userId); 20244 } 20245 } 20246 20247 @Override 20248 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20249 synchronized (mPackages) { 20250 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20251 packageName, userId); 20252 } 20253 } 20254 20255 @Override 20256 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20257 synchronized (mPackages) { 20258 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20259 packageName, userId); 20260 } 20261 } 20262 20263 @Override 20264 public void setKeepUninstalledPackages(final List<String> packageList) { 20265 Preconditions.checkNotNull(packageList); 20266 List<String> removedFromList = null; 20267 synchronized (mPackages) { 20268 if (mKeepUninstalledPackages != null) { 20269 final int packagesCount = mKeepUninstalledPackages.size(); 20270 for (int i = 0; i < packagesCount; i++) { 20271 String oldPackage = mKeepUninstalledPackages.get(i); 20272 if (packageList != null && packageList.contains(oldPackage)) { 20273 continue; 20274 } 20275 if (removedFromList == null) { 20276 removedFromList = new ArrayList<>(); 20277 } 20278 removedFromList.add(oldPackage); 20279 } 20280 } 20281 mKeepUninstalledPackages = new ArrayList<>(packageList); 20282 if (removedFromList != null) { 20283 final int removedCount = removedFromList.size(); 20284 for (int i = 0; i < removedCount; i++) { 20285 deletePackageIfUnusedLPr(removedFromList.get(i)); 20286 } 20287 } 20288 } 20289 } 20290 20291 @Override 20292 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20293 synchronized (mPackages) { 20294 // If we do not support permission review, done. 20295 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20296 return false; 20297 } 20298 20299 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20300 if (packageSetting == null) { 20301 return false; 20302 } 20303 20304 // Permission review applies only to apps not supporting the new permission model. 20305 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20306 return false; 20307 } 20308 20309 // Legacy apps have the permission and get user consent on launch. 20310 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20311 return permissionsState.isPermissionReviewRequired(userId); 20312 } 20313 } 20314 20315 @Override 20316 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20317 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20318 } 20319 20320 @Override 20321 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20322 int userId) { 20323 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20324 } 20325 } 20326 20327 @Override 20328 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20329 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20330 synchronized (mPackages) { 20331 final long identity = Binder.clearCallingIdentity(); 20332 try { 20333 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20334 packageNames, userId); 20335 } finally { 20336 Binder.restoreCallingIdentity(identity); 20337 } 20338 } 20339 } 20340 20341 private static void enforceSystemOrPhoneCaller(String tag) { 20342 int callingUid = Binder.getCallingUid(); 20343 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20344 throw new SecurityException( 20345 "Cannot call " + tag + " from UID " + callingUid); 20346 } 20347 } 20348 20349 boolean isHistoricalPackageUsageAvailable() { 20350 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20351 } 20352 20353 /** 20354 * Return a <b>copy</b> of the collection of packages known to the package manager. 20355 * @return A copy of the values of mPackages. 20356 */ 20357 Collection<PackageParser.Package> getPackages() { 20358 synchronized (mPackages) { 20359 return new ArrayList<>(mPackages.values()); 20360 } 20361 } 20362 20363 /** 20364 * Logs process start information (including base APK hash) to the security log. 20365 * @hide 20366 */ 20367 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20368 String apkFile, int pid) { 20369 if (!SecurityLog.isLoggingEnabled()) { 20370 return; 20371 } 20372 Bundle data = new Bundle(); 20373 data.putLong("startTimestamp", System.currentTimeMillis()); 20374 data.putString("processName", processName); 20375 data.putInt("uid", uid); 20376 data.putString("seinfo", seinfo); 20377 data.putString("apkFile", apkFile); 20378 data.putInt("pid", pid); 20379 Message msg = mProcessLoggingHandler.obtainMessage( 20380 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20381 msg.setData(data); 20382 mProcessLoggingHandler.sendMessage(msg); 20383 } 20384} 20385