PackageManagerService.java revision f2812853b820ad994be2b9c42e7905f61e4a0106
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.FileInputStream; 270import java.io.FileNotFoundException; 271import java.io.FileOutputStream; 272import java.io.FileReader; 273import java.io.FilenameFilter; 274import java.io.IOException; 275import java.io.InputStream; 276import java.io.PrintWriter; 277import java.nio.charset.StandardCharsets; 278import java.security.DigestInputStream; 279import java.security.MessageDigest; 280import java.security.NoSuchAlgorithmException; 281import java.security.PublicKey; 282import java.security.cert.Certificate; 283import java.security.cert.CertificateEncodingException; 284import java.security.cert.CertificateException; 285import java.text.SimpleDateFormat; 286import java.util.ArrayList; 287import java.util.Arrays; 288import java.util.Collection; 289import java.util.Collections; 290import java.util.Comparator; 291import java.util.Date; 292import java.util.HashSet; 293import java.util.Iterator; 294import java.util.List; 295import java.util.Map; 296import java.util.Objects; 297import java.util.Set; 298import java.util.concurrent.CountDownLatch; 299import java.util.concurrent.TimeUnit; 300import java.util.concurrent.atomic.AtomicBoolean; 301import java.util.concurrent.atomic.AtomicInteger; 302import java.util.concurrent.atomic.AtomicLong; 303 304/** 305 * Keep track of all those APKs everywhere. 306 * <p> 307 * Internally there are two important locks: 308 * <ul> 309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 310 * and other related state. It is a fine-grained lock that should only be held 311 * momentarily, as it's one of the most contended locks in the system. 312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 313 * operations typically involve heavy lifting of application data on disk. Since 314 * {@code installd} is single-threaded, and it's operations can often be slow, 315 * this lock should never be acquired while already holding {@link #mPackages}. 316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 317 * holding {@link #mInstallLock}. 318 * </ul> 319 * Many internal methods rely on the caller to hold the appropriate locks, and 320 * this contract is expressed through method name suffixes: 321 * <ul> 322 * <li>fooLI(): the caller must hold {@link #mInstallLock} 323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 324 * being modified must be frozen 325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 327 * </ul> 328 * <p> 329 * Because this class is very central to the platform's security; please run all 330 * CTS and unit tests whenever making modifications: 331 * 332 * <pre> 333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 335 * </pre> 336 */ 337public class PackageManagerService extends IPackageManager.Stub { 338 static final String TAG = "PackageManager"; 339 static final boolean DEBUG_SETTINGS = false; 340 static final boolean DEBUG_PREFERRED = false; 341 static final boolean DEBUG_UPGRADE = false; 342 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 343 private static final boolean DEBUG_BACKUP = false; 344 private static final boolean DEBUG_INSTALL = false; 345 private static final boolean DEBUG_REMOVE = false; 346 private static final boolean DEBUG_BROADCASTS = false; 347 private static final boolean DEBUG_SHOW_INFO = false; 348 private static final boolean DEBUG_PACKAGE_INFO = false; 349 private static final boolean DEBUG_INTENT_MATCHING = false; 350 private static final boolean DEBUG_PACKAGE_SCANNING = false; 351 private static final boolean DEBUG_VERIFY = false; 352 private static final boolean DEBUG_FILTERS = false; 353 354 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 355 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 356 // user, but by default initialize to this. 357 static final boolean DEBUG_DEXOPT = false; 358 359 private static final boolean DEBUG_ABI_SELECTION = false; 360 private static final boolean DEBUG_EPHEMERAL = false; 361 private static final boolean DEBUG_TRIAGED_MISSING = false; 362 private static final boolean DEBUG_APP_DATA = false; 363 364 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 365 366 private static final boolean DISABLE_EPHEMERAL_APPS = true; 367 368 private static final int RADIO_UID = Process.PHONE_UID; 369 private static final int LOG_UID = Process.LOG_UID; 370 private static final int NFC_UID = Process.NFC_UID; 371 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 372 private static final int SHELL_UID = Process.SHELL_UID; 373 374 // Cap the size of permission trees that 3rd party apps can define 375 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 376 377 // Suffix used during package installation when copying/moving 378 // package apks to install directory. 379 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 380 381 static final int SCAN_NO_DEX = 1<<1; 382 static final int SCAN_FORCE_DEX = 1<<2; 383 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 384 static final int SCAN_NEW_INSTALL = 1<<4; 385 static final int SCAN_NO_PATHS = 1<<5; 386 static final int SCAN_UPDATE_TIME = 1<<6; 387 static final int SCAN_DEFER_DEX = 1<<7; 388 static final int SCAN_BOOTING = 1<<8; 389 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 390 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 391 static final int SCAN_REPLACING = 1<<11; 392 static final int SCAN_REQUIRE_KNOWN = 1<<12; 393 static final int SCAN_MOVE = 1<<13; 394 static final int SCAN_INITIAL = 1<<14; 395 static final int SCAN_CHECK_ONLY = 1<<15; 396 static final int SCAN_DONT_KILL_APP = 1<<17; 397 static final int SCAN_IGNORE_FROZEN = 1<<18; 398 399 static final int REMOVE_CHATTY = 1<<16; 400 401 private static final int[] EMPTY_INT_ARRAY = new int[0]; 402 403 /** 404 * Timeout (in milliseconds) after which the watchdog should declare that 405 * our handler thread is wedged. The usual default for such things is one 406 * minute but we sometimes do very lengthy I/O operations on this thread, 407 * such as installing multi-gigabyte applications, so ours needs to be longer. 408 */ 409 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 410 411 /** 412 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 413 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 414 * settings entry if available, otherwise we use the hardcoded default. If it's been 415 * more than this long since the last fstrim, we force one during the boot sequence. 416 * 417 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 418 * one gets run at the next available charging+idle time. This final mandatory 419 * no-fstrim check kicks in only of the other scheduling criteria is never met. 420 */ 421 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 422 423 /** 424 * Whether verification is enabled by default. 425 */ 426 private static final boolean DEFAULT_VERIFY_ENABLE = true; 427 428 /** 429 * The default maximum time to wait for the verification agent to return in 430 * milliseconds. 431 */ 432 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 433 434 /** 435 * The default response for package verification timeout. 436 * 437 * This can be either PackageManager.VERIFICATION_ALLOW or 438 * PackageManager.VERIFICATION_REJECT. 439 */ 440 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 441 442 static final String PLATFORM_PACKAGE_NAME = "android"; 443 444 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 445 446 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 447 DEFAULT_CONTAINER_PACKAGE, 448 "com.android.defcontainer.DefaultContainerService"); 449 450 private static final String KILL_APP_REASON_GIDS_CHANGED = 451 "permission grant or revoke changed gids"; 452 453 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 454 "permissions revoked"; 455 456 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 457 458 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 459 460 /** Permission grant: not grant the permission. */ 461 private static final int GRANT_DENIED = 1; 462 463 /** Permission grant: grant the permission as an install permission. */ 464 private static final int GRANT_INSTALL = 2; 465 466 /** Permission grant: grant the permission as a runtime one. */ 467 private static final int GRANT_RUNTIME = 3; 468 469 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 470 private static final int GRANT_UPGRADE = 4; 471 472 /** Canonical intent used to identify what counts as a "web browser" app */ 473 private static final Intent sBrowserIntent; 474 static { 475 sBrowserIntent = new Intent(); 476 sBrowserIntent.setAction(Intent.ACTION_VIEW); 477 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 478 sBrowserIntent.setData(Uri.parse("http:")); 479 } 480 481 /** 482 * The set of all protected actions [i.e. those actions for which a high priority 483 * intent filter is disallowed]. 484 */ 485 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 486 static { 487 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 488 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 489 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 490 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 491 } 492 493 // Compilation reasons. 494 public static final int REASON_FIRST_BOOT = 0; 495 public static final int REASON_BOOT = 1; 496 public static final int REASON_INSTALL = 2; 497 public static final int REASON_BACKGROUND_DEXOPT = 3; 498 public static final int REASON_AB_OTA = 4; 499 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 500 public static final int REASON_SHARED_APK = 6; 501 public static final int REASON_FORCED_DEXOPT = 7; 502 503 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 504 505 /** Special library name that skips shared libraries check during compilation. */ 506 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 507 508 final ServiceThread mHandlerThread; 509 510 final PackageHandler mHandler; 511 512 private final ProcessLoggingHandler mProcessLoggingHandler; 513 514 /** 515 * Messages for {@link #mHandler} that need to wait for system ready before 516 * being dispatched. 517 */ 518 private ArrayList<Message> mPostSystemReadyMessages; 519 520 final int mSdkVersion = Build.VERSION.SDK_INT; 521 522 final Context mContext; 523 final boolean mFactoryTest; 524 final boolean mOnlyCore; 525 final DisplayMetrics mMetrics; 526 final int mDefParseFlags; 527 final String[] mSeparateProcesses; 528 final boolean mIsUpgrade; 529 final boolean mIsPreNUpgrade; 530 531 /** The location for ASEC container files on internal storage. */ 532 final String mAsecInternalPath; 533 534 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 535 // LOCK HELD. Can be called with mInstallLock held. 536 @GuardedBy("mInstallLock") 537 final Installer mInstaller; 538 539 /** Directory where installed third-party apps stored */ 540 final File mAppInstallDir; 541 final File mEphemeralInstallDir; 542 543 /** 544 * Directory to which applications installed internally have their 545 * 32 bit native libraries copied. 546 */ 547 private File mAppLib32InstallDir; 548 549 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 550 // apps. 551 final File mDrmAppPrivateInstallDir; 552 553 // ---------------------------------------------------------------- 554 555 // Lock for state used when installing and doing other long running 556 // operations. Methods that must be called with this lock held have 557 // the suffix "LI". 558 final Object mInstallLock = new Object(); 559 560 // ---------------------------------------------------------------- 561 562 // Keys are String (package name), values are Package. This also serves 563 // as the lock for the global state. Methods that must be called with 564 // this lock held have the prefix "LP". 565 @GuardedBy("mPackages") 566 final ArrayMap<String, PackageParser.Package> mPackages = 567 new ArrayMap<String, PackageParser.Package>(); 568 569 final ArrayMap<String, Set<String>> mKnownCodebase = 570 new ArrayMap<String, Set<String>>(); 571 572 // Tracks available target package names -> overlay package paths. 573 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 574 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 575 576 /** 577 * Tracks new system packages [received in an OTA] that we expect to 578 * find updated user-installed versions. Keys are package name, values 579 * are package location. 580 */ 581 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 582 /** 583 * Tracks high priority intent filters for protected actions. During boot, certain 584 * filter actions are protected and should never be allowed to have a high priority 585 * intent filter for them. However, there is one, and only one exception -- the 586 * setup wizard. It must be able to define a high priority intent filter for these 587 * actions to ensure there are no escapes from the wizard. We need to delay processing 588 * of these during boot as we need to look at all of the system packages in order 589 * to know which component is the setup wizard. 590 */ 591 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 592 /** 593 * Whether or not processing protected filters should be deferred. 594 */ 595 private boolean mDeferProtectedFilters = true; 596 597 /** 598 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 599 */ 600 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 601 /** 602 * Whether or not system app permissions should be promoted from install to runtime. 603 */ 604 boolean mPromoteSystemApps; 605 606 @GuardedBy("mPackages") 607 final Settings mSettings; 608 609 /** 610 * Set of package names that are currently "frozen", which means active 611 * surgery is being done on the code/data for that package. The platform 612 * will refuse to launch frozen packages to avoid race conditions. 613 * 614 * @see PackageFreezer 615 */ 616 @GuardedBy("mPackages") 617 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 618 619 boolean mRestoredSettings; 620 621 // System configuration read by SystemConfig. 622 final int[] mGlobalGids; 623 final SparseArray<ArraySet<String>> mSystemPermissions; 624 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 625 626 // If mac_permissions.xml was found for seinfo labeling. 627 boolean mFoundPolicyFile; 628 629 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 630 631 public static final class SharedLibraryEntry { 632 public final String path; 633 public final String apk; 634 635 SharedLibraryEntry(String _path, String _apk) { 636 path = _path; 637 apk = _apk; 638 } 639 } 640 641 // Currently known shared libraries. 642 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 643 new ArrayMap<String, SharedLibraryEntry>(); 644 645 // All available activities, for your resolving pleasure. 646 final ActivityIntentResolver mActivities = 647 new ActivityIntentResolver(); 648 649 // All available receivers, for your resolving pleasure. 650 final ActivityIntentResolver mReceivers = 651 new ActivityIntentResolver(); 652 653 // All available services, for your resolving pleasure. 654 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 655 656 // All available providers, for your resolving pleasure. 657 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 658 659 // Mapping from provider base names (first directory in content URI codePath) 660 // to the provider information. 661 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 662 new ArrayMap<String, PackageParser.Provider>(); 663 664 // Mapping from instrumentation class names to info about them. 665 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 666 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 667 668 // Mapping from permission names to info about them. 669 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 670 new ArrayMap<String, PackageParser.PermissionGroup>(); 671 672 // Packages whose data we have transfered into another package, thus 673 // should no longer exist. 674 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 675 676 // Broadcast actions that are only available to the system. 677 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 678 679 /** List of packages waiting for verification. */ 680 final SparseArray<PackageVerificationState> mPendingVerification 681 = new SparseArray<PackageVerificationState>(); 682 683 /** Set of packages associated with each app op permission. */ 684 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 685 686 final PackageInstallerService mInstallerService; 687 688 private final PackageDexOptimizer mPackageDexOptimizer; 689 690 private AtomicInteger mNextMoveId = new AtomicInteger(); 691 private final MoveCallbacks mMoveCallbacks; 692 693 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 694 695 // Cache of users who need badging. 696 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 697 698 /** Token for keys in mPendingVerification. */ 699 private int mPendingVerificationToken = 0; 700 701 volatile boolean mSystemReady; 702 volatile boolean mSafeMode; 703 volatile boolean mHasSystemUidErrors; 704 705 ApplicationInfo mAndroidApplication; 706 final ActivityInfo mResolveActivity = new ActivityInfo(); 707 final ResolveInfo mResolveInfo = new ResolveInfo(); 708 ComponentName mResolveComponentName; 709 PackageParser.Package mPlatformPackage; 710 ComponentName mCustomResolverComponentName; 711 712 boolean mResolverReplaced = false; 713 714 private final @Nullable ComponentName mIntentFilterVerifierComponent; 715 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 716 717 private int mIntentFilterVerificationToken = 0; 718 719 /** Component that knows whether or not an ephemeral application exists */ 720 final ComponentName mEphemeralResolverComponent; 721 /** The service connection to the ephemeral resolver */ 722 final EphemeralResolverConnection mEphemeralResolverConnection; 723 724 /** Component used to install ephemeral applications */ 725 final ComponentName mEphemeralInstallerComponent; 726 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 727 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 728 729 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 730 = new SparseArray<IntentFilterVerificationState>(); 731 732 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 733 new DefaultPermissionGrantPolicy(this); 734 735 // List of packages names to keep cached, even if they are uninstalled for all users 736 private List<String> mKeepUninstalledPackages; 737 738 private static class IFVerificationParams { 739 PackageParser.Package pkg; 740 boolean replacing; 741 int userId; 742 int verifierUid; 743 744 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 745 int _userId, int _verifierUid) { 746 pkg = _pkg; 747 replacing = _replacing; 748 userId = _userId; 749 replacing = _replacing; 750 verifierUid = _verifierUid; 751 } 752 } 753 754 private interface IntentFilterVerifier<T extends IntentFilter> { 755 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 756 T filter, String packageName); 757 void startVerifications(int userId); 758 void receiveVerificationResponse(int verificationId); 759 } 760 761 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 762 private Context mContext; 763 private ComponentName mIntentFilterVerifierComponent; 764 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 765 766 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 767 mContext = context; 768 mIntentFilterVerifierComponent = verifierComponent; 769 } 770 771 private String getDefaultScheme() { 772 return IntentFilter.SCHEME_HTTPS; 773 } 774 775 @Override 776 public void startVerifications(int userId) { 777 // Launch verifications requests 778 int count = mCurrentIntentFilterVerifications.size(); 779 for (int n=0; n<count; n++) { 780 int verificationId = mCurrentIntentFilterVerifications.get(n); 781 final IntentFilterVerificationState ivs = 782 mIntentFilterVerificationStates.get(verificationId); 783 784 String packageName = ivs.getPackageName(); 785 786 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 787 final int filterCount = filters.size(); 788 ArraySet<String> domainsSet = new ArraySet<>(); 789 for (int m=0; m<filterCount; m++) { 790 PackageParser.ActivityIntentInfo filter = filters.get(m); 791 domainsSet.addAll(filter.getHostsList()); 792 } 793 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 794 synchronized (mPackages) { 795 if (mSettings.createIntentFilterVerificationIfNeededLPw( 796 packageName, domainsList) != null) { 797 scheduleWriteSettingsLocked(); 798 } 799 } 800 sendVerificationRequest(userId, verificationId, ivs); 801 } 802 mCurrentIntentFilterVerifications.clear(); 803 } 804 805 private void sendVerificationRequest(int userId, int verificationId, 806 IntentFilterVerificationState ivs) { 807 808 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 809 verificationIntent.putExtra( 810 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 811 verificationId); 812 verificationIntent.putExtra( 813 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 814 getDefaultScheme()); 815 verificationIntent.putExtra( 816 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 817 ivs.getHostsString()); 818 verificationIntent.putExtra( 819 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 820 ivs.getPackageName()); 821 verificationIntent.setComponent(mIntentFilterVerifierComponent); 822 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 823 824 UserHandle user = new UserHandle(userId); 825 mContext.sendBroadcastAsUser(verificationIntent, user); 826 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 827 "Sending IntentFilter verification broadcast"); 828 } 829 830 public void receiveVerificationResponse(int verificationId) { 831 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 832 833 final boolean verified = ivs.isVerified(); 834 835 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 836 final int count = filters.size(); 837 if (DEBUG_DOMAIN_VERIFICATION) { 838 Slog.i(TAG, "Received verification response " + verificationId 839 + " for " + count + " filters, verified=" + verified); 840 } 841 for (int n=0; n<count; n++) { 842 PackageParser.ActivityIntentInfo filter = filters.get(n); 843 filter.setVerified(verified); 844 845 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 846 + " verified with result:" + verified + " and hosts:" 847 + ivs.getHostsString()); 848 } 849 850 mIntentFilterVerificationStates.remove(verificationId); 851 852 final String packageName = ivs.getPackageName(); 853 IntentFilterVerificationInfo ivi = null; 854 855 synchronized (mPackages) { 856 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 857 } 858 if (ivi == null) { 859 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 860 + verificationId + " packageName:" + packageName); 861 return; 862 } 863 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 864 "Updating IntentFilterVerificationInfo for package " + packageName 865 +" verificationId:" + verificationId); 866 867 synchronized (mPackages) { 868 if (verified) { 869 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 870 } else { 871 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 872 } 873 scheduleWriteSettingsLocked(); 874 875 final int userId = ivs.getUserId(); 876 if (userId != UserHandle.USER_ALL) { 877 final int userStatus = 878 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 879 880 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 881 boolean needUpdate = false; 882 883 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 884 // already been set by the User thru the Disambiguation dialog 885 switch (userStatus) { 886 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 887 if (verified) { 888 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 889 } else { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 891 } 892 needUpdate = true; 893 break; 894 895 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 896 if (verified) { 897 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 898 needUpdate = true; 899 } 900 break; 901 902 default: 903 // Nothing to do 904 } 905 906 if (needUpdate) { 907 mSettings.updateIntentFilterVerificationStatusLPw( 908 packageName, updatedStatus, userId); 909 scheduleWritePackageRestrictionsLocked(userId); 910 } 911 } 912 } 913 } 914 915 @Override 916 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 917 ActivityIntentInfo filter, String packageName) { 918 if (!hasValidDomains(filter)) { 919 return false; 920 } 921 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 922 if (ivs == null) { 923 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 924 packageName); 925 } 926 if (DEBUG_DOMAIN_VERIFICATION) { 927 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 928 } 929 ivs.addFilter(filter); 930 return true; 931 } 932 933 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 934 int userId, int verificationId, String packageName) { 935 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 936 verifierUid, userId, packageName); 937 ivs.setPendingState(); 938 synchronized (mPackages) { 939 mIntentFilterVerificationStates.append(verificationId, ivs); 940 mCurrentIntentFilterVerifications.add(verificationId); 941 } 942 return ivs; 943 } 944 } 945 946 private static boolean hasValidDomains(ActivityIntentInfo filter) { 947 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 948 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 949 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 950 } 951 952 // Set of pending broadcasts for aggregating enable/disable of components. 953 static class PendingPackageBroadcasts { 954 // for each user id, a map of <package name -> components within that package> 955 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 956 957 public PendingPackageBroadcasts() { 958 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 959 } 960 961 public ArrayList<String> get(int userId, String packageName) { 962 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 963 return packages.get(packageName); 964 } 965 966 public void put(int userId, String packageName, ArrayList<String> components) { 967 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 968 packages.put(packageName, components); 969 } 970 971 public void remove(int userId, String packageName) { 972 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 973 if (packages != null) { 974 packages.remove(packageName); 975 } 976 } 977 978 public void remove(int userId) { 979 mUidMap.remove(userId); 980 } 981 982 public int userIdCount() { 983 return mUidMap.size(); 984 } 985 986 public int userIdAt(int n) { 987 return mUidMap.keyAt(n); 988 } 989 990 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 991 return mUidMap.get(userId); 992 } 993 994 public int size() { 995 // total number of pending broadcast entries across all userIds 996 int num = 0; 997 for (int i = 0; i< mUidMap.size(); i++) { 998 num += mUidMap.valueAt(i).size(); 999 } 1000 return num; 1001 } 1002 1003 public void clear() { 1004 mUidMap.clear(); 1005 } 1006 1007 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1008 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1009 if (map == null) { 1010 map = new ArrayMap<String, ArrayList<String>>(); 1011 mUidMap.put(userId, map); 1012 } 1013 return map; 1014 } 1015 } 1016 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1017 1018 // Service Connection to remote media container service to copy 1019 // package uri's from external media onto secure containers 1020 // or internal storage. 1021 private IMediaContainerService mContainerService = null; 1022 1023 static final int SEND_PENDING_BROADCAST = 1; 1024 static final int MCS_BOUND = 3; 1025 static final int END_COPY = 4; 1026 static final int INIT_COPY = 5; 1027 static final int MCS_UNBIND = 6; 1028 static final int START_CLEANING_PACKAGE = 7; 1029 static final int FIND_INSTALL_LOC = 8; 1030 static final int POST_INSTALL = 9; 1031 static final int MCS_RECONNECT = 10; 1032 static final int MCS_GIVE_UP = 11; 1033 static final int UPDATED_MEDIA_STATUS = 12; 1034 static final int WRITE_SETTINGS = 13; 1035 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1036 static final int PACKAGE_VERIFIED = 15; 1037 static final int CHECK_PENDING_VERIFICATION = 16; 1038 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1039 static final int INTENT_FILTER_VERIFIED = 18; 1040 1041 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1042 1043 // Delay time in millisecs 1044 static final int BROADCAST_DELAY = 10 * 1000; 1045 1046 static UserManagerService sUserManager; 1047 1048 // Stores a list of users whose package restrictions file needs to be updated 1049 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1050 1051 final private DefaultContainerConnection mDefContainerConn = 1052 new DefaultContainerConnection(); 1053 class DefaultContainerConnection implements ServiceConnection { 1054 public void onServiceConnected(ComponentName name, IBinder service) { 1055 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1056 IMediaContainerService imcs = 1057 IMediaContainerService.Stub.asInterface(service); 1058 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1059 } 1060 1061 public void onServiceDisconnected(ComponentName name) { 1062 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1063 } 1064 } 1065 1066 // Recordkeeping of restore-after-install operations that are currently in flight 1067 // between the Package Manager and the Backup Manager 1068 static class PostInstallData { 1069 public InstallArgs args; 1070 public PackageInstalledInfo res; 1071 1072 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1073 args = _a; 1074 res = _r; 1075 } 1076 } 1077 1078 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1079 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1080 1081 // XML tags for backup/restore of various bits of state 1082 private static final String TAG_PREFERRED_BACKUP = "pa"; 1083 private static final String TAG_DEFAULT_APPS = "da"; 1084 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1085 1086 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1087 private static final String TAG_ALL_GRANTS = "rt-grants"; 1088 private static final String TAG_GRANT = "grant"; 1089 private static final String ATTR_PACKAGE_NAME = "pkg"; 1090 1091 private static final String TAG_PERMISSION = "perm"; 1092 private static final String ATTR_PERMISSION_NAME = "name"; 1093 private static final String ATTR_IS_GRANTED = "g"; 1094 private static final String ATTR_USER_SET = "set"; 1095 private static final String ATTR_USER_FIXED = "fixed"; 1096 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1097 1098 // System/policy permission grants are not backed up 1099 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1100 FLAG_PERMISSION_POLICY_FIXED 1101 | FLAG_PERMISSION_SYSTEM_FIXED 1102 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1103 1104 // And we back up these user-adjusted states 1105 private static final int USER_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_USER_SET 1107 | FLAG_PERMISSION_USER_FIXED 1108 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1109 1110 final @Nullable String mRequiredVerifierPackage; 1111 final @NonNull String mRequiredInstallerPackage; 1112 final @Nullable String mSetupWizardPackage; 1113 final @NonNull String mServicesSystemSharedLibraryPackageName; 1114 final @NonNull String mSharedSystemSharedLibraryPackageName; 1115 1116 private final PackageUsage mPackageUsage = new PackageUsage(); 1117 1118 private class PackageUsage { 1119 private static final int WRITE_INTERVAL 1120 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1121 1122 private final Object mFileLock = new Object(); 1123 private final AtomicLong mLastWritten = new AtomicLong(0); 1124 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1125 1126 private boolean mIsHistoricalPackageUsageAvailable = true; 1127 1128 boolean isHistoricalPackageUsageAvailable() { 1129 return mIsHistoricalPackageUsageAvailable; 1130 } 1131 1132 void write(boolean force) { 1133 if (force) { 1134 writeInternal(); 1135 return; 1136 } 1137 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1138 && !DEBUG_DEXOPT) { 1139 return; 1140 } 1141 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1142 new Thread("PackageUsage_DiskWriter") { 1143 @Override 1144 public void run() { 1145 try { 1146 writeInternal(); 1147 } finally { 1148 mBackgroundWriteRunning.set(false); 1149 } 1150 } 1151 }.start(); 1152 } 1153 } 1154 1155 private void writeInternal() { 1156 synchronized (mPackages) { 1157 synchronized (mFileLock) { 1158 AtomicFile file = getFile(); 1159 FileOutputStream f = null; 1160 try { 1161 f = file.startWrite(); 1162 BufferedOutputStream out = new BufferedOutputStream(f); 1163 FileUtils.setPermissions(file.getBaseFile().getPath(), 1164 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1165 StringBuilder sb = new StringBuilder(); 1166 1167 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1168 sb.append('\n'); 1169 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1170 1171 for (PackageParser.Package pkg : mPackages.values()) { 1172 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1173 continue; 1174 } 1175 sb.setLength(0); 1176 sb.append(pkg.packageName); 1177 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1178 sb.append(' '); 1179 sb.append(usageTimeInMillis); 1180 } 1181 sb.append('\n'); 1182 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1183 } 1184 out.flush(); 1185 file.finishWrite(f); 1186 } catch (IOException e) { 1187 if (f != null) { 1188 file.failWrite(f); 1189 } 1190 Log.e(TAG, "Failed to write package usage times", e); 1191 } 1192 } 1193 } 1194 mLastWritten.set(SystemClock.elapsedRealtime()); 1195 } 1196 1197 void readLP() { 1198 synchronized (mFileLock) { 1199 AtomicFile file = getFile(); 1200 BufferedInputStream in = null; 1201 try { 1202 in = new BufferedInputStream(file.openRead()); 1203 StringBuffer sb = new StringBuffer(); 1204 1205 String firstLine = readLine(in, sb); 1206 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1207 readVersion1LP(in, sb); 1208 } else { 1209 readVersion0LP(in, sb, firstLine); 1210 } 1211 } catch (FileNotFoundException expected) { 1212 mIsHistoricalPackageUsageAvailable = false; 1213 } catch (IOException e) { 1214 Log.w(TAG, "Failed to read package usage times", e); 1215 } finally { 1216 IoUtils.closeQuietly(in); 1217 } 1218 } 1219 mLastWritten.set(SystemClock.elapsedRealtime()); 1220 } 1221 1222 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1223 throws IOException { 1224 // Initial version of the file had no version number and stored one 1225 // package-timestamp pair per line. 1226 // Note that the first line has already been read from the InputStream. 1227 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1228 String[] tokens = line.split(" "); 1229 if (tokens.length != 2) { 1230 throw new IOException("Failed to parse " + line + 1231 " as package-timestamp pair."); 1232 } 1233 1234 String packageName = tokens[0]; 1235 PackageParser.Package pkg = mPackages.get(packageName); 1236 if (pkg == null) { 1237 continue; 1238 } 1239 1240 long timestamp = parseAsLong(tokens[1]); 1241 for (int reason = 0; 1242 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1243 reason++) { 1244 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1245 } 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 for (String permission : pkg.requestedPermissions) { 2066 final BasePermission bp; 2067 synchronized (mPackages) { 2068 bp = mSettings.mPermissions.get(permission); 2069 } 2070 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2071 && (grantedPermissions == null 2072 || ArrayUtils.contains(grantedPermissions, permission))) { 2073 final int flags = permissionsState.getPermissionFlags(permission, userId); 2074 // Installer cannot change immutable permissions. 2075 if ((flags & immutableFlags) == 0) { 2076 grantRuntimePermission(pkg.packageName, permission, userId); 2077 } 2078 } 2079 } 2080 } 2081 2082 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2083 Bundle extras = null; 2084 switch (res.returnCode) { 2085 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2086 extras = new Bundle(); 2087 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2088 res.origPermission); 2089 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2090 res.origPackage); 2091 break; 2092 } 2093 case PackageManager.INSTALL_SUCCEEDED: { 2094 extras = new Bundle(); 2095 extras.putBoolean(Intent.EXTRA_REPLACING, 2096 res.removedInfo != null && res.removedInfo.removedPackage != null); 2097 break; 2098 } 2099 } 2100 return extras; 2101 } 2102 2103 void scheduleWriteSettingsLocked() { 2104 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2105 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2106 } 2107 } 2108 2109 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2110 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2111 scheduleWritePackageRestrictionsLocked(userId); 2112 } 2113 2114 void scheduleWritePackageRestrictionsLocked(int userId) { 2115 final int[] userIds = (userId == UserHandle.USER_ALL) 2116 ? sUserManager.getUserIds() : new int[]{userId}; 2117 for (int nextUserId : userIds) { 2118 if (!sUserManager.exists(nextUserId)) return; 2119 mDirtyUsers.add(nextUserId); 2120 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2121 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2122 } 2123 } 2124 } 2125 2126 public static PackageManagerService main(Context context, Installer installer, 2127 boolean factoryTest, boolean onlyCore) { 2128 // Self-check for initial settings. 2129 PackageManagerServiceCompilerMapping.checkProperties(); 2130 2131 PackageManagerService m = new PackageManagerService(context, installer, 2132 factoryTest, onlyCore); 2133 m.enableSystemUserPackages(); 2134 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2135 // disabled after already being started. 2136 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2137 UserHandle.USER_SYSTEM); 2138 ServiceManager.addService("package", m); 2139 return m; 2140 } 2141 2142 private void enableSystemUserPackages() { 2143 if (!UserManager.isSplitSystemUser()) { 2144 return; 2145 } 2146 // For system user, enable apps based on the following conditions: 2147 // - app is whitelisted or belong to one of these groups: 2148 // -- system app which has no launcher icons 2149 // -- system app which has INTERACT_ACROSS_USERS permission 2150 // -- system IME app 2151 // - app is not in the blacklist 2152 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2153 Set<String> enableApps = new ArraySet<>(); 2154 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2155 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2156 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2157 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2158 enableApps.addAll(wlApps); 2159 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2160 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2161 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2162 enableApps.removeAll(blApps); 2163 Log.i(TAG, "Applications installed for system user: " + enableApps); 2164 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2165 UserHandle.SYSTEM); 2166 final int allAppsSize = allAps.size(); 2167 synchronized (mPackages) { 2168 for (int i = 0; i < allAppsSize; i++) { 2169 String pName = allAps.get(i); 2170 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2171 // Should not happen, but we shouldn't be failing if it does 2172 if (pkgSetting == null) { 2173 continue; 2174 } 2175 boolean install = enableApps.contains(pName); 2176 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2177 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2178 + " for system user"); 2179 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2180 } 2181 } 2182 } 2183 } 2184 2185 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2186 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2187 Context.DISPLAY_SERVICE); 2188 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2189 } 2190 2191 public PackageManagerService(Context context, Installer installer, 2192 boolean factoryTest, boolean onlyCore) { 2193 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2194 SystemClock.uptimeMillis()); 2195 2196 if (mSdkVersion <= 0) { 2197 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2198 } 2199 2200 mContext = context; 2201 mFactoryTest = factoryTest; 2202 mOnlyCore = onlyCore; 2203 mMetrics = new DisplayMetrics(); 2204 mSettings = new Settings(mPackages); 2205 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2206 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2207 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2208 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2209 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2210 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2211 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 2218 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2219 if (separateProcesses != null && separateProcesses.length() > 0) { 2220 if ("*".equals(separateProcesses)) { 2221 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2222 mSeparateProcesses = null; 2223 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2224 } else { 2225 mDefParseFlags = 0; 2226 mSeparateProcesses = separateProcesses.split(","); 2227 Slog.w(TAG, "Running with debug.separate_processes: " 2228 + separateProcesses); 2229 } 2230 } else { 2231 mDefParseFlags = 0; 2232 mSeparateProcesses = null; 2233 } 2234 2235 mInstaller = installer; 2236 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2237 "*dexopt*"); 2238 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2239 2240 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2241 FgThread.get().getLooper()); 2242 2243 getDefaultDisplayMetrics(context, mMetrics); 2244 2245 SystemConfig systemConfig = SystemConfig.getInstance(); 2246 mGlobalGids = systemConfig.getGlobalGids(); 2247 mSystemPermissions = systemConfig.getSystemPermissions(); 2248 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2249 2250 synchronized (mInstallLock) { 2251 // writer 2252 synchronized (mPackages) { 2253 mHandlerThread = new ServiceThread(TAG, 2254 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2255 mHandlerThread.start(); 2256 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2257 mProcessLoggingHandler = new ProcessLoggingHandler(); 2258 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2259 2260 File dataDir = Environment.getDataDirectory(); 2261 mAppInstallDir = new File(dataDir, "app"); 2262 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2263 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2264 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2265 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2266 2267 sUserManager = new UserManagerService(context, this, mPackages); 2268 2269 // Propagate permission configuration in to package manager. 2270 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2271 = systemConfig.getPermissions(); 2272 for (int i=0; i<permConfig.size(); i++) { 2273 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2274 BasePermission bp = mSettings.mPermissions.get(perm.name); 2275 if (bp == null) { 2276 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2277 mSettings.mPermissions.put(perm.name, bp); 2278 } 2279 if (perm.gids != null) { 2280 bp.setGids(perm.gids, perm.perUser); 2281 } 2282 } 2283 2284 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2285 for (int i=0; i<libConfig.size(); i++) { 2286 mSharedLibraries.put(libConfig.keyAt(i), 2287 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2288 } 2289 2290 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2291 2292 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2293 2294 String customResolverActivity = Resources.getSystem().getString( 2295 R.string.config_customResolverActivity); 2296 if (TextUtils.isEmpty(customResolverActivity)) { 2297 customResolverActivity = null; 2298 } else { 2299 mCustomResolverComponentName = ComponentName.unflattenFromString( 2300 customResolverActivity); 2301 } 2302 2303 long startTime = SystemClock.uptimeMillis(); 2304 2305 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2306 startTime); 2307 2308 // Set flag to monitor and not change apk file paths when 2309 // scanning install directories. 2310 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2311 2312 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2313 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2314 2315 if (bootClassPath == null) { 2316 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2317 } 2318 2319 if (systemServerClassPath == null) { 2320 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2321 } 2322 2323 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2324 final String[] dexCodeInstructionSets = 2325 getDexCodeInstructionSets( 2326 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2327 2328 /** 2329 * Ensure all external libraries have had dexopt run on them. 2330 */ 2331 if (mSharedLibraries.size() > 0) { 2332 // NOTE: For now, we're compiling these system "shared libraries" 2333 // (and framework jars) into all available architectures. It's possible 2334 // to compile them only when we come across an app that uses them (there's 2335 // already logic for that in scanPackageLI) but that adds some complexity. 2336 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2337 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2338 final String lib = libEntry.path; 2339 if (lib == null) { 2340 continue; 2341 } 2342 2343 try { 2344 // Shared libraries do not have profiles so we perform a full 2345 // AOT compilation (if needed). 2346 int dexoptNeeded = DexFile.getDexOptNeeded( 2347 lib, dexCodeInstructionSet, 2348 getCompilerFilterForReason(REASON_SHARED_APK), 2349 false /* newProfile */); 2350 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2351 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2352 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2353 getCompilerFilterForReason(REASON_SHARED_APK), 2354 StorageManager.UUID_PRIVATE_INTERNAL, 2355 SKIP_SHARED_LIBRARY_CHECK); 2356 } 2357 } catch (FileNotFoundException e) { 2358 Slog.w(TAG, "Library not found: " + lib); 2359 } catch (IOException | InstallerException e) { 2360 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2361 + e.getMessage()); 2362 } 2363 } 2364 } 2365 } 2366 2367 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2368 2369 final VersionInfo ver = mSettings.getInternalVersion(); 2370 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2371 2372 // when upgrading from pre-M, promote system app permissions from install to runtime 2373 mPromoteSystemApps = 2374 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2375 2376 // save off the names of pre-existing system packages prior to scanning; we don't 2377 // want to automatically grant runtime permissions for new system apps 2378 if (mPromoteSystemApps) { 2379 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2380 while (pkgSettingIter.hasNext()) { 2381 PackageSetting ps = pkgSettingIter.next(); 2382 if (isSystemApp(ps)) { 2383 mExistingSystemPackages.add(ps.name); 2384 } 2385 } 2386 } 2387 2388 // When upgrading from pre-N, we need to handle package extraction like first boot, 2389 // as there is no profiling data available. 2390 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2391 mSettings.setNWorkDone(); 2392 2393 // Collect vendor overlay packages. 2394 // (Do this before scanning any apps.) 2395 // For security and version matching reason, only consider 2396 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2397 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2398 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2399 | PackageParser.PARSE_IS_SYSTEM 2400 | PackageParser.PARSE_IS_SYSTEM_DIR 2401 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2402 2403 // Find base frameworks (resource packages without code). 2404 scanDirTracedLI(frameworkDir, mDefParseFlags 2405 | PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR 2407 | PackageParser.PARSE_IS_PRIVILEGED, 2408 scanFlags | SCAN_NO_DEX, 0); 2409 2410 // Collected privileged system packages. 2411 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2412 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2413 | PackageParser.PARSE_IS_SYSTEM 2414 | PackageParser.PARSE_IS_SYSTEM_DIR 2415 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2416 2417 // Collect ordinary system packages. 2418 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2419 scanDirTracedLI(systemAppDir, mDefParseFlags 2420 | PackageParser.PARSE_IS_SYSTEM 2421 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2422 2423 // Collect all vendor packages. 2424 File vendorAppDir = new File("/vendor/app"); 2425 try { 2426 vendorAppDir = vendorAppDir.getCanonicalFile(); 2427 } catch (IOException e) { 2428 // failed to look up canonical path, continue with original one 2429 } 2430 scanDirTracedLI(vendorAppDir, mDefParseFlags 2431 | PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2433 2434 // Collect all OEM packages. 2435 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2436 scanDirTracedLI(oemAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2439 2440 // Prune any system packages that no longer exist. 2441 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2442 if (!mOnlyCore) { 2443 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2444 while (psit.hasNext()) { 2445 PackageSetting ps = psit.next(); 2446 2447 /* 2448 * If this is not a system app, it can't be a 2449 * disable system app. 2450 */ 2451 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2452 continue; 2453 } 2454 2455 /* 2456 * If the package is scanned, it's not erased. 2457 */ 2458 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2459 if (scannedPkg != null) { 2460 /* 2461 * If the system app is both scanned and in the 2462 * disabled packages list, then it must have been 2463 * added via OTA. Remove it from the currently 2464 * scanned package so the previously user-installed 2465 * application can be scanned. 2466 */ 2467 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2468 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2469 + ps.name + "; removing system app. Last known codePath=" 2470 + ps.codePathString + ", installStatus=" + ps.installStatus 2471 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2472 + scannedPkg.mVersionCode); 2473 removePackageLI(scannedPkg, true); 2474 mExpectingBetter.put(ps.name, ps.codePath); 2475 } 2476 2477 continue; 2478 } 2479 2480 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2481 psit.remove(); 2482 logCriticalInfo(Log.WARN, "System package " + ps.name 2483 + " no longer exists; it's data will be wiped"); 2484 // Actual deletion of code and data will be handled by later 2485 // reconciliation step 2486 } else { 2487 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2488 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2489 possiblyDeletedUpdatedSystemApps.add(ps.name); 2490 } 2491 } 2492 } 2493 } 2494 2495 //look for any incomplete package installations 2496 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2497 for (int i = 0; i < deletePkgsList.size(); i++) { 2498 // Actual deletion of code and data will be handled by later 2499 // reconciliation step 2500 final String packageName = deletePkgsList.get(i).name; 2501 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2502 synchronized (mPackages) { 2503 mSettings.removePackageLPw(packageName); 2504 } 2505 } 2506 2507 //delete tmp files 2508 deleteTempPackageFiles(); 2509 2510 // Remove any shared userIDs that have no associated packages 2511 mSettings.pruneSharedUsersLPw(); 2512 2513 if (!mOnlyCore) { 2514 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2515 SystemClock.uptimeMillis()); 2516 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2517 2518 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2519 | PackageParser.PARSE_FORWARD_LOCK, 2520 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2521 2522 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2523 | PackageParser.PARSE_IS_EPHEMERAL, 2524 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2525 2526 /** 2527 * Remove disable package settings for any updated system 2528 * apps that were removed via an OTA. If they're not a 2529 * previously-updated app, remove them completely. 2530 * Otherwise, just revoke their system-level permissions. 2531 */ 2532 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2533 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2534 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2535 2536 String msg; 2537 if (deletedPkg == null) { 2538 msg = "Updated system package " + deletedAppName 2539 + " no longer exists; it's data will be wiped"; 2540 // Actual deletion of code and data will be handled by later 2541 // reconciliation step 2542 } else { 2543 msg = "Updated system app + " + deletedAppName 2544 + " no longer present; removing system privileges for " 2545 + deletedAppName; 2546 2547 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2548 2549 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2550 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2551 } 2552 logCriticalInfo(Log.WARN, msg); 2553 } 2554 2555 /** 2556 * Make sure all system apps that we expected to appear on 2557 * the userdata partition actually showed up. If they never 2558 * appeared, crawl back and revive the system version. 2559 */ 2560 for (int i = 0; i < mExpectingBetter.size(); i++) { 2561 final String packageName = mExpectingBetter.keyAt(i); 2562 if (!mPackages.containsKey(packageName)) { 2563 final File scanFile = mExpectingBetter.valueAt(i); 2564 2565 logCriticalInfo(Log.WARN, "Expected better " + packageName 2566 + " but never showed up; reverting to system"); 2567 2568 int reparseFlags = mDefParseFlags; 2569 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2570 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2571 | PackageParser.PARSE_IS_SYSTEM_DIR 2572 | PackageParser.PARSE_IS_PRIVILEGED; 2573 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2574 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2575 | PackageParser.PARSE_IS_SYSTEM_DIR; 2576 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2577 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2578 | PackageParser.PARSE_IS_SYSTEM_DIR; 2579 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else { 2583 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2584 continue; 2585 } 2586 2587 mSettings.enableSystemPackageLPw(packageName); 2588 2589 try { 2590 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2591 } catch (PackageManagerException e) { 2592 Slog.e(TAG, "Failed to parse original system package: " 2593 + e.getMessage()); 2594 } 2595 } 2596 } 2597 } 2598 mExpectingBetter.clear(); 2599 2600 // Resolve protected action filters. Only the setup wizard is allowed to 2601 // have a high priority filter for these actions. 2602 mSetupWizardPackage = getSetupWizardPackageName(); 2603 if (mProtectedFilters.size() > 0) { 2604 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2605 Slog.i(TAG, "No setup wizard;" 2606 + " All protected intents capped to priority 0"); 2607 } 2608 for (ActivityIntentInfo filter : mProtectedFilters) { 2609 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2610 if (DEBUG_FILTERS) { 2611 Slog.i(TAG, "Found setup wizard;" 2612 + " allow priority " + filter.getPriority() + ";" 2613 + " package: " + filter.activity.info.packageName 2614 + " activity: " + filter.activity.className 2615 + " priority: " + filter.getPriority()); 2616 } 2617 // skip setup wizard; allow it to keep the high priority filter 2618 continue; 2619 } 2620 Slog.w(TAG, "Protected action; cap priority to 0;" 2621 + " package: " + filter.activity.info.packageName 2622 + " activity: " + filter.activity.className 2623 + " origPrio: " + filter.getPriority()); 2624 filter.setPriority(0); 2625 } 2626 } 2627 mDeferProtectedFilters = false; 2628 mProtectedFilters.clear(); 2629 2630 // Now that we know all of the shared libraries, update all clients to have 2631 // the correct library paths. 2632 updateAllSharedLibrariesLPw(); 2633 2634 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2635 // NOTE: We ignore potential failures here during a system scan (like 2636 // the rest of the commands above) because there's precious little we 2637 // can do about it. A settings error is reported, though. 2638 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2639 false /* boot complete */); 2640 } 2641 2642 // Now that we know all the packages we are keeping, 2643 // read and update their last usage times. 2644 mPackageUsage.readLP(); 2645 2646 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2647 SystemClock.uptimeMillis()); 2648 Slog.i(TAG, "Time to scan packages: " 2649 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2650 + " seconds"); 2651 2652 // If the platform SDK has changed since the last time we booted, 2653 // we need to re-grant app permission to catch any new ones that 2654 // appear. This is really a hack, and means that apps can in some 2655 // cases get permissions that the user didn't initially explicitly 2656 // allow... it would be nice to have some better way to handle 2657 // this situation. 2658 int updateFlags = UPDATE_PERMISSIONS_ALL; 2659 if (ver.sdkVersion != mSdkVersion) { 2660 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2661 + mSdkVersion + "; regranting permissions for internal storage"); 2662 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2663 } 2664 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2665 ver.sdkVersion = mSdkVersion; 2666 2667 // If this is the first boot or an update from pre-M, and it is a normal 2668 // boot, then we need to initialize the default preferred apps across 2669 // all defined users. 2670 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2671 for (UserInfo user : sUserManager.getUsers(true)) { 2672 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2673 applyFactoryDefaultBrowserLPw(user.id); 2674 primeDomainVerificationsLPw(user.id); 2675 } 2676 } 2677 2678 // Prepare storage for system user really early during boot, 2679 // since core system apps like SettingsProvider and SystemUI 2680 // can't wait for user to start 2681 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2682 StorageManager.FLAG_STORAGE_DE); 2683 2684 // If this is first boot after an OTA, and a normal boot, then 2685 // we need to clear code cache directories. 2686 if (mIsUpgrade && !onlyCore) { 2687 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2688 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2689 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2690 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2691 // No apps are running this early, so no need to freeze 2692 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2693 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2694 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2695 } 2696 clearAppProfilesLIF(ps.pkg); 2697 } 2698 ver.fingerprint = Build.FINGERPRINT; 2699 } 2700 2701 checkDefaultBrowser(); 2702 2703 // clear only after permissions and other defaults have been updated 2704 mExistingSystemPackages.clear(); 2705 mPromoteSystemApps = false; 2706 2707 // All the changes are done during package scanning. 2708 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2709 2710 // can downgrade to reader 2711 mSettings.writeLPr(); 2712 2713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2714 SystemClock.uptimeMillis()); 2715 2716 if (!mOnlyCore) { 2717 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2718 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2719 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2720 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2721 mIntentFilterVerifierComponent); 2722 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2723 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2724 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2725 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2726 } else { 2727 mRequiredVerifierPackage = null; 2728 mRequiredInstallerPackage = null; 2729 mIntentFilterVerifierComponent = null; 2730 mIntentFilterVerifier = null; 2731 mServicesSystemSharedLibraryPackageName = null; 2732 mSharedSystemSharedLibraryPackageName = null; 2733 } 2734 2735 mInstallerService = new PackageInstallerService(context, this); 2736 2737 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2738 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2739 // both the installer and resolver must be present to enable ephemeral 2740 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2741 if (DEBUG_EPHEMERAL) { 2742 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2743 + " installer:" + ephemeralInstallerComponent); 2744 } 2745 mEphemeralResolverComponent = ephemeralResolverComponent; 2746 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2747 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2748 mEphemeralResolverConnection = 2749 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2750 } else { 2751 if (DEBUG_EPHEMERAL) { 2752 final String missingComponent = 2753 (ephemeralResolverComponent == null) 2754 ? (ephemeralInstallerComponent == null) 2755 ? "resolver and installer" 2756 : "resolver" 2757 : "installer"; 2758 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2759 } 2760 mEphemeralResolverComponent = null; 2761 mEphemeralInstallerComponent = null; 2762 mEphemeralResolverConnection = null; 2763 } 2764 2765 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2766 } // synchronized (mPackages) 2767 } // synchronized (mInstallLock) 2768 2769 // Now after opening every single application zip, make sure they 2770 // are all flushed. Not really needed, but keeps things nice and 2771 // tidy. 2772 Runtime.getRuntime().gc(); 2773 2774 // The initial scanning above does many calls into installd while 2775 // holding the mPackages lock, but we're mostly interested in yelling 2776 // once we have a booted system. 2777 mInstaller.setWarnIfHeld(mPackages); 2778 2779 // Expose private service for system components to use. 2780 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2781 } 2782 2783 @Override 2784 public boolean isFirstBoot() { 2785 return !mRestoredSettings; 2786 } 2787 2788 @Override 2789 public boolean isOnlyCoreApps() { 2790 return mOnlyCore; 2791 } 2792 2793 @Override 2794 public boolean isUpgrade() { 2795 return mIsUpgrade; 2796 } 2797 2798 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2799 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2800 2801 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2802 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2803 UserHandle.USER_SYSTEM); 2804 if (matches.size() == 1) { 2805 return matches.get(0).getComponentInfo().packageName; 2806 } else { 2807 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2808 return null; 2809 } 2810 } 2811 2812 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2813 synchronized (mPackages) { 2814 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2815 if (libraryEntry == null) { 2816 throw new IllegalStateException("Missing required shared library:" + libraryName); 2817 } 2818 return libraryEntry.apk; 2819 } 2820 } 2821 2822 private @NonNull String getRequiredInstallerLPr() { 2823 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2824 intent.addCategory(Intent.CATEGORY_DEFAULT); 2825 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2826 2827 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2828 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2829 UserHandle.USER_SYSTEM); 2830 if (matches.size() == 1) { 2831 ResolveInfo resolveInfo = matches.get(0); 2832 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2833 throw new RuntimeException("The installer must be a privileged app"); 2834 } 2835 return matches.get(0).getComponentInfo().packageName; 2836 } else { 2837 throw new RuntimeException("There must be exactly one installer; found " + matches); 2838 } 2839 } 2840 2841 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2842 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2843 2844 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2845 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2846 UserHandle.USER_SYSTEM); 2847 ResolveInfo best = null; 2848 final int N = matches.size(); 2849 for (int i = 0; i < N; i++) { 2850 final ResolveInfo cur = matches.get(i); 2851 final String packageName = cur.getComponentInfo().packageName; 2852 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2853 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2854 continue; 2855 } 2856 2857 if (best == null || cur.priority > best.priority) { 2858 best = cur; 2859 } 2860 } 2861 2862 if (best != null) { 2863 return best.getComponentInfo().getComponentName(); 2864 } else { 2865 throw new RuntimeException("There must be at least one intent filter verifier"); 2866 } 2867 } 2868 2869 private @Nullable ComponentName getEphemeralResolverLPr() { 2870 final String[] packageArray = 2871 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2872 if (packageArray.length == 0) { 2873 if (DEBUG_EPHEMERAL) { 2874 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2875 } 2876 return null; 2877 } 2878 2879 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2880 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2881 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2882 UserHandle.USER_SYSTEM); 2883 2884 final int N = resolvers.size(); 2885 if (N == 0) { 2886 if (DEBUG_EPHEMERAL) { 2887 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2888 } 2889 return null; 2890 } 2891 2892 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2893 for (int i = 0; i < N; i++) { 2894 final ResolveInfo info = resolvers.get(i); 2895 2896 if (info.serviceInfo == null) { 2897 continue; 2898 } 2899 2900 final String packageName = info.serviceInfo.packageName; 2901 if (!possiblePackages.contains(packageName)) { 2902 if (DEBUG_EPHEMERAL) { 2903 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2904 + " pkg: " + packageName + ", info:" + info); 2905 } 2906 continue; 2907 } 2908 2909 if (DEBUG_EPHEMERAL) { 2910 Slog.v(TAG, "Ephemeral resolver found;" 2911 + " pkg: " + packageName + ", info:" + info); 2912 } 2913 return new ComponentName(packageName, info.serviceInfo.name); 2914 } 2915 if (DEBUG_EPHEMERAL) { 2916 Slog.v(TAG, "Ephemeral resolver NOT found"); 2917 } 2918 return null; 2919 } 2920 2921 private @Nullable ComponentName getEphemeralInstallerLPr() { 2922 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2923 intent.addCategory(Intent.CATEGORY_DEFAULT); 2924 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2925 2926 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2927 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2928 UserHandle.USER_SYSTEM); 2929 if (matches.size() == 0) { 2930 return null; 2931 } else if (matches.size() == 1) { 2932 return matches.get(0).getComponentInfo().getComponentName(); 2933 } else { 2934 throw new RuntimeException( 2935 "There must be at most one ephemeral installer; found " + matches); 2936 } 2937 } 2938 2939 private void primeDomainVerificationsLPw(int userId) { 2940 if (DEBUG_DOMAIN_VERIFICATION) { 2941 Slog.d(TAG, "Priming domain verifications in user " + userId); 2942 } 2943 2944 SystemConfig systemConfig = SystemConfig.getInstance(); 2945 ArraySet<String> packages = systemConfig.getLinkedApps(); 2946 ArraySet<String> domains = new ArraySet<String>(); 2947 2948 for (String packageName : packages) { 2949 PackageParser.Package pkg = mPackages.get(packageName); 2950 if (pkg != null) { 2951 if (!pkg.isSystemApp()) { 2952 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2953 continue; 2954 } 2955 2956 domains.clear(); 2957 for (PackageParser.Activity a : pkg.activities) { 2958 for (ActivityIntentInfo filter : a.intents) { 2959 if (hasValidDomains(filter)) { 2960 domains.addAll(filter.getHostsList()); 2961 } 2962 } 2963 } 2964 2965 if (domains.size() > 0) { 2966 if (DEBUG_DOMAIN_VERIFICATION) { 2967 Slog.v(TAG, " + " + packageName); 2968 } 2969 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2970 // state w.r.t. the formal app-linkage "no verification attempted" state; 2971 // and then 'always' in the per-user state actually used for intent resolution. 2972 final IntentFilterVerificationInfo ivi; 2973 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2974 new ArrayList<String>(domains)); 2975 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2976 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2977 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2978 } else { 2979 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2980 + "' does not handle web links"); 2981 } 2982 } else { 2983 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2984 } 2985 } 2986 2987 scheduleWritePackageRestrictionsLocked(userId); 2988 scheduleWriteSettingsLocked(); 2989 } 2990 2991 private void applyFactoryDefaultBrowserLPw(int userId) { 2992 // The default browser app's package name is stored in a string resource, 2993 // with a product-specific overlay used for vendor customization. 2994 String browserPkg = mContext.getResources().getString( 2995 com.android.internal.R.string.default_browser); 2996 if (!TextUtils.isEmpty(browserPkg)) { 2997 // non-empty string => required to be a known package 2998 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2999 if (ps == null) { 3000 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3001 browserPkg = null; 3002 } else { 3003 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3004 } 3005 } 3006 3007 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3008 // default. If there's more than one, just leave everything alone. 3009 if (browserPkg == null) { 3010 calculateDefaultBrowserLPw(userId); 3011 } 3012 } 3013 3014 private void calculateDefaultBrowserLPw(int userId) { 3015 List<String> allBrowsers = resolveAllBrowserApps(userId); 3016 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3017 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3018 } 3019 3020 private List<String> resolveAllBrowserApps(int userId) { 3021 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3022 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3023 PackageManager.MATCH_ALL, userId); 3024 3025 final int count = list.size(); 3026 List<String> result = new ArrayList<String>(count); 3027 for (int i=0; i<count; i++) { 3028 ResolveInfo info = list.get(i); 3029 if (info.activityInfo == null 3030 || !info.handleAllWebDataURI 3031 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3032 || result.contains(info.activityInfo.packageName)) { 3033 continue; 3034 } 3035 result.add(info.activityInfo.packageName); 3036 } 3037 3038 return result; 3039 } 3040 3041 private boolean packageIsBrowser(String packageName, int userId) { 3042 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3043 PackageManager.MATCH_ALL, userId); 3044 final int N = list.size(); 3045 for (int i = 0; i < N; i++) { 3046 ResolveInfo info = list.get(i); 3047 if (packageName.equals(info.activityInfo.packageName)) { 3048 return true; 3049 } 3050 } 3051 return false; 3052 } 3053 3054 private void checkDefaultBrowser() { 3055 final int myUserId = UserHandle.myUserId(); 3056 final String packageName = getDefaultBrowserPackageName(myUserId); 3057 if (packageName != null) { 3058 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3059 if (info == null) { 3060 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3061 synchronized (mPackages) { 3062 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3063 } 3064 } 3065 } 3066 } 3067 3068 @Override 3069 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3070 throws RemoteException { 3071 try { 3072 return super.onTransact(code, data, reply, flags); 3073 } catch (RuntimeException e) { 3074 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3075 Slog.wtf(TAG, "Package Manager Crash", e); 3076 } 3077 throw e; 3078 } 3079 } 3080 3081 static int[] appendInts(int[] cur, int[] add) { 3082 if (add == null) return cur; 3083 if (cur == null) return add; 3084 final int N = add.length; 3085 for (int i=0; i<N; i++) { 3086 cur = appendInt(cur, add[i]); 3087 } 3088 return cur; 3089 } 3090 3091 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3092 if (!sUserManager.exists(userId)) return null; 3093 if (ps == null) { 3094 return null; 3095 } 3096 final PackageParser.Package p = ps.pkg; 3097 if (p == null) { 3098 return null; 3099 } 3100 3101 final PermissionsState permissionsState = ps.getPermissionsState(); 3102 3103 final int[] gids = permissionsState.computeGids(userId); 3104 final Set<String> permissions = permissionsState.getPermissions(userId); 3105 final PackageUserState state = ps.readUserState(userId); 3106 3107 return PackageParser.generatePackageInfo(p, gids, flags, 3108 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3109 } 3110 3111 @Override 3112 public void checkPackageStartable(String packageName, int userId) { 3113 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3114 3115 synchronized (mPackages) { 3116 final PackageSetting ps = mSettings.mPackages.get(packageName); 3117 if (ps == null) { 3118 throw new SecurityException("Package " + packageName + " was not found!"); 3119 } 3120 3121 if (!ps.getInstalled(userId)) { 3122 throw new SecurityException( 3123 "Package " + packageName + " was not installed for user " + userId + "!"); 3124 } 3125 3126 if (mSafeMode && !ps.isSystem()) { 3127 throw new SecurityException("Package " + packageName + " not a system app!"); 3128 } 3129 3130 if (mFrozenPackages.contains(packageName)) { 3131 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3132 } 3133 3134 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3135 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3136 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3137 } 3138 } 3139 } 3140 3141 @Override 3142 public boolean isPackageAvailable(String packageName, int userId) { 3143 if (!sUserManager.exists(userId)) return false; 3144 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3145 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3146 synchronized (mPackages) { 3147 PackageParser.Package p = mPackages.get(packageName); 3148 if (p != null) { 3149 final PackageSetting ps = (PackageSetting) p.mExtras; 3150 if (ps != null) { 3151 final PackageUserState state = ps.readUserState(userId); 3152 if (state != null) { 3153 return PackageParser.isAvailable(state); 3154 } 3155 } 3156 } 3157 } 3158 return false; 3159 } 3160 3161 @Override 3162 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3163 if (!sUserManager.exists(userId)) return null; 3164 flags = updateFlagsForPackage(flags, userId, packageName); 3165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3166 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3167 // reader 3168 synchronized (mPackages) { 3169 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3170 PackageParser.Package p = null; 3171 if (matchFactoryOnly) { 3172 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3173 if (ps != null) { 3174 return generatePackageInfo(ps, flags, userId); 3175 } 3176 } 3177 if (p == null) { 3178 p = mPackages.get(packageName); 3179 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3180 return null; 3181 } 3182 } 3183 if (DEBUG_PACKAGE_INFO) 3184 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3185 if (p != null) { 3186 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3187 } 3188 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3189 final PackageSetting ps = mSettings.mPackages.get(packageName); 3190 return generatePackageInfo(ps, flags, userId); 3191 } 3192 } 3193 return null; 3194 } 3195 3196 @Override 3197 public String[] currentToCanonicalPackageNames(String[] names) { 3198 String[] out = new String[names.length]; 3199 // reader 3200 synchronized (mPackages) { 3201 for (int i=names.length-1; i>=0; i--) { 3202 PackageSetting ps = mSettings.mPackages.get(names[i]); 3203 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3204 } 3205 } 3206 return out; 3207 } 3208 3209 @Override 3210 public String[] canonicalToCurrentPackageNames(String[] names) { 3211 String[] out = new String[names.length]; 3212 // reader 3213 synchronized (mPackages) { 3214 for (int i=names.length-1; i>=0; i--) { 3215 String cur = mSettings.mRenamedPackages.get(names[i]); 3216 out[i] = cur != null ? cur : names[i]; 3217 } 3218 } 3219 return out; 3220 } 3221 3222 @Override 3223 public int getPackageUid(String packageName, int flags, int userId) { 3224 if (!sUserManager.exists(userId)) return -1; 3225 flags = updateFlagsForPackage(flags, userId, packageName); 3226 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3227 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3228 3229 // reader 3230 synchronized (mPackages) { 3231 final PackageParser.Package p = mPackages.get(packageName); 3232 if (p != null && p.isMatch(flags)) { 3233 return UserHandle.getUid(userId, p.applicationInfo.uid); 3234 } 3235 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3236 final PackageSetting ps = mSettings.mPackages.get(packageName); 3237 if (ps != null && ps.isMatch(flags)) { 3238 return UserHandle.getUid(userId, ps.appId); 3239 } 3240 } 3241 } 3242 3243 return -1; 3244 } 3245 3246 @Override 3247 public int[] getPackageGids(String packageName, int flags, int userId) { 3248 if (!sUserManager.exists(userId)) return null; 3249 flags = updateFlagsForPackage(flags, userId, packageName); 3250 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3251 false /* requireFullPermission */, false /* checkShell */, 3252 "getPackageGids"); 3253 3254 // reader 3255 synchronized (mPackages) { 3256 final PackageParser.Package p = mPackages.get(packageName); 3257 if (p != null && p.isMatch(flags)) { 3258 PackageSetting ps = (PackageSetting) p.mExtras; 3259 return ps.getPermissionsState().computeGids(userId); 3260 } 3261 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3262 final PackageSetting ps = mSettings.mPackages.get(packageName); 3263 if (ps != null && ps.isMatch(flags)) { 3264 return ps.getPermissionsState().computeGids(userId); 3265 } 3266 } 3267 } 3268 3269 return null; 3270 } 3271 3272 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3273 if (bp.perm != null) { 3274 return PackageParser.generatePermissionInfo(bp.perm, flags); 3275 } 3276 PermissionInfo pi = new PermissionInfo(); 3277 pi.name = bp.name; 3278 pi.packageName = bp.sourcePackage; 3279 pi.nonLocalizedLabel = bp.name; 3280 pi.protectionLevel = bp.protectionLevel; 3281 return pi; 3282 } 3283 3284 @Override 3285 public PermissionInfo getPermissionInfo(String name, int flags) { 3286 // reader 3287 synchronized (mPackages) { 3288 final BasePermission p = mSettings.mPermissions.get(name); 3289 if (p != null) { 3290 return generatePermissionInfo(p, flags); 3291 } 3292 return null; 3293 } 3294 } 3295 3296 @Override 3297 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3298 int flags) { 3299 // reader 3300 synchronized (mPackages) { 3301 if (group != null && !mPermissionGroups.containsKey(group)) { 3302 // This is thrown as NameNotFoundException 3303 return null; 3304 } 3305 3306 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3307 for (BasePermission p : mSettings.mPermissions.values()) { 3308 if (group == null) { 3309 if (p.perm == null || p.perm.info.group == null) { 3310 out.add(generatePermissionInfo(p, flags)); 3311 } 3312 } else { 3313 if (p.perm != null && group.equals(p.perm.info.group)) { 3314 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3315 } 3316 } 3317 } 3318 return new ParceledListSlice<>(out); 3319 } 3320 } 3321 3322 @Override 3323 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3324 // reader 3325 synchronized (mPackages) { 3326 return PackageParser.generatePermissionGroupInfo( 3327 mPermissionGroups.get(name), flags); 3328 } 3329 } 3330 3331 @Override 3332 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3333 // reader 3334 synchronized (mPackages) { 3335 final int N = mPermissionGroups.size(); 3336 ArrayList<PermissionGroupInfo> out 3337 = new ArrayList<PermissionGroupInfo>(N); 3338 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3339 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3340 } 3341 return new ParceledListSlice<>(out); 3342 } 3343 } 3344 3345 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3346 int userId) { 3347 if (!sUserManager.exists(userId)) return null; 3348 PackageSetting ps = mSettings.mPackages.get(packageName); 3349 if (ps != null) { 3350 if (ps.pkg == null) { 3351 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3352 if (pInfo != null) { 3353 return pInfo.applicationInfo; 3354 } 3355 return null; 3356 } 3357 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3358 ps.readUserState(userId), userId); 3359 } 3360 return null; 3361 } 3362 3363 @Override 3364 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3365 if (!sUserManager.exists(userId)) return null; 3366 flags = updateFlagsForApplication(flags, userId, packageName); 3367 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3368 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3369 // writer 3370 synchronized (mPackages) { 3371 PackageParser.Package p = mPackages.get(packageName); 3372 if (DEBUG_PACKAGE_INFO) Log.v( 3373 TAG, "getApplicationInfo " + packageName 3374 + ": " + p); 3375 if (p != null) { 3376 PackageSetting ps = mSettings.mPackages.get(packageName); 3377 if (ps == null) return null; 3378 // Note: isEnabledLP() does not apply here - always return info 3379 return PackageParser.generateApplicationInfo( 3380 p, flags, ps.readUserState(userId), userId); 3381 } 3382 if ("android".equals(packageName)||"system".equals(packageName)) { 3383 return mAndroidApplication; 3384 } 3385 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3386 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3387 } 3388 } 3389 return null; 3390 } 3391 3392 @Override 3393 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3394 final IPackageDataObserver observer) { 3395 mContext.enforceCallingOrSelfPermission( 3396 android.Manifest.permission.CLEAR_APP_CACHE, null); 3397 // Queue up an async operation since clearing cache may take a little while. 3398 mHandler.post(new Runnable() { 3399 public void run() { 3400 mHandler.removeCallbacks(this); 3401 boolean success = true; 3402 synchronized (mInstallLock) { 3403 try { 3404 mInstaller.freeCache(volumeUuid, freeStorageSize); 3405 } catch (InstallerException e) { 3406 Slog.w(TAG, "Couldn't clear application caches: " + e); 3407 success = false; 3408 } 3409 } 3410 if (observer != null) { 3411 try { 3412 observer.onRemoveCompleted(null, success); 3413 } catch (RemoteException e) { 3414 Slog.w(TAG, "RemoveException when invoking call back"); 3415 } 3416 } 3417 } 3418 }); 3419 } 3420 3421 @Override 3422 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3423 final IntentSender pi) { 3424 mContext.enforceCallingOrSelfPermission( 3425 android.Manifest.permission.CLEAR_APP_CACHE, null); 3426 // Queue up an async operation since clearing cache may take a little while. 3427 mHandler.post(new Runnable() { 3428 public void run() { 3429 mHandler.removeCallbacks(this); 3430 boolean success = true; 3431 synchronized (mInstallLock) { 3432 try { 3433 mInstaller.freeCache(volumeUuid, freeStorageSize); 3434 } catch (InstallerException e) { 3435 Slog.w(TAG, "Couldn't clear application caches: " + e); 3436 success = false; 3437 } 3438 } 3439 if(pi != null) { 3440 try { 3441 // Callback via pending intent 3442 int code = success ? 1 : 0; 3443 pi.sendIntent(null, code, null, 3444 null, null); 3445 } catch (SendIntentException e1) { 3446 Slog.i(TAG, "Failed to send pending intent"); 3447 } 3448 } 3449 } 3450 }); 3451 } 3452 3453 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3454 synchronized (mInstallLock) { 3455 try { 3456 mInstaller.freeCache(volumeUuid, freeStorageSize); 3457 } catch (InstallerException e) { 3458 throw new IOException("Failed to free enough space", e); 3459 } 3460 } 3461 } 3462 3463 /** 3464 * Update given flags based on encryption status of current user. 3465 */ 3466 private int updateFlags(int flags, int userId) { 3467 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3468 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3469 // Caller expressed an explicit opinion about what encryption 3470 // aware/unaware components they want to see, so fall through and 3471 // give them what they want 3472 } else { 3473 // Caller expressed no opinion, so match based on user state 3474 if (StorageManager.isUserKeyUnlocked(userId)) { 3475 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3476 } else { 3477 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3478 } 3479 } 3480 return flags; 3481 } 3482 3483 /** 3484 * Update given flags when being used to request {@link PackageInfo}. 3485 */ 3486 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3487 boolean triaged = true; 3488 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3489 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3490 // Caller is asking for component details, so they'd better be 3491 // asking for specific encryption matching behavior, or be triaged 3492 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3493 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3494 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3495 triaged = false; 3496 } 3497 } 3498 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3499 | PackageManager.MATCH_SYSTEM_ONLY 3500 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3501 triaged = false; 3502 } 3503 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3504 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3505 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3506 } 3507 return updateFlags(flags, userId); 3508 } 3509 3510 /** 3511 * Update given flags when being used to request {@link ApplicationInfo}. 3512 */ 3513 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3514 return updateFlagsForPackage(flags, userId, cookie); 3515 } 3516 3517 /** 3518 * Update given flags when being used to request {@link ComponentInfo}. 3519 */ 3520 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3521 if (cookie instanceof Intent) { 3522 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3523 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3524 } 3525 } 3526 3527 boolean triaged = true; 3528 // Caller is asking for component details, so they'd better be 3529 // asking for specific encryption matching behavior, or be triaged 3530 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3531 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3532 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3533 triaged = false; 3534 } 3535 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3536 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3537 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3538 } 3539 3540 return updateFlags(flags, userId); 3541 } 3542 3543 /** 3544 * Update given flags when being used to request {@link ResolveInfo}. 3545 */ 3546 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3547 // Safe mode means we shouldn't match any third-party components 3548 if (mSafeMode) { 3549 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3550 } 3551 3552 return updateFlagsForComponent(flags, userId, cookie); 3553 } 3554 3555 @Override 3556 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3557 if (!sUserManager.exists(userId)) return null; 3558 flags = updateFlagsForComponent(flags, userId, component); 3559 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3560 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3561 synchronized (mPackages) { 3562 PackageParser.Activity a = mActivities.mActivities.get(component); 3563 3564 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3565 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3566 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3567 if (ps == null) return null; 3568 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3569 userId); 3570 } 3571 if (mResolveComponentName.equals(component)) { 3572 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3573 new PackageUserState(), userId); 3574 } 3575 } 3576 return null; 3577 } 3578 3579 @Override 3580 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3581 String resolvedType) { 3582 synchronized (mPackages) { 3583 if (component.equals(mResolveComponentName)) { 3584 // The resolver supports EVERYTHING! 3585 return true; 3586 } 3587 PackageParser.Activity a = mActivities.mActivities.get(component); 3588 if (a == null) { 3589 return false; 3590 } 3591 for (int i=0; i<a.intents.size(); i++) { 3592 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3593 intent.getData(), intent.getCategories(), TAG) >= 0) { 3594 return true; 3595 } 3596 } 3597 return false; 3598 } 3599 } 3600 3601 @Override 3602 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3603 if (!sUserManager.exists(userId)) return null; 3604 flags = updateFlagsForComponent(flags, userId, component); 3605 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3606 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3607 synchronized (mPackages) { 3608 PackageParser.Activity a = mReceivers.mActivities.get(component); 3609 if (DEBUG_PACKAGE_INFO) Log.v( 3610 TAG, "getReceiverInfo " + component + ": " + a); 3611 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3612 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3613 if (ps == null) return null; 3614 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3615 userId); 3616 } 3617 } 3618 return null; 3619 } 3620 3621 @Override 3622 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3623 if (!sUserManager.exists(userId)) return null; 3624 flags = updateFlagsForComponent(flags, userId, component); 3625 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3626 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3627 synchronized (mPackages) { 3628 PackageParser.Service s = mServices.mServices.get(component); 3629 if (DEBUG_PACKAGE_INFO) Log.v( 3630 TAG, "getServiceInfo " + component + ": " + s); 3631 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3632 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3633 if (ps == null) return null; 3634 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3635 userId); 3636 } 3637 } 3638 return null; 3639 } 3640 3641 @Override 3642 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3643 if (!sUserManager.exists(userId)) return null; 3644 flags = updateFlagsForComponent(flags, userId, component); 3645 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3646 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3647 synchronized (mPackages) { 3648 PackageParser.Provider p = mProviders.mProviders.get(component); 3649 if (DEBUG_PACKAGE_INFO) Log.v( 3650 TAG, "getProviderInfo " + component + ": " + p); 3651 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3652 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3653 if (ps == null) return null; 3654 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3655 userId); 3656 } 3657 } 3658 return null; 3659 } 3660 3661 @Override 3662 public String[] getSystemSharedLibraryNames() { 3663 Set<String> libSet; 3664 synchronized (mPackages) { 3665 libSet = mSharedLibraries.keySet(); 3666 int size = libSet.size(); 3667 if (size > 0) { 3668 String[] libs = new String[size]; 3669 libSet.toArray(libs); 3670 return libs; 3671 } 3672 } 3673 return null; 3674 } 3675 3676 @Override 3677 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3678 synchronized (mPackages) { 3679 return mServicesSystemSharedLibraryPackageName; 3680 } 3681 } 3682 3683 @Override 3684 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3685 synchronized (mPackages) { 3686 return mSharedSystemSharedLibraryPackageName; 3687 } 3688 } 3689 3690 @Override 3691 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3692 synchronized (mPackages) { 3693 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3694 3695 final FeatureInfo fi = new FeatureInfo(); 3696 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3697 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3698 res.add(fi); 3699 3700 return new ParceledListSlice<>(res); 3701 } 3702 } 3703 3704 @Override 3705 public boolean hasSystemFeature(String name, int version) { 3706 synchronized (mPackages) { 3707 final FeatureInfo feat = mAvailableFeatures.get(name); 3708 if (feat == null) { 3709 return false; 3710 } else { 3711 return feat.version >= version; 3712 } 3713 } 3714 } 3715 3716 @Override 3717 public int checkPermission(String permName, String pkgName, int userId) { 3718 if (!sUserManager.exists(userId)) { 3719 return PackageManager.PERMISSION_DENIED; 3720 } 3721 3722 synchronized (mPackages) { 3723 final PackageParser.Package p = mPackages.get(pkgName); 3724 if (p != null && p.mExtras != null) { 3725 final PackageSetting ps = (PackageSetting) p.mExtras; 3726 final PermissionsState permissionsState = ps.getPermissionsState(); 3727 if (permissionsState.hasPermission(permName, userId)) { 3728 return PackageManager.PERMISSION_GRANTED; 3729 } 3730 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3731 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3732 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3733 return PackageManager.PERMISSION_GRANTED; 3734 } 3735 } 3736 } 3737 3738 return PackageManager.PERMISSION_DENIED; 3739 } 3740 3741 @Override 3742 public int checkUidPermission(String permName, int uid) { 3743 final int userId = UserHandle.getUserId(uid); 3744 3745 if (!sUserManager.exists(userId)) { 3746 return PackageManager.PERMISSION_DENIED; 3747 } 3748 3749 synchronized (mPackages) { 3750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3751 if (obj != null) { 3752 final SettingBase ps = (SettingBase) obj; 3753 final PermissionsState permissionsState = ps.getPermissionsState(); 3754 if (permissionsState.hasPermission(permName, userId)) { 3755 return PackageManager.PERMISSION_GRANTED; 3756 } 3757 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3758 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3759 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3760 return PackageManager.PERMISSION_GRANTED; 3761 } 3762 } else { 3763 ArraySet<String> perms = mSystemPermissions.get(uid); 3764 if (perms != null) { 3765 if (perms.contains(permName)) { 3766 return PackageManager.PERMISSION_GRANTED; 3767 } 3768 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3769 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3770 return PackageManager.PERMISSION_GRANTED; 3771 } 3772 } 3773 } 3774 } 3775 3776 return PackageManager.PERMISSION_DENIED; 3777 } 3778 3779 @Override 3780 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3781 if (UserHandle.getCallingUserId() != userId) { 3782 mContext.enforceCallingPermission( 3783 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3784 "isPermissionRevokedByPolicy for user " + userId); 3785 } 3786 3787 if (checkPermission(permission, packageName, userId) 3788 == PackageManager.PERMISSION_GRANTED) { 3789 return false; 3790 } 3791 3792 final long identity = Binder.clearCallingIdentity(); 3793 try { 3794 final int flags = getPermissionFlags(permission, packageName, userId); 3795 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3796 } finally { 3797 Binder.restoreCallingIdentity(identity); 3798 } 3799 } 3800 3801 @Override 3802 public String getPermissionControllerPackageName() { 3803 synchronized (mPackages) { 3804 return mRequiredInstallerPackage; 3805 } 3806 } 3807 3808 /** 3809 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3810 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3811 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3812 * @param message the message to log on security exception 3813 */ 3814 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3815 boolean checkShell, String message) { 3816 if (userId < 0) { 3817 throw new IllegalArgumentException("Invalid userId " + userId); 3818 } 3819 if (checkShell) { 3820 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3821 } 3822 if (userId == UserHandle.getUserId(callingUid)) return; 3823 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3824 if (requireFullPermission) { 3825 mContext.enforceCallingOrSelfPermission( 3826 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3827 } else { 3828 try { 3829 mContext.enforceCallingOrSelfPermission( 3830 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3831 } catch (SecurityException se) { 3832 mContext.enforceCallingOrSelfPermission( 3833 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3834 } 3835 } 3836 } 3837 } 3838 3839 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3840 if (callingUid == Process.SHELL_UID) { 3841 if (userHandle >= 0 3842 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3843 throw new SecurityException("Shell does not have permission to access user " 3844 + userHandle); 3845 } else if (userHandle < 0) { 3846 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3847 + Debug.getCallers(3)); 3848 } 3849 } 3850 } 3851 3852 private BasePermission findPermissionTreeLP(String permName) { 3853 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3854 if (permName.startsWith(bp.name) && 3855 permName.length() > bp.name.length() && 3856 permName.charAt(bp.name.length()) == '.') { 3857 return bp; 3858 } 3859 } 3860 return null; 3861 } 3862 3863 private BasePermission checkPermissionTreeLP(String permName) { 3864 if (permName != null) { 3865 BasePermission bp = findPermissionTreeLP(permName); 3866 if (bp != null) { 3867 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3868 return bp; 3869 } 3870 throw new SecurityException("Calling uid " 3871 + Binder.getCallingUid() 3872 + " is not allowed to add to permission tree " 3873 + bp.name + " owned by uid " + bp.uid); 3874 } 3875 } 3876 throw new SecurityException("No permission tree found for " + permName); 3877 } 3878 3879 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3880 if (s1 == null) { 3881 return s2 == null; 3882 } 3883 if (s2 == null) { 3884 return false; 3885 } 3886 if (s1.getClass() != s2.getClass()) { 3887 return false; 3888 } 3889 return s1.equals(s2); 3890 } 3891 3892 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3893 if (pi1.icon != pi2.icon) return false; 3894 if (pi1.logo != pi2.logo) return false; 3895 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3896 if (!compareStrings(pi1.name, pi2.name)) return false; 3897 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3898 // We'll take care of setting this one. 3899 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3900 // These are not currently stored in settings. 3901 //if (!compareStrings(pi1.group, pi2.group)) return false; 3902 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3903 //if (pi1.labelRes != pi2.labelRes) return false; 3904 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3905 return true; 3906 } 3907 3908 int permissionInfoFootprint(PermissionInfo info) { 3909 int size = info.name.length(); 3910 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3911 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3912 return size; 3913 } 3914 3915 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3916 int size = 0; 3917 for (BasePermission perm : mSettings.mPermissions.values()) { 3918 if (perm.uid == tree.uid) { 3919 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3920 } 3921 } 3922 return size; 3923 } 3924 3925 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3926 // We calculate the max size of permissions defined by this uid and throw 3927 // if that plus the size of 'info' would exceed our stated maximum. 3928 if (tree.uid != Process.SYSTEM_UID) { 3929 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3930 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3931 throw new SecurityException("Permission tree size cap exceeded"); 3932 } 3933 } 3934 } 3935 3936 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3937 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3938 throw new SecurityException("Label must be specified in permission"); 3939 } 3940 BasePermission tree = checkPermissionTreeLP(info.name); 3941 BasePermission bp = mSettings.mPermissions.get(info.name); 3942 boolean added = bp == null; 3943 boolean changed = true; 3944 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3945 if (added) { 3946 enforcePermissionCapLocked(info, tree); 3947 bp = new BasePermission(info.name, tree.sourcePackage, 3948 BasePermission.TYPE_DYNAMIC); 3949 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3950 throw new SecurityException( 3951 "Not allowed to modify non-dynamic permission " 3952 + info.name); 3953 } else { 3954 if (bp.protectionLevel == fixedLevel 3955 && bp.perm.owner.equals(tree.perm.owner) 3956 && bp.uid == tree.uid 3957 && comparePermissionInfos(bp.perm.info, info)) { 3958 changed = false; 3959 } 3960 } 3961 bp.protectionLevel = fixedLevel; 3962 info = new PermissionInfo(info); 3963 info.protectionLevel = fixedLevel; 3964 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3965 bp.perm.info.packageName = tree.perm.info.packageName; 3966 bp.uid = tree.uid; 3967 if (added) { 3968 mSettings.mPermissions.put(info.name, bp); 3969 } 3970 if (changed) { 3971 if (!async) { 3972 mSettings.writeLPr(); 3973 } else { 3974 scheduleWriteSettingsLocked(); 3975 } 3976 } 3977 return added; 3978 } 3979 3980 @Override 3981 public boolean addPermission(PermissionInfo info) { 3982 synchronized (mPackages) { 3983 return addPermissionLocked(info, false); 3984 } 3985 } 3986 3987 @Override 3988 public boolean addPermissionAsync(PermissionInfo info) { 3989 synchronized (mPackages) { 3990 return addPermissionLocked(info, true); 3991 } 3992 } 3993 3994 @Override 3995 public void removePermission(String name) { 3996 synchronized (mPackages) { 3997 checkPermissionTreeLP(name); 3998 BasePermission bp = mSettings.mPermissions.get(name); 3999 if (bp != null) { 4000 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4001 throw new SecurityException( 4002 "Not allowed to modify non-dynamic permission " 4003 + name); 4004 } 4005 mSettings.mPermissions.remove(name); 4006 mSettings.writeLPr(); 4007 } 4008 } 4009 } 4010 4011 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4012 BasePermission bp) { 4013 int index = pkg.requestedPermissions.indexOf(bp.name); 4014 if (index == -1) { 4015 throw new SecurityException("Package " + pkg.packageName 4016 + " has not requested permission " + bp.name); 4017 } 4018 if (!bp.isRuntime() && !bp.isDevelopment()) { 4019 throw new SecurityException("Permission " + bp.name 4020 + " is not a changeable permission type"); 4021 } 4022 } 4023 4024 @Override 4025 public void grantRuntimePermission(String packageName, String name, final int userId) { 4026 if (!sUserManager.exists(userId)) { 4027 Log.e(TAG, "No such user:" + userId); 4028 return; 4029 } 4030 4031 mContext.enforceCallingOrSelfPermission( 4032 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4033 "grantRuntimePermission"); 4034 4035 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4036 true /* requireFullPermission */, true /* checkShell */, 4037 "grantRuntimePermission"); 4038 4039 final int uid; 4040 final SettingBase sb; 4041 4042 synchronized (mPackages) { 4043 final PackageParser.Package pkg = mPackages.get(packageName); 4044 if (pkg == null) { 4045 throw new IllegalArgumentException("Unknown package: " + packageName); 4046 } 4047 4048 final BasePermission bp = mSettings.mPermissions.get(name); 4049 if (bp == null) { 4050 throw new IllegalArgumentException("Unknown permission: " + name); 4051 } 4052 4053 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4054 4055 // If a permission review is required for legacy apps we represent 4056 // their permissions as always granted runtime ones since we need 4057 // to keep the review required permission flag per user while an 4058 // install permission's state is shared across all users. 4059 if (Build.PERMISSIONS_REVIEW_REQUIRED 4060 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4061 && bp.isRuntime()) { 4062 return; 4063 } 4064 4065 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4066 sb = (SettingBase) pkg.mExtras; 4067 if (sb == null) { 4068 throw new IllegalArgumentException("Unknown package: " + packageName); 4069 } 4070 4071 final PermissionsState permissionsState = sb.getPermissionsState(); 4072 4073 final int flags = permissionsState.getPermissionFlags(name, userId); 4074 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4075 throw new SecurityException("Cannot grant system fixed permission " 4076 + name + " for package " + packageName); 4077 } 4078 4079 if (bp.isDevelopment()) { 4080 // Development permissions must be handled specially, since they are not 4081 // normal runtime permissions. For now they apply to all users. 4082 if (permissionsState.grantInstallPermission(bp) != 4083 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4084 scheduleWriteSettingsLocked(); 4085 } 4086 return; 4087 } 4088 4089 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4090 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4091 return; 4092 } 4093 4094 final int result = permissionsState.grantRuntimePermission(bp, userId); 4095 switch (result) { 4096 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4097 return; 4098 } 4099 4100 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4101 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4102 mHandler.post(new Runnable() { 4103 @Override 4104 public void run() { 4105 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4106 } 4107 }); 4108 } 4109 break; 4110 } 4111 4112 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4113 4114 // Not critical if that is lost - app has to request again. 4115 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4116 } 4117 4118 // Only need to do this if user is initialized. Otherwise it's a new user 4119 // and there are no processes running as the user yet and there's no need 4120 // to make an expensive call to remount processes for the changed permissions. 4121 if (READ_EXTERNAL_STORAGE.equals(name) 4122 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4123 final long token = Binder.clearCallingIdentity(); 4124 try { 4125 if (sUserManager.isInitialized(userId)) { 4126 MountServiceInternal mountServiceInternal = LocalServices.getService( 4127 MountServiceInternal.class); 4128 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4129 } 4130 } finally { 4131 Binder.restoreCallingIdentity(token); 4132 } 4133 } 4134 } 4135 4136 @Override 4137 public void revokeRuntimePermission(String packageName, String name, int userId) { 4138 if (!sUserManager.exists(userId)) { 4139 Log.e(TAG, "No such user:" + userId); 4140 return; 4141 } 4142 4143 mContext.enforceCallingOrSelfPermission( 4144 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4145 "revokeRuntimePermission"); 4146 4147 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4148 true /* requireFullPermission */, true /* checkShell */, 4149 "revokeRuntimePermission"); 4150 4151 final int appId; 4152 4153 synchronized (mPackages) { 4154 final PackageParser.Package pkg = mPackages.get(packageName); 4155 if (pkg == null) { 4156 throw new IllegalArgumentException("Unknown package: " + packageName); 4157 } 4158 4159 final BasePermission bp = mSettings.mPermissions.get(name); 4160 if (bp == null) { 4161 throw new IllegalArgumentException("Unknown permission: " + name); 4162 } 4163 4164 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4165 4166 // If a permission review is required for legacy apps we represent 4167 // their permissions as always granted runtime ones since we need 4168 // to keep the review required permission flag per user while an 4169 // install permission's state is shared across all users. 4170 if (Build.PERMISSIONS_REVIEW_REQUIRED 4171 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4172 && bp.isRuntime()) { 4173 return; 4174 } 4175 4176 SettingBase sb = (SettingBase) pkg.mExtras; 4177 if (sb == null) { 4178 throw new IllegalArgumentException("Unknown package: " + packageName); 4179 } 4180 4181 final PermissionsState permissionsState = sb.getPermissionsState(); 4182 4183 final int flags = permissionsState.getPermissionFlags(name, userId); 4184 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4185 throw new SecurityException("Cannot revoke system fixed permission " 4186 + name + " for package " + packageName); 4187 } 4188 4189 if (bp.isDevelopment()) { 4190 // Development permissions must be handled specially, since they are not 4191 // normal runtime permissions. For now they apply to all users. 4192 if (permissionsState.revokeInstallPermission(bp) != 4193 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4194 scheduleWriteSettingsLocked(); 4195 } 4196 return; 4197 } 4198 4199 if (permissionsState.revokeRuntimePermission(bp, userId) == 4200 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4201 return; 4202 } 4203 4204 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4205 4206 // Critical, after this call app should never have the permission. 4207 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4208 4209 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4210 } 4211 4212 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4213 } 4214 4215 @Override 4216 public void resetRuntimePermissions() { 4217 mContext.enforceCallingOrSelfPermission( 4218 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4219 "revokeRuntimePermission"); 4220 4221 int callingUid = Binder.getCallingUid(); 4222 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4223 mContext.enforceCallingOrSelfPermission( 4224 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4225 "resetRuntimePermissions"); 4226 } 4227 4228 synchronized (mPackages) { 4229 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4230 for (int userId : UserManagerService.getInstance().getUserIds()) { 4231 final int packageCount = mPackages.size(); 4232 for (int i = 0; i < packageCount; i++) { 4233 PackageParser.Package pkg = mPackages.valueAt(i); 4234 if (!(pkg.mExtras instanceof PackageSetting)) { 4235 continue; 4236 } 4237 PackageSetting ps = (PackageSetting) pkg.mExtras; 4238 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4239 } 4240 } 4241 } 4242 } 4243 4244 @Override 4245 public int getPermissionFlags(String name, String packageName, int userId) { 4246 if (!sUserManager.exists(userId)) { 4247 return 0; 4248 } 4249 4250 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4251 4252 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4253 true /* requireFullPermission */, false /* checkShell */, 4254 "getPermissionFlags"); 4255 4256 synchronized (mPackages) { 4257 final PackageParser.Package pkg = mPackages.get(packageName); 4258 if (pkg == null) { 4259 throw new IllegalArgumentException("Unknown package: " + packageName); 4260 } 4261 4262 final BasePermission bp = mSettings.mPermissions.get(name); 4263 if (bp == null) { 4264 throw new IllegalArgumentException("Unknown permission: " + name); 4265 } 4266 4267 SettingBase sb = (SettingBase) pkg.mExtras; 4268 if (sb == null) { 4269 throw new IllegalArgumentException("Unknown package: " + packageName); 4270 } 4271 4272 PermissionsState permissionsState = sb.getPermissionsState(); 4273 return permissionsState.getPermissionFlags(name, userId); 4274 } 4275 } 4276 4277 @Override 4278 public void updatePermissionFlags(String name, String packageName, int flagMask, 4279 int flagValues, int userId) { 4280 if (!sUserManager.exists(userId)) { 4281 return; 4282 } 4283 4284 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4285 4286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4287 true /* requireFullPermission */, true /* checkShell */, 4288 "updatePermissionFlags"); 4289 4290 // Only the system can change these flags and nothing else. 4291 if (getCallingUid() != Process.SYSTEM_UID) { 4292 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4293 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4294 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4295 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4296 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4297 } 4298 4299 synchronized (mPackages) { 4300 final PackageParser.Package pkg = mPackages.get(packageName); 4301 if (pkg == null) { 4302 throw new IllegalArgumentException("Unknown package: " + packageName); 4303 } 4304 4305 final BasePermission bp = mSettings.mPermissions.get(name); 4306 if (bp == null) { 4307 throw new IllegalArgumentException("Unknown permission: " + name); 4308 } 4309 4310 SettingBase sb = (SettingBase) pkg.mExtras; 4311 if (sb == null) { 4312 throw new IllegalArgumentException("Unknown package: " + packageName); 4313 } 4314 4315 PermissionsState permissionsState = sb.getPermissionsState(); 4316 4317 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4318 4319 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4320 // Install and runtime permissions are stored in different places, 4321 // so figure out what permission changed and persist the change. 4322 if (permissionsState.getInstallPermissionState(name) != null) { 4323 scheduleWriteSettingsLocked(); 4324 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4325 || hadState) { 4326 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4327 } 4328 } 4329 } 4330 } 4331 4332 /** 4333 * Update the permission flags for all packages and runtime permissions of a user in order 4334 * to allow device or profile owner to remove POLICY_FIXED. 4335 */ 4336 @Override 4337 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4338 if (!sUserManager.exists(userId)) { 4339 return; 4340 } 4341 4342 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4343 4344 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4345 true /* requireFullPermission */, true /* checkShell */, 4346 "updatePermissionFlagsForAllApps"); 4347 4348 // Only the system can change system fixed flags. 4349 if (getCallingUid() != Process.SYSTEM_UID) { 4350 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4351 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4352 } 4353 4354 synchronized (mPackages) { 4355 boolean changed = false; 4356 final int packageCount = mPackages.size(); 4357 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4358 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4359 SettingBase sb = (SettingBase) pkg.mExtras; 4360 if (sb == null) { 4361 continue; 4362 } 4363 PermissionsState permissionsState = sb.getPermissionsState(); 4364 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4365 userId, flagMask, flagValues); 4366 } 4367 if (changed) { 4368 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4369 } 4370 } 4371 } 4372 4373 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4374 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4375 != PackageManager.PERMISSION_GRANTED 4376 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4377 != PackageManager.PERMISSION_GRANTED) { 4378 throw new SecurityException(message + " requires " 4379 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4380 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4381 } 4382 } 4383 4384 @Override 4385 public boolean shouldShowRequestPermissionRationale(String permissionName, 4386 String packageName, int userId) { 4387 if (UserHandle.getCallingUserId() != userId) { 4388 mContext.enforceCallingPermission( 4389 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4390 "canShowRequestPermissionRationale for user " + userId); 4391 } 4392 4393 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4394 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4395 return false; 4396 } 4397 4398 if (checkPermission(permissionName, packageName, userId) 4399 == PackageManager.PERMISSION_GRANTED) { 4400 return false; 4401 } 4402 4403 final int flags; 4404 4405 final long identity = Binder.clearCallingIdentity(); 4406 try { 4407 flags = getPermissionFlags(permissionName, 4408 packageName, userId); 4409 } finally { 4410 Binder.restoreCallingIdentity(identity); 4411 } 4412 4413 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4414 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4415 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4416 4417 if ((flags & fixedFlags) != 0) { 4418 return false; 4419 } 4420 4421 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4422 } 4423 4424 @Override 4425 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4426 mContext.enforceCallingOrSelfPermission( 4427 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4428 "addOnPermissionsChangeListener"); 4429 4430 synchronized (mPackages) { 4431 mOnPermissionChangeListeners.addListenerLocked(listener); 4432 } 4433 } 4434 4435 @Override 4436 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4437 synchronized (mPackages) { 4438 mOnPermissionChangeListeners.removeListenerLocked(listener); 4439 } 4440 } 4441 4442 @Override 4443 public boolean isProtectedBroadcast(String actionName) { 4444 synchronized (mPackages) { 4445 if (mProtectedBroadcasts.contains(actionName)) { 4446 return true; 4447 } else if (actionName != null) { 4448 // TODO: remove these terrible hacks 4449 if (actionName.startsWith("android.net.netmon.lingerExpired") 4450 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4451 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4452 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4453 return true; 4454 } 4455 } 4456 } 4457 return false; 4458 } 4459 4460 @Override 4461 public int checkSignatures(String pkg1, String pkg2) { 4462 synchronized (mPackages) { 4463 final PackageParser.Package p1 = mPackages.get(pkg1); 4464 final PackageParser.Package p2 = mPackages.get(pkg2); 4465 if (p1 == null || p1.mExtras == null 4466 || p2 == null || p2.mExtras == null) { 4467 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4468 } 4469 return compareSignatures(p1.mSignatures, p2.mSignatures); 4470 } 4471 } 4472 4473 @Override 4474 public int checkUidSignatures(int uid1, int uid2) { 4475 // Map to base uids. 4476 uid1 = UserHandle.getAppId(uid1); 4477 uid2 = UserHandle.getAppId(uid2); 4478 // reader 4479 synchronized (mPackages) { 4480 Signature[] s1; 4481 Signature[] s2; 4482 Object obj = mSettings.getUserIdLPr(uid1); 4483 if (obj != null) { 4484 if (obj instanceof SharedUserSetting) { 4485 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4486 } else if (obj instanceof PackageSetting) { 4487 s1 = ((PackageSetting)obj).signatures.mSignatures; 4488 } else { 4489 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4490 } 4491 } else { 4492 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4493 } 4494 obj = mSettings.getUserIdLPr(uid2); 4495 if (obj != null) { 4496 if (obj instanceof SharedUserSetting) { 4497 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4498 } else if (obj instanceof PackageSetting) { 4499 s2 = ((PackageSetting)obj).signatures.mSignatures; 4500 } else { 4501 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4502 } 4503 } else { 4504 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4505 } 4506 return compareSignatures(s1, s2); 4507 } 4508 } 4509 4510 /** 4511 * This method should typically only be used when granting or revoking 4512 * permissions, since the app may immediately restart after this call. 4513 * <p> 4514 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4515 * guard your work against the app being relaunched. 4516 */ 4517 private void killUid(int appId, int userId, String reason) { 4518 final long identity = Binder.clearCallingIdentity(); 4519 try { 4520 IActivityManager am = ActivityManagerNative.getDefault(); 4521 if (am != null) { 4522 try { 4523 am.killUid(appId, userId, reason); 4524 } catch (RemoteException e) { 4525 /* ignore - same process */ 4526 } 4527 } 4528 } finally { 4529 Binder.restoreCallingIdentity(identity); 4530 } 4531 } 4532 4533 /** 4534 * Compares two sets of signatures. Returns: 4535 * <br /> 4536 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4537 * <br /> 4538 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4539 * <br /> 4540 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4541 * <br /> 4542 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4543 * <br /> 4544 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4545 */ 4546 static int compareSignatures(Signature[] s1, Signature[] s2) { 4547 if (s1 == null) { 4548 return s2 == null 4549 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4550 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4551 } 4552 4553 if (s2 == null) { 4554 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4555 } 4556 4557 if (s1.length != s2.length) { 4558 return PackageManager.SIGNATURE_NO_MATCH; 4559 } 4560 4561 // Since both signature sets are of size 1, we can compare without HashSets. 4562 if (s1.length == 1) { 4563 return s1[0].equals(s2[0]) ? 4564 PackageManager.SIGNATURE_MATCH : 4565 PackageManager.SIGNATURE_NO_MATCH; 4566 } 4567 4568 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4569 for (Signature sig : s1) { 4570 set1.add(sig); 4571 } 4572 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4573 for (Signature sig : s2) { 4574 set2.add(sig); 4575 } 4576 // Make sure s2 contains all signatures in s1. 4577 if (set1.equals(set2)) { 4578 return PackageManager.SIGNATURE_MATCH; 4579 } 4580 return PackageManager.SIGNATURE_NO_MATCH; 4581 } 4582 4583 /** 4584 * If the database version for this type of package (internal storage or 4585 * external storage) is less than the version where package signatures 4586 * were updated, return true. 4587 */ 4588 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4589 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4590 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4591 } 4592 4593 /** 4594 * Used for backward compatibility to make sure any packages with 4595 * certificate chains get upgraded to the new style. {@code existingSigs} 4596 * will be in the old format (since they were stored on disk from before the 4597 * system upgrade) and {@code scannedSigs} will be in the newer format. 4598 */ 4599 private int compareSignaturesCompat(PackageSignatures existingSigs, 4600 PackageParser.Package scannedPkg) { 4601 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4602 return PackageManager.SIGNATURE_NO_MATCH; 4603 } 4604 4605 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4606 for (Signature sig : existingSigs.mSignatures) { 4607 existingSet.add(sig); 4608 } 4609 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4610 for (Signature sig : scannedPkg.mSignatures) { 4611 try { 4612 Signature[] chainSignatures = sig.getChainSignatures(); 4613 for (Signature chainSig : chainSignatures) { 4614 scannedCompatSet.add(chainSig); 4615 } 4616 } catch (CertificateEncodingException e) { 4617 scannedCompatSet.add(sig); 4618 } 4619 } 4620 /* 4621 * Make sure the expanded scanned set contains all signatures in the 4622 * existing one. 4623 */ 4624 if (scannedCompatSet.equals(existingSet)) { 4625 // Migrate the old signatures to the new scheme. 4626 existingSigs.assignSignatures(scannedPkg.mSignatures); 4627 // The new KeySets will be re-added later in the scanning process. 4628 synchronized (mPackages) { 4629 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4630 } 4631 return PackageManager.SIGNATURE_MATCH; 4632 } 4633 return PackageManager.SIGNATURE_NO_MATCH; 4634 } 4635 4636 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4637 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4638 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4639 } 4640 4641 private int compareSignaturesRecover(PackageSignatures existingSigs, 4642 PackageParser.Package scannedPkg) { 4643 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4644 return PackageManager.SIGNATURE_NO_MATCH; 4645 } 4646 4647 String msg = null; 4648 try { 4649 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4650 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4651 + scannedPkg.packageName); 4652 return PackageManager.SIGNATURE_MATCH; 4653 } 4654 } catch (CertificateException e) { 4655 msg = e.getMessage(); 4656 } 4657 4658 logCriticalInfo(Log.INFO, 4659 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4660 return PackageManager.SIGNATURE_NO_MATCH; 4661 } 4662 4663 @Override 4664 public List<String> getAllPackages() { 4665 synchronized (mPackages) { 4666 return new ArrayList<String>(mPackages.keySet()); 4667 } 4668 } 4669 4670 @Override 4671 public String[] getPackagesForUid(int uid) { 4672 uid = UserHandle.getAppId(uid); 4673 // reader 4674 synchronized (mPackages) { 4675 Object obj = mSettings.getUserIdLPr(uid); 4676 if (obj instanceof SharedUserSetting) { 4677 final SharedUserSetting sus = (SharedUserSetting) obj; 4678 final int N = sus.packages.size(); 4679 final String[] res = new String[N]; 4680 final Iterator<PackageSetting> it = sus.packages.iterator(); 4681 int i = 0; 4682 while (it.hasNext()) { 4683 res[i++] = it.next().name; 4684 } 4685 return res; 4686 } else if (obj instanceof PackageSetting) { 4687 final PackageSetting ps = (PackageSetting) obj; 4688 return new String[] { ps.name }; 4689 } 4690 } 4691 return null; 4692 } 4693 4694 @Override 4695 public String getNameForUid(int uid) { 4696 // reader 4697 synchronized (mPackages) { 4698 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4699 if (obj instanceof SharedUserSetting) { 4700 final SharedUserSetting sus = (SharedUserSetting) obj; 4701 return sus.name + ":" + sus.userId; 4702 } else if (obj instanceof PackageSetting) { 4703 final PackageSetting ps = (PackageSetting) obj; 4704 return ps.name; 4705 } 4706 } 4707 return null; 4708 } 4709 4710 @Override 4711 public int getUidForSharedUser(String sharedUserName) { 4712 if(sharedUserName == null) { 4713 return -1; 4714 } 4715 // reader 4716 synchronized (mPackages) { 4717 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4718 if (suid == null) { 4719 return -1; 4720 } 4721 return suid.userId; 4722 } 4723 } 4724 4725 @Override 4726 public int getFlagsForUid(int uid) { 4727 synchronized (mPackages) { 4728 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4729 if (obj instanceof SharedUserSetting) { 4730 final SharedUserSetting sus = (SharedUserSetting) obj; 4731 return sus.pkgFlags; 4732 } else if (obj instanceof PackageSetting) { 4733 final PackageSetting ps = (PackageSetting) obj; 4734 return ps.pkgFlags; 4735 } 4736 } 4737 return 0; 4738 } 4739 4740 @Override 4741 public int getPrivateFlagsForUid(int uid) { 4742 synchronized (mPackages) { 4743 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4744 if (obj instanceof SharedUserSetting) { 4745 final SharedUserSetting sus = (SharedUserSetting) obj; 4746 return sus.pkgPrivateFlags; 4747 } else if (obj instanceof PackageSetting) { 4748 final PackageSetting ps = (PackageSetting) obj; 4749 return ps.pkgPrivateFlags; 4750 } 4751 } 4752 return 0; 4753 } 4754 4755 @Override 4756 public boolean isUidPrivileged(int uid) { 4757 uid = UserHandle.getAppId(uid); 4758 // reader 4759 synchronized (mPackages) { 4760 Object obj = mSettings.getUserIdLPr(uid); 4761 if (obj instanceof SharedUserSetting) { 4762 final SharedUserSetting sus = (SharedUserSetting) obj; 4763 final Iterator<PackageSetting> it = sus.packages.iterator(); 4764 while (it.hasNext()) { 4765 if (it.next().isPrivileged()) { 4766 return true; 4767 } 4768 } 4769 } else if (obj instanceof PackageSetting) { 4770 final PackageSetting ps = (PackageSetting) obj; 4771 return ps.isPrivileged(); 4772 } 4773 } 4774 return false; 4775 } 4776 4777 @Override 4778 public String[] getAppOpPermissionPackages(String permissionName) { 4779 synchronized (mPackages) { 4780 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4781 if (pkgs == null) { 4782 return null; 4783 } 4784 return pkgs.toArray(new String[pkgs.size()]); 4785 } 4786 } 4787 4788 @Override 4789 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4790 int flags, int userId) { 4791 try { 4792 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4793 4794 if (!sUserManager.exists(userId)) return null; 4795 flags = updateFlagsForResolve(flags, userId, intent); 4796 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4797 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4798 4799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4800 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4801 flags, userId); 4802 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4803 4804 final ResolveInfo bestChoice = 4805 chooseBestActivity(intent, resolvedType, flags, query, userId); 4806 4807 if (isEphemeralAllowed(intent, query, userId)) { 4808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4809 final EphemeralResolveInfo ai = 4810 getEphemeralResolveInfo(intent, resolvedType, userId); 4811 if (ai != null) { 4812 if (DEBUG_EPHEMERAL) { 4813 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4814 } 4815 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4816 bestChoice.ephemeralResolveInfo = ai; 4817 } 4818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4819 } 4820 return bestChoice; 4821 } finally { 4822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4823 } 4824 } 4825 4826 @Override 4827 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4828 IntentFilter filter, int match, ComponentName activity) { 4829 final int userId = UserHandle.getCallingUserId(); 4830 if (DEBUG_PREFERRED) { 4831 Log.v(TAG, "setLastChosenActivity intent=" + intent 4832 + " resolvedType=" + resolvedType 4833 + " flags=" + flags 4834 + " filter=" + filter 4835 + " match=" + match 4836 + " activity=" + activity); 4837 filter.dump(new PrintStreamPrinter(System.out), " "); 4838 } 4839 intent.setComponent(null); 4840 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4841 userId); 4842 // Find any earlier preferred or last chosen entries and nuke them 4843 findPreferredActivity(intent, resolvedType, 4844 flags, query, 0, false, true, false, userId); 4845 // Add the new activity as the last chosen for this filter 4846 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4847 "Setting last chosen"); 4848 } 4849 4850 @Override 4851 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4852 final int userId = UserHandle.getCallingUserId(); 4853 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4854 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4855 userId); 4856 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4857 false, false, false, userId); 4858 } 4859 4860 4861 private boolean isEphemeralAllowed( 4862 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4863 // Short circuit and return early if possible. 4864 if (DISABLE_EPHEMERAL_APPS) { 4865 return false; 4866 } 4867 final int callingUser = UserHandle.getCallingUserId(); 4868 if (callingUser != UserHandle.USER_SYSTEM) { 4869 return false; 4870 } 4871 if (mEphemeralResolverConnection == null) { 4872 return false; 4873 } 4874 if (intent.getComponent() != null) { 4875 return false; 4876 } 4877 if (intent.getPackage() != null) { 4878 return false; 4879 } 4880 final boolean isWebUri = hasWebURI(intent); 4881 if (!isWebUri) { 4882 return false; 4883 } 4884 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4885 synchronized (mPackages) { 4886 final int count = resolvedActivites.size(); 4887 for (int n = 0; n < count; n++) { 4888 ResolveInfo info = resolvedActivites.get(n); 4889 String packageName = info.activityInfo.packageName; 4890 PackageSetting ps = mSettings.mPackages.get(packageName); 4891 if (ps != null) { 4892 // Try to get the status from User settings first 4893 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4894 int status = (int) (packedStatus >> 32); 4895 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4896 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4897 if (DEBUG_EPHEMERAL) { 4898 Slog.v(TAG, "DENY ephemeral apps;" 4899 + " pkg: " + packageName + ", status: " + status); 4900 } 4901 return false; 4902 } 4903 } 4904 } 4905 } 4906 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4907 return true; 4908 } 4909 4910 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4911 int userId) { 4912 MessageDigest digest = null; 4913 try { 4914 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4915 } catch (NoSuchAlgorithmException e) { 4916 // If we can't create a digest, ignore ephemeral apps. 4917 return null; 4918 } 4919 4920 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4921 final byte[] digestBytes = digest.digest(hostBytes); 4922 int shaPrefix = 4923 digestBytes[0] << 24 4924 | digestBytes[1] << 16 4925 | digestBytes[2] << 8 4926 | digestBytes[3] << 0; 4927 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4928 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4929 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4930 // No hash prefix match; there are no ephemeral apps for this domain. 4931 return null; 4932 } 4933 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4934 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4935 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4936 continue; 4937 } 4938 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4939 // No filters; this should never happen. 4940 if (filters.isEmpty()) { 4941 continue; 4942 } 4943 // We have a domain match; resolve the filters to see if anything matches. 4944 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4945 for (int j = filters.size() - 1; j >= 0; --j) { 4946 final EphemeralResolveIntentInfo intentInfo = 4947 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4948 ephemeralResolver.addFilter(intentInfo); 4949 } 4950 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4951 intent, resolvedType, false /*defaultOnly*/, userId); 4952 if (!matchedResolveInfoList.isEmpty()) { 4953 return matchedResolveInfoList.get(0); 4954 } 4955 } 4956 // Hash or filter mis-match; no ephemeral apps for this domain. 4957 return null; 4958 } 4959 4960 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4961 int flags, List<ResolveInfo> query, int userId) { 4962 if (query != null) { 4963 final int N = query.size(); 4964 if (N == 1) { 4965 return query.get(0); 4966 } else if (N > 1) { 4967 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4968 // If there is more than one activity with the same priority, 4969 // then let the user decide between them. 4970 ResolveInfo r0 = query.get(0); 4971 ResolveInfo r1 = query.get(1); 4972 if (DEBUG_INTENT_MATCHING || debug) { 4973 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4974 + r1.activityInfo.name + "=" + r1.priority); 4975 } 4976 // If the first activity has a higher priority, or a different 4977 // default, then it is always desirable to pick it. 4978 if (r0.priority != r1.priority 4979 || r0.preferredOrder != r1.preferredOrder 4980 || r0.isDefault != r1.isDefault) { 4981 return query.get(0); 4982 } 4983 // If we have saved a preference for a preferred activity for 4984 // this Intent, use that. 4985 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4986 flags, query, r0.priority, true, false, debug, userId); 4987 if (ri != null) { 4988 return ri; 4989 } 4990 ri = new ResolveInfo(mResolveInfo); 4991 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4992 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4993 ri.activityInfo.applicationInfo = new ApplicationInfo( 4994 ri.activityInfo.applicationInfo); 4995 if (userId != 0) { 4996 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4997 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4998 } 4999 // Make sure that the resolver is displayable in car mode 5000 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5001 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5002 return ri; 5003 } 5004 } 5005 return null; 5006 } 5007 5008 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5009 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5010 final int N = query.size(); 5011 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5012 .get(userId); 5013 // Get the list of persistent preferred activities that handle the intent 5014 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5015 List<PersistentPreferredActivity> pprefs = ppir != null 5016 ? ppir.queryIntent(intent, resolvedType, 5017 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5018 : null; 5019 if (pprefs != null && pprefs.size() > 0) { 5020 final int M = pprefs.size(); 5021 for (int i=0; i<M; i++) { 5022 final PersistentPreferredActivity ppa = pprefs.get(i); 5023 if (DEBUG_PREFERRED || debug) { 5024 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5025 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5026 + "\n component=" + ppa.mComponent); 5027 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5028 } 5029 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5030 flags | MATCH_DISABLED_COMPONENTS, userId); 5031 if (DEBUG_PREFERRED || debug) { 5032 Slog.v(TAG, "Found persistent preferred activity:"); 5033 if (ai != null) { 5034 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5035 } else { 5036 Slog.v(TAG, " null"); 5037 } 5038 } 5039 if (ai == null) { 5040 // This previously registered persistent preferred activity 5041 // component is no longer known. Ignore it and do NOT remove it. 5042 continue; 5043 } 5044 for (int j=0; j<N; j++) { 5045 final ResolveInfo ri = query.get(j); 5046 if (!ri.activityInfo.applicationInfo.packageName 5047 .equals(ai.applicationInfo.packageName)) { 5048 continue; 5049 } 5050 if (!ri.activityInfo.name.equals(ai.name)) { 5051 continue; 5052 } 5053 // Found a persistent preference that can handle the intent. 5054 if (DEBUG_PREFERRED || debug) { 5055 Slog.v(TAG, "Returning persistent preferred activity: " + 5056 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5057 } 5058 return ri; 5059 } 5060 } 5061 } 5062 return null; 5063 } 5064 5065 // TODO: handle preferred activities missing while user has amnesia 5066 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5067 List<ResolveInfo> query, int priority, boolean always, 5068 boolean removeMatches, boolean debug, int userId) { 5069 if (!sUserManager.exists(userId)) return null; 5070 flags = updateFlagsForResolve(flags, userId, intent); 5071 // writer 5072 synchronized (mPackages) { 5073 if (intent.getSelector() != null) { 5074 intent = intent.getSelector(); 5075 } 5076 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5077 5078 // Try to find a matching persistent preferred activity. 5079 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5080 debug, userId); 5081 5082 // If a persistent preferred activity matched, use it. 5083 if (pri != null) { 5084 return pri; 5085 } 5086 5087 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5088 // Get the list of preferred activities that handle the intent 5089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5090 List<PreferredActivity> prefs = pir != null 5091 ? pir.queryIntent(intent, resolvedType, 5092 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5093 : null; 5094 if (prefs != null && prefs.size() > 0) { 5095 boolean changed = false; 5096 try { 5097 // First figure out how good the original match set is. 5098 // We will only allow preferred activities that came 5099 // from the same match quality. 5100 int match = 0; 5101 5102 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5103 5104 final int N = query.size(); 5105 for (int j=0; j<N; j++) { 5106 final ResolveInfo ri = query.get(j); 5107 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5108 + ": 0x" + Integer.toHexString(match)); 5109 if (ri.match > match) { 5110 match = ri.match; 5111 } 5112 } 5113 5114 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5115 + Integer.toHexString(match)); 5116 5117 match &= IntentFilter.MATCH_CATEGORY_MASK; 5118 final int M = prefs.size(); 5119 for (int i=0; i<M; i++) { 5120 final PreferredActivity pa = prefs.get(i); 5121 if (DEBUG_PREFERRED || debug) { 5122 Slog.v(TAG, "Checking PreferredActivity ds=" 5123 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5124 + "\n component=" + pa.mPref.mComponent); 5125 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5126 } 5127 if (pa.mPref.mMatch != match) { 5128 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5129 + Integer.toHexString(pa.mPref.mMatch)); 5130 continue; 5131 } 5132 // If it's not an "always" type preferred activity and that's what we're 5133 // looking for, skip it. 5134 if (always && !pa.mPref.mAlways) { 5135 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5136 continue; 5137 } 5138 final ActivityInfo ai = getActivityInfo( 5139 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5140 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5141 userId); 5142 if (DEBUG_PREFERRED || debug) { 5143 Slog.v(TAG, "Found preferred activity:"); 5144 if (ai != null) { 5145 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5146 } else { 5147 Slog.v(TAG, " null"); 5148 } 5149 } 5150 if (ai == null) { 5151 // This previously registered preferred activity 5152 // component is no longer known. Most likely an update 5153 // to the app was installed and in the new version this 5154 // component no longer exists. Clean it up by removing 5155 // it from the preferred activities list, and skip it. 5156 Slog.w(TAG, "Removing dangling preferred activity: " 5157 + pa.mPref.mComponent); 5158 pir.removeFilter(pa); 5159 changed = true; 5160 continue; 5161 } 5162 for (int j=0; j<N; j++) { 5163 final ResolveInfo ri = query.get(j); 5164 if (!ri.activityInfo.applicationInfo.packageName 5165 .equals(ai.applicationInfo.packageName)) { 5166 continue; 5167 } 5168 if (!ri.activityInfo.name.equals(ai.name)) { 5169 continue; 5170 } 5171 5172 if (removeMatches) { 5173 pir.removeFilter(pa); 5174 changed = true; 5175 if (DEBUG_PREFERRED) { 5176 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5177 } 5178 break; 5179 } 5180 5181 // Okay we found a previously set preferred or last chosen app. 5182 // If the result set is different from when this 5183 // was created, we need to clear it and re-ask the 5184 // user their preference, if we're looking for an "always" type entry. 5185 if (always && !pa.mPref.sameSet(query)) { 5186 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5187 + intent + " type " + resolvedType); 5188 if (DEBUG_PREFERRED) { 5189 Slog.v(TAG, "Removing preferred activity since set changed " 5190 + pa.mPref.mComponent); 5191 } 5192 pir.removeFilter(pa); 5193 // Re-add the filter as a "last chosen" entry (!always) 5194 PreferredActivity lastChosen = new PreferredActivity( 5195 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5196 pir.addFilter(lastChosen); 5197 changed = true; 5198 return null; 5199 } 5200 5201 // Yay! Either the set matched or we're looking for the last chosen 5202 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5203 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5204 return ri; 5205 } 5206 } 5207 } finally { 5208 if (changed) { 5209 if (DEBUG_PREFERRED) { 5210 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5211 } 5212 scheduleWritePackageRestrictionsLocked(userId); 5213 } 5214 } 5215 } 5216 } 5217 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5218 return null; 5219 } 5220 5221 /* 5222 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5223 */ 5224 @Override 5225 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5226 int targetUserId) { 5227 mContext.enforceCallingOrSelfPermission( 5228 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5229 List<CrossProfileIntentFilter> matches = 5230 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5231 if (matches != null) { 5232 int size = matches.size(); 5233 for (int i = 0; i < size; i++) { 5234 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5235 } 5236 } 5237 if (hasWebURI(intent)) { 5238 // cross-profile app linking works only towards the parent. 5239 final UserInfo parent = getProfileParent(sourceUserId); 5240 synchronized(mPackages) { 5241 int flags = updateFlagsForResolve(0, parent.id, intent); 5242 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5243 intent, resolvedType, flags, sourceUserId, parent.id); 5244 return xpDomainInfo != null; 5245 } 5246 } 5247 return false; 5248 } 5249 5250 private UserInfo getProfileParent(int userId) { 5251 final long identity = Binder.clearCallingIdentity(); 5252 try { 5253 return sUserManager.getProfileParent(userId); 5254 } finally { 5255 Binder.restoreCallingIdentity(identity); 5256 } 5257 } 5258 5259 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5260 String resolvedType, int userId) { 5261 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5262 if (resolver != null) { 5263 return resolver.queryIntent(intent, resolvedType, false, userId); 5264 } 5265 return null; 5266 } 5267 5268 @Override 5269 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5270 String resolvedType, int flags, int userId) { 5271 try { 5272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5273 5274 return new ParceledListSlice<>( 5275 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5276 } finally { 5277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5278 } 5279 } 5280 5281 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5282 String resolvedType, int flags, int userId) { 5283 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5284 flags = updateFlagsForResolve(flags, userId, intent); 5285 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5286 false /* requireFullPermission */, false /* checkShell */, 5287 "query intent activities"); 5288 ComponentName comp = intent.getComponent(); 5289 if (comp == null) { 5290 if (intent.getSelector() != null) { 5291 intent = intent.getSelector(); 5292 comp = intent.getComponent(); 5293 } 5294 } 5295 5296 if (comp != null) { 5297 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5298 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5299 if (ai != null) { 5300 final ResolveInfo ri = new ResolveInfo(); 5301 ri.activityInfo = ai; 5302 list.add(ri); 5303 } 5304 return list; 5305 } 5306 5307 // reader 5308 synchronized (mPackages) { 5309 final String pkgName = intent.getPackage(); 5310 if (pkgName == null) { 5311 List<CrossProfileIntentFilter> matchingFilters = 5312 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5313 // Check for results that need to skip the current profile. 5314 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5315 resolvedType, flags, userId); 5316 if (xpResolveInfo != null) { 5317 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5318 result.add(xpResolveInfo); 5319 return filterIfNotSystemUser(result, userId); 5320 } 5321 5322 // Check for results in the current profile. 5323 List<ResolveInfo> result = mActivities.queryIntent( 5324 intent, resolvedType, flags, userId); 5325 result = filterIfNotSystemUser(result, userId); 5326 5327 // Check for cross profile results. 5328 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5329 xpResolveInfo = queryCrossProfileIntents( 5330 matchingFilters, intent, resolvedType, flags, userId, 5331 hasNonNegativePriorityResult); 5332 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5333 boolean isVisibleToUser = filterIfNotSystemUser( 5334 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5335 if (isVisibleToUser) { 5336 result.add(xpResolveInfo); 5337 Collections.sort(result, mResolvePrioritySorter); 5338 } 5339 } 5340 if (hasWebURI(intent)) { 5341 CrossProfileDomainInfo xpDomainInfo = null; 5342 final UserInfo parent = getProfileParent(userId); 5343 if (parent != null) { 5344 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5345 flags, userId, parent.id); 5346 } 5347 if (xpDomainInfo != null) { 5348 if (xpResolveInfo != null) { 5349 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5350 // in the result. 5351 result.remove(xpResolveInfo); 5352 } 5353 if (result.size() == 0) { 5354 result.add(xpDomainInfo.resolveInfo); 5355 return result; 5356 } 5357 } else if (result.size() <= 1) { 5358 return result; 5359 } 5360 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5361 xpDomainInfo, userId); 5362 Collections.sort(result, mResolvePrioritySorter); 5363 } 5364 return result; 5365 } 5366 final PackageParser.Package pkg = mPackages.get(pkgName); 5367 if (pkg != null) { 5368 return filterIfNotSystemUser( 5369 mActivities.queryIntentForPackage( 5370 intent, resolvedType, flags, pkg.activities, userId), 5371 userId); 5372 } 5373 return new ArrayList<ResolveInfo>(); 5374 } 5375 } 5376 5377 private static class CrossProfileDomainInfo { 5378 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5379 ResolveInfo resolveInfo; 5380 /* Best domain verification status of the activities found in the other profile */ 5381 int bestDomainVerificationStatus; 5382 } 5383 5384 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5385 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5386 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5387 sourceUserId)) { 5388 return null; 5389 } 5390 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5391 resolvedType, flags, parentUserId); 5392 5393 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5394 return null; 5395 } 5396 CrossProfileDomainInfo result = null; 5397 int size = resultTargetUser.size(); 5398 for (int i = 0; i < size; i++) { 5399 ResolveInfo riTargetUser = resultTargetUser.get(i); 5400 // Intent filter verification is only for filters that specify a host. So don't return 5401 // those that handle all web uris. 5402 if (riTargetUser.handleAllWebDataURI) { 5403 continue; 5404 } 5405 String packageName = riTargetUser.activityInfo.packageName; 5406 PackageSetting ps = mSettings.mPackages.get(packageName); 5407 if (ps == null) { 5408 continue; 5409 } 5410 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5411 int status = (int)(verificationState >> 32); 5412 if (result == null) { 5413 result = new CrossProfileDomainInfo(); 5414 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5415 sourceUserId, parentUserId); 5416 result.bestDomainVerificationStatus = status; 5417 } else { 5418 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5419 result.bestDomainVerificationStatus); 5420 } 5421 } 5422 // Don't consider matches with status NEVER across profiles. 5423 if (result != null && result.bestDomainVerificationStatus 5424 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5425 return null; 5426 } 5427 return result; 5428 } 5429 5430 /** 5431 * Verification statuses are ordered from the worse to the best, except for 5432 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5433 */ 5434 private int bestDomainVerificationStatus(int status1, int status2) { 5435 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5436 return status2; 5437 } 5438 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5439 return status1; 5440 } 5441 return (int) MathUtils.max(status1, status2); 5442 } 5443 5444 private boolean isUserEnabled(int userId) { 5445 long callingId = Binder.clearCallingIdentity(); 5446 try { 5447 UserInfo userInfo = sUserManager.getUserInfo(userId); 5448 return userInfo != null && userInfo.isEnabled(); 5449 } finally { 5450 Binder.restoreCallingIdentity(callingId); 5451 } 5452 } 5453 5454 /** 5455 * Filter out activities with systemUserOnly flag set, when current user is not System. 5456 * 5457 * @return filtered list 5458 */ 5459 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5460 if (userId == UserHandle.USER_SYSTEM) { 5461 return resolveInfos; 5462 } 5463 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5464 ResolveInfo info = resolveInfos.get(i); 5465 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5466 resolveInfos.remove(i); 5467 } 5468 } 5469 return resolveInfos; 5470 } 5471 5472 /** 5473 * @param resolveInfos list of resolve infos in descending priority order 5474 * @return if the list contains a resolve info with non-negative priority 5475 */ 5476 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5477 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5478 } 5479 5480 private static boolean hasWebURI(Intent intent) { 5481 if (intent.getData() == null) { 5482 return false; 5483 } 5484 final String scheme = intent.getScheme(); 5485 if (TextUtils.isEmpty(scheme)) { 5486 return false; 5487 } 5488 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5489 } 5490 5491 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5492 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5493 int userId) { 5494 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5495 5496 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5497 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5498 candidates.size()); 5499 } 5500 5501 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5502 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5503 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5504 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5505 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5506 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5507 5508 synchronized (mPackages) { 5509 final int count = candidates.size(); 5510 // First, try to use linked apps. Partition the candidates into four lists: 5511 // one for the final results, one for the "do not use ever", one for "undefined status" 5512 // and finally one for "browser app type". 5513 for (int n=0; n<count; n++) { 5514 ResolveInfo info = candidates.get(n); 5515 String packageName = info.activityInfo.packageName; 5516 PackageSetting ps = mSettings.mPackages.get(packageName); 5517 if (ps != null) { 5518 // Add to the special match all list (Browser use case) 5519 if (info.handleAllWebDataURI) { 5520 matchAllList.add(info); 5521 continue; 5522 } 5523 // Try to get the status from User settings first 5524 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5525 int status = (int)(packedStatus >> 32); 5526 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5527 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5528 if (DEBUG_DOMAIN_VERIFICATION) { 5529 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5530 + " : linkgen=" + linkGeneration); 5531 } 5532 // Use link-enabled generation as preferredOrder, i.e. 5533 // prefer newly-enabled over earlier-enabled. 5534 info.preferredOrder = linkGeneration; 5535 alwaysList.add(info); 5536 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5537 if (DEBUG_DOMAIN_VERIFICATION) { 5538 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5539 } 5540 neverList.add(info); 5541 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5542 if (DEBUG_DOMAIN_VERIFICATION) { 5543 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5544 } 5545 alwaysAskList.add(info); 5546 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5547 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5548 if (DEBUG_DOMAIN_VERIFICATION) { 5549 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5550 } 5551 undefinedList.add(info); 5552 } 5553 } 5554 } 5555 5556 // We'll want to include browser possibilities in a few cases 5557 boolean includeBrowser = false; 5558 5559 // First try to add the "always" resolution(s) for the current user, if any 5560 if (alwaysList.size() > 0) { 5561 result.addAll(alwaysList); 5562 } else { 5563 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5564 result.addAll(undefinedList); 5565 // Maybe add one for the other profile. 5566 if (xpDomainInfo != null && ( 5567 xpDomainInfo.bestDomainVerificationStatus 5568 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5569 result.add(xpDomainInfo.resolveInfo); 5570 } 5571 includeBrowser = true; 5572 } 5573 5574 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5575 // If there were 'always' entries their preferred order has been set, so we also 5576 // back that off to make the alternatives equivalent 5577 if (alwaysAskList.size() > 0) { 5578 for (ResolveInfo i : result) { 5579 i.preferredOrder = 0; 5580 } 5581 result.addAll(alwaysAskList); 5582 includeBrowser = true; 5583 } 5584 5585 if (includeBrowser) { 5586 // Also add browsers (all of them or only the default one) 5587 if (DEBUG_DOMAIN_VERIFICATION) { 5588 Slog.v(TAG, " ...including browsers in candidate set"); 5589 } 5590 if ((matchFlags & MATCH_ALL) != 0) { 5591 result.addAll(matchAllList); 5592 } else { 5593 // Browser/generic handling case. If there's a default browser, go straight 5594 // to that (but only if there is no other higher-priority match). 5595 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5596 int maxMatchPrio = 0; 5597 ResolveInfo defaultBrowserMatch = null; 5598 final int numCandidates = matchAllList.size(); 5599 for (int n = 0; n < numCandidates; n++) { 5600 ResolveInfo info = matchAllList.get(n); 5601 // track the highest overall match priority... 5602 if (info.priority > maxMatchPrio) { 5603 maxMatchPrio = info.priority; 5604 } 5605 // ...and the highest-priority default browser match 5606 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5607 if (defaultBrowserMatch == null 5608 || (defaultBrowserMatch.priority < info.priority)) { 5609 if (debug) { 5610 Slog.v(TAG, "Considering default browser match " + info); 5611 } 5612 defaultBrowserMatch = info; 5613 } 5614 } 5615 } 5616 if (defaultBrowserMatch != null 5617 && defaultBrowserMatch.priority >= maxMatchPrio 5618 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5619 { 5620 if (debug) { 5621 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5622 } 5623 result.add(defaultBrowserMatch); 5624 } else { 5625 result.addAll(matchAllList); 5626 } 5627 } 5628 5629 // If there is nothing selected, add all candidates and remove the ones that the user 5630 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5631 if (result.size() == 0) { 5632 result.addAll(candidates); 5633 result.removeAll(neverList); 5634 } 5635 } 5636 } 5637 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5638 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5639 result.size()); 5640 for (ResolveInfo info : result) { 5641 Slog.v(TAG, " + " + info.activityInfo); 5642 } 5643 } 5644 return result; 5645 } 5646 5647 // Returns a packed value as a long: 5648 // 5649 // high 'int'-sized word: link status: undefined/ask/never/always. 5650 // low 'int'-sized word: relative priority among 'always' results. 5651 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5652 long result = ps.getDomainVerificationStatusForUser(userId); 5653 // if none available, get the master status 5654 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5655 if (ps.getIntentFilterVerificationInfo() != null) { 5656 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5657 } 5658 } 5659 return result; 5660 } 5661 5662 private ResolveInfo querySkipCurrentProfileIntents( 5663 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5664 int flags, int sourceUserId) { 5665 if (matchingFilters != null) { 5666 int size = matchingFilters.size(); 5667 for (int i = 0; i < size; i ++) { 5668 CrossProfileIntentFilter filter = matchingFilters.get(i); 5669 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5670 // Checking if there are activities in the target user that can handle the 5671 // intent. 5672 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5673 resolvedType, flags, sourceUserId); 5674 if (resolveInfo != null) { 5675 return resolveInfo; 5676 } 5677 } 5678 } 5679 } 5680 return null; 5681 } 5682 5683 // Return matching ResolveInfo in target user if any. 5684 private ResolveInfo queryCrossProfileIntents( 5685 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5686 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5687 if (matchingFilters != null) { 5688 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5689 // match the same intent. For performance reasons, it is better not to 5690 // run queryIntent twice for the same userId 5691 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5692 int size = matchingFilters.size(); 5693 for (int i = 0; i < size; i++) { 5694 CrossProfileIntentFilter filter = matchingFilters.get(i); 5695 int targetUserId = filter.getTargetUserId(); 5696 boolean skipCurrentProfile = 5697 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5698 boolean skipCurrentProfileIfNoMatchFound = 5699 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5700 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5701 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5702 // Checking if there are activities in the target user that can handle the 5703 // intent. 5704 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5705 resolvedType, flags, sourceUserId); 5706 if (resolveInfo != null) return resolveInfo; 5707 alreadyTriedUserIds.put(targetUserId, true); 5708 } 5709 } 5710 } 5711 return null; 5712 } 5713 5714 /** 5715 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5716 * will forward the intent to the filter's target user. 5717 * Otherwise, returns null. 5718 */ 5719 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5720 String resolvedType, int flags, int sourceUserId) { 5721 int targetUserId = filter.getTargetUserId(); 5722 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5723 resolvedType, flags, targetUserId); 5724 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5725 // If all the matches in the target profile are suspended, return null. 5726 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5727 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5728 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5729 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5730 targetUserId); 5731 } 5732 } 5733 } 5734 return null; 5735 } 5736 5737 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5738 int sourceUserId, int targetUserId) { 5739 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5740 long ident = Binder.clearCallingIdentity(); 5741 boolean targetIsProfile; 5742 try { 5743 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5744 } finally { 5745 Binder.restoreCallingIdentity(ident); 5746 } 5747 String className; 5748 if (targetIsProfile) { 5749 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5750 } else { 5751 className = FORWARD_INTENT_TO_PARENT; 5752 } 5753 ComponentName forwardingActivityComponentName = new ComponentName( 5754 mAndroidApplication.packageName, className); 5755 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5756 sourceUserId); 5757 if (!targetIsProfile) { 5758 forwardingActivityInfo.showUserIcon = targetUserId; 5759 forwardingResolveInfo.noResourceId = true; 5760 } 5761 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5762 forwardingResolveInfo.priority = 0; 5763 forwardingResolveInfo.preferredOrder = 0; 5764 forwardingResolveInfo.match = 0; 5765 forwardingResolveInfo.isDefault = true; 5766 forwardingResolveInfo.filter = filter; 5767 forwardingResolveInfo.targetUserId = targetUserId; 5768 return forwardingResolveInfo; 5769 } 5770 5771 @Override 5772 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5773 Intent[] specifics, String[] specificTypes, Intent intent, 5774 String resolvedType, int flags, int userId) { 5775 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5776 specificTypes, intent, resolvedType, flags, userId)); 5777 } 5778 5779 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5780 Intent[] specifics, String[] specificTypes, Intent intent, 5781 String resolvedType, int flags, int userId) { 5782 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5783 flags = updateFlagsForResolve(flags, userId, intent); 5784 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5785 false /* requireFullPermission */, false /* checkShell */, 5786 "query intent activity options"); 5787 final String resultsAction = intent.getAction(); 5788 5789 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5790 | PackageManager.GET_RESOLVED_FILTER, userId); 5791 5792 if (DEBUG_INTENT_MATCHING) { 5793 Log.v(TAG, "Query " + intent + ": " + results); 5794 } 5795 5796 int specificsPos = 0; 5797 int N; 5798 5799 // todo: note that the algorithm used here is O(N^2). This 5800 // isn't a problem in our current environment, but if we start running 5801 // into situations where we have more than 5 or 10 matches then this 5802 // should probably be changed to something smarter... 5803 5804 // First we go through and resolve each of the specific items 5805 // that were supplied, taking care of removing any corresponding 5806 // duplicate items in the generic resolve list. 5807 if (specifics != null) { 5808 for (int i=0; i<specifics.length; i++) { 5809 final Intent sintent = specifics[i]; 5810 if (sintent == null) { 5811 continue; 5812 } 5813 5814 if (DEBUG_INTENT_MATCHING) { 5815 Log.v(TAG, "Specific #" + i + ": " + sintent); 5816 } 5817 5818 String action = sintent.getAction(); 5819 if (resultsAction != null && resultsAction.equals(action)) { 5820 // If this action was explicitly requested, then don't 5821 // remove things that have it. 5822 action = null; 5823 } 5824 5825 ResolveInfo ri = null; 5826 ActivityInfo ai = null; 5827 5828 ComponentName comp = sintent.getComponent(); 5829 if (comp == null) { 5830 ri = resolveIntent( 5831 sintent, 5832 specificTypes != null ? specificTypes[i] : null, 5833 flags, userId); 5834 if (ri == null) { 5835 continue; 5836 } 5837 if (ri == mResolveInfo) { 5838 // ACK! Must do something better with this. 5839 } 5840 ai = ri.activityInfo; 5841 comp = new ComponentName(ai.applicationInfo.packageName, 5842 ai.name); 5843 } else { 5844 ai = getActivityInfo(comp, flags, userId); 5845 if (ai == null) { 5846 continue; 5847 } 5848 } 5849 5850 // Look for any generic query activities that are duplicates 5851 // of this specific one, and remove them from the results. 5852 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5853 N = results.size(); 5854 int j; 5855 for (j=specificsPos; j<N; j++) { 5856 ResolveInfo sri = results.get(j); 5857 if ((sri.activityInfo.name.equals(comp.getClassName()) 5858 && sri.activityInfo.applicationInfo.packageName.equals( 5859 comp.getPackageName())) 5860 || (action != null && sri.filter.matchAction(action))) { 5861 results.remove(j); 5862 if (DEBUG_INTENT_MATCHING) Log.v( 5863 TAG, "Removing duplicate item from " + j 5864 + " due to specific " + specificsPos); 5865 if (ri == null) { 5866 ri = sri; 5867 } 5868 j--; 5869 N--; 5870 } 5871 } 5872 5873 // Add this specific item to its proper place. 5874 if (ri == null) { 5875 ri = new ResolveInfo(); 5876 ri.activityInfo = ai; 5877 } 5878 results.add(specificsPos, ri); 5879 ri.specificIndex = i; 5880 specificsPos++; 5881 } 5882 } 5883 5884 // Now we go through the remaining generic results and remove any 5885 // duplicate actions that are found here. 5886 N = results.size(); 5887 for (int i=specificsPos; i<N-1; i++) { 5888 final ResolveInfo rii = results.get(i); 5889 if (rii.filter == null) { 5890 continue; 5891 } 5892 5893 // Iterate over all of the actions of this result's intent 5894 // filter... typically this should be just one. 5895 final Iterator<String> it = rii.filter.actionsIterator(); 5896 if (it == null) { 5897 continue; 5898 } 5899 while (it.hasNext()) { 5900 final String action = it.next(); 5901 if (resultsAction != null && resultsAction.equals(action)) { 5902 // If this action was explicitly requested, then don't 5903 // remove things that have it. 5904 continue; 5905 } 5906 for (int j=i+1; j<N; j++) { 5907 final ResolveInfo rij = results.get(j); 5908 if (rij.filter != null && rij.filter.hasAction(action)) { 5909 results.remove(j); 5910 if (DEBUG_INTENT_MATCHING) Log.v( 5911 TAG, "Removing duplicate item from " + j 5912 + " due to action " + action + " at " + i); 5913 j--; 5914 N--; 5915 } 5916 } 5917 } 5918 5919 // If the caller didn't request filter information, drop it now 5920 // so we don't have to marshall/unmarshall it. 5921 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5922 rii.filter = null; 5923 } 5924 } 5925 5926 // Filter out the caller activity if so requested. 5927 if (caller != null) { 5928 N = results.size(); 5929 for (int i=0; i<N; i++) { 5930 ActivityInfo ainfo = results.get(i).activityInfo; 5931 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5932 && caller.getClassName().equals(ainfo.name)) { 5933 results.remove(i); 5934 break; 5935 } 5936 } 5937 } 5938 5939 // If the caller didn't request filter information, 5940 // drop them now so we don't have to 5941 // marshall/unmarshall it. 5942 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5943 N = results.size(); 5944 for (int i=0; i<N; i++) { 5945 results.get(i).filter = null; 5946 } 5947 } 5948 5949 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5950 return results; 5951 } 5952 5953 @Override 5954 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5955 String resolvedType, int flags, int userId) { 5956 return new ParceledListSlice<>( 5957 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5958 } 5959 5960 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5961 String resolvedType, int flags, int userId) { 5962 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5963 flags = updateFlagsForResolve(flags, userId, intent); 5964 ComponentName comp = intent.getComponent(); 5965 if (comp == null) { 5966 if (intent.getSelector() != null) { 5967 intent = intent.getSelector(); 5968 comp = intent.getComponent(); 5969 } 5970 } 5971 if (comp != null) { 5972 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5973 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5974 if (ai != null) { 5975 ResolveInfo ri = new ResolveInfo(); 5976 ri.activityInfo = ai; 5977 list.add(ri); 5978 } 5979 return list; 5980 } 5981 5982 // reader 5983 synchronized (mPackages) { 5984 String pkgName = intent.getPackage(); 5985 if (pkgName == null) { 5986 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5987 } 5988 final PackageParser.Package pkg = mPackages.get(pkgName); 5989 if (pkg != null) { 5990 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5991 userId); 5992 } 5993 return Collections.emptyList(); 5994 } 5995 } 5996 5997 @Override 5998 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5999 if (!sUserManager.exists(userId)) return null; 6000 flags = updateFlagsForResolve(flags, userId, intent); 6001 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6002 if (query != null) { 6003 if (query.size() >= 1) { 6004 // If there is more than one service with the same priority, 6005 // just arbitrarily pick the first one. 6006 return query.get(0); 6007 } 6008 } 6009 return null; 6010 } 6011 6012 @Override 6013 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6014 String resolvedType, int flags, int userId) { 6015 return new ParceledListSlice<>( 6016 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6017 } 6018 6019 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6020 String resolvedType, int flags, int userId) { 6021 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6022 flags = updateFlagsForResolve(flags, userId, intent); 6023 ComponentName comp = intent.getComponent(); 6024 if (comp == null) { 6025 if (intent.getSelector() != null) { 6026 intent = intent.getSelector(); 6027 comp = intent.getComponent(); 6028 } 6029 } 6030 if (comp != null) { 6031 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6032 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6033 if (si != null) { 6034 final ResolveInfo ri = new ResolveInfo(); 6035 ri.serviceInfo = si; 6036 list.add(ri); 6037 } 6038 return list; 6039 } 6040 6041 // reader 6042 synchronized (mPackages) { 6043 String pkgName = intent.getPackage(); 6044 if (pkgName == null) { 6045 return mServices.queryIntent(intent, resolvedType, flags, userId); 6046 } 6047 final PackageParser.Package pkg = mPackages.get(pkgName); 6048 if (pkg != null) { 6049 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6050 userId); 6051 } 6052 return Collections.emptyList(); 6053 } 6054 } 6055 6056 @Override 6057 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6058 String resolvedType, int flags, int userId) { 6059 return new ParceledListSlice<>( 6060 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6061 } 6062 6063 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6064 Intent intent, String resolvedType, int flags, int userId) { 6065 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6066 flags = updateFlagsForResolve(flags, userId, intent); 6067 ComponentName comp = intent.getComponent(); 6068 if (comp == null) { 6069 if (intent.getSelector() != null) { 6070 intent = intent.getSelector(); 6071 comp = intent.getComponent(); 6072 } 6073 } 6074 if (comp != null) { 6075 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6076 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6077 if (pi != null) { 6078 final ResolveInfo ri = new ResolveInfo(); 6079 ri.providerInfo = pi; 6080 list.add(ri); 6081 } 6082 return list; 6083 } 6084 6085 // reader 6086 synchronized (mPackages) { 6087 String pkgName = intent.getPackage(); 6088 if (pkgName == null) { 6089 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6090 } 6091 final PackageParser.Package pkg = mPackages.get(pkgName); 6092 if (pkg != null) { 6093 return mProviders.queryIntentForPackage( 6094 intent, resolvedType, flags, pkg.providers, userId); 6095 } 6096 return Collections.emptyList(); 6097 } 6098 } 6099 6100 @Override 6101 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6102 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6103 flags = updateFlagsForPackage(flags, userId, null); 6104 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6105 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6106 true /* requireFullPermission */, false /* checkShell */, 6107 "get installed packages"); 6108 6109 // writer 6110 synchronized (mPackages) { 6111 ArrayList<PackageInfo> list; 6112 if (listUninstalled) { 6113 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6114 for (PackageSetting ps : mSettings.mPackages.values()) { 6115 final PackageInfo pi; 6116 if (ps.pkg != null) { 6117 pi = generatePackageInfo(ps, flags, userId); 6118 } else { 6119 pi = generatePackageInfo(ps, flags, userId); 6120 } 6121 if (pi != null) { 6122 list.add(pi); 6123 } 6124 } 6125 } else { 6126 list = new ArrayList<PackageInfo>(mPackages.size()); 6127 for (PackageParser.Package p : mPackages.values()) { 6128 final PackageInfo pi = 6129 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6130 if (pi != null) { 6131 list.add(pi); 6132 } 6133 } 6134 } 6135 6136 return new ParceledListSlice<PackageInfo>(list); 6137 } 6138 } 6139 6140 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6141 String[] permissions, boolean[] tmp, int flags, int userId) { 6142 int numMatch = 0; 6143 final PermissionsState permissionsState = ps.getPermissionsState(); 6144 for (int i=0; i<permissions.length; i++) { 6145 final String permission = permissions[i]; 6146 if (permissionsState.hasPermission(permission, userId)) { 6147 tmp[i] = true; 6148 numMatch++; 6149 } else { 6150 tmp[i] = false; 6151 } 6152 } 6153 if (numMatch == 0) { 6154 return; 6155 } 6156 final PackageInfo pi; 6157 if (ps.pkg != null) { 6158 pi = generatePackageInfo(ps, flags, userId); 6159 } else { 6160 pi = generatePackageInfo(ps, flags, userId); 6161 } 6162 // The above might return null in cases of uninstalled apps or install-state 6163 // skew across users/profiles. 6164 if (pi != null) { 6165 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6166 if (numMatch == permissions.length) { 6167 pi.requestedPermissions = permissions; 6168 } else { 6169 pi.requestedPermissions = new String[numMatch]; 6170 numMatch = 0; 6171 for (int i=0; i<permissions.length; i++) { 6172 if (tmp[i]) { 6173 pi.requestedPermissions[numMatch] = permissions[i]; 6174 numMatch++; 6175 } 6176 } 6177 } 6178 } 6179 list.add(pi); 6180 } 6181 } 6182 6183 @Override 6184 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6185 String[] permissions, int flags, int userId) { 6186 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6187 flags = updateFlagsForPackage(flags, userId, permissions); 6188 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6189 6190 // writer 6191 synchronized (mPackages) { 6192 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6193 boolean[] tmpBools = new boolean[permissions.length]; 6194 if (listUninstalled) { 6195 for (PackageSetting ps : mSettings.mPackages.values()) { 6196 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6197 } 6198 } else { 6199 for (PackageParser.Package pkg : mPackages.values()) { 6200 PackageSetting ps = (PackageSetting)pkg.mExtras; 6201 if (ps != null) { 6202 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6203 userId); 6204 } 6205 } 6206 } 6207 6208 return new ParceledListSlice<PackageInfo>(list); 6209 } 6210 } 6211 6212 @Override 6213 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6214 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6215 flags = updateFlagsForApplication(flags, userId, null); 6216 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6217 6218 // writer 6219 synchronized (mPackages) { 6220 ArrayList<ApplicationInfo> list; 6221 if (listUninstalled) { 6222 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6223 for (PackageSetting ps : mSettings.mPackages.values()) { 6224 ApplicationInfo ai; 6225 if (ps.pkg != null) { 6226 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6227 ps.readUserState(userId), userId); 6228 } else { 6229 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6230 } 6231 if (ai != null) { 6232 list.add(ai); 6233 } 6234 } 6235 } else { 6236 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6237 for (PackageParser.Package p : mPackages.values()) { 6238 if (p.mExtras != null) { 6239 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6240 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6241 if (ai != null) { 6242 list.add(ai); 6243 } 6244 } 6245 } 6246 } 6247 6248 return new ParceledListSlice<ApplicationInfo>(list); 6249 } 6250 } 6251 6252 @Override 6253 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6254 if (DISABLE_EPHEMERAL_APPS) { 6255 return null; 6256 } 6257 6258 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6259 "getEphemeralApplications"); 6260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6261 true /* requireFullPermission */, false /* checkShell */, 6262 "getEphemeralApplications"); 6263 synchronized (mPackages) { 6264 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6265 .getEphemeralApplicationsLPw(userId); 6266 if (ephemeralApps != null) { 6267 return new ParceledListSlice<>(ephemeralApps); 6268 } 6269 } 6270 return null; 6271 } 6272 6273 @Override 6274 public boolean isEphemeralApplication(String packageName, int userId) { 6275 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6276 true /* requireFullPermission */, false /* checkShell */, 6277 "isEphemeral"); 6278 if (DISABLE_EPHEMERAL_APPS) { 6279 return false; 6280 } 6281 6282 if (!isCallerSameApp(packageName)) { 6283 return false; 6284 } 6285 synchronized (mPackages) { 6286 PackageParser.Package pkg = mPackages.get(packageName); 6287 if (pkg != null) { 6288 return pkg.applicationInfo.isEphemeralApp(); 6289 } 6290 } 6291 return false; 6292 } 6293 6294 @Override 6295 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6296 if (DISABLE_EPHEMERAL_APPS) { 6297 return null; 6298 } 6299 6300 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6301 true /* requireFullPermission */, false /* checkShell */, 6302 "getCookie"); 6303 if (!isCallerSameApp(packageName)) { 6304 return null; 6305 } 6306 synchronized (mPackages) { 6307 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6308 packageName, userId); 6309 } 6310 } 6311 6312 @Override 6313 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6314 if (DISABLE_EPHEMERAL_APPS) { 6315 return true; 6316 } 6317 6318 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6319 true /* requireFullPermission */, true /* checkShell */, 6320 "setCookie"); 6321 if (!isCallerSameApp(packageName)) { 6322 return false; 6323 } 6324 synchronized (mPackages) { 6325 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6326 packageName, cookie, userId); 6327 } 6328 } 6329 6330 @Override 6331 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6332 if (DISABLE_EPHEMERAL_APPS) { 6333 return null; 6334 } 6335 6336 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6337 "getEphemeralApplicationIcon"); 6338 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6339 true /* requireFullPermission */, false /* checkShell */, 6340 "getEphemeralApplicationIcon"); 6341 synchronized (mPackages) { 6342 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6343 packageName, userId); 6344 } 6345 } 6346 6347 private boolean isCallerSameApp(String packageName) { 6348 PackageParser.Package pkg = mPackages.get(packageName); 6349 return pkg != null 6350 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6351 } 6352 6353 @Override 6354 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6355 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6356 } 6357 6358 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6359 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6360 6361 // reader 6362 synchronized (mPackages) { 6363 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6364 final int userId = UserHandle.getCallingUserId(); 6365 while (i.hasNext()) { 6366 final PackageParser.Package p = i.next(); 6367 if (p.applicationInfo == null) continue; 6368 6369 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6370 && !p.applicationInfo.isDirectBootAware(); 6371 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6372 && p.applicationInfo.isDirectBootAware(); 6373 6374 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6375 && (!mSafeMode || isSystemApp(p)) 6376 && (matchesUnaware || matchesAware)) { 6377 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6378 if (ps != null) { 6379 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6380 ps.readUserState(userId), userId); 6381 if (ai != null) { 6382 finalList.add(ai); 6383 } 6384 } 6385 } 6386 } 6387 } 6388 6389 return finalList; 6390 } 6391 6392 @Override 6393 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6394 if (!sUserManager.exists(userId)) return null; 6395 flags = updateFlagsForComponent(flags, userId, name); 6396 // reader 6397 synchronized (mPackages) { 6398 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6399 PackageSetting ps = provider != null 6400 ? mSettings.mPackages.get(provider.owner.packageName) 6401 : null; 6402 return ps != null 6403 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6404 ? PackageParser.generateProviderInfo(provider, flags, 6405 ps.readUserState(userId), userId) 6406 : null; 6407 } 6408 } 6409 6410 /** 6411 * @deprecated 6412 */ 6413 @Deprecated 6414 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6415 // reader 6416 synchronized (mPackages) { 6417 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6418 .entrySet().iterator(); 6419 final int userId = UserHandle.getCallingUserId(); 6420 while (i.hasNext()) { 6421 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6422 PackageParser.Provider p = entry.getValue(); 6423 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6424 6425 if (ps != null && p.syncable 6426 && (!mSafeMode || (p.info.applicationInfo.flags 6427 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6428 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6429 ps.readUserState(userId), userId); 6430 if (info != null) { 6431 outNames.add(entry.getKey()); 6432 outInfo.add(info); 6433 } 6434 } 6435 } 6436 } 6437 } 6438 6439 @Override 6440 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6441 int uid, int flags) { 6442 final int userId = processName != null ? UserHandle.getUserId(uid) 6443 : UserHandle.getCallingUserId(); 6444 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6445 flags = updateFlagsForComponent(flags, userId, processName); 6446 6447 ArrayList<ProviderInfo> finalList = null; 6448 // reader 6449 synchronized (mPackages) { 6450 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6451 while (i.hasNext()) { 6452 final PackageParser.Provider p = i.next(); 6453 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6454 if (ps != null && p.info.authority != null 6455 && (processName == null 6456 || (p.info.processName.equals(processName) 6457 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6458 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6459 if (finalList == null) { 6460 finalList = new ArrayList<ProviderInfo>(3); 6461 } 6462 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6463 ps.readUserState(userId), userId); 6464 if (info != null) { 6465 finalList.add(info); 6466 } 6467 } 6468 } 6469 } 6470 6471 if (finalList != null) { 6472 Collections.sort(finalList, mProviderInitOrderSorter); 6473 return new ParceledListSlice<ProviderInfo>(finalList); 6474 } 6475 6476 return ParceledListSlice.emptyList(); 6477 } 6478 6479 @Override 6480 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6481 // reader 6482 synchronized (mPackages) { 6483 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6484 return PackageParser.generateInstrumentationInfo(i, flags); 6485 } 6486 } 6487 6488 @Override 6489 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6490 String targetPackage, int flags) { 6491 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6492 } 6493 6494 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6495 int flags) { 6496 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6497 6498 // reader 6499 synchronized (mPackages) { 6500 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6501 while (i.hasNext()) { 6502 final PackageParser.Instrumentation p = i.next(); 6503 if (targetPackage == null 6504 || targetPackage.equals(p.info.targetPackage)) { 6505 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6506 flags); 6507 if (ii != null) { 6508 finalList.add(ii); 6509 } 6510 } 6511 } 6512 } 6513 6514 return finalList; 6515 } 6516 6517 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6518 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6519 if (overlays == null) { 6520 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6521 return; 6522 } 6523 for (PackageParser.Package opkg : overlays.values()) { 6524 // Not much to do if idmap fails: we already logged the error 6525 // and we certainly don't want to abort installation of pkg simply 6526 // because an overlay didn't fit properly. For these reasons, 6527 // ignore the return value of createIdmapForPackagePairLI. 6528 createIdmapForPackagePairLI(pkg, opkg); 6529 } 6530 } 6531 6532 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6533 PackageParser.Package opkg) { 6534 if (!opkg.mTrustedOverlay) { 6535 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6536 opkg.baseCodePath + ": overlay not trusted"); 6537 return false; 6538 } 6539 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6540 if (overlaySet == null) { 6541 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6542 opkg.baseCodePath + " but target package has no known overlays"); 6543 return false; 6544 } 6545 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6546 // TODO: generate idmap for split APKs 6547 try { 6548 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6549 } catch (InstallerException e) { 6550 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6551 + opkg.baseCodePath); 6552 return false; 6553 } 6554 PackageParser.Package[] overlayArray = 6555 overlaySet.values().toArray(new PackageParser.Package[0]); 6556 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6557 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6558 return p1.mOverlayPriority - p2.mOverlayPriority; 6559 } 6560 }; 6561 Arrays.sort(overlayArray, cmp); 6562 6563 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6564 int i = 0; 6565 for (PackageParser.Package p : overlayArray) { 6566 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6567 } 6568 return true; 6569 } 6570 6571 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6573 try { 6574 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6575 } finally { 6576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6577 } 6578 } 6579 6580 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6581 final File[] files = dir.listFiles(); 6582 if (ArrayUtils.isEmpty(files)) { 6583 Log.d(TAG, "No files in app dir " + dir); 6584 return; 6585 } 6586 6587 if (DEBUG_PACKAGE_SCANNING) { 6588 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6589 + " flags=0x" + Integer.toHexString(parseFlags)); 6590 } 6591 6592 for (File file : files) { 6593 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6594 && !PackageInstallerService.isStageName(file.getName()); 6595 if (!isPackage) { 6596 // Ignore entries which are not packages 6597 continue; 6598 } 6599 try { 6600 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6601 scanFlags, currentTime, null); 6602 } catch (PackageManagerException e) { 6603 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6604 6605 // Delete invalid userdata apps 6606 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6607 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6608 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6609 removeCodePathLI(file); 6610 } 6611 } 6612 } 6613 } 6614 6615 private static File getSettingsProblemFile() { 6616 File dataDir = Environment.getDataDirectory(); 6617 File systemDir = new File(dataDir, "system"); 6618 File fname = new File(systemDir, "uiderrors.txt"); 6619 return fname; 6620 } 6621 6622 static void reportSettingsProblem(int priority, String msg) { 6623 logCriticalInfo(priority, msg); 6624 } 6625 6626 static void logCriticalInfo(int priority, String msg) { 6627 Slog.println(priority, TAG, msg); 6628 EventLogTags.writePmCriticalInfo(msg); 6629 try { 6630 File fname = getSettingsProblemFile(); 6631 FileOutputStream out = new FileOutputStream(fname, true); 6632 PrintWriter pw = new FastPrintWriter(out); 6633 SimpleDateFormat formatter = new SimpleDateFormat(); 6634 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6635 pw.println(dateString + ": " + msg); 6636 pw.close(); 6637 FileUtils.setPermissions( 6638 fname.toString(), 6639 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6640 -1, -1); 6641 } catch (java.io.IOException e) { 6642 } 6643 } 6644 6645 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6646 final int policyFlags) throws PackageManagerException { 6647 if (ps != null 6648 && ps.codePath.equals(srcFile) 6649 && ps.timeStamp == srcFile.lastModified() 6650 && !isCompatSignatureUpdateNeeded(pkg) 6651 && !isRecoverSignatureUpdateNeeded(pkg)) { 6652 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6653 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6654 ArraySet<PublicKey> signingKs; 6655 synchronized (mPackages) { 6656 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6657 } 6658 if (ps.signatures.mSignatures != null 6659 && ps.signatures.mSignatures.length != 0 6660 && signingKs != null) { 6661 // Optimization: reuse the existing cached certificates 6662 // if the package appears to be unchanged. 6663 pkg.mSignatures = ps.signatures.mSignatures; 6664 pkg.mSigningKeys = signingKs; 6665 return; 6666 } 6667 6668 Slog.w(TAG, "PackageSetting for " + ps.name 6669 + " is missing signatures. Collecting certs again to recover them."); 6670 } else { 6671 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6672 } 6673 6674 try { 6675 PackageParser.collectCertificates(pkg, policyFlags); 6676 } catch (PackageParserException e) { 6677 throw PackageManagerException.from(e); 6678 } 6679 } 6680 6681 /** 6682 * Traces a package scan. 6683 * @see #scanPackageLI(File, int, int, long, UserHandle) 6684 */ 6685 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6686 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6687 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6688 try { 6689 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6690 } finally { 6691 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6692 } 6693 } 6694 6695 /** 6696 * Scans a package and returns the newly parsed package. 6697 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6698 */ 6699 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6700 long currentTime, UserHandle user) throws PackageManagerException { 6701 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6702 PackageParser pp = new PackageParser(); 6703 pp.setSeparateProcesses(mSeparateProcesses); 6704 pp.setOnlyCoreApps(mOnlyCore); 6705 pp.setDisplayMetrics(mMetrics); 6706 6707 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6708 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6709 } 6710 6711 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6712 final PackageParser.Package pkg; 6713 try { 6714 pkg = pp.parsePackage(scanFile, parseFlags); 6715 } catch (PackageParserException e) { 6716 throw PackageManagerException.from(e); 6717 } finally { 6718 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6719 } 6720 6721 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6722 } 6723 6724 /** 6725 * Scans a package and returns the newly parsed package. 6726 * @throws PackageManagerException on a parse error. 6727 */ 6728 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6729 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6730 throws PackageManagerException { 6731 // If the package has children and this is the first dive in the function 6732 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6733 // packages (parent and children) would be successfully scanned before the 6734 // actual scan since scanning mutates internal state and we want to atomically 6735 // install the package and its children. 6736 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6737 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6738 scanFlags |= SCAN_CHECK_ONLY; 6739 } 6740 } else { 6741 scanFlags &= ~SCAN_CHECK_ONLY; 6742 } 6743 6744 // Scan the parent 6745 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6746 scanFlags, currentTime, user); 6747 6748 // Scan the children 6749 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6750 for (int i = 0; i < childCount; i++) { 6751 PackageParser.Package childPackage = pkg.childPackages.get(i); 6752 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6753 currentTime, user); 6754 } 6755 6756 6757 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6758 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6759 } 6760 6761 return scannedPkg; 6762 } 6763 6764 /** 6765 * Scans a package and returns the newly parsed package. 6766 * @throws PackageManagerException on a parse error. 6767 */ 6768 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6769 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6770 throws PackageManagerException { 6771 PackageSetting ps = null; 6772 PackageSetting updatedPkg; 6773 // reader 6774 synchronized (mPackages) { 6775 // Look to see if we already know about this package. 6776 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6777 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6778 // This package has been renamed to its original name. Let's 6779 // use that. 6780 ps = mSettings.peekPackageLPr(oldName); 6781 } 6782 // If there was no original package, see one for the real package name. 6783 if (ps == null) { 6784 ps = mSettings.peekPackageLPr(pkg.packageName); 6785 } 6786 // Check to see if this package could be hiding/updating a system 6787 // package. Must look for it either under the original or real 6788 // package name depending on our state. 6789 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6790 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6791 6792 // If this is a package we don't know about on the system partition, we 6793 // may need to remove disabled child packages on the system partition 6794 // or may need to not add child packages if the parent apk is updated 6795 // on the data partition and no longer defines this child package. 6796 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6797 // If this is a parent package for an updated system app and this system 6798 // app got an OTA update which no longer defines some of the child packages 6799 // we have to prune them from the disabled system packages. 6800 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6801 if (disabledPs != null) { 6802 final int scannedChildCount = (pkg.childPackages != null) 6803 ? pkg.childPackages.size() : 0; 6804 final int disabledChildCount = disabledPs.childPackageNames != null 6805 ? disabledPs.childPackageNames.size() : 0; 6806 for (int i = 0; i < disabledChildCount; i++) { 6807 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6808 boolean disabledPackageAvailable = false; 6809 for (int j = 0; j < scannedChildCount; j++) { 6810 PackageParser.Package childPkg = pkg.childPackages.get(j); 6811 if (childPkg.packageName.equals(disabledChildPackageName)) { 6812 disabledPackageAvailable = true; 6813 break; 6814 } 6815 } 6816 if (!disabledPackageAvailable) { 6817 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6818 } 6819 } 6820 } 6821 } 6822 } 6823 6824 boolean updatedPkgBetter = false; 6825 // First check if this is a system package that may involve an update 6826 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6827 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6828 // it needs to drop FLAG_PRIVILEGED. 6829 if (locationIsPrivileged(scanFile)) { 6830 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6831 } else { 6832 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6833 } 6834 6835 if (ps != null && !ps.codePath.equals(scanFile)) { 6836 // The path has changed from what was last scanned... check the 6837 // version of the new path against what we have stored to determine 6838 // what to do. 6839 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6840 if (pkg.mVersionCode <= ps.versionCode) { 6841 // The system package has been updated and the code path does not match 6842 // Ignore entry. Skip it. 6843 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6844 + " ignored: updated version " + ps.versionCode 6845 + " better than this " + pkg.mVersionCode); 6846 if (!updatedPkg.codePath.equals(scanFile)) { 6847 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6848 + ps.name + " changing from " + updatedPkg.codePathString 6849 + " to " + scanFile); 6850 updatedPkg.codePath = scanFile; 6851 updatedPkg.codePathString = scanFile.toString(); 6852 updatedPkg.resourcePath = scanFile; 6853 updatedPkg.resourcePathString = scanFile.toString(); 6854 } 6855 updatedPkg.pkg = pkg; 6856 updatedPkg.versionCode = pkg.mVersionCode; 6857 6858 // Update the disabled system child packages to point to the package too. 6859 final int childCount = updatedPkg.childPackageNames != null 6860 ? updatedPkg.childPackageNames.size() : 0; 6861 for (int i = 0; i < childCount; i++) { 6862 String childPackageName = updatedPkg.childPackageNames.get(i); 6863 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6864 childPackageName); 6865 if (updatedChildPkg != null) { 6866 updatedChildPkg.pkg = pkg; 6867 updatedChildPkg.versionCode = pkg.mVersionCode; 6868 } 6869 } 6870 6871 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6872 + scanFile + " ignored: updated version " + ps.versionCode 6873 + " better than this " + pkg.mVersionCode); 6874 } else { 6875 // The current app on the system partition is better than 6876 // what we have updated to on the data partition; switch 6877 // back to the system partition version. 6878 // At this point, its safely assumed that package installation for 6879 // apps in system partition will go through. If not there won't be a working 6880 // version of the app 6881 // writer 6882 synchronized (mPackages) { 6883 // Just remove the loaded entries from package lists. 6884 mPackages.remove(ps.name); 6885 } 6886 6887 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6888 + " reverting from " + ps.codePathString 6889 + ": new version " + pkg.mVersionCode 6890 + " better than installed " + ps.versionCode); 6891 6892 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6893 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6894 synchronized (mInstallLock) { 6895 args.cleanUpResourcesLI(); 6896 } 6897 synchronized (mPackages) { 6898 mSettings.enableSystemPackageLPw(ps.name); 6899 } 6900 updatedPkgBetter = true; 6901 } 6902 } 6903 } 6904 6905 if (updatedPkg != null) { 6906 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6907 // initially 6908 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6909 6910 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6911 // flag set initially 6912 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6913 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6914 } 6915 } 6916 6917 // Verify certificates against what was last scanned 6918 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6919 6920 /* 6921 * A new system app appeared, but we already had a non-system one of the 6922 * same name installed earlier. 6923 */ 6924 boolean shouldHideSystemApp = false; 6925 if (updatedPkg == null && ps != null 6926 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6927 /* 6928 * Check to make sure the signatures match first. If they don't, 6929 * wipe the installed application and its data. 6930 */ 6931 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6932 != PackageManager.SIGNATURE_MATCH) { 6933 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6934 + " signatures don't match existing userdata copy; removing"); 6935 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6936 "scanPackageInternalLI")) { 6937 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6938 } 6939 ps = null; 6940 } else { 6941 /* 6942 * If the newly-added system app is an older version than the 6943 * already installed version, hide it. It will be scanned later 6944 * and re-added like an update. 6945 */ 6946 if (pkg.mVersionCode <= ps.versionCode) { 6947 shouldHideSystemApp = true; 6948 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6949 + " but new version " + pkg.mVersionCode + " better than installed " 6950 + ps.versionCode + "; hiding system"); 6951 } else { 6952 /* 6953 * The newly found system app is a newer version that the 6954 * one previously installed. Simply remove the 6955 * already-installed application and replace it with our own 6956 * while keeping the application data. 6957 */ 6958 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6959 + " reverting from " + ps.codePathString + ": new version " 6960 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6961 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6962 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6963 synchronized (mInstallLock) { 6964 args.cleanUpResourcesLI(); 6965 } 6966 } 6967 } 6968 } 6969 6970 // The apk is forward locked (not public) if its code and resources 6971 // are kept in different files. (except for app in either system or 6972 // vendor path). 6973 // TODO grab this value from PackageSettings 6974 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6975 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6976 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6977 } 6978 } 6979 6980 // TODO: extend to support forward-locked splits 6981 String resourcePath = null; 6982 String baseResourcePath = null; 6983 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6984 if (ps != null && ps.resourcePathString != null) { 6985 resourcePath = ps.resourcePathString; 6986 baseResourcePath = ps.resourcePathString; 6987 } else { 6988 // Should not happen at all. Just log an error. 6989 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6990 } 6991 } else { 6992 resourcePath = pkg.codePath; 6993 baseResourcePath = pkg.baseCodePath; 6994 } 6995 6996 // Set application objects path explicitly. 6997 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6998 pkg.setApplicationInfoCodePath(pkg.codePath); 6999 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7000 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7001 pkg.setApplicationInfoResourcePath(resourcePath); 7002 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7003 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7004 7005 // Note that we invoke the following method only if we are about to unpack an application 7006 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7007 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7008 7009 /* 7010 * If the system app should be overridden by a previously installed 7011 * data, hide the system app now and let the /data/app scan pick it up 7012 * again. 7013 */ 7014 if (shouldHideSystemApp) { 7015 synchronized (mPackages) { 7016 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7017 } 7018 } 7019 7020 return scannedPkg; 7021 } 7022 7023 private static String fixProcessName(String defProcessName, 7024 String processName, int uid) { 7025 if (processName == null) { 7026 return defProcessName; 7027 } 7028 return processName; 7029 } 7030 7031 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7032 throws PackageManagerException { 7033 if (pkgSetting.signatures.mSignatures != null) { 7034 // Already existing package. Make sure signatures match 7035 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7036 == PackageManager.SIGNATURE_MATCH; 7037 if (!match) { 7038 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7039 == PackageManager.SIGNATURE_MATCH; 7040 } 7041 if (!match) { 7042 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7043 == PackageManager.SIGNATURE_MATCH; 7044 } 7045 if (!match) { 7046 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7047 + pkg.packageName + " signatures do not match the " 7048 + "previously installed version; ignoring!"); 7049 } 7050 } 7051 7052 // Check for shared user signatures 7053 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7054 // Already existing package. Make sure signatures match 7055 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7056 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7057 if (!match) { 7058 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7059 == PackageManager.SIGNATURE_MATCH; 7060 } 7061 if (!match) { 7062 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7063 == PackageManager.SIGNATURE_MATCH; 7064 } 7065 if (!match) { 7066 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7067 "Package " + pkg.packageName 7068 + " has no signatures that match those in shared user " 7069 + pkgSetting.sharedUser.name + "; ignoring!"); 7070 } 7071 } 7072 } 7073 7074 /** 7075 * Enforces that only the system UID or root's UID can call a method exposed 7076 * via Binder. 7077 * 7078 * @param message used as message if SecurityException is thrown 7079 * @throws SecurityException if the caller is not system or root 7080 */ 7081 private static final void enforceSystemOrRoot(String message) { 7082 final int uid = Binder.getCallingUid(); 7083 if (uid != Process.SYSTEM_UID && uid != 0) { 7084 throw new SecurityException(message); 7085 } 7086 } 7087 7088 @Override 7089 public void performFstrimIfNeeded() { 7090 enforceSystemOrRoot("Only the system can request fstrim"); 7091 7092 // Before everything else, see whether we need to fstrim. 7093 try { 7094 IMountService ms = PackageHelper.getMountService(); 7095 if (ms != null) { 7096 final boolean isUpgrade = isUpgrade(); 7097 boolean doTrim = isUpgrade; 7098 if (doTrim) { 7099 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7100 } else { 7101 final long interval = android.provider.Settings.Global.getLong( 7102 mContext.getContentResolver(), 7103 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7104 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7105 if (interval > 0) { 7106 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7107 if (timeSinceLast > interval) { 7108 doTrim = true; 7109 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7110 + "; running immediately"); 7111 } 7112 } 7113 } 7114 if (doTrim) { 7115 if (!isFirstBoot()) { 7116 try { 7117 ActivityManagerNative.getDefault().showBootMessage( 7118 mContext.getResources().getString( 7119 R.string.android_upgrading_fstrim), true); 7120 } catch (RemoteException e) { 7121 } 7122 } 7123 ms.runMaintenance(); 7124 } 7125 } else { 7126 Slog.e(TAG, "Mount service unavailable!"); 7127 } 7128 } catch (RemoteException e) { 7129 // Can't happen; MountService is local 7130 } 7131 } 7132 7133 @Override 7134 public void updatePackagesIfNeeded() { 7135 enforceSystemOrRoot("Only the system can request package update"); 7136 7137 // We need to re-extract after an OTA. 7138 boolean causeUpgrade = isUpgrade(); 7139 7140 // First boot or factory reset. 7141 // Note: we also handle devices that are upgrading to N right now as if it is their 7142 // first boot, as they do not have profile data. 7143 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7144 7145 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7146 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7147 7148 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7149 return; 7150 } 7151 7152 List<PackageParser.Package> pkgs; 7153 synchronized (mPackages) { 7154 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7155 } 7156 7157 int curr = 0; 7158 int total = pkgs.size(); 7159 for (PackageParser.Package pkg : pkgs) { 7160 curr++; 7161 7162 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7163 if (DEBUG_DEXOPT) { 7164 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7165 } 7166 continue; 7167 } 7168 7169 if (DEBUG_DEXOPT) { 7170 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7171 } 7172 7173 if (!isFirstBoot()) { 7174 try { 7175 ActivityManagerNative.getDefault().showBootMessage( 7176 mContext.getResources().getString(R.string.android_upgrading_apk, 7177 curr, total), true); 7178 } catch (RemoteException e) { 7179 } 7180 } 7181 7182 performDexOpt(pkg.packageName, 7183 null /* instructionSet */, 7184 true /* checkProfiles */, 7185 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7186 false /* force */); 7187 } 7188 } 7189 7190 @Override 7191 public void notifyPackageUse(String packageName, int reason) { 7192 synchronized (mPackages) { 7193 PackageParser.Package p = mPackages.get(packageName); 7194 if (p == null) { 7195 return; 7196 } 7197 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7198 } 7199 } 7200 7201 // TODO: this is not used nor needed. Delete it. 7202 @Override 7203 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7204 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7205 getFullCompilerFilter(), false /* force */); 7206 } 7207 7208 @Override 7209 public boolean performDexOpt(String packageName, String instructionSet, 7210 boolean checkProfiles, int compileReason, boolean force) { 7211 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7212 getCompilerFilterForReason(compileReason), force); 7213 } 7214 7215 @Override 7216 public boolean performDexOptMode(String packageName, String instructionSet, 7217 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7218 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7219 targetCompilerFilter, force); 7220 } 7221 7222 private boolean performDexOptTraced(String packageName, String instructionSet, 7223 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7225 try { 7226 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7227 targetCompilerFilter, force); 7228 } finally { 7229 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7230 } 7231 } 7232 7233 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7234 // if the package can now be considered up to date for the given filter. 7235 private boolean performDexOptInternal(String packageName, String instructionSet, 7236 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7237 PackageParser.Package p; 7238 final String targetInstructionSet; 7239 synchronized (mPackages) { 7240 p = mPackages.get(packageName); 7241 if (p == null) { 7242 return false; 7243 } 7244 mPackageUsage.write(false); 7245 7246 targetInstructionSet = instructionSet != null ? instructionSet : 7247 getPrimaryInstructionSet(p.applicationInfo); 7248 } 7249 long callingId = Binder.clearCallingIdentity(); 7250 try { 7251 synchronized (mInstallLock) { 7252 final String[] instructionSets = new String[] { targetInstructionSet }; 7253 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7254 checkProfiles, targetCompilerFilter, force); 7255 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7256 } 7257 } finally { 7258 Binder.restoreCallingIdentity(callingId); 7259 } 7260 } 7261 7262 public ArraySet<String> getOptimizablePackages() { 7263 ArraySet<String> pkgs = new ArraySet<String>(); 7264 synchronized (mPackages) { 7265 for (PackageParser.Package p : mPackages.values()) { 7266 if (PackageDexOptimizer.canOptimizePackage(p)) { 7267 pkgs.add(p.packageName); 7268 } 7269 } 7270 } 7271 return pkgs; 7272 } 7273 7274 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7275 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7276 boolean force) { 7277 // Select the dex optimizer based on the force parameter. 7278 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7279 // allocate an object here. 7280 PackageDexOptimizer pdo = force 7281 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7282 : mPackageDexOptimizer; 7283 7284 // Optimize all dependencies first. Note: we ignore the return value and march on 7285 // on errors. 7286 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7287 if (!deps.isEmpty()) { 7288 for (PackageParser.Package depPackage : deps) { 7289 // TODO: Analyze and investigate if we (should) profile libraries. 7290 // Currently this will do a full compilation of the library by default. 7291 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7292 false /* checkProfiles */, 7293 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7294 } 7295 } 7296 7297 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7298 targetCompilerFilter); 7299 } 7300 7301 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7302 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7303 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7304 Set<String> collectedNames = new HashSet<>(); 7305 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7306 7307 retValue.remove(p); 7308 7309 return retValue; 7310 } else { 7311 return Collections.emptyList(); 7312 } 7313 } 7314 7315 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7316 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7317 if (!collectedNames.contains(p.packageName)) { 7318 collectedNames.add(p.packageName); 7319 collected.add(p); 7320 7321 if (p.usesLibraries != null) { 7322 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7323 } 7324 if (p.usesOptionalLibraries != null) { 7325 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7326 collectedNames); 7327 } 7328 } 7329 } 7330 7331 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7332 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7333 for (String libName : libs) { 7334 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7335 if (libPkg != null) { 7336 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7337 } 7338 } 7339 } 7340 7341 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7342 synchronized (mPackages) { 7343 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7344 if (lib != null && lib.apk != null) { 7345 return mPackages.get(lib.apk); 7346 } 7347 } 7348 return null; 7349 } 7350 7351 public void shutdown() { 7352 mPackageUsage.write(true); 7353 } 7354 7355 @Override 7356 public void forceDexOpt(String packageName) { 7357 enforceSystemOrRoot("forceDexOpt"); 7358 7359 PackageParser.Package pkg; 7360 synchronized (mPackages) { 7361 pkg = mPackages.get(packageName); 7362 if (pkg == null) { 7363 throw new IllegalArgumentException("Unknown package: " + packageName); 7364 } 7365 } 7366 7367 synchronized (mInstallLock) { 7368 final String[] instructionSets = new String[] { 7369 getPrimaryInstructionSet(pkg.applicationInfo) }; 7370 7371 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7372 7373 // Whoever is calling forceDexOpt wants a fully compiled package. 7374 // Don't use profiles since that may cause compilation to be skipped. 7375 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7376 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7377 true /* force */); 7378 7379 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7380 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7381 throw new IllegalStateException("Failed to dexopt: " + res); 7382 } 7383 } 7384 } 7385 7386 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7387 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7388 Slog.w(TAG, "Unable to update from " + oldPkg.name 7389 + " to " + newPkg.packageName 7390 + ": old package not in system partition"); 7391 return false; 7392 } else if (mPackages.get(oldPkg.name) != null) { 7393 Slog.w(TAG, "Unable to update from " + oldPkg.name 7394 + " to " + newPkg.packageName 7395 + ": old package still exists"); 7396 return false; 7397 } 7398 return true; 7399 } 7400 7401 void removeCodePathLI(File codePath) { 7402 if (codePath.isDirectory()) { 7403 try { 7404 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7405 } catch (InstallerException e) { 7406 Slog.w(TAG, "Failed to remove code path", e); 7407 } 7408 } else { 7409 codePath.delete(); 7410 } 7411 } 7412 7413 private int[] resolveUserIds(int userId) { 7414 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7415 } 7416 7417 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7418 if (pkg == null) { 7419 Slog.wtf(TAG, "Package was null!", new Throwable()); 7420 return; 7421 } 7422 clearAppDataLeafLIF(pkg, userId, flags); 7423 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7424 for (int i = 0; i < childCount; i++) { 7425 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7426 } 7427 } 7428 7429 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7430 final PackageSetting ps; 7431 synchronized (mPackages) { 7432 ps = mSettings.mPackages.get(pkg.packageName); 7433 } 7434 for (int realUserId : resolveUserIds(userId)) { 7435 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7436 try { 7437 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7438 ceDataInode); 7439 } catch (InstallerException e) { 7440 Slog.w(TAG, String.valueOf(e)); 7441 } 7442 } 7443 } 7444 7445 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7446 if (pkg == null) { 7447 Slog.wtf(TAG, "Package was null!", new Throwable()); 7448 return; 7449 } 7450 destroyAppDataLeafLIF(pkg, userId, flags); 7451 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7452 for (int i = 0; i < childCount; i++) { 7453 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7454 } 7455 } 7456 7457 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7458 final PackageSetting ps; 7459 synchronized (mPackages) { 7460 ps = mSettings.mPackages.get(pkg.packageName); 7461 } 7462 for (int realUserId : resolveUserIds(userId)) { 7463 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7464 try { 7465 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7466 ceDataInode); 7467 } catch (InstallerException e) { 7468 Slog.w(TAG, String.valueOf(e)); 7469 } 7470 } 7471 } 7472 7473 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7474 if (pkg == null) { 7475 Slog.wtf(TAG, "Package was null!", new Throwable()); 7476 return; 7477 } 7478 destroyAppProfilesLeafLIF(pkg); 7479 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7480 for (int i = 0; i < childCount; i++) { 7481 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7482 } 7483 } 7484 7485 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7486 try { 7487 mInstaller.destroyAppProfiles(pkg.packageName); 7488 } catch (InstallerException e) { 7489 Slog.w(TAG, String.valueOf(e)); 7490 } 7491 } 7492 7493 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7494 if (pkg == null) { 7495 Slog.wtf(TAG, "Package was null!", new Throwable()); 7496 return; 7497 } 7498 clearAppProfilesLeafLIF(pkg); 7499 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7500 for (int i = 0; i < childCount; i++) { 7501 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7502 } 7503 } 7504 7505 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7506 try { 7507 mInstaller.clearAppProfiles(pkg.packageName); 7508 } catch (InstallerException e) { 7509 Slog.w(TAG, String.valueOf(e)); 7510 } 7511 } 7512 7513 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7514 long lastUpdateTime) { 7515 // Set parent install/update time 7516 PackageSetting ps = (PackageSetting) pkg.mExtras; 7517 if (ps != null) { 7518 ps.firstInstallTime = firstInstallTime; 7519 ps.lastUpdateTime = lastUpdateTime; 7520 } 7521 // Set children install/update time 7522 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7523 for (int i = 0; i < childCount; i++) { 7524 PackageParser.Package childPkg = pkg.childPackages.get(i); 7525 ps = (PackageSetting) childPkg.mExtras; 7526 if (ps != null) { 7527 ps.firstInstallTime = firstInstallTime; 7528 ps.lastUpdateTime = lastUpdateTime; 7529 } 7530 } 7531 } 7532 7533 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7534 PackageParser.Package changingLib) { 7535 if (file.path != null) { 7536 usesLibraryFiles.add(file.path); 7537 return; 7538 } 7539 PackageParser.Package p = mPackages.get(file.apk); 7540 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7541 // If we are doing this while in the middle of updating a library apk, 7542 // then we need to make sure to use that new apk for determining the 7543 // dependencies here. (We haven't yet finished committing the new apk 7544 // to the package manager state.) 7545 if (p == null || p.packageName.equals(changingLib.packageName)) { 7546 p = changingLib; 7547 } 7548 } 7549 if (p != null) { 7550 usesLibraryFiles.addAll(p.getAllCodePaths()); 7551 } 7552 } 7553 7554 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7555 PackageParser.Package changingLib) throws PackageManagerException { 7556 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7557 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7558 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7559 for (int i=0; i<N; i++) { 7560 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7561 if (file == null) { 7562 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7563 "Package " + pkg.packageName + " requires unavailable shared library " 7564 + pkg.usesLibraries.get(i) + "; failing!"); 7565 } 7566 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7567 } 7568 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7569 for (int i=0; i<N; i++) { 7570 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7571 if (file == null) { 7572 Slog.w(TAG, "Package " + pkg.packageName 7573 + " desires unavailable shared library " 7574 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7575 } else { 7576 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7577 } 7578 } 7579 N = usesLibraryFiles.size(); 7580 if (N > 0) { 7581 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7582 } else { 7583 pkg.usesLibraryFiles = null; 7584 } 7585 } 7586 } 7587 7588 private static boolean hasString(List<String> list, List<String> which) { 7589 if (list == null) { 7590 return false; 7591 } 7592 for (int i=list.size()-1; i>=0; i--) { 7593 for (int j=which.size()-1; j>=0; j--) { 7594 if (which.get(j).equals(list.get(i))) { 7595 return true; 7596 } 7597 } 7598 } 7599 return false; 7600 } 7601 7602 private void updateAllSharedLibrariesLPw() { 7603 for (PackageParser.Package pkg : mPackages.values()) { 7604 try { 7605 updateSharedLibrariesLPw(pkg, null); 7606 } catch (PackageManagerException e) { 7607 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7608 } 7609 } 7610 } 7611 7612 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7613 PackageParser.Package changingPkg) { 7614 ArrayList<PackageParser.Package> res = null; 7615 for (PackageParser.Package pkg : mPackages.values()) { 7616 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7617 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7618 if (res == null) { 7619 res = new ArrayList<PackageParser.Package>(); 7620 } 7621 res.add(pkg); 7622 try { 7623 updateSharedLibrariesLPw(pkg, changingPkg); 7624 } catch (PackageManagerException e) { 7625 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7626 } 7627 } 7628 } 7629 return res; 7630 } 7631 7632 /** 7633 * Derive the value of the {@code cpuAbiOverride} based on the provided 7634 * value and an optional stored value from the package settings. 7635 */ 7636 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7637 String cpuAbiOverride = null; 7638 7639 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7640 cpuAbiOverride = null; 7641 } else if (abiOverride != null) { 7642 cpuAbiOverride = abiOverride; 7643 } else if (settings != null) { 7644 cpuAbiOverride = settings.cpuAbiOverrideString; 7645 } 7646 7647 return cpuAbiOverride; 7648 } 7649 7650 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7651 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7652 throws PackageManagerException { 7653 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7654 // If the package has children and this is the first dive in the function 7655 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7656 // whether all packages (parent and children) would be successfully scanned 7657 // before the actual scan since scanning mutates internal state and we want 7658 // to atomically install the package and its children. 7659 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7660 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7661 scanFlags |= SCAN_CHECK_ONLY; 7662 } 7663 } else { 7664 scanFlags &= ~SCAN_CHECK_ONLY; 7665 } 7666 7667 final PackageParser.Package scannedPkg; 7668 try { 7669 // Scan the parent 7670 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7671 // Scan the children 7672 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7673 for (int i = 0; i < childCount; i++) { 7674 PackageParser.Package childPkg = pkg.childPackages.get(i); 7675 scanPackageLI(childPkg, policyFlags, 7676 scanFlags, currentTime, user); 7677 } 7678 } finally { 7679 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7680 } 7681 7682 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7683 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7684 } 7685 7686 return scannedPkg; 7687 } 7688 7689 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7690 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7691 boolean success = false; 7692 try { 7693 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7694 currentTime, user); 7695 success = true; 7696 return res; 7697 } finally { 7698 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7699 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7700 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7701 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7702 destroyAppProfilesLIF(pkg); 7703 } 7704 } 7705 } 7706 7707 /** 7708 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7709 */ 7710 private static boolean apkHasCode(String fileName) { 7711 StrictJarFile jarFile = null; 7712 try { 7713 jarFile = new StrictJarFile(fileName, 7714 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7715 return jarFile.findEntry("classes.dex") != null; 7716 } catch (IOException ignore) { 7717 } finally { 7718 try { 7719 jarFile.close(); 7720 } catch (IOException ignore) {} 7721 } 7722 return false; 7723 } 7724 7725 /** 7726 * Enforces code policy for the package. This ensures that if an APK has 7727 * declared hasCode="true" in its manifest that the APK actually contains 7728 * code. 7729 * 7730 * @throws PackageManagerException If bytecode could not be found when it should exist 7731 */ 7732 private static void enforceCodePolicy(PackageParser.Package pkg) 7733 throws PackageManagerException { 7734 final boolean shouldHaveCode = 7735 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7736 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7737 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7738 "Package " + pkg.baseCodePath + " code is missing"); 7739 } 7740 7741 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7742 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7743 final boolean splitShouldHaveCode = 7744 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7745 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7746 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7747 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7748 } 7749 } 7750 } 7751 } 7752 7753 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7754 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7755 throws PackageManagerException { 7756 final File scanFile = new File(pkg.codePath); 7757 if (pkg.applicationInfo.getCodePath() == null || 7758 pkg.applicationInfo.getResourcePath() == null) { 7759 // Bail out. The resource and code paths haven't been set. 7760 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7761 "Code and resource paths haven't been set correctly"); 7762 } 7763 7764 // Apply policy 7765 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7766 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7767 if (pkg.applicationInfo.isDirectBootAware()) { 7768 // we're direct boot aware; set for all components 7769 for (PackageParser.Service s : pkg.services) { 7770 s.info.encryptionAware = s.info.directBootAware = true; 7771 } 7772 for (PackageParser.Provider p : pkg.providers) { 7773 p.info.encryptionAware = p.info.directBootAware = true; 7774 } 7775 for (PackageParser.Activity a : pkg.activities) { 7776 a.info.encryptionAware = a.info.directBootAware = true; 7777 } 7778 for (PackageParser.Activity r : pkg.receivers) { 7779 r.info.encryptionAware = r.info.directBootAware = true; 7780 } 7781 } 7782 } else { 7783 // Only allow system apps to be flagged as core apps. 7784 pkg.coreApp = false; 7785 // clear flags not applicable to regular apps 7786 pkg.applicationInfo.privateFlags &= 7787 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7788 pkg.applicationInfo.privateFlags &= 7789 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7790 } 7791 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7792 7793 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7794 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7795 } 7796 7797 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7798 enforceCodePolicy(pkg); 7799 } 7800 7801 if (mCustomResolverComponentName != null && 7802 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7803 setUpCustomResolverActivity(pkg); 7804 } 7805 7806 if (pkg.packageName.equals("android")) { 7807 synchronized (mPackages) { 7808 if (mAndroidApplication != null) { 7809 Slog.w(TAG, "*************************************************"); 7810 Slog.w(TAG, "Core android package being redefined. Skipping."); 7811 Slog.w(TAG, " file=" + scanFile); 7812 Slog.w(TAG, "*************************************************"); 7813 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7814 "Core android package being redefined. Skipping."); 7815 } 7816 7817 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7818 // Set up information for our fall-back user intent resolution activity. 7819 mPlatformPackage = pkg; 7820 pkg.mVersionCode = mSdkVersion; 7821 mAndroidApplication = pkg.applicationInfo; 7822 7823 if (!mResolverReplaced) { 7824 mResolveActivity.applicationInfo = mAndroidApplication; 7825 mResolveActivity.name = ResolverActivity.class.getName(); 7826 mResolveActivity.packageName = mAndroidApplication.packageName; 7827 mResolveActivity.processName = "system:ui"; 7828 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7829 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7830 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7831 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7832 mResolveActivity.exported = true; 7833 mResolveActivity.enabled = true; 7834 mResolveInfo.activityInfo = mResolveActivity; 7835 mResolveInfo.priority = 0; 7836 mResolveInfo.preferredOrder = 0; 7837 mResolveInfo.match = 0; 7838 mResolveComponentName = new ComponentName( 7839 mAndroidApplication.packageName, mResolveActivity.name); 7840 } 7841 } 7842 } 7843 } 7844 7845 if (DEBUG_PACKAGE_SCANNING) { 7846 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7847 Log.d(TAG, "Scanning package " + pkg.packageName); 7848 } 7849 7850 synchronized (mPackages) { 7851 if (mPackages.containsKey(pkg.packageName) 7852 || mSharedLibraries.containsKey(pkg.packageName)) { 7853 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7854 "Application package " + pkg.packageName 7855 + " already installed. Skipping duplicate."); 7856 } 7857 7858 // If we're only installing presumed-existing packages, require that the 7859 // scanned APK is both already known and at the path previously established 7860 // for it. Previously unknown packages we pick up normally, but if we have an 7861 // a priori expectation about this package's install presence, enforce it. 7862 // With a singular exception for new system packages. When an OTA contains 7863 // a new system package, we allow the codepath to change from a system location 7864 // to the user-installed location. If we don't allow this change, any newer, 7865 // user-installed version of the application will be ignored. 7866 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7867 if (mExpectingBetter.containsKey(pkg.packageName)) { 7868 logCriticalInfo(Log.WARN, 7869 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7870 } else { 7871 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7872 if (known != null) { 7873 if (DEBUG_PACKAGE_SCANNING) { 7874 Log.d(TAG, "Examining " + pkg.codePath 7875 + " and requiring known paths " + known.codePathString 7876 + " & " + known.resourcePathString); 7877 } 7878 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7879 || !pkg.applicationInfo.getResourcePath().equals( 7880 known.resourcePathString)) { 7881 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7882 "Application package " + pkg.packageName 7883 + " found at " + pkg.applicationInfo.getCodePath() 7884 + " but expected at " + known.codePathString 7885 + "; ignoring."); 7886 } 7887 } 7888 } 7889 } 7890 } 7891 7892 // Initialize package source and resource directories 7893 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7894 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7895 7896 SharedUserSetting suid = null; 7897 PackageSetting pkgSetting = null; 7898 7899 if (!isSystemApp(pkg)) { 7900 // Only system apps can use these features. 7901 pkg.mOriginalPackages = null; 7902 pkg.mRealPackage = null; 7903 pkg.mAdoptPermissions = null; 7904 } 7905 7906 // Getting the package setting may have a side-effect, so if we 7907 // are only checking if scan would succeed, stash a copy of the 7908 // old setting to restore at the end. 7909 PackageSetting nonMutatedPs = null; 7910 7911 // writer 7912 synchronized (mPackages) { 7913 if (pkg.mSharedUserId != null) { 7914 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7915 if (suid == null) { 7916 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7917 "Creating application package " + pkg.packageName 7918 + " for shared user failed"); 7919 } 7920 if (DEBUG_PACKAGE_SCANNING) { 7921 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7922 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7923 + "): packages=" + suid.packages); 7924 } 7925 } 7926 7927 // Check if we are renaming from an original package name. 7928 PackageSetting origPackage = null; 7929 String realName = null; 7930 if (pkg.mOriginalPackages != null) { 7931 // This package may need to be renamed to a previously 7932 // installed name. Let's check on that... 7933 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7934 if (pkg.mOriginalPackages.contains(renamed)) { 7935 // This package had originally been installed as the 7936 // original name, and we have already taken care of 7937 // transitioning to the new one. Just update the new 7938 // one to continue using the old name. 7939 realName = pkg.mRealPackage; 7940 if (!pkg.packageName.equals(renamed)) { 7941 // Callers into this function may have already taken 7942 // care of renaming the package; only do it here if 7943 // it is not already done. 7944 pkg.setPackageName(renamed); 7945 } 7946 7947 } else { 7948 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7949 if ((origPackage = mSettings.peekPackageLPr( 7950 pkg.mOriginalPackages.get(i))) != null) { 7951 // We do have the package already installed under its 7952 // original name... should we use it? 7953 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7954 // New package is not compatible with original. 7955 origPackage = null; 7956 continue; 7957 } else if (origPackage.sharedUser != null) { 7958 // Make sure uid is compatible between packages. 7959 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7960 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7961 + " to " + pkg.packageName + ": old uid " 7962 + origPackage.sharedUser.name 7963 + " differs from " + pkg.mSharedUserId); 7964 origPackage = null; 7965 continue; 7966 } 7967 // TODO: Add case when shared user id is added [b/28144775] 7968 } else { 7969 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7970 + pkg.packageName + " to old name " + origPackage.name); 7971 } 7972 break; 7973 } 7974 } 7975 } 7976 } 7977 7978 if (mTransferedPackages.contains(pkg.packageName)) { 7979 Slog.w(TAG, "Package " + pkg.packageName 7980 + " was transferred to another, but its .apk remains"); 7981 } 7982 7983 // See comments in nonMutatedPs declaration 7984 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7985 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7986 if (foundPs != null) { 7987 nonMutatedPs = new PackageSetting(foundPs); 7988 } 7989 } 7990 7991 // Just create the setting, don't add it yet. For already existing packages 7992 // the PkgSetting exists already and doesn't have to be created. 7993 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7994 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7995 pkg.applicationInfo.primaryCpuAbi, 7996 pkg.applicationInfo.secondaryCpuAbi, 7997 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7998 user, false); 7999 if (pkgSetting == null) { 8000 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8001 "Creating application package " + pkg.packageName + " failed"); 8002 } 8003 8004 if (pkgSetting.origPackage != null) { 8005 // If we are first transitioning from an original package, 8006 // fix up the new package's name now. We need to do this after 8007 // looking up the package under its new name, so getPackageLP 8008 // can take care of fiddling things correctly. 8009 pkg.setPackageName(origPackage.name); 8010 8011 // File a report about this. 8012 String msg = "New package " + pkgSetting.realName 8013 + " renamed to replace old package " + pkgSetting.name; 8014 reportSettingsProblem(Log.WARN, msg); 8015 8016 // Make a note of it. 8017 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8018 mTransferedPackages.add(origPackage.name); 8019 } 8020 8021 // No longer need to retain this. 8022 pkgSetting.origPackage = null; 8023 } 8024 8025 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8026 // Make a note of it. 8027 mTransferedPackages.add(pkg.packageName); 8028 } 8029 8030 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8031 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8032 } 8033 8034 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8035 // Check all shared libraries and map to their actual file path. 8036 // We only do this here for apps not on a system dir, because those 8037 // are the only ones that can fail an install due to this. We 8038 // will take care of the system apps by updating all of their 8039 // library paths after the scan is done. 8040 updateSharedLibrariesLPw(pkg, null); 8041 } 8042 8043 if (mFoundPolicyFile) { 8044 SELinuxMMAC.assignSeinfoValue(pkg); 8045 } 8046 8047 pkg.applicationInfo.uid = pkgSetting.appId; 8048 pkg.mExtras = pkgSetting; 8049 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8050 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8051 // We just determined the app is signed correctly, so bring 8052 // over the latest parsed certs. 8053 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8054 } else { 8055 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8056 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8057 "Package " + pkg.packageName + " upgrade keys do not match the " 8058 + "previously installed version"); 8059 } else { 8060 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8061 String msg = "System package " + pkg.packageName 8062 + " signature changed; retaining data."; 8063 reportSettingsProblem(Log.WARN, msg); 8064 } 8065 } 8066 } else { 8067 try { 8068 verifySignaturesLP(pkgSetting, pkg); 8069 // We just determined the app is signed correctly, so bring 8070 // over the latest parsed certs. 8071 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8072 } catch (PackageManagerException e) { 8073 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8074 throw e; 8075 } 8076 // The signature has changed, but this package is in the system 8077 // image... let's recover! 8078 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8079 // However... if this package is part of a shared user, but it 8080 // doesn't match the signature of the shared user, let's fail. 8081 // What this means is that you can't change the signatures 8082 // associated with an overall shared user, which doesn't seem all 8083 // that unreasonable. 8084 if (pkgSetting.sharedUser != null) { 8085 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8086 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8087 throw new PackageManagerException( 8088 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8089 "Signature mismatch for shared user: " 8090 + pkgSetting.sharedUser); 8091 } 8092 } 8093 // File a report about this. 8094 String msg = "System package " + pkg.packageName 8095 + " signature changed; retaining data."; 8096 reportSettingsProblem(Log.WARN, msg); 8097 } 8098 } 8099 // Verify that this new package doesn't have any content providers 8100 // that conflict with existing packages. Only do this if the 8101 // package isn't already installed, since we don't want to break 8102 // things that are installed. 8103 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8104 final int N = pkg.providers.size(); 8105 int i; 8106 for (i=0; i<N; i++) { 8107 PackageParser.Provider p = pkg.providers.get(i); 8108 if (p.info.authority != null) { 8109 String names[] = p.info.authority.split(";"); 8110 for (int j = 0; j < names.length; j++) { 8111 if (mProvidersByAuthority.containsKey(names[j])) { 8112 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8113 final String otherPackageName = 8114 ((other != null && other.getComponentName() != null) ? 8115 other.getComponentName().getPackageName() : "?"); 8116 throw new PackageManagerException( 8117 INSTALL_FAILED_CONFLICTING_PROVIDER, 8118 "Can't install because provider name " + names[j] 8119 + " (in package " + pkg.applicationInfo.packageName 8120 + ") is already used by " + otherPackageName); 8121 } 8122 } 8123 } 8124 } 8125 } 8126 8127 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8128 // This package wants to adopt ownership of permissions from 8129 // another package. 8130 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8131 final String origName = pkg.mAdoptPermissions.get(i); 8132 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8133 if (orig != null) { 8134 if (verifyPackageUpdateLPr(orig, pkg)) { 8135 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8136 + pkg.packageName); 8137 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8138 } 8139 } 8140 } 8141 } 8142 } 8143 8144 final String pkgName = pkg.packageName; 8145 8146 final long scanFileTime = scanFile.lastModified(); 8147 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8148 pkg.applicationInfo.processName = fixProcessName( 8149 pkg.applicationInfo.packageName, 8150 pkg.applicationInfo.processName, 8151 pkg.applicationInfo.uid); 8152 8153 if (pkg != mPlatformPackage) { 8154 // Get all of our default paths setup 8155 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8156 } 8157 8158 final String path = scanFile.getPath(); 8159 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8160 8161 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8162 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8163 8164 // Some system apps still use directory structure for native libraries 8165 // in which case we might end up not detecting abi solely based on apk 8166 // structure. Try to detect abi based on directory structure. 8167 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8168 pkg.applicationInfo.primaryCpuAbi == null) { 8169 setBundledAppAbisAndRoots(pkg, pkgSetting); 8170 setNativeLibraryPaths(pkg); 8171 } 8172 8173 } else { 8174 if ((scanFlags & SCAN_MOVE) != 0) { 8175 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8176 // but we already have this packages package info in the PackageSetting. We just 8177 // use that and derive the native library path based on the new codepath. 8178 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8179 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8180 } 8181 8182 // Set native library paths again. For moves, the path will be updated based on the 8183 // ABIs we've determined above. For non-moves, the path will be updated based on the 8184 // ABIs we determined during compilation, but the path will depend on the final 8185 // package path (after the rename away from the stage path). 8186 setNativeLibraryPaths(pkg); 8187 } 8188 8189 // This is a special case for the "system" package, where the ABI is 8190 // dictated by the zygote configuration (and init.rc). We should keep track 8191 // of this ABI so that we can deal with "normal" applications that run under 8192 // the same UID correctly. 8193 if (mPlatformPackage == pkg) { 8194 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8195 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8196 } 8197 8198 // If there's a mismatch between the abi-override in the package setting 8199 // and the abiOverride specified for the install. Warn about this because we 8200 // would've already compiled the app without taking the package setting into 8201 // account. 8202 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8203 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8204 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8205 " for package " + pkg.packageName); 8206 } 8207 } 8208 8209 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8210 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8211 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8212 8213 // Copy the derived override back to the parsed package, so that we can 8214 // update the package settings accordingly. 8215 pkg.cpuAbiOverride = cpuAbiOverride; 8216 8217 if (DEBUG_ABI_SELECTION) { 8218 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8219 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8220 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8221 } 8222 8223 // Push the derived path down into PackageSettings so we know what to 8224 // clean up at uninstall time. 8225 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8226 8227 if (DEBUG_ABI_SELECTION) { 8228 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8229 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8230 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8231 } 8232 8233 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8234 // We don't do this here during boot because we can do it all 8235 // at once after scanning all existing packages. 8236 // 8237 // We also do this *before* we perform dexopt on this package, so that 8238 // we can avoid redundant dexopts, and also to make sure we've got the 8239 // code and package path correct. 8240 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8241 pkg, true /* boot complete */); 8242 } 8243 8244 if (mFactoryTest && pkg.requestedPermissions.contains( 8245 android.Manifest.permission.FACTORY_TEST)) { 8246 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8247 } 8248 8249 ArrayList<PackageParser.Package> clientLibPkgs = null; 8250 8251 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8252 if (nonMutatedPs != null) { 8253 synchronized (mPackages) { 8254 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8255 } 8256 } 8257 return pkg; 8258 } 8259 8260 // Only privileged apps and updated privileged apps can add child packages. 8261 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8262 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8263 throw new PackageManagerException("Only privileged apps and updated " 8264 + "privileged apps can add child packages. Ignoring package " 8265 + pkg.packageName); 8266 } 8267 final int childCount = pkg.childPackages.size(); 8268 for (int i = 0; i < childCount; i++) { 8269 PackageParser.Package childPkg = pkg.childPackages.get(i); 8270 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8271 childPkg.packageName)) { 8272 throw new PackageManagerException("Cannot override a child package of " 8273 + "another disabled system app. Ignoring package " + pkg.packageName); 8274 } 8275 } 8276 } 8277 8278 // writer 8279 synchronized (mPackages) { 8280 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8281 // Only system apps can add new shared libraries. 8282 if (pkg.libraryNames != null) { 8283 for (int i=0; i<pkg.libraryNames.size(); i++) { 8284 String name = pkg.libraryNames.get(i); 8285 boolean allowed = false; 8286 if (pkg.isUpdatedSystemApp()) { 8287 // New library entries can only be added through the 8288 // system image. This is important to get rid of a lot 8289 // of nasty edge cases: for example if we allowed a non- 8290 // system update of the app to add a library, then uninstalling 8291 // the update would make the library go away, and assumptions 8292 // we made such as through app install filtering would now 8293 // have allowed apps on the device which aren't compatible 8294 // with it. Better to just have the restriction here, be 8295 // conservative, and create many fewer cases that can negatively 8296 // impact the user experience. 8297 final PackageSetting sysPs = mSettings 8298 .getDisabledSystemPkgLPr(pkg.packageName); 8299 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8300 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8301 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8302 allowed = true; 8303 break; 8304 } 8305 } 8306 } 8307 } else { 8308 allowed = true; 8309 } 8310 if (allowed) { 8311 if (!mSharedLibraries.containsKey(name)) { 8312 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8313 } else if (!name.equals(pkg.packageName)) { 8314 Slog.w(TAG, "Package " + pkg.packageName + " library " 8315 + name + " already exists; skipping"); 8316 } 8317 } else { 8318 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8319 + name + " that is not declared on system image; skipping"); 8320 } 8321 } 8322 if ((scanFlags & SCAN_BOOTING) == 0) { 8323 // If we are not booting, we need to update any applications 8324 // that are clients of our shared library. If we are booting, 8325 // this will all be done once the scan is complete. 8326 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8327 } 8328 } 8329 } 8330 } 8331 8332 if ((scanFlags & SCAN_BOOTING) != 0) { 8333 // No apps can run during boot scan, so they don't need to be frozen 8334 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8335 // Caller asked to not kill app, so it's probably not frozen 8336 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8337 // Caller asked us to ignore frozen check for some reason; they 8338 // probably didn't know the package name 8339 } else { 8340 // We're doing major surgery on this package, so it better be frozen 8341 // right now to keep it from launching 8342 checkPackageFrozen(pkgName); 8343 } 8344 8345 // Also need to kill any apps that are dependent on the library. 8346 if (clientLibPkgs != null) { 8347 for (int i=0; i<clientLibPkgs.size(); i++) { 8348 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8349 killApplication(clientPkg.applicationInfo.packageName, 8350 clientPkg.applicationInfo.uid, "update lib"); 8351 } 8352 } 8353 8354 // Make sure we're not adding any bogus keyset info 8355 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8356 ksms.assertScannedPackageValid(pkg); 8357 8358 // writer 8359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8360 8361 boolean createIdmapFailed = false; 8362 synchronized (mPackages) { 8363 // We don't expect installation to fail beyond this point 8364 8365 // Add the new setting to mSettings 8366 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8367 // Add the new setting to mPackages 8368 mPackages.put(pkg.applicationInfo.packageName, pkg); 8369 // Make sure we don't accidentally delete its data. 8370 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8371 while (iter.hasNext()) { 8372 PackageCleanItem item = iter.next(); 8373 if (pkgName.equals(item.packageName)) { 8374 iter.remove(); 8375 } 8376 } 8377 8378 // Take care of first install / last update times. 8379 if (currentTime != 0) { 8380 if (pkgSetting.firstInstallTime == 0) { 8381 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8382 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8383 pkgSetting.lastUpdateTime = currentTime; 8384 } 8385 } else if (pkgSetting.firstInstallTime == 0) { 8386 // We need *something*. Take time time stamp of the file. 8387 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8388 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8389 if (scanFileTime != pkgSetting.timeStamp) { 8390 // A package on the system image has changed; consider this 8391 // to be an update. 8392 pkgSetting.lastUpdateTime = scanFileTime; 8393 } 8394 } 8395 8396 // Add the package's KeySets to the global KeySetManagerService 8397 ksms.addScannedPackageLPw(pkg); 8398 8399 int N = pkg.providers.size(); 8400 StringBuilder r = null; 8401 int i; 8402 for (i=0; i<N; i++) { 8403 PackageParser.Provider p = pkg.providers.get(i); 8404 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8405 p.info.processName, pkg.applicationInfo.uid); 8406 mProviders.addProvider(p); 8407 p.syncable = p.info.isSyncable; 8408 if (p.info.authority != null) { 8409 String names[] = p.info.authority.split(";"); 8410 p.info.authority = null; 8411 for (int j = 0; j < names.length; j++) { 8412 if (j == 1 && p.syncable) { 8413 // We only want the first authority for a provider to possibly be 8414 // syncable, so if we already added this provider using a different 8415 // authority clear the syncable flag. We copy the provider before 8416 // changing it because the mProviders object contains a reference 8417 // to a provider that we don't want to change. 8418 // Only do this for the second authority since the resulting provider 8419 // object can be the same for all future authorities for this provider. 8420 p = new PackageParser.Provider(p); 8421 p.syncable = false; 8422 } 8423 if (!mProvidersByAuthority.containsKey(names[j])) { 8424 mProvidersByAuthority.put(names[j], p); 8425 if (p.info.authority == null) { 8426 p.info.authority = names[j]; 8427 } else { 8428 p.info.authority = p.info.authority + ";" + names[j]; 8429 } 8430 if (DEBUG_PACKAGE_SCANNING) { 8431 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8432 Log.d(TAG, "Registered content provider: " + names[j] 8433 + ", className = " + p.info.name + ", isSyncable = " 8434 + p.info.isSyncable); 8435 } 8436 } else { 8437 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8438 Slog.w(TAG, "Skipping provider name " + names[j] + 8439 " (in package " + pkg.applicationInfo.packageName + 8440 "): name already used by " 8441 + ((other != null && other.getComponentName() != null) 8442 ? other.getComponentName().getPackageName() : "?")); 8443 } 8444 } 8445 } 8446 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8447 if (r == null) { 8448 r = new StringBuilder(256); 8449 } else { 8450 r.append(' '); 8451 } 8452 r.append(p.info.name); 8453 } 8454 } 8455 if (r != null) { 8456 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8457 } 8458 8459 N = pkg.services.size(); 8460 r = null; 8461 for (i=0; i<N; i++) { 8462 PackageParser.Service s = pkg.services.get(i); 8463 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8464 s.info.processName, pkg.applicationInfo.uid); 8465 mServices.addService(s); 8466 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8467 if (r == null) { 8468 r = new StringBuilder(256); 8469 } else { 8470 r.append(' '); 8471 } 8472 r.append(s.info.name); 8473 } 8474 } 8475 if (r != null) { 8476 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8477 } 8478 8479 N = pkg.receivers.size(); 8480 r = null; 8481 for (i=0; i<N; i++) { 8482 PackageParser.Activity a = pkg.receivers.get(i); 8483 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8484 a.info.processName, pkg.applicationInfo.uid); 8485 mReceivers.addActivity(a, "receiver"); 8486 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8487 if (r == null) { 8488 r = new StringBuilder(256); 8489 } else { 8490 r.append(' '); 8491 } 8492 r.append(a.info.name); 8493 } 8494 } 8495 if (r != null) { 8496 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8497 } 8498 8499 N = pkg.activities.size(); 8500 r = null; 8501 for (i=0; i<N; i++) { 8502 PackageParser.Activity a = pkg.activities.get(i); 8503 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8504 a.info.processName, pkg.applicationInfo.uid); 8505 mActivities.addActivity(a, "activity"); 8506 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8507 if (r == null) { 8508 r = new StringBuilder(256); 8509 } else { 8510 r.append(' '); 8511 } 8512 r.append(a.info.name); 8513 } 8514 } 8515 if (r != null) { 8516 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8517 } 8518 8519 N = pkg.permissionGroups.size(); 8520 r = null; 8521 for (i=0; i<N; i++) { 8522 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8523 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8524 if (cur == null) { 8525 mPermissionGroups.put(pg.info.name, pg); 8526 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8527 if (r == null) { 8528 r = new StringBuilder(256); 8529 } else { 8530 r.append(' '); 8531 } 8532 r.append(pg.info.name); 8533 } 8534 } else { 8535 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8536 + pg.info.packageName + " ignored: original from " 8537 + cur.info.packageName); 8538 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8539 if (r == null) { 8540 r = new StringBuilder(256); 8541 } else { 8542 r.append(' '); 8543 } 8544 r.append("DUP:"); 8545 r.append(pg.info.name); 8546 } 8547 } 8548 } 8549 if (r != null) { 8550 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8551 } 8552 8553 N = pkg.permissions.size(); 8554 r = null; 8555 for (i=0; i<N; i++) { 8556 PackageParser.Permission p = pkg.permissions.get(i); 8557 8558 // Assume by default that we did not install this permission into the system. 8559 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8560 8561 // Now that permission groups have a special meaning, we ignore permission 8562 // groups for legacy apps to prevent unexpected behavior. In particular, 8563 // permissions for one app being granted to someone just becase they happen 8564 // to be in a group defined by another app (before this had no implications). 8565 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8566 p.group = mPermissionGroups.get(p.info.group); 8567 // Warn for a permission in an unknown group. 8568 if (p.info.group != null && p.group == null) { 8569 Slog.w(TAG, "Permission " + p.info.name + " from package " 8570 + p.info.packageName + " in an unknown group " + p.info.group); 8571 } 8572 } 8573 8574 ArrayMap<String, BasePermission> permissionMap = 8575 p.tree ? mSettings.mPermissionTrees 8576 : mSettings.mPermissions; 8577 BasePermission bp = permissionMap.get(p.info.name); 8578 8579 // Allow system apps to redefine non-system permissions 8580 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8581 final boolean currentOwnerIsSystem = (bp.perm != null 8582 && isSystemApp(bp.perm.owner)); 8583 if (isSystemApp(p.owner)) { 8584 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8585 // It's a built-in permission and no owner, take ownership now 8586 bp.packageSetting = pkgSetting; 8587 bp.perm = p; 8588 bp.uid = pkg.applicationInfo.uid; 8589 bp.sourcePackage = p.info.packageName; 8590 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8591 } else if (!currentOwnerIsSystem) { 8592 String msg = "New decl " + p.owner + " of permission " 8593 + p.info.name + " is system; overriding " + bp.sourcePackage; 8594 reportSettingsProblem(Log.WARN, msg); 8595 bp = null; 8596 } 8597 } 8598 } 8599 8600 if (bp == null) { 8601 bp = new BasePermission(p.info.name, p.info.packageName, 8602 BasePermission.TYPE_NORMAL); 8603 permissionMap.put(p.info.name, bp); 8604 } 8605 8606 if (bp.perm == null) { 8607 if (bp.sourcePackage == null 8608 || bp.sourcePackage.equals(p.info.packageName)) { 8609 BasePermission tree = findPermissionTreeLP(p.info.name); 8610 if (tree == null 8611 || tree.sourcePackage.equals(p.info.packageName)) { 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 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8618 if (r == null) { 8619 r = new StringBuilder(256); 8620 } else { 8621 r.append(' '); 8622 } 8623 r.append(p.info.name); 8624 } 8625 } else { 8626 Slog.w(TAG, "Permission " + p.info.name + " from package " 8627 + p.info.packageName + " ignored: base tree " 8628 + tree.name + " is from package " 8629 + tree.sourcePackage); 8630 } 8631 } else { 8632 Slog.w(TAG, "Permission " + p.info.name + " from package " 8633 + p.info.packageName + " ignored: original from " 8634 + bp.sourcePackage); 8635 } 8636 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8637 if (r == null) { 8638 r = new StringBuilder(256); 8639 } else { 8640 r.append(' '); 8641 } 8642 r.append("DUP:"); 8643 r.append(p.info.name); 8644 } 8645 if (bp.perm == p) { 8646 bp.protectionLevel = p.info.protectionLevel; 8647 } 8648 } 8649 8650 if (r != null) { 8651 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8652 } 8653 8654 N = pkg.instrumentation.size(); 8655 r = null; 8656 for (i=0; i<N; i++) { 8657 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8658 a.info.packageName = pkg.applicationInfo.packageName; 8659 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8660 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8661 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8662 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8663 a.info.dataDir = pkg.applicationInfo.dataDir; 8664 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8665 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8666 8667 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8668 // need other information about the application, like the ABI and what not ? 8669 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8670 mInstrumentation.put(a.getComponentName(), a); 8671 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8672 if (r == null) { 8673 r = new StringBuilder(256); 8674 } else { 8675 r.append(' '); 8676 } 8677 r.append(a.info.name); 8678 } 8679 } 8680 if (r != null) { 8681 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8682 } 8683 8684 if (pkg.protectedBroadcasts != null) { 8685 N = pkg.protectedBroadcasts.size(); 8686 for (i=0; i<N; i++) { 8687 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8688 } 8689 } 8690 8691 pkgSetting.setTimeStamp(scanFileTime); 8692 8693 // Create idmap files for pairs of (packages, overlay packages). 8694 // Note: "android", ie framework-res.apk, is handled by native layers. 8695 if (pkg.mOverlayTarget != null) { 8696 // This is an overlay package. 8697 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8698 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8699 mOverlays.put(pkg.mOverlayTarget, 8700 new ArrayMap<String, PackageParser.Package>()); 8701 } 8702 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8703 map.put(pkg.packageName, pkg); 8704 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8705 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8706 createIdmapFailed = true; 8707 } 8708 } 8709 } else if (mOverlays.containsKey(pkg.packageName) && 8710 !pkg.packageName.equals("android")) { 8711 // This is a regular package, with one or more known overlay packages. 8712 createIdmapsForPackageLI(pkg); 8713 } 8714 } 8715 8716 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8717 8718 if (createIdmapFailed) { 8719 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8720 "scanPackageLI failed to createIdmap"); 8721 } 8722 return pkg; 8723 } 8724 8725 /** 8726 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8727 * is derived purely on the basis of the contents of {@code scanFile} and 8728 * {@code cpuAbiOverride}. 8729 * 8730 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8731 */ 8732 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8733 String cpuAbiOverride, boolean extractLibs) 8734 throws PackageManagerException { 8735 // TODO: We can probably be smarter about this stuff. For installed apps, 8736 // we can calculate this information at install time once and for all. For 8737 // system apps, we can probably assume that this information doesn't change 8738 // after the first boot scan. As things stand, we do lots of unnecessary work. 8739 8740 // Give ourselves some initial paths; we'll come back for another 8741 // pass once we've determined ABI below. 8742 setNativeLibraryPaths(pkg); 8743 8744 // We would never need to extract libs for forward-locked and external packages, 8745 // since the container service will do it for us. We shouldn't attempt to 8746 // extract libs from system app when it was not updated. 8747 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8748 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8749 extractLibs = false; 8750 } 8751 8752 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8753 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8754 8755 NativeLibraryHelper.Handle handle = null; 8756 try { 8757 handle = NativeLibraryHelper.Handle.create(pkg); 8758 // TODO(multiArch): This can be null for apps that didn't go through the 8759 // usual installation process. We can calculate it again, like we 8760 // do during install time. 8761 // 8762 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8763 // unnecessary. 8764 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8765 8766 // Null out the abis so that they can be recalculated. 8767 pkg.applicationInfo.primaryCpuAbi = null; 8768 pkg.applicationInfo.secondaryCpuAbi = null; 8769 if (isMultiArch(pkg.applicationInfo)) { 8770 // Warn if we've set an abiOverride for multi-lib packages.. 8771 // By definition, we need to copy both 32 and 64 bit libraries for 8772 // such packages. 8773 if (pkg.cpuAbiOverride != null 8774 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8775 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8776 } 8777 8778 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8779 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8780 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8781 if (extractLibs) { 8782 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8783 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8784 useIsaSpecificSubdirs); 8785 } else { 8786 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8787 } 8788 } 8789 8790 maybeThrowExceptionForMultiArchCopy( 8791 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8792 8793 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8794 if (extractLibs) { 8795 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8796 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8797 useIsaSpecificSubdirs); 8798 } else { 8799 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8800 } 8801 } 8802 8803 maybeThrowExceptionForMultiArchCopy( 8804 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8805 8806 if (abi64 >= 0) { 8807 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8808 } 8809 8810 if (abi32 >= 0) { 8811 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8812 if (abi64 >= 0) { 8813 if (pkg.use32bitAbi) { 8814 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8815 pkg.applicationInfo.primaryCpuAbi = abi; 8816 } else { 8817 pkg.applicationInfo.secondaryCpuAbi = abi; 8818 } 8819 } else { 8820 pkg.applicationInfo.primaryCpuAbi = abi; 8821 } 8822 } 8823 8824 } else { 8825 String[] abiList = (cpuAbiOverride != null) ? 8826 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8827 8828 // Enable gross and lame hacks for apps that are built with old 8829 // SDK tools. We must scan their APKs for renderscript bitcode and 8830 // not launch them if it's present. Don't bother checking on devices 8831 // that don't have 64 bit support. 8832 boolean needsRenderScriptOverride = false; 8833 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8834 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8835 abiList = Build.SUPPORTED_32_BIT_ABIS; 8836 needsRenderScriptOverride = true; 8837 } 8838 8839 final int copyRet; 8840 if (extractLibs) { 8841 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8842 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8843 } else { 8844 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8845 } 8846 8847 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8848 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8849 "Error unpackaging native libs for app, errorCode=" + copyRet); 8850 } 8851 8852 if (copyRet >= 0) { 8853 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8854 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8855 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8856 } else if (needsRenderScriptOverride) { 8857 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8858 } 8859 } 8860 } catch (IOException ioe) { 8861 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8862 } finally { 8863 IoUtils.closeQuietly(handle); 8864 } 8865 8866 // Now that we've calculated the ABIs and determined if it's an internal app, 8867 // we will go ahead and populate the nativeLibraryPath. 8868 setNativeLibraryPaths(pkg); 8869 } 8870 8871 /** 8872 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8873 * i.e, so that all packages can be run inside a single process if required. 8874 * 8875 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8876 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8877 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8878 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8879 * updating a package that belongs to a shared user. 8880 * 8881 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8882 * adds unnecessary complexity. 8883 */ 8884 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8885 PackageParser.Package scannedPackage, boolean bootComplete) { 8886 String requiredInstructionSet = null; 8887 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8888 requiredInstructionSet = VMRuntime.getInstructionSet( 8889 scannedPackage.applicationInfo.primaryCpuAbi); 8890 } 8891 8892 PackageSetting requirer = null; 8893 for (PackageSetting ps : packagesForUser) { 8894 // If packagesForUser contains scannedPackage, we skip it. This will happen 8895 // when scannedPackage is an update of an existing package. Without this check, 8896 // we will never be able to change the ABI of any package belonging to a shared 8897 // user, even if it's compatible with other packages. 8898 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8899 if (ps.primaryCpuAbiString == null) { 8900 continue; 8901 } 8902 8903 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8904 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8905 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8906 // this but there's not much we can do. 8907 String errorMessage = "Instruction set mismatch, " 8908 + ((requirer == null) ? "[caller]" : requirer) 8909 + " requires " + requiredInstructionSet + " whereas " + ps 8910 + " requires " + instructionSet; 8911 Slog.w(TAG, errorMessage); 8912 } 8913 8914 if (requiredInstructionSet == null) { 8915 requiredInstructionSet = instructionSet; 8916 requirer = ps; 8917 } 8918 } 8919 } 8920 8921 if (requiredInstructionSet != null) { 8922 String adjustedAbi; 8923 if (requirer != null) { 8924 // requirer != null implies that either scannedPackage was null or that scannedPackage 8925 // did not require an ABI, in which case we have to adjust scannedPackage to match 8926 // the ABI of the set (which is the same as requirer's ABI) 8927 adjustedAbi = requirer.primaryCpuAbiString; 8928 if (scannedPackage != null) { 8929 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8930 } 8931 } else { 8932 // requirer == null implies that we're updating all ABIs in the set to 8933 // match scannedPackage. 8934 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8935 } 8936 8937 for (PackageSetting ps : packagesForUser) { 8938 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8939 if (ps.primaryCpuAbiString != null) { 8940 continue; 8941 } 8942 8943 ps.primaryCpuAbiString = adjustedAbi; 8944 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8945 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8946 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8947 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8948 + " (requirer=" 8949 + (requirer == null ? "null" : requirer.pkg.packageName) 8950 + ", scannedPackage=" 8951 + (scannedPackage != null ? scannedPackage.packageName : "null") 8952 + ")"); 8953 try { 8954 mInstaller.rmdex(ps.codePathString, 8955 getDexCodeInstructionSet(getPreferredInstructionSet())); 8956 } catch (InstallerException ignored) { 8957 } 8958 } 8959 } 8960 } 8961 } 8962 } 8963 8964 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8965 synchronized (mPackages) { 8966 mResolverReplaced = true; 8967 // Set up information for custom user intent resolution activity. 8968 mResolveActivity.applicationInfo = pkg.applicationInfo; 8969 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8970 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8971 mResolveActivity.processName = pkg.applicationInfo.packageName; 8972 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8973 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8974 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8975 mResolveActivity.theme = 0; 8976 mResolveActivity.exported = true; 8977 mResolveActivity.enabled = true; 8978 mResolveInfo.activityInfo = mResolveActivity; 8979 mResolveInfo.priority = 0; 8980 mResolveInfo.preferredOrder = 0; 8981 mResolveInfo.match = 0; 8982 mResolveComponentName = mCustomResolverComponentName; 8983 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8984 mResolveComponentName); 8985 } 8986 } 8987 8988 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8989 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8990 8991 // Set up information for ephemeral installer activity 8992 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8993 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8994 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8995 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8996 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8997 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8998 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8999 mEphemeralInstallerActivity.theme = 0; 9000 mEphemeralInstallerActivity.exported = true; 9001 mEphemeralInstallerActivity.enabled = true; 9002 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9003 mEphemeralInstallerInfo.priority = 0; 9004 mEphemeralInstallerInfo.preferredOrder = 0; 9005 mEphemeralInstallerInfo.match = 0; 9006 9007 if (DEBUG_EPHEMERAL) { 9008 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9009 } 9010 } 9011 9012 private static String calculateBundledApkRoot(final String codePathString) { 9013 final File codePath = new File(codePathString); 9014 final File codeRoot; 9015 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9016 codeRoot = Environment.getRootDirectory(); 9017 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9018 codeRoot = Environment.getOemDirectory(); 9019 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9020 codeRoot = Environment.getVendorDirectory(); 9021 } else { 9022 // Unrecognized code path; take its top real segment as the apk root: 9023 // e.g. /something/app/blah.apk => /something 9024 try { 9025 File f = codePath.getCanonicalFile(); 9026 File parent = f.getParentFile(); // non-null because codePath is a file 9027 File tmp; 9028 while ((tmp = parent.getParentFile()) != null) { 9029 f = parent; 9030 parent = tmp; 9031 } 9032 codeRoot = f; 9033 Slog.w(TAG, "Unrecognized code path " 9034 + codePath + " - using " + codeRoot); 9035 } catch (IOException e) { 9036 // Can't canonicalize the code path -- shenanigans? 9037 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9038 return Environment.getRootDirectory().getPath(); 9039 } 9040 } 9041 return codeRoot.getPath(); 9042 } 9043 9044 /** 9045 * Derive and set the location of native libraries for the given package, 9046 * which varies depending on where and how the package was installed. 9047 */ 9048 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9049 final ApplicationInfo info = pkg.applicationInfo; 9050 final String codePath = pkg.codePath; 9051 final File codeFile = new File(codePath); 9052 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9053 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9054 9055 info.nativeLibraryRootDir = null; 9056 info.nativeLibraryRootRequiresIsa = false; 9057 info.nativeLibraryDir = null; 9058 info.secondaryNativeLibraryDir = null; 9059 9060 if (isApkFile(codeFile)) { 9061 // Monolithic install 9062 if (bundledApp) { 9063 // If "/system/lib64/apkname" exists, assume that is the per-package 9064 // native library directory to use; otherwise use "/system/lib/apkname". 9065 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9066 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9067 getPrimaryInstructionSet(info)); 9068 9069 // This is a bundled system app so choose the path based on the ABI. 9070 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9071 // is just the default path. 9072 final String apkName = deriveCodePathName(codePath); 9073 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9074 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9075 apkName).getAbsolutePath(); 9076 9077 if (info.secondaryCpuAbi != null) { 9078 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9079 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9080 secondaryLibDir, apkName).getAbsolutePath(); 9081 } 9082 } else if (asecApp) { 9083 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9084 .getAbsolutePath(); 9085 } else { 9086 final String apkName = deriveCodePathName(codePath); 9087 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9088 .getAbsolutePath(); 9089 } 9090 9091 info.nativeLibraryRootRequiresIsa = false; 9092 info.nativeLibraryDir = info.nativeLibraryRootDir; 9093 } else { 9094 // Cluster install 9095 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9096 info.nativeLibraryRootRequiresIsa = true; 9097 9098 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9099 getPrimaryInstructionSet(info)).getAbsolutePath(); 9100 9101 if (info.secondaryCpuAbi != null) { 9102 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9103 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9104 } 9105 } 9106 } 9107 9108 /** 9109 * Calculate the abis and roots for a bundled app. These can uniquely 9110 * be determined from the contents of the system partition, i.e whether 9111 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9112 * of this information, and instead assume that the system was built 9113 * sensibly. 9114 */ 9115 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9116 PackageSetting pkgSetting) { 9117 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9118 9119 // If "/system/lib64/apkname" exists, assume that is the per-package 9120 // native library directory to use; otherwise use "/system/lib/apkname". 9121 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9122 setBundledAppAbi(pkg, apkRoot, apkName); 9123 // pkgSetting might be null during rescan following uninstall of updates 9124 // to a bundled app, so accommodate that possibility. The settings in 9125 // that case will be established later from the parsed package. 9126 // 9127 // If the settings aren't null, sync them up with what we've just derived. 9128 // note that apkRoot isn't stored in the package settings. 9129 if (pkgSetting != null) { 9130 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9131 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9132 } 9133 } 9134 9135 /** 9136 * Deduces the ABI of a bundled app and sets the relevant fields on the 9137 * parsed pkg object. 9138 * 9139 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9140 * under which system libraries are installed. 9141 * @param apkName the name of the installed package. 9142 */ 9143 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9144 final File codeFile = new File(pkg.codePath); 9145 9146 final boolean has64BitLibs; 9147 final boolean has32BitLibs; 9148 if (isApkFile(codeFile)) { 9149 // Monolithic install 9150 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9151 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9152 } else { 9153 // Cluster install 9154 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9155 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9156 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9157 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9158 has64BitLibs = (new File(rootDir, isa)).exists(); 9159 } else { 9160 has64BitLibs = false; 9161 } 9162 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9163 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9164 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9165 has32BitLibs = (new File(rootDir, isa)).exists(); 9166 } else { 9167 has32BitLibs = false; 9168 } 9169 } 9170 9171 if (has64BitLibs && !has32BitLibs) { 9172 // The package has 64 bit libs, but not 32 bit libs. Its primary 9173 // ABI should be 64 bit. We can safely assume here that the bundled 9174 // native libraries correspond to the most preferred ABI in the list. 9175 9176 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9177 pkg.applicationInfo.secondaryCpuAbi = null; 9178 } else if (has32BitLibs && !has64BitLibs) { 9179 // The package has 32 bit libs but not 64 bit libs. Its primary 9180 // ABI should be 32 bit. 9181 9182 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9183 pkg.applicationInfo.secondaryCpuAbi = null; 9184 } else if (has32BitLibs && has64BitLibs) { 9185 // The application has both 64 and 32 bit bundled libraries. We check 9186 // here that the app declares multiArch support, and warn if it doesn't. 9187 // 9188 // We will be lenient here and record both ABIs. The primary will be the 9189 // ABI that's higher on the list, i.e, a device that's configured to prefer 9190 // 64 bit apps will see a 64 bit primary ABI, 9191 9192 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9193 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9194 } 9195 9196 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9197 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9198 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9199 } else { 9200 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9201 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9202 } 9203 } else { 9204 pkg.applicationInfo.primaryCpuAbi = null; 9205 pkg.applicationInfo.secondaryCpuAbi = null; 9206 } 9207 } 9208 9209 private void killApplication(String pkgName, int appId, String reason) { 9210 // Request the ActivityManager to kill the process(only for existing packages) 9211 // so that we do not end up in a confused state while the user is still using the older 9212 // version of the application while the new one gets installed. 9213 final long token = Binder.clearCallingIdentity(); 9214 try { 9215 IActivityManager am = ActivityManagerNative.getDefault(); 9216 if (am != null) { 9217 try { 9218 am.killApplicationWithAppId(pkgName, appId, reason); 9219 } catch (RemoteException e) { 9220 } 9221 } 9222 } finally { 9223 Binder.restoreCallingIdentity(token); 9224 } 9225 } 9226 9227 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9228 // Remove the parent package setting 9229 PackageSetting ps = (PackageSetting) pkg.mExtras; 9230 if (ps != null) { 9231 removePackageLI(ps, chatty); 9232 } 9233 // Remove the child package setting 9234 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9235 for (int i = 0; i < childCount; i++) { 9236 PackageParser.Package childPkg = pkg.childPackages.get(i); 9237 ps = (PackageSetting) childPkg.mExtras; 9238 if (ps != null) { 9239 removePackageLI(ps, chatty); 9240 } 9241 } 9242 } 9243 9244 void removePackageLI(PackageSetting ps, boolean chatty) { 9245 if (DEBUG_INSTALL) { 9246 if (chatty) 9247 Log.d(TAG, "Removing package " + ps.name); 9248 } 9249 9250 // writer 9251 synchronized (mPackages) { 9252 mPackages.remove(ps.name); 9253 final PackageParser.Package pkg = ps.pkg; 9254 if (pkg != null) { 9255 cleanPackageDataStructuresLILPw(pkg, chatty); 9256 } 9257 } 9258 } 9259 9260 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9261 if (DEBUG_INSTALL) { 9262 if (chatty) 9263 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9264 } 9265 9266 // writer 9267 synchronized (mPackages) { 9268 // Remove the parent package 9269 mPackages.remove(pkg.applicationInfo.packageName); 9270 cleanPackageDataStructuresLILPw(pkg, chatty); 9271 9272 // Remove the child packages 9273 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9274 for (int i = 0; i < childCount; i++) { 9275 PackageParser.Package childPkg = pkg.childPackages.get(i); 9276 mPackages.remove(childPkg.applicationInfo.packageName); 9277 cleanPackageDataStructuresLILPw(childPkg, chatty); 9278 } 9279 } 9280 } 9281 9282 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9283 int N = pkg.providers.size(); 9284 StringBuilder r = null; 9285 int i; 9286 for (i=0; i<N; i++) { 9287 PackageParser.Provider p = pkg.providers.get(i); 9288 mProviders.removeProvider(p); 9289 if (p.info.authority == null) { 9290 9291 /* There was another ContentProvider with this authority when 9292 * this app was installed so this authority is null, 9293 * Ignore it as we don't have to unregister the provider. 9294 */ 9295 continue; 9296 } 9297 String names[] = p.info.authority.split(";"); 9298 for (int j = 0; j < names.length; j++) { 9299 if (mProvidersByAuthority.get(names[j]) == p) { 9300 mProvidersByAuthority.remove(names[j]); 9301 if (DEBUG_REMOVE) { 9302 if (chatty) 9303 Log.d(TAG, "Unregistered content provider: " + names[j] 9304 + ", className = " + p.info.name + ", isSyncable = " 9305 + p.info.isSyncable); 9306 } 9307 } 9308 } 9309 if (DEBUG_REMOVE && chatty) { 9310 if (r == null) { 9311 r = new StringBuilder(256); 9312 } else { 9313 r.append(' '); 9314 } 9315 r.append(p.info.name); 9316 } 9317 } 9318 if (r != null) { 9319 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9320 } 9321 9322 N = pkg.services.size(); 9323 r = null; 9324 for (i=0; i<N; i++) { 9325 PackageParser.Service s = pkg.services.get(i); 9326 mServices.removeService(s); 9327 if (chatty) { 9328 if (r == null) { 9329 r = new StringBuilder(256); 9330 } else { 9331 r.append(' '); 9332 } 9333 r.append(s.info.name); 9334 } 9335 } 9336 if (r != null) { 9337 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9338 } 9339 9340 N = pkg.receivers.size(); 9341 r = null; 9342 for (i=0; i<N; i++) { 9343 PackageParser.Activity a = pkg.receivers.get(i); 9344 mReceivers.removeActivity(a, "receiver"); 9345 if (DEBUG_REMOVE && chatty) { 9346 if (r == null) { 9347 r = new StringBuilder(256); 9348 } else { 9349 r.append(' '); 9350 } 9351 r.append(a.info.name); 9352 } 9353 } 9354 if (r != null) { 9355 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9356 } 9357 9358 N = pkg.activities.size(); 9359 r = null; 9360 for (i=0; i<N; i++) { 9361 PackageParser.Activity a = pkg.activities.get(i); 9362 mActivities.removeActivity(a, "activity"); 9363 if (DEBUG_REMOVE && chatty) { 9364 if (r == null) { 9365 r = new StringBuilder(256); 9366 } else { 9367 r.append(' '); 9368 } 9369 r.append(a.info.name); 9370 } 9371 } 9372 if (r != null) { 9373 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9374 } 9375 9376 N = pkg.permissions.size(); 9377 r = null; 9378 for (i=0; i<N; i++) { 9379 PackageParser.Permission p = pkg.permissions.get(i); 9380 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9381 if (bp == null) { 9382 bp = mSettings.mPermissionTrees.get(p.info.name); 9383 } 9384 if (bp != null && bp.perm == p) { 9385 bp.perm = null; 9386 if (DEBUG_REMOVE && chatty) { 9387 if (r == null) { 9388 r = new StringBuilder(256); 9389 } else { 9390 r.append(' '); 9391 } 9392 r.append(p.info.name); 9393 } 9394 } 9395 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9396 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9397 if (appOpPkgs != null) { 9398 appOpPkgs.remove(pkg.packageName); 9399 } 9400 } 9401 } 9402 if (r != null) { 9403 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9404 } 9405 9406 N = pkg.requestedPermissions.size(); 9407 r = null; 9408 for (i=0; i<N; i++) { 9409 String perm = pkg.requestedPermissions.get(i); 9410 BasePermission bp = mSettings.mPermissions.get(perm); 9411 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9412 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9413 if (appOpPkgs != null) { 9414 appOpPkgs.remove(pkg.packageName); 9415 if (appOpPkgs.isEmpty()) { 9416 mAppOpPermissionPackages.remove(perm); 9417 } 9418 } 9419 } 9420 } 9421 if (r != null) { 9422 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9423 } 9424 9425 N = pkg.instrumentation.size(); 9426 r = null; 9427 for (i=0; i<N; i++) { 9428 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9429 mInstrumentation.remove(a.getComponentName()); 9430 if (DEBUG_REMOVE && chatty) { 9431 if (r == null) { 9432 r = new StringBuilder(256); 9433 } else { 9434 r.append(' '); 9435 } 9436 r.append(a.info.name); 9437 } 9438 } 9439 if (r != null) { 9440 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9441 } 9442 9443 r = null; 9444 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9445 // Only system apps can hold shared libraries. 9446 if (pkg.libraryNames != null) { 9447 for (i=0; i<pkg.libraryNames.size(); i++) { 9448 String name = pkg.libraryNames.get(i); 9449 SharedLibraryEntry cur = mSharedLibraries.get(name); 9450 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9451 mSharedLibraries.remove(name); 9452 if (DEBUG_REMOVE && chatty) { 9453 if (r == null) { 9454 r = new StringBuilder(256); 9455 } else { 9456 r.append(' '); 9457 } 9458 r.append(name); 9459 } 9460 } 9461 } 9462 } 9463 } 9464 if (r != null) { 9465 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9466 } 9467 } 9468 9469 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9470 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9471 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9472 return true; 9473 } 9474 } 9475 return false; 9476 } 9477 9478 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9479 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9480 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9481 9482 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9483 // Update the parent permissions 9484 updatePermissionsLPw(pkg.packageName, pkg, flags); 9485 // Update the child permissions 9486 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9487 for (int i = 0; i < childCount; i++) { 9488 PackageParser.Package childPkg = pkg.childPackages.get(i); 9489 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9490 } 9491 } 9492 9493 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9494 int flags) { 9495 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9496 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9497 } 9498 9499 private void updatePermissionsLPw(String changingPkg, 9500 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9501 // Make sure there are no dangling permission trees. 9502 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9503 while (it.hasNext()) { 9504 final BasePermission bp = it.next(); 9505 if (bp.packageSetting == null) { 9506 // We may not yet have parsed the package, so just see if 9507 // we still know about its settings. 9508 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9509 } 9510 if (bp.packageSetting == null) { 9511 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9512 + " from package " + bp.sourcePackage); 9513 it.remove(); 9514 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9515 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9516 Slog.i(TAG, "Removing old permission tree: " + bp.name 9517 + " from package " + bp.sourcePackage); 9518 flags |= UPDATE_PERMISSIONS_ALL; 9519 it.remove(); 9520 } 9521 } 9522 } 9523 9524 // Make sure all dynamic permissions have been assigned to a package, 9525 // and make sure there are no dangling permissions. 9526 it = mSettings.mPermissions.values().iterator(); 9527 while (it.hasNext()) { 9528 final BasePermission bp = it.next(); 9529 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9530 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9531 + bp.name + " pkg=" + bp.sourcePackage 9532 + " info=" + bp.pendingInfo); 9533 if (bp.packageSetting == null && bp.pendingInfo != null) { 9534 final BasePermission tree = findPermissionTreeLP(bp.name); 9535 if (tree != null && tree.perm != null) { 9536 bp.packageSetting = tree.packageSetting; 9537 bp.perm = new PackageParser.Permission(tree.perm.owner, 9538 new PermissionInfo(bp.pendingInfo)); 9539 bp.perm.info.packageName = tree.perm.info.packageName; 9540 bp.perm.info.name = bp.name; 9541 bp.uid = tree.uid; 9542 } 9543 } 9544 } 9545 if (bp.packageSetting == null) { 9546 // We may not yet have parsed the package, so just see if 9547 // we still know about its settings. 9548 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9549 } 9550 if (bp.packageSetting == null) { 9551 Slog.w(TAG, "Removing dangling permission: " + bp.name 9552 + " from package " + bp.sourcePackage); 9553 it.remove(); 9554 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9555 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9556 Slog.i(TAG, "Removing old permission: " + bp.name 9557 + " from package " + bp.sourcePackage); 9558 flags |= UPDATE_PERMISSIONS_ALL; 9559 it.remove(); 9560 } 9561 } 9562 } 9563 9564 // Now update the permissions for all packages, in particular 9565 // replace the granted permissions of the system packages. 9566 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9567 for (PackageParser.Package pkg : mPackages.values()) { 9568 if (pkg != pkgInfo) { 9569 // Only replace for packages on requested volume 9570 final String volumeUuid = getVolumeUuidForPackage(pkg); 9571 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9572 && Objects.equals(replaceVolumeUuid, volumeUuid); 9573 grantPermissionsLPw(pkg, replace, changingPkg); 9574 } 9575 } 9576 } 9577 9578 if (pkgInfo != null) { 9579 // Only replace for packages on requested volume 9580 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9581 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9582 && Objects.equals(replaceVolumeUuid, volumeUuid); 9583 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9584 } 9585 } 9586 9587 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9588 String packageOfInterest) { 9589 // IMPORTANT: There are two types of permissions: install and runtime. 9590 // Install time permissions are granted when the app is installed to 9591 // all device users and users added in the future. Runtime permissions 9592 // are granted at runtime explicitly to specific users. Normal and signature 9593 // protected permissions are install time permissions. Dangerous permissions 9594 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9595 // otherwise they are runtime permissions. This function does not manage 9596 // runtime permissions except for the case an app targeting Lollipop MR1 9597 // being upgraded to target a newer SDK, in which case dangerous permissions 9598 // are transformed from install time to runtime ones. 9599 9600 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9601 if (ps == null) { 9602 return; 9603 } 9604 9605 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9606 9607 PermissionsState permissionsState = ps.getPermissionsState(); 9608 PermissionsState origPermissions = permissionsState; 9609 9610 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9611 9612 boolean runtimePermissionsRevoked = false; 9613 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9614 9615 boolean changedInstallPermission = false; 9616 9617 if (replace) { 9618 ps.installPermissionsFixed = false; 9619 if (!ps.isSharedUser()) { 9620 origPermissions = new PermissionsState(permissionsState); 9621 permissionsState.reset(); 9622 } else { 9623 // We need to know only about runtime permission changes since the 9624 // calling code always writes the install permissions state but 9625 // the runtime ones are written only if changed. The only cases of 9626 // changed runtime permissions here are promotion of an install to 9627 // runtime and revocation of a runtime from a shared user. 9628 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9629 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9630 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9631 runtimePermissionsRevoked = true; 9632 } 9633 } 9634 } 9635 9636 permissionsState.setGlobalGids(mGlobalGids); 9637 9638 final int N = pkg.requestedPermissions.size(); 9639 for (int i=0; i<N; i++) { 9640 final String name = pkg.requestedPermissions.get(i); 9641 final BasePermission bp = mSettings.mPermissions.get(name); 9642 9643 if (DEBUG_INSTALL) { 9644 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9645 } 9646 9647 if (bp == null || bp.packageSetting == null) { 9648 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9649 Slog.w(TAG, "Unknown permission " + name 9650 + " in package " + pkg.packageName); 9651 } 9652 continue; 9653 } 9654 9655 final String perm = bp.name; 9656 boolean allowedSig = false; 9657 int grant = GRANT_DENIED; 9658 9659 // Keep track of app op permissions. 9660 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9661 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9662 if (pkgs == null) { 9663 pkgs = new ArraySet<>(); 9664 mAppOpPermissionPackages.put(bp.name, pkgs); 9665 } 9666 pkgs.add(pkg.packageName); 9667 } 9668 9669 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9670 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9671 >= Build.VERSION_CODES.M; 9672 switch (level) { 9673 case PermissionInfo.PROTECTION_NORMAL: { 9674 // For all apps normal permissions are install time ones. 9675 grant = GRANT_INSTALL; 9676 } break; 9677 9678 case PermissionInfo.PROTECTION_DANGEROUS: { 9679 // If a permission review is required for legacy apps we represent 9680 // their permissions as always granted runtime ones since we need 9681 // to keep the review required permission flag per user while an 9682 // install permission's state is shared across all users. 9683 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9684 // For legacy apps dangerous permissions are install time ones. 9685 grant = GRANT_INSTALL; 9686 } else if (origPermissions.hasInstallPermission(bp.name)) { 9687 // For legacy apps that became modern, install becomes runtime. 9688 grant = GRANT_UPGRADE; 9689 } else if (mPromoteSystemApps 9690 && isSystemApp(ps) 9691 && mExistingSystemPackages.contains(ps.name)) { 9692 // For legacy system apps, install becomes runtime. 9693 // We cannot check hasInstallPermission() for system apps since those 9694 // permissions were granted implicitly and not persisted pre-M. 9695 grant = GRANT_UPGRADE; 9696 } else { 9697 // For modern apps keep runtime permissions unchanged. 9698 grant = GRANT_RUNTIME; 9699 } 9700 } break; 9701 9702 case PermissionInfo.PROTECTION_SIGNATURE: { 9703 // For all apps signature permissions are install time ones. 9704 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9705 if (allowedSig) { 9706 grant = GRANT_INSTALL; 9707 } 9708 } break; 9709 } 9710 9711 if (DEBUG_INSTALL) { 9712 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9713 } 9714 9715 if (grant != GRANT_DENIED) { 9716 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9717 // If this is an existing, non-system package, then 9718 // we can't add any new permissions to it. 9719 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9720 // Except... if this is a permission that was added 9721 // to the platform (note: need to only do this when 9722 // updating the platform). 9723 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9724 grant = GRANT_DENIED; 9725 } 9726 } 9727 } 9728 9729 switch (grant) { 9730 case GRANT_INSTALL: { 9731 // Revoke this as runtime permission to handle the case of 9732 // a runtime permission being downgraded to an install one. 9733 // Also in permission review mode we keep dangerous permissions 9734 // for legacy apps 9735 for (int userId : UserManagerService.getInstance().getUserIds()) { 9736 if (origPermissions.getRuntimePermissionState( 9737 bp.name, userId) != null) { 9738 // Revoke the runtime permission and clear the flags. 9739 origPermissions.revokeRuntimePermission(bp, userId); 9740 origPermissions.updatePermissionFlags(bp, userId, 9741 PackageManager.MASK_PERMISSION_FLAGS, 0); 9742 // If we revoked a permission permission, we have to write. 9743 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9744 changedRuntimePermissionUserIds, userId); 9745 } 9746 } 9747 // Grant an install permission. 9748 if (permissionsState.grantInstallPermission(bp) != 9749 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9750 changedInstallPermission = true; 9751 } 9752 } break; 9753 9754 case GRANT_RUNTIME: { 9755 // Grant previously granted runtime permissions. 9756 for (int userId : UserManagerService.getInstance().getUserIds()) { 9757 PermissionState permissionState = origPermissions 9758 .getRuntimePermissionState(bp.name, userId); 9759 int flags = permissionState != null 9760 ? permissionState.getFlags() : 0; 9761 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9762 if (permissionsState.grantRuntimePermission(bp, userId) == 9763 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9764 // If we cannot put the permission as it was, we have to write. 9765 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9766 changedRuntimePermissionUserIds, userId); 9767 } 9768 // If the app supports runtime permissions no need for a review. 9769 if (Build.PERMISSIONS_REVIEW_REQUIRED 9770 && appSupportsRuntimePermissions 9771 && (flags & PackageManager 9772 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9773 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9774 // Since we changed the flags, we have to write. 9775 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9776 changedRuntimePermissionUserIds, userId); 9777 } 9778 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9779 && !appSupportsRuntimePermissions) { 9780 // For legacy apps that need a permission review, every new 9781 // runtime permission is granted but it is pending a review. 9782 // We also need to review only platform defined runtime 9783 // permissions as these are the only ones the platform knows 9784 // how to disable the API to simulate revocation as legacy 9785 // apps don't expect to run with revoked permissions. 9786 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9787 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9788 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9789 // We changed the flags, hence have to write. 9790 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9791 changedRuntimePermissionUserIds, userId); 9792 } 9793 } 9794 if (permissionsState.grantRuntimePermission(bp, userId) 9795 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9796 // We changed the permission, hence have to write. 9797 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9798 changedRuntimePermissionUserIds, userId); 9799 } 9800 } 9801 // Propagate the permission flags. 9802 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9803 } 9804 } break; 9805 9806 case GRANT_UPGRADE: { 9807 // Grant runtime permissions for a previously held install permission. 9808 PermissionState permissionState = origPermissions 9809 .getInstallPermissionState(bp.name); 9810 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9811 9812 if (origPermissions.revokeInstallPermission(bp) 9813 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9814 // We will be transferring the permission flags, so clear them. 9815 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9816 PackageManager.MASK_PERMISSION_FLAGS, 0); 9817 changedInstallPermission = true; 9818 } 9819 9820 // If the permission is not to be promoted to runtime we ignore it and 9821 // also its other flags as they are not applicable to install permissions. 9822 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9823 for (int userId : currentUserIds) { 9824 if (permissionsState.grantRuntimePermission(bp, userId) != 9825 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9826 // Transfer the permission flags. 9827 permissionsState.updatePermissionFlags(bp, userId, 9828 flags, flags); 9829 // If we granted the permission, we have to write. 9830 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9831 changedRuntimePermissionUserIds, userId); 9832 } 9833 } 9834 } 9835 } break; 9836 9837 default: { 9838 if (packageOfInterest == null 9839 || packageOfInterest.equals(pkg.packageName)) { 9840 Slog.w(TAG, "Not granting permission " + perm 9841 + " to package " + pkg.packageName 9842 + " because it was previously installed without"); 9843 } 9844 } break; 9845 } 9846 } else { 9847 if (permissionsState.revokeInstallPermission(bp) != 9848 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9849 // Also drop the permission flags. 9850 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9851 PackageManager.MASK_PERMISSION_FLAGS, 0); 9852 changedInstallPermission = true; 9853 Slog.i(TAG, "Un-granting permission " + perm 9854 + " from package " + pkg.packageName 9855 + " (protectionLevel=" + bp.protectionLevel 9856 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9857 + ")"); 9858 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9859 // Don't print warning for app op permissions, since it is fine for them 9860 // not to be granted, there is a UI for the user to decide. 9861 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9862 Slog.w(TAG, "Not granting permission " + perm 9863 + " to package " + pkg.packageName 9864 + " (protectionLevel=" + bp.protectionLevel 9865 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9866 + ")"); 9867 } 9868 } 9869 } 9870 } 9871 9872 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9873 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9874 // This is the first that we have heard about this package, so the 9875 // permissions we have now selected are fixed until explicitly 9876 // changed. 9877 ps.installPermissionsFixed = true; 9878 } 9879 9880 // Persist the runtime permissions state for users with changes. If permissions 9881 // were revoked because no app in the shared user declares them we have to 9882 // write synchronously to avoid losing runtime permissions state. 9883 for (int userId : changedRuntimePermissionUserIds) { 9884 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9885 } 9886 9887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9888 } 9889 9890 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9891 boolean allowed = false; 9892 final int NP = PackageParser.NEW_PERMISSIONS.length; 9893 for (int ip=0; ip<NP; ip++) { 9894 final PackageParser.NewPermissionInfo npi 9895 = PackageParser.NEW_PERMISSIONS[ip]; 9896 if (npi.name.equals(perm) 9897 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9898 allowed = true; 9899 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9900 + pkg.packageName); 9901 break; 9902 } 9903 } 9904 return allowed; 9905 } 9906 9907 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9908 BasePermission bp, PermissionsState origPermissions) { 9909 boolean allowed; 9910 allowed = (compareSignatures( 9911 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9912 == PackageManager.SIGNATURE_MATCH) 9913 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9914 == PackageManager.SIGNATURE_MATCH); 9915 if (!allowed && (bp.protectionLevel 9916 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9917 if (isSystemApp(pkg)) { 9918 // For updated system applications, a system permission 9919 // is granted only if it had been defined by the original application. 9920 if (pkg.isUpdatedSystemApp()) { 9921 final PackageSetting sysPs = mSettings 9922 .getDisabledSystemPkgLPr(pkg.packageName); 9923 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9924 // If the original was granted this permission, we take 9925 // that grant decision as read and propagate it to the 9926 // update. 9927 if (sysPs.isPrivileged()) { 9928 allowed = true; 9929 } 9930 } else { 9931 // The system apk may have been updated with an older 9932 // version of the one on the data partition, but which 9933 // granted a new system permission that it didn't have 9934 // before. In this case we do want to allow the app to 9935 // now get the new permission if the ancestral apk is 9936 // privileged to get it. 9937 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9938 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9939 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9940 allowed = true; 9941 break; 9942 } 9943 } 9944 } 9945 // Also if a privileged parent package on the system image or any of 9946 // its children requested a privileged permission, the updated child 9947 // packages can also get the permission. 9948 if (pkg.parentPackage != null) { 9949 final PackageSetting disabledSysParentPs = mSettings 9950 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9951 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9952 && disabledSysParentPs.isPrivileged()) { 9953 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9954 allowed = true; 9955 } else if (disabledSysParentPs.pkg.childPackages != null) { 9956 final int count = disabledSysParentPs.pkg.childPackages.size(); 9957 for (int i = 0; i < count; i++) { 9958 PackageParser.Package disabledSysChildPkg = 9959 disabledSysParentPs.pkg.childPackages.get(i); 9960 if (isPackageRequestingPermission(disabledSysChildPkg, 9961 perm)) { 9962 allowed = true; 9963 break; 9964 } 9965 } 9966 } 9967 } 9968 } 9969 } 9970 } else { 9971 allowed = isPrivilegedApp(pkg); 9972 } 9973 } 9974 } 9975 if (!allowed) { 9976 if (!allowed && (bp.protectionLevel 9977 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9978 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9979 // If this was a previously normal/dangerous permission that got moved 9980 // to a system permission as part of the runtime permission redesign, then 9981 // we still want to blindly grant it to old apps. 9982 allowed = true; 9983 } 9984 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9985 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9986 // If this permission is to be granted to the system installer and 9987 // this app is an installer, then it gets the permission. 9988 allowed = true; 9989 } 9990 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9991 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9992 // If this permission is to be granted to the system verifier and 9993 // this app is a verifier, then it gets the permission. 9994 allowed = true; 9995 } 9996 if (!allowed && (bp.protectionLevel 9997 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9998 && isSystemApp(pkg)) { 9999 // Any pre-installed system app is allowed to get this permission. 10000 allowed = true; 10001 } 10002 if (!allowed && (bp.protectionLevel 10003 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10004 // For development permissions, a development permission 10005 // is granted only if it was already granted. 10006 allowed = origPermissions.hasInstallPermission(perm); 10007 } 10008 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10009 && pkg.packageName.equals(mSetupWizardPackage)) { 10010 // If this permission is to be granted to the system setup wizard and 10011 // this app is a setup wizard, then it gets the permission. 10012 allowed = true; 10013 } 10014 } 10015 return allowed; 10016 } 10017 10018 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10019 final int permCount = pkg.requestedPermissions.size(); 10020 for (int j = 0; j < permCount; j++) { 10021 String requestedPermission = pkg.requestedPermissions.get(j); 10022 if (permission.equals(requestedPermission)) { 10023 return true; 10024 } 10025 } 10026 return false; 10027 } 10028 10029 final class ActivityIntentResolver 10030 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10031 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10032 boolean defaultOnly, int userId) { 10033 if (!sUserManager.exists(userId)) return null; 10034 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10035 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10036 } 10037 10038 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10039 int userId) { 10040 if (!sUserManager.exists(userId)) return null; 10041 mFlags = flags; 10042 return super.queryIntent(intent, resolvedType, 10043 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10044 } 10045 10046 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10047 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10048 if (!sUserManager.exists(userId)) return null; 10049 if (packageActivities == null) { 10050 return null; 10051 } 10052 mFlags = flags; 10053 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10054 final int N = packageActivities.size(); 10055 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10056 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10057 10058 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10059 for (int i = 0; i < N; ++i) { 10060 intentFilters = packageActivities.get(i).intents; 10061 if (intentFilters != null && intentFilters.size() > 0) { 10062 PackageParser.ActivityIntentInfo[] array = 10063 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10064 intentFilters.toArray(array); 10065 listCut.add(array); 10066 } 10067 } 10068 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10069 } 10070 10071 /** 10072 * Finds a privileged activity that matches the specified activity names. 10073 */ 10074 private PackageParser.Activity findMatchingActivity( 10075 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10076 for (PackageParser.Activity sysActivity : activityList) { 10077 if (sysActivity.info.name.equals(activityInfo.name)) { 10078 return sysActivity; 10079 } 10080 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10081 return sysActivity; 10082 } 10083 if (sysActivity.info.targetActivity != null) { 10084 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10085 return sysActivity; 10086 } 10087 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10088 return sysActivity; 10089 } 10090 } 10091 } 10092 return null; 10093 } 10094 10095 public class IterGenerator<E> { 10096 public Iterator<E> generate(ActivityIntentInfo info) { 10097 return null; 10098 } 10099 } 10100 10101 public class ActionIterGenerator extends IterGenerator<String> { 10102 @Override 10103 public Iterator<String> generate(ActivityIntentInfo info) { 10104 return info.actionsIterator(); 10105 } 10106 } 10107 10108 public class CategoriesIterGenerator extends IterGenerator<String> { 10109 @Override 10110 public Iterator<String> generate(ActivityIntentInfo info) { 10111 return info.categoriesIterator(); 10112 } 10113 } 10114 10115 public class SchemesIterGenerator extends IterGenerator<String> { 10116 @Override 10117 public Iterator<String> generate(ActivityIntentInfo info) { 10118 return info.schemesIterator(); 10119 } 10120 } 10121 10122 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10123 @Override 10124 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10125 return info.authoritiesIterator(); 10126 } 10127 } 10128 10129 /** 10130 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10131 * MODIFIED. Do not pass in a list that should not be changed. 10132 */ 10133 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10134 IterGenerator<T> generator, Iterator<T> searchIterator) { 10135 // loop through the set of actions; every one must be found in the intent filter 10136 while (searchIterator.hasNext()) { 10137 // we must have at least one filter in the list to consider a match 10138 if (intentList.size() == 0) { 10139 break; 10140 } 10141 10142 final T searchAction = searchIterator.next(); 10143 10144 // loop through the set of intent filters 10145 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10146 while (intentIter.hasNext()) { 10147 final ActivityIntentInfo intentInfo = intentIter.next(); 10148 boolean selectionFound = false; 10149 10150 // loop through the intent filter's selection criteria; at least one 10151 // of them must match the searched criteria 10152 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10153 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10154 final T intentSelection = intentSelectionIter.next(); 10155 if (intentSelection != null && intentSelection.equals(searchAction)) { 10156 selectionFound = true; 10157 break; 10158 } 10159 } 10160 10161 // the selection criteria wasn't found in this filter's set; this filter 10162 // is not a potential match 10163 if (!selectionFound) { 10164 intentIter.remove(); 10165 } 10166 } 10167 } 10168 } 10169 10170 private boolean isProtectedAction(ActivityIntentInfo filter) { 10171 final Iterator<String> actionsIter = filter.actionsIterator(); 10172 while (actionsIter != null && actionsIter.hasNext()) { 10173 final String filterAction = actionsIter.next(); 10174 if (PROTECTED_ACTIONS.contains(filterAction)) { 10175 return true; 10176 } 10177 } 10178 return false; 10179 } 10180 10181 /** 10182 * Adjusts the priority of the given intent filter according to policy. 10183 * <p> 10184 * <ul> 10185 * <li>The priority for non privileged applications is capped to '0'</li> 10186 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10187 * <li>The priority for unbundled updates to privileged applications is capped to the 10188 * priority defined on the system partition</li> 10189 * </ul> 10190 * <p> 10191 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10192 * allowed to obtain any priority on any action. 10193 */ 10194 private void adjustPriority( 10195 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10196 // nothing to do; priority is fine as-is 10197 if (intent.getPriority() <= 0) { 10198 return; 10199 } 10200 10201 final ActivityInfo activityInfo = intent.activity.info; 10202 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10203 10204 final boolean privilegedApp = 10205 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10206 if (!privilegedApp) { 10207 // non-privileged applications can never define a priority >0 10208 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10209 + " package: " + applicationInfo.packageName 10210 + " activity: " + intent.activity.className 10211 + " origPrio: " + intent.getPriority()); 10212 intent.setPriority(0); 10213 return; 10214 } 10215 10216 if (systemActivities == null) { 10217 // the system package is not disabled; we're parsing the system partition 10218 if (isProtectedAction(intent)) { 10219 if (mDeferProtectedFilters) { 10220 // We can't deal with these just yet. No component should ever obtain a 10221 // >0 priority for a protected actions, with ONE exception -- the setup 10222 // wizard. The setup wizard, however, cannot be known until we're able to 10223 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10224 // until all intent filters have been processed. Chicken, meet egg. 10225 // Let the filter temporarily have a high priority and rectify the 10226 // priorities after all system packages have been scanned. 10227 mProtectedFilters.add(intent); 10228 if (DEBUG_FILTERS) { 10229 Slog.i(TAG, "Protected action; save for later;" 10230 + " package: " + applicationInfo.packageName 10231 + " activity: " + intent.activity.className 10232 + " origPrio: " + intent.getPriority()); 10233 } 10234 return; 10235 } else { 10236 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10237 Slog.i(TAG, "No setup wizard;" 10238 + " All protected intents capped to priority 0"); 10239 } 10240 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10241 if (DEBUG_FILTERS) { 10242 Slog.i(TAG, "Found setup wizard;" 10243 + " allow priority " + intent.getPriority() + ";" 10244 + " package: " + intent.activity.info.packageName 10245 + " activity: " + intent.activity.className 10246 + " priority: " + intent.getPriority()); 10247 } 10248 // setup wizard gets whatever it wants 10249 return; 10250 } 10251 Slog.w(TAG, "Protected action; cap priority to 0;" 10252 + " package: " + intent.activity.info.packageName 10253 + " activity: " + intent.activity.className 10254 + " origPrio: " + intent.getPriority()); 10255 intent.setPriority(0); 10256 return; 10257 } 10258 } 10259 // privileged apps on the system image get whatever priority they request 10260 return; 10261 } 10262 10263 // privileged app unbundled update ... try to find the same activity 10264 final PackageParser.Activity foundActivity = 10265 findMatchingActivity(systemActivities, activityInfo); 10266 if (foundActivity == null) { 10267 // this is a new activity; it cannot obtain >0 priority 10268 if (DEBUG_FILTERS) { 10269 Slog.i(TAG, "New activity; cap priority to 0;" 10270 + " package: " + applicationInfo.packageName 10271 + " activity: " + intent.activity.className 10272 + " origPrio: " + intent.getPriority()); 10273 } 10274 intent.setPriority(0); 10275 return; 10276 } 10277 10278 // found activity, now check for filter equivalence 10279 10280 // a shallow copy is enough; we modify the list, not its contents 10281 final List<ActivityIntentInfo> intentListCopy = 10282 new ArrayList<>(foundActivity.intents); 10283 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10284 10285 // find matching action subsets 10286 final Iterator<String> actionsIterator = intent.actionsIterator(); 10287 if (actionsIterator != null) { 10288 getIntentListSubset( 10289 intentListCopy, new ActionIterGenerator(), actionsIterator); 10290 if (intentListCopy.size() == 0) { 10291 // no more intents to match; we're not equivalent 10292 if (DEBUG_FILTERS) { 10293 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10294 + " package: " + applicationInfo.packageName 10295 + " activity: " + intent.activity.className 10296 + " origPrio: " + intent.getPriority()); 10297 } 10298 intent.setPriority(0); 10299 return; 10300 } 10301 } 10302 10303 // find matching category subsets 10304 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10305 if (categoriesIterator != null) { 10306 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10307 categoriesIterator); 10308 if (intentListCopy.size() == 0) { 10309 // no more intents to match; we're not equivalent 10310 if (DEBUG_FILTERS) { 10311 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10312 + " package: " + applicationInfo.packageName 10313 + " activity: " + intent.activity.className 10314 + " origPrio: " + intent.getPriority()); 10315 } 10316 intent.setPriority(0); 10317 return; 10318 } 10319 } 10320 10321 // find matching schemes subsets 10322 final Iterator<String> schemesIterator = intent.schemesIterator(); 10323 if (schemesIterator != null) { 10324 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10325 schemesIterator); 10326 if (intentListCopy.size() == 0) { 10327 // no more intents to match; we're not equivalent 10328 if (DEBUG_FILTERS) { 10329 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10330 + " package: " + applicationInfo.packageName 10331 + " activity: " + intent.activity.className 10332 + " origPrio: " + intent.getPriority()); 10333 } 10334 intent.setPriority(0); 10335 return; 10336 } 10337 } 10338 10339 // find matching authorities subsets 10340 final Iterator<IntentFilter.AuthorityEntry> 10341 authoritiesIterator = intent.authoritiesIterator(); 10342 if (authoritiesIterator != null) { 10343 getIntentListSubset(intentListCopy, 10344 new AuthoritiesIterGenerator(), 10345 authoritiesIterator); 10346 if (intentListCopy.size() == 0) { 10347 // no more intents to match; we're not equivalent 10348 if (DEBUG_FILTERS) { 10349 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10350 + " package: " + applicationInfo.packageName 10351 + " activity: " + intent.activity.className 10352 + " origPrio: " + intent.getPriority()); 10353 } 10354 intent.setPriority(0); 10355 return; 10356 } 10357 } 10358 10359 // we found matching filter(s); app gets the max priority of all intents 10360 int cappedPriority = 0; 10361 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10362 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10363 } 10364 if (intent.getPriority() > cappedPriority) { 10365 if (DEBUG_FILTERS) { 10366 Slog.i(TAG, "Found matching filter(s);" 10367 + " cap priority to " + cappedPriority + ";" 10368 + " package: " + applicationInfo.packageName 10369 + " activity: " + intent.activity.className 10370 + " origPrio: " + intent.getPriority()); 10371 } 10372 intent.setPriority(cappedPriority); 10373 return; 10374 } 10375 // all this for nothing; the requested priority was <= what was on the system 10376 } 10377 10378 public final void addActivity(PackageParser.Activity a, String type) { 10379 mActivities.put(a.getComponentName(), a); 10380 if (DEBUG_SHOW_INFO) 10381 Log.v( 10382 TAG, " " + type + " " + 10383 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10384 if (DEBUG_SHOW_INFO) 10385 Log.v(TAG, " Class=" + a.info.name); 10386 final int NI = a.intents.size(); 10387 for (int j=0; j<NI; j++) { 10388 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10389 if ("activity".equals(type)) { 10390 final PackageSetting ps = 10391 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10392 final List<PackageParser.Activity> systemActivities = 10393 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10394 adjustPriority(systemActivities, intent); 10395 } 10396 if (DEBUG_SHOW_INFO) { 10397 Log.v(TAG, " IntentFilter:"); 10398 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10399 } 10400 if (!intent.debugCheck()) { 10401 Log.w(TAG, "==> For Activity " + a.info.name); 10402 } 10403 addFilter(intent); 10404 } 10405 } 10406 10407 public final void removeActivity(PackageParser.Activity a, String type) { 10408 mActivities.remove(a.getComponentName()); 10409 if (DEBUG_SHOW_INFO) { 10410 Log.v(TAG, " " + type + " " 10411 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10412 : a.info.name) + ":"); 10413 Log.v(TAG, " Class=" + a.info.name); 10414 } 10415 final int NI = a.intents.size(); 10416 for (int j=0; j<NI; j++) { 10417 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10418 if (DEBUG_SHOW_INFO) { 10419 Log.v(TAG, " IntentFilter:"); 10420 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10421 } 10422 removeFilter(intent); 10423 } 10424 } 10425 10426 @Override 10427 protected boolean allowFilterResult( 10428 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10429 ActivityInfo filterAi = filter.activity.info; 10430 for (int i=dest.size()-1; i>=0; i--) { 10431 ActivityInfo destAi = dest.get(i).activityInfo; 10432 if (destAi.name == filterAi.name 10433 && destAi.packageName == filterAi.packageName) { 10434 return false; 10435 } 10436 } 10437 return true; 10438 } 10439 10440 @Override 10441 protected ActivityIntentInfo[] newArray(int size) { 10442 return new ActivityIntentInfo[size]; 10443 } 10444 10445 @Override 10446 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10447 if (!sUserManager.exists(userId)) return true; 10448 PackageParser.Package p = filter.activity.owner; 10449 if (p != null) { 10450 PackageSetting ps = (PackageSetting)p.mExtras; 10451 if (ps != null) { 10452 // System apps are never considered stopped for purposes of 10453 // filtering, because there may be no way for the user to 10454 // actually re-launch them. 10455 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10456 && ps.getStopped(userId); 10457 } 10458 } 10459 return false; 10460 } 10461 10462 @Override 10463 protected boolean isPackageForFilter(String packageName, 10464 PackageParser.ActivityIntentInfo info) { 10465 return packageName.equals(info.activity.owner.packageName); 10466 } 10467 10468 @Override 10469 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10470 int match, int userId) { 10471 if (!sUserManager.exists(userId)) return null; 10472 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10473 return null; 10474 } 10475 final PackageParser.Activity activity = info.activity; 10476 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10477 if (ps == null) { 10478 return null; 10479 } 10480 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10481 ps.readUserState(userId), userId); 10482 if (ai == null) { 10483 return null; 10484 } 10485 final ResolveInfo res = new ResolveInfo(); 10486 res.activityInfo = ai; 10487 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10488 res.filter = info; 10489 } 10490 if (info != null) { 10491 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10492 } 10493 res.priority = info.getPriority(); 10494 res.preferredOrder = activity.owner.mPreferredOrder; 10495 //System.out.println("Result: " + res.activityInfo.className + 10496 // " = " + res.priority); 10497 res.match = match; 10498 res.isDefault = info.hasDefault; 10499 res.labelRes = info.labelRes; 10500 res.nonLocalizedLabel = info.nonLocalizedLabel; 10501 if (userNeedsBadging(userId)) { 10502 res.noResourceId = true; 10503 } else { 10504 res.icon = info.icon; 10505 } 10506 res.iconResourceId = info.icon; 10507 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10508 return res; 10509 } 10510 10511 @Override 10512 protected void sortResults(List<ResolveInfo> results) { 10513 Collections.sort(results, mResolvePrioritySorter); 10514 } 10515 10516 @Override 10517 protected void dumpFilter(PrintWriter out, String prefix, 10518 PackageParser.ActivityIntentInfo filter) { 10519 out.print(prefix); out.print( 10520 Integer.toHexString(System.identityHashCode(filter.activity))); 10521 out.print(' '); 10522 filter.activity.printComponentShortName(out); 10523 out.print(" filter "); 10524 out.println(Integer.toHexString(System.identityHashCode(filter))); 10525 } 10526 10527 @Override 10528 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10529 return filter.activity; 10530 } 10531 10532 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10533 PackageParser.Activity activity = (PackageParser.Activity)label; 10534 out.print(prefix); out.print( 10535 Integer.toHexString(System.identityHashCode(activity))); 10536 out.print(' '); 10537 activity.printComponentShortName(out); 10538 if (count > 1) { 10539 out.print(" ("); out.print(count); out.print(" filters)"); 10540 } 10541 out.println(); 10542 } 10543 10544 // Keys are String (activity class name), values are Activity. 10545 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10546 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10547 private int mFlags; 10548 } 10549 10550 private final class ServiceIntentResolver 10551 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10552 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10553 boolean defaultOnly, int userId) { 10554 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10555 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10556 } 10557 10558 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10559 int userId) { 10560 if (!sUserManager.exists(userId)) return null; 10561 mFlags = flags; 10562 return super.queryIntent(intent, resolvedType, 10563 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10564 } 10565 10566 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10567 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10568 if (!sUserManager.exists(userId)) return null; 10569 if (packageServices == null) { 10570 return null; 10571 } 10572 mFlags = flags; 10573 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10574 final int N = packageServices.size(); 10575 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10576 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10577 10578 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10579 for (int i = 0; i < N; ++i) { 10580 intentFilters = packageServices.get(i).intents; 10581 if (intentFilters != null && intentFilters.size() > 0) { 10582 PackageParser.ServiceIntentInfo[] array = 10583 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10584 intentFilters.toArray(array); 10585 listCut.add(array); 10586 } 10587 } 10588 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10589 } 10590 10591 public final void addService(PackageParser.Service s) { 10592 mServices.put(s.getComponentName(), s); 10593 if (DEBUG_SHOW_INFO) { 10594 Log.v(TAG, " " 10595 + (s.info.nonLocalizedLabel != null 10596 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10597 Log.v(TAG, " Class=" + s.info.name); 10598 } 10599 final int NI = s.intents.size(); 10600 int j; 10601 for (j=0; j<NI; j++) { 10602 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10603 if (DEBUG_SHOW_INFO) { 10604 Log.v(TAG, " IntentFilter:"); 10605 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10606 } 10607 if (!intent.debugCheck()) { 10608 Log.w(TAG, "==> For Service " + s.info.name); 10609 } 10610 addFilter(intent); 10611 } 10612 } 10613 10614 public final void removeService(PackageParser.Service s) { 10615 mServices.remove(s.getComponentName()); 10616 if (DEBUG_SHOW_INFO) { 10617 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10618 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10619 Log.v(TAG, " Class=" + s.info.name); 10620 } 10621 final int NI = s.intents.size(); 10622 int j; 10623 for (j=0; j<NI; j++) { 10624 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10625 if (DEBUG_SHOW_INFO) { 10626 Log.v(TAG, " IntentFilter:"); 10627 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10628 } 10629 removeFilter(intent); 10630 } 10631 } 10632 10633 @Override 10634 protected boolean allowFilterResult( 10635 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10636 ServiceInfo filterSi = filter.service.info; 10637 for (int i=dest.size()-1; i>=0; i--) { 10638 ServiceInfo destAi = dest.get(i).serviceInfo; 10639 if (destAi.name == filterSi.name 10640 && destAi.packageName == filterSi.packageName) { 10641 return false; 10642 } 10643 } 10644 return true; 10645 } 10646 10647 @Override 10648 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10649 return new PackageParser.ServiceIntentInfo[size]; 10650 } 10651 10652 @Override 10653 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10654 if (!sUserManager.exists(userId)) return true; 10655 PackageParser.Package p = filter.service.owner; 10656 if (p != null) { 10657 PackageSetting ps = (PackageSetting)p.mExtras; 10658 if (ps != null) { 10659 // System apps are never considered stopped for purposes of 10660 // filtering, because there may be no way for the user to 10661 // actually re-launch them. 10662 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10663 && ps.getStopped(userId); 10664 } 10665 } 10666 return false; 10667 } 10668 10669 @Override 10670 protected boolean isPackageForFilter(String packageName, 10671 PackageParser.ServiceIntentInfo info) { 10672 return packageName.equals(info.service.owner.packageName); 10673 } 10674 10675 @Override 10676 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10677 int match, int userId) { 10678 if (!sUserManager.exists(userId)) return null; 10679 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10680 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10681 return null; 10682 } 10683 final PackageParser.Service service = info.service; 10684 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10685 if (ps == null) { 10686 return null; 10687 } 10688 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10689 ps.readUserState(userId), userId); 10690 if (si == null) { 10691 return null; 10692 } 10693 final ResolveInfo res = new ResolveInfo(); 10694 res.serviceInfo = si; 10695 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10696 res.filter = filter; 10697 } 10698 res.priority = info.getPriority(); 10699 res.preferredOrder = service.owner.mPreferredOrder; 10700 res.match = match; 10701 res.isDefault = info.hasDefault; 10702 res.labelRes = info.labelRes; 10703 res.nonLocalizedLabel = info.nonLocalizedLabel; 10704 res.icon = info.icon; 10705 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10706 return res; 10707 } 10708 10709 @Override 10710 protected void sortResults(List<ResolveInfo> results) { 10711 Collections.sort(results, mResolvePrioritySorter); 10712 } 10713 10714 @Override 10715 protected void dumpFilter(PrintWriter out, String prefix, 10716 PackageParser.ServiceIntentInfo filter) { 10717 out.print(prefix); out.print( 10718 Integer.toHexString(System.identityHashCode(filter.service))); 10719 out.print(' '); 10720 filter.service.printComponentShortName(out); 10721 out.print(" filter "); 10722 out.println(Integer.toHexString(System.identityHashCode(filter))); 10723 } 10724 10725 @Override 10726 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10727 return filter.service; 10728 } 10729 10730 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10731 PackageParser.Service service = (PackageParser.Service)label; 10732 out.print(prefix); out.print( 10733 Integer.toHexString(System.identityHashCode(service))); 10734 out.print(' '); 10735 service.printComponentShortName(out); 10736 if (count > 1) { 10737 out.print(" ("); out.print(count); out.print(" filters)"); 10738 } 10739 out.println(); 10740 } 10741 10742// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10743// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10744// final List<ResolveInfo> retList = Lists.newArrayList(); 10745// while (i.hasNext()) { 10746// final ResolveInfo resolveInfo = (ResolveInfo) i; 10747// if (isEnabledLP(resolveInfo.serviceInfo)) { 10748// retList.add(resolveInfo); 10749// } 10750// } 10751// return retList; 10752// } 10753 10754 // Keys are String (activity class name), values are Activity. 10755 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10756 = new ArrayMap<ComponentName, PackageParser.Service>(); 10757 private int mFlags; 10758 }; 10759 10760 private final class ProviderIntentResolver 10761 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10762 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10763 boolean defaultOnly, int userId) { 10764 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10765 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10766 } 10767 10768 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10769 int userId) { 10770 if (!sUserManager.exists(userId)) 10771 return null; 10772 mFlags = flags; 10773 return super.queryIntent(intent, resolvedType, 10774 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10775 } 10776 10777 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10778 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10779 if (!sUserManager.exists(userId)) 10780 return null; 10781 if (packageProviders == null) { 10782 return null; 10783 } 10784 mFlags = flags; 10785 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10786 final int N = packageProviders.size(); 10787 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10788 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10789 10790 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10791 for (int i = 0; i < N; ++i) { 10792 intentFilters = packageProviders.get(i).intents; 10793 if (intentFilters != null && intentFilters.size() > 0) { 10794 PackageParser.ProviderIntentInfo[] array = 10795 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10796 intentFilters.toArray(array); 10797 listCut.add(array); 10798 } 10799 } 10800 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10801 } 10802 10803 public final void addProvider(PackageParser.Provider p) { 10804 if (mProviders.containsKey(p.getComponentName())) { 10805 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10806 return; 10807 } 10808 10809 mProviders.put(p.getComponentName(), p); 10810 if (DEBUG_SHOW_INFO) { 10811 Log.v(TAG, " " 10812 + (p.info.nonLocalizedLabel != null 10813 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10814 Log.v(TAG, " Class=" + p.info.name); 10815 } 10816 final int NI = p.intents.size(); 10817 int j; 10818 for (j = 0; j < NI; j++) { 10819 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10820 if (DEBUG_SHOW_INFO) { 10821 Log.v(TAG, " IntentFilter:"); 10822 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10823 } 10824 if (!intent.debugCheck()) { 10825 Log.w(TAG, "==> For Provider " + p.info.name); 10826 } 10827 addFilter(intent); 10828 } 10829 } 10830 10831 public final void removeProvider(PackageParser.Provider p) { 10832 mProviders.remove(p.getComponentName()); 10833 if (DEBUG_SHOW_INFO) { 10834 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10835 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10836 Log.v(TAG, " Class=" + p.info.name); 10837 } 10838 final int NI = p.intents.size(); 10839 int j; 10840 for (j = 0; j < NI; j++) { 10841 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10842 if (DEBUG_SHOW_INFO) { 10843 Log.v(TAG, " IntentFilter:"); 10844 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10845 } 10846 removeFilter(intent); 10847 } 10848 } 10849 10850 @Override 10851 protected boolean allowFilterResult( 10852 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10853 ProviderInfo filterPi = filter.provider.info; 10854 for (int i = dest.size() - 1; i >= 0; i--) { 10855 ProviderInfo destPi = dest.get(i).providerInfo; 10856 if (destPi.name == filterPi.name 10857 && destPi.packageName == filterPi.packageName) { 10858 return false; 10859 } 10860 } 10861 return true; 10862 } 10863 10864 @Override 10865 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10866 return new PackageParser.ProviderIntentInfo[size]; 10867 } 10868 10869 @Override 10870 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10871 if (!sUserManager.exists(userId)) 10872 return true; 10873 PackageParser.Package p = filter.provider.owner; 10874 if (p != null) { 10875 PackageSetting ps = (PackageSetting) p.mExtras; 10876 if (ps != null) { 10877 // System apps are never considered stopped for purposes of 10878 // filtering, because there may be no way for the user to 10879 // actually re-launch them. 10880 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10881 && ps.getStopped(userId); 10882 } 10883 } 10884 return false; 10885 } 10886 10887 @Override 10888 protected boolean isPackageForFilter(String packageName, 10889 PackageParser.ProviderIntentInfo info) { 10890 return packageName.equals(info.provider.owner.packageName); 10891 } 10892 10893 @Override 10894 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10895 int match, int userId) { 10896 if (!sUserManager.exists(userId)) 10897 return null; 10898 final PackageParser.ProviderIntentInfo info = filter; 10899 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10900 return null; 10901 } 10902 final PackageParser.Provider provider = info.provider; 10903 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10904 if (ps == null) { 10905 return null; 10906 } 10907 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10908 ps.readUserState(userId), userId); 10909 if (pi == null) { 10910 return null; 10911 } 10912 final ResolveInfo res = new ResolveInfo(); 10913 res.providerInfo = pi; 10914 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10915 res.filter = filter; 10916 } 10917 res.priority = info.getPriority(); 10918 res.preferredOrder = provider.owner.mPreferredOrder; 10919 res.match = match; 10920 res.isDefault = info.hasDefault; 10921 res.labelRes = info.labelRes; 10922 res.nonLocalizedLabel = info.nonLocalizedLabel; 10923 res.icon = info.icon; 10924 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10925 return res; 10926 } 10927 10928 @Override 10929 protected void sortResults(List<ResolveInfo> results) { 10930 Collections.sort(results, mResolvePrioritySorter); 10931 } 10932 10933 @Override 10934 protected void dumpFilter(PrintWriter out, String prefix, 10935 PackageParser.ProviderIntentInfo filter) { 10936 out.print(prefix); 10937 out.print( 10938 Integer.toHexString(System.identityHashCode(filter.provider))); 10939 out.print(' '); 10940 filter.provider.printComponentShortName(out); 10941 out.print(" filter "); 10942 out.println(Integer.toHexString(System.identityHashCode(filter))); 10943 } 10944 10945 @Override 10946 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10947 return filter.provider; 10948 } 10949 10950 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10951 PackageParser.Provider provider = (PackageParser.Provider)label; 10952 out.print(prefix); out.print( 10953 Integer.toHexString(System.identityHashCode(provider))); 10954 out.print(' '); 10955 provider.printComponentShortName(out); 10956 if (count > 1) { 10957 out.print(" ("); out.print(count); out.print(" filters)"); 10958 } 10959 out.println(); 10960 } 10961 10962 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10963 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10964 private int mFlags; 10965 } 10966 10967 private static final class EphemeralIntentResolver 10968 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10969 @Override 10970 protected EphemeralResolveIntentInfo[] newArray(int size) { 10971 return new EphemeralResolveIntentInfo[size]; 10972 } 10973 10974 @Override 10975 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10976 return true; 10977 } 10978 10979 @Override 10980 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10981 int userId) { 10982 if (!sUserManager.exists(userId)) { 10983 return null; 10984 } 10985 return info.getEphemeralResolveInfo(); 10986 } 10987 } 10988 10989 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10990 new Comparator<ResolveInfo>() { 10991 public int compare(ResolveInfo r1, ResolveInfo r2) { 10992 int v1 = r1.priority; 10993 int v2 = r2.priority; 10994 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10995 if (v1 != v2) { 10996 return (v1 > v2) ? -1 : 1; 10997 } 10998 v1 = r1.preferredOrder; 10999 v2 = r2.preferredOrder; 11000 if (v1 != v2) { 11001 return (v1 > v2) ? -1 : 1; 11002 } 11003 if (r1.isDefault != r2.isDefault) { 11004 return r1.isDefault ? -1 : 1; 11005 } 11006 v1 = r1.match; 11007 v2 = r2.match; 11008 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11009 if (v1 != v2) { 11010 return (v1 > v2) ? -1 : 1; 11011 } 11012 if (r1.system != r2.system) { 11013 return r1.system ? -1 : 1; 11014 } 11015 if (r1.activityInfo != null) { 11016 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11017 } 11018 if (r1.serviceInfo != null) { 11019 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11020 } 11021 if (r1.providerInfo != null) { 11022 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11023 } 11024 return 0; 11025 } 11026 }; 11027 11028 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11029 new Comparator<ProviderInfo>() { 11030 public int compare(ProviderInfo p1, ProviderInfo p2) { 11031 final int v1 = p1.initOrder; 11032 final int v2 = p2.initOrder; 11033 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11034 } 11035 }; 11036 11037 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11038 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11039 final int[] userIds) { 11040 mHandler.post(new Runnable() { 11041 @Override 11042 public void run() { 11043 try { 11044 final IActivityManager am = ActivityManagerNative.getDefault(); 11045 if (am == null) return; 11046 final int[] resolvedUserIds; 11047 if (userIds == null) { 11048 resolvedUserIds = am.getRunningUserIds(); 11049 } else { 11050 resolvedUserIds = userIds; 11051 } 11052 for (int id : resolvedUserIds) { 11053 final Intent intent = new Intent(action, 11054 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11055 if (extras != null) { 11056 intent.putExtras(extras); 11057 } 11058 if (targetPkg != null) { 11059 intent.setPackage(targetPkg); 11060 } 11061 // Modify the UID when posting to other users 11062 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11063 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11064 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11065 intent.putExtra(Intent.EXTRA_UID, uid); 11066 } 11067 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11068 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11069 if (DEBUG_BROADCASTS) { 11070 RuntimeException here = new RuntimeException("here"); 11071 here.fillInStackTrace(); 11072 Slog.d(TAG, "Sending to user " + id + ": " 11073 + intent.toShortString(false, true, false, false) 11074 + " " + intent.getExtras(), here); 11075 } 11076 am.broadcastIntent(null, intent, null, finishedReceiver, 11077 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11078 null, finishedReceiver != null, false, id); 11079 } 11080 } catch (RemoteException ex) { 11081 } 11082 } 11083 }); 11084 } 11085 11086 /** 11087 * Check if the external storage media is available. This is true if there 11088 * is a mounted external storage medium or if the external storage is 11089 * emulated. 11090 */ 11091 private boolean isExternalMediaAvailable() { 11092 return mMediaMounted || Environment.isExternalStorageEmulated(); 11093 } 11094 11095 @Override 11096 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11097 // writer 11098 synchronized (mPackages) { 11099 if (!isExternalMediaAvailable()) { 11100 // If the external storage is no longer mounted at this point, 11101 // the caller may not have been able to delete all of this 11102 // packages files and can not delete any more. Bail. 11103 return null; 11104 } 11105 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11106 if (lastPackage != null) { 11107 pkgs.remove(lastPackage); 11108 } 11109 if (pkgs.size() > 0) { 11110 return pkgs.get(0); 11111 } 11112 } 11113 return null; 11114 } 11115 11116 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11117 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11118 userId, andCode ? 1 : 0, packageName); 11119 if (mSystemReady) { 11120 msg.sendToTarget(); 11121 } else { 11122 if (mPostSystemReadyMessages == null) { 11123 mPostSystemReadyMessages = new ArrayList<>(); 11124 } 11125 mPostSystemReadyMessages.add(msg); 11126 } 11127 } 11128 11129 void startCleaningPackages() { 11130 // reader 11131 if (!isExternalMediaAvailable()) { 11132 return; 11133 } 11134 synchronized (mPackages) { 11135 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11136 return; 11137 } 11138 } 11139 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11140 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11141 IActivityManager am = ActivityManagerNative.getDefault(); 11142 if (am != null) { 11143 try { 11144 am.startService(null, intent, null, mContext.getOpPackageName(), 11145 UserHandle.USER_SYSTEM); 11146 } catch (RemoteException e) { 11147 } 11148 } 11149 } 11150 11151 @Override 11152 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11153 int installFlags, String installerPackageName, int userId) { 11154 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11155 11156 final int callingUid = Binder.getCallingUid(); 11157 enforceCrossUserPermission(callingUid, userId, 11158 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11159 11160 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11161 try { 11162 if (observer != null) { 11163 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11164 } 11165 } catch (RemoteException re) { 11166 } 11167 return; 11168 } 11169 11170 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11171 installFlags |= PackageManager.INSTALL_FROM_ADB; 11172 11173 } else { 11174 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11175 // about installerPackageName. 11176 11177 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11178 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11179 } 11180 11181 UserHandle user; 11182 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11183 user = UserHandle.ALL; 11184 } else { 11185 user = new UserHandle(userId); 11186 } 11187 11188 // Only system components can circumvent runtime permissions when installing. 11189 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11190 && mContext.checkCallingOrSelfPermission(Manifest.permission 11191 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11192 throw new SecurityException("You need the " 11193 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11194 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11195 } 11196 11197 final File originFile = new File(originPath); 11198 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11199 11200 final Message msg = mHandler.obtainMessage(INIT_COPY); 11201 final VerificationInfo verificationInfo = new VerificationInfo( 11202 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11203 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11204 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11205 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11206 null /*certificates*/); 11207 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11208 msg.obj = params; 11209 11210 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11211 System.identityHashCode(msg.obj)); 11212 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11213 System.identityHashCode(msg.obj)); 11214 11215 mHandler.sendMessage(msg); 11216 } 11217 11218 void installStage(String packageName, File stagedDir, String stagedCid, 11219 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11220 String installerPackageName, int installerUid, UserHandle user, 11221 Certificate[][] certificates) { 11222 if (DEBUG_EPHEMERAL) { 11223 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11224 Slog.d(TAG, "Ephemeral install of " + packageName); 11225 } 11226 } 11227 final VerificationInfo verificationInfo = new VerificationInfo( 11228 sessionParams.originatingUri, sessionParams.referrerUri, 11229 sessionParams.originatingUid, installerUid); 11230 11231 final OriginInfo origin; 11232 if (stagedDir != null) { 11233 origin = OriginInfo.fromStagedFile(stagedDir); 11234 } else { 11235 origin = OriginInfo.fromStagedContainer(stagedCid); 11236 } 11237 11238 final Message msg = mHandler.obtainMessage(INIT_COPY); 11239 final InstallParams params = new InstallParams(origin, null, observer, 11240 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11241 verificationInfo, user, sessionParams.abiOverride, 11242 sessionParams.grantedRuntimePermissions, certificates); 11243 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11244 msg.obj = params; 11245 11246 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11247 System.identityHashCode(msg.obj)); 11248 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11249 System.identityHashCode(msg.obj)); 11250 11251 mHandler.sendMessage(msg); 11252 } 11253 11254 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11255 int userId) { 11256 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11257 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11258 } 11259 11260 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11261 int appId, int userId) { 11262 Bundle extras = new Bundle(1); 11263 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11264 11265 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11266 packageName, extras, 0, null, null, new int[] {userId}); 11267 try { 11268 IActivityManager am = ActivityManagerNative.getDefault(); 11269 if (isSystem && am.isUserRunning(userId, 0)) { 11270 // The just-installed/enabled app is bundled on the system, so presumed 11271 // to be able to run automatically without needing an explicit launch. 11272 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11273 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11274 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11275 .setPackage(packageName); 11276 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11277 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11278 } 11279 } catch (RemoteException e) { 11280 // shouldn't happen 11281 Slog.w(TAG, "Unable to bootstrap installed package", e); 11282 } 11283 } 11284 11285 @Override 11286 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11287 int userId) { 11288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11289 PackageSetting pkgSetting; 11290 final int uid = Binder.getCallingUid(); 11291 enforceCrossUserPermission(uid, userId, 11292 true /* requireFullPermission */, true /* checkShell */, 11293 "setApplicationHiddenSetting for user " + userId); 11294 11295 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11296 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11297 return false; 11298 } 11299 11300 long callingId = Binder.clearCallingIdentity(); 11301 try { 11302 boolean sendAdded = false; 11303 boolean sendRemoved = false; 11304 // writer 11305 synchronized (mPackages) { 11306 pkgSetting = mSettings.mPackages.get(packageName); 11307 if (pkgSetting == null) { 11308 return false; 11309 } 11310 if (pkgSetting.getHidden(userId) != hidden) { 11311 pkgSetting.setHidden(hidden, userId); 11312 mSettings.writePackageRestrictionsLPr(userId); 11313 if (hidden) { 11314 sendRemoved = true; 11315 } else { 11316 sendAdded = true; 11317 } 11318 } 11319 } 11320 if (sendAdded) { 11321 sendPackageAddedForUser(packageName, pkgSetting, userId); 11322 return true; 11323 } 11324 if (sendRemoved) { 11325 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11326 "hiding pkg"); 11327 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11328 return true; 11329 } 11330 } finally { 11331 Binder.restoreCallingIdentity(callingId); 11332 } 11333 return false; 11334 } 11335 11336 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11337 int userId) { 11338 final PackageRemovedInfo info = new PackageRemovedInfo(); 11339 info.removedPackage = packageName; 11340 info.removedUsers = new int[] {userId}; 11341 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11342 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11343 } 11344 11345 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11346 if (pkgList.length > 0) { 11347 Bundle extras = new Bundle(1); 11348 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11349 11350 sendPackageBroadcast( 11351 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11352 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11353 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11354 new int[] {userId}); 11355 } 11356 } 11357 11358 /** 11359 * Returns true if application is not found or there was an error. Otherwise it returns 11360 * the hidden state of the package for the given user. 11361 */ 11362 @Override 11363 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11364 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11365 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11366 true /* requireFullPermission */, false /* checkShell */, 11367 "getApplicationHidden for user " + userId); 11368 PackageSetting pkgSetting; 11369 long callingId = Binder.clearCallingIdentity(); 11370 try { 11371 // writer 11372 synchronized (mPackages) { 11373 pkgSetting = mSettings.mPackages.get(packageName); 11374 if (pkgSetting == null) { 11375 return true; 11376 } 11377 return pkgSetting.getHidden(userId); 11378 } 11379 } finally { 11380 Binder.restoreCallingIdentity(callingId); 11381 } 11382 } 11383 11384 /** 11385 * @hide 11386 */ 11387 @Override 11388 public int installExistingPackageAsUser(String packageName, int userId) { 11389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11390 null); 11391 PackageSetting pkgSetting; 11392 final int uid = Binder.getCallingUid(); 11393 enforceCrossUserPermission(uid, userId, 11394 true /* requireFullPermission */, true /* checkShell */, 11395 "installExistingPackage for user " + userId); 11396 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11397 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11398 } 11399 11400 long callingId = Binder.clearCallingIdentity(); 11401 try { 11402 boolean installed = false; 11403 11404 // writer 11405 synchronized (mPackages) { 11406 pkgSetting = mSettings.mPackages.get(packageName); 11407 if (pkgSetting == null) { 11408 return PackageManager.INSTALL_FAILED_INVALID_URI; 11409 } 11410 if (!pkgSetting.getInstalled(userId)) { 11411 pkgSetting.setInstalled(true, userId); 11412 pkgSetting.setHidden(false, userId); 11413 mSettings.writePackageRestrictionsLPr(userId); 11414 installed = true; 11415 } 11416 } 11417 11418 if (installed) { 11419 if (pkgSetting.pkg != null) { 11420 synchronized (mInstallLock) { 11421 // We don't need to freeze for a brand new install 11422 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11423 } 11424 } 11425 sendPackageAddedForUser(packageName, pkgSetting, userId); 11426 } 11427 } finally { 11428 Binder.restoreCallingIdentity(callingId); 11429 } 11430 11431 return PackageManager.INSTALL_SUCCEEDED; 11432 } 11433 11434 boolean isUserRestricted(int userId, String restrictionKey) { 11435 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11436 if (restrictions.getBoolean(restrictionKey, false)) { 11437 Log.w(TAG, "User is restricted: " + restrictionKey); 11438 return true; 11439 } 11440 return false; 11441 } 11442 11443 @Override 11444 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11445 int userId) { 11446 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11447 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11448 true /* requireFullPermission */, true /* checkShell */, 11449 "setPackagesSuspended for user " + userId); 11450 11451 if (ArrayUtils.isEmpty(packageNames)) { 11452 return packageNames; 11453 } 11454 11455 // List of package names for whom the suspended state has changed. 11456 List<String> changedPackages = new ArrayList<>(packageNames.length); 11457 // List of package names for whom the suspended state is not set as requested in this 11458 // method. 11459 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11460 for (int i = 0; i < packageNames.length; i++) { 11461 String packageName = packageNames[i]; 11462 long callingId = Binder.clearCallingIdentity(); 11463 try { 11464 boolean changed = false; 11465 final int appId; 11466 synchronized (mPackages) { 11467 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11468 if (pkgSetting == null) { 11469 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11470 + "\". Skipping suspending/un-suspending."); 11471 unactionedPackages.add(packageName); 11472 continue; 11473 } 11474 appId = pkgSetting.appId; 11475 if (pkgSetting.getSuspended(userId) != suspended) { 11476 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11477 unactionedPackages.add(packageName); 11478 continue; 11479 } 11480 pkgSetting.setSuspended(suspended, userId); 11481 mSettings.writePackageRestrictionsLPr(userId); 11482 changed = true; 11483 changedPackages.add(packageName); 11484 } 11485 } 11486 11487 if (changed && suspended) { 11488 killApplication(packageName, UserHandle.getUid(userId, appId), 11489 "suspending package"); 11490 } 11491 } finally { 11492 Binder.restoreCallingIdentity(callingId); 11493 } 11494 } 11495 11496 if (!changedPackages.isEmpty()) { 11497 sendPackagesSuspendedForUser(changedPackages.toArray( 11498 new String[changedPackages.size()]), userId, suspended); 11499 } 11500 11501 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11502 } 11503 11504 @Override 11505 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11506 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11507 true /* requireFullPermission */, false /* checkShell */, 11508 "isPackageSuspendedForUser for user " + userId); 11509 synchronized (mPackages) { 11510 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11511 if (pkgSetting == null) { 11512 throw new IllegalArgumentException("Unknown target package: " + packageName); 11513 } 11514 return pkgSetting.getSuspended(userId); 11515 } 11516 } 11517 11518 /** 11519 * TODO: cache and disallow blocking the active dialer. 11520 * 11521 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11522 */ 11523 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11524 if (isPackageDeviceAdmin(packageName, userId)) { 11525 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11526 + "\": has an active device admin"); 11527 return false; 11528 } 11529 11530 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11531 if (packageName.equals(activeLauncherPackageName)) { 11532 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11533 + "\": contains the active launcher"); 11534 return false; 11535 } 11536 11537 if (packageName.equals(mRequiredInstallerPackage)) { 11538 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11539 + "\": required for package installation"); 11540 return false; 11541 } 11542 11543 if (packageName.equals(mRequiredVerifierPackage)) { 11544 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11545 + "\": required for package verification"); 11546 return false; 11547 } 11548 11549 final PackageParser.Package pkg = mPackages.get(packageName); 11550 if (pkg != null && isPrivilegedApp(pkg)) { 11551 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11552 + "\": is a privileged app"); 11553 return false; 11554 } 11555 11556 return true; 11557 } 11558 11559 private String getActiveLauncherPackageName(int userId) { 11560 Intent intent = new Intent(Intent.ACTION_MAIN); 11561 intent.addCategory(Intent.CATEGORY_HOME); 11562 ResolveInfo resolveInfo = resolveIntent( 11563 intent, 11564 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11565 PackageManager.MATCH_DEFAULT_ONLY, 11566 userId); 11567 11568 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11569 } 11570 11571 @Override 11572 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11573 mContext.enforceCallingOrSelfPermission( 11574 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11575 "Only package verification agents can verify applications"); 11576 11577 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11578 final PackageVerificationResponse response = new PackageVerificationResponse( 11579 verificationCode, Binder.getCallingUid()); 11580 msg.arg1 = id; 11581 msg.obj = response; 11582 mHandler.sendMessage(msg); 11583 } 11584 11585 @Override 11586 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11587 long millisecondsToDelay) { 11588 mContext.enforceCallingOrSelfPermission( 11589 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11590 "Only package verification agents can extend verification timeouts"); 11591 11592 final PackageVerificationState state = mPendingVerification.get(id); 11593 final PackageVerificationResponse response = new PackageVerificationResponse( 11594 verificationCodeAtTimeout, Binder.getCallingUid()); 11595 11596 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11597 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11598 } 11599 if (millisecondsToDelay < 0) { 11600 millisecondsToDelay = 0; 11601 } 11602 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11603 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11604 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11605 } 11606 11607 if ((state != null) && !state.timeoutExtended()) { 11608 state.extendTimeout(); 11609 11610 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11611 msg.arg1 = id; 11612 msg.obj = response; 11613 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11614 } 11615 } 11616 11617 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11618 int verificationCode, UserHandle user) { 11619 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11620 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11621 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11622 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11623 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11624 11625 mContext.sendBroadcastAsUser(intent, user, 11626 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11627 } 11628 11629 private ComponentName matchComponentForVerifier(String packageName, 11630 List<ResolveInfo> receivers) { 11631 ActivityInfo targetReceiver = null; 11632 11633 final int NR = receivers.size(); 11634 for (int i = 0; i < NR; i++) { 11635 final ResolveInfo info = receivers.get(i); 11636 if (info.activityInfo == null) { 11637 continue; 11638 } 11639 11640 if (packageName.equals(info.activityInfo.packageName)) { 11641 targetReceiver = info.activityInfo; 11642 break; 11643 } 11644 } 11645 11646 if (targetReceiver == null) { 11647 return null; 11648 } 11649 11650 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11651 } 11652 11653 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11654 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11655 if (pkgInfo.verifiers.length == 0) { 11656 return null; 11657 } 11658 11659 final int N = pkgInfo.verifiers.length; 11660 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11661 for (int i = 0; i < N; i++) { 11662 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11663 11664 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11665 receivers); 11666 if (comp == null) { 11667 continue; 11668 } 11669 11670 final int verifierUid = getUidForVerifier(verifierInfo); 11671 if (verifierUid == -1) { 11672 continue; 11673 } 11674 11675 if (DEBUG_VERIFY) { 11676 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11677 + " with the correct signature"); 11678 } 11679 sufficientVerifiers.add(comp); 11680 verificationState.addSufficientVerifier(verifierUid); 11681 } 11682 11683 return sufficientVerifiers; 11684 } 11685 11686 private int getUidForVerifier(VerifierInfo verifierInfo) { 11687 synchronized (mPackages) { 11688 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11689 if (pkg == null) { 11690 return -1; 11691 } else if (pkg.mSignatures.length != 1) { 11692 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11693 + " has more than one signature; ignoring"); 11694 return -1; 11695 } 11696 11697 /* 11698 * If the public key of the package's signature does not match 11699 * our expected public key, then this is a different package and 11700 * we should skip. 11701 */ 11702 11703 final byte[] expectedPublicKey; 11704 try { 11705 final Signature verifierSig = pkg.mSignatures[0]; 11706 final PublicKey publicKey = verifierSig.getPublicKey(); 11707 expectedPublicKey = publicKey.getEncoded(); 11708 } catch (CertificateException e) { 11709 return -1; 11710 } 11711 11712 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11713 11714 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11715 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11716 + " does not have the expected public key; ignoring"); 11717 return -1; 11718 } 11719 11720 return pkg.applicationInfo.uid; 11721 } 11722 } 11723 11724 @Override 11725 public void finishPackageInstall(int token, boolean didLaunch) { 11726 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11727 11728 if (DEBUG_INSTALL) { 11729 Slog.v(TAG, "BM finishing package install for " + token); 11730 } 11731 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11732 11733 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11734 mHandler.sendMessage(msg); 11735 } 11736 11737 /** 11738 * Get the verification agent timeout. 11739 * 11740 * @return verification timeout in milliseconds 11741 */ 11742 private long getVerificationTimeout() { 11743 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11744 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11745 DEFAULT_VERIFICATION_TIMEOUT); 11746 } 11747 11748 /** 11749 * Get the default verification agent response code. 11750 * 11751 * @return default verification response code 11752 */ 11753 private int getDefaultVerificationResponse() { 11754 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11755 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11756 DEFAULT_VERIFICATION_RESPONSE); 11757 } 11758 11759 /** 11760 * Check whether or not package verification has been enabled. 11761 * 11762 * @return true if verification should be performed 11763 */ 11764 private boolean isVerificationEnabled(int userId, int installFlags) { 11765 if (!DEFAULT_VERIFY_ENABLE) { 11766 return false; 11767 } 11768 // Ephemeral apps don't get the full verification treatment 11769 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11770 if (DEBUG_EPHEMERAL) { 11771 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11772 } 11773 return false; 11774 } 11775 11776 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11777 11778 // Check if installing from ADB 11779 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11780 // Do not run verification in a test harness environment 11781 if (ActivityManager.isRunningInTestHarness()) { 11782 return false; 11783 } 11784 if (ensureVerifyAppsEnabled) { 11785 return true; 11786 } 11787 // Check if the developer does not want package verification for ADB installs 11788 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11789 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11790 return false; 11791 } 11792 } 11793 11794 if (ensureVerifyAppsEnabled) { 11795 return true; 11796 } 11797 11798 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11799 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11800 } 11801 11802 @Override 11803 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11804 throws RemoteException { 11805 mContext.enforceCallingOrSelfPermission( 11806 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11807 "Only intentfilter verification agents can verify applications"); 11808 11809 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11810 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11811 Binder.getCallingUid(), verificationCode, failedDomains); 11812 msg.arg1 = id; 11813 msg.obj = response; 11814 mHandler.sendMessage(msg); 11815 } 11816 11817 @Override 11818 public int getIntentVerificationStatus(String packageName, int userId) { 11819 synchronized (mPackages) { 11820 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11821 } 11822 } 11823 11824 @Override 11825 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11826 mContext.enforceCallingOrSelfPermission( 11827 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11828 11829 boolean result = false; 11830 synchronized (mPackages) { 11831 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11832 } 11833 if (result) { 11834 scheduleWritePackageRestrictionsLocked(userId); 11835 } 11836 return result; 11837 } 11838 11839 @Override 11840 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11841 String packageName) { 11842 synchronized (mPackages) { 11843 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11844 } 11845 } 11846 11847 @Override 11848 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11849 if (TextUtils.isEmpty(packageName)) { 11850 return ParceledListSlice.emptyList(); 11851 } 11852 synchronized (mPackages) { 11853 PackageParser.Package pkg = mPackages.get(packageName); 11854 if (pkg == null || pkg.activities == null) { 11855 return ParceledListSlice.emptyList(); 11856 } 11857 final int count = pkg.activities.size(); 11858 ArrayList<IntentFilter> result = new ArrayList<>(); 11859 for (int n=0; n<count; n++) { 11860 PackageParser.Activity activity = pkg.activities.get(n); 11861 if (activity.intents != null && activity.intents.size() > 0) { 11862 result.addAll(activity.intents); 11863 } 11864 } 11865 return new ParceledListSlice<>(result); 11866 } 11867 } 11868 11869 @Override 11870 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11871 mContext.enforceCallingOrSelfPermission( 11872 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11873 11874 synchronized (mPackages) { 11875 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11876 if (packageName != null) { 11877 result |= updateIntentVerificationStatus(packageName, 11878 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11879 userId); 11880 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11881 packageName, userId); 11882 } 11883 return result; 11884 } 11885 } 11886 11887 @Override 11888 public String getDefaultBrowserPackageName(int userId) { 11889 synchronized (mPackages) { 11890 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11891 } 11892 } 11893 11894 /** 11895 * Get the "allow unknown sources" setting. 11896 * 11897 * @return the current "allow unknown sources" setting 11898 */ 11899 private int getUnknownSourcesSettings() { 11900 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11901 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11902 -1); 11903 } 11904 11905 @Override 11906 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11907 final int uid = Binder.getCallingUid(); 11908 // writer 11909 synchronized (mPackages) { 11910 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11911 if (targetPackageSetting == null) { 11912 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11913 } 11914 11915 PackageSetting installerPackageSetting; 11916 if (installerPackageName != null) { 11917 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11918 if (installerPackageSetting == null) { 11919 throw new IllegalArgumentException("Unknown installer package: " 11920 + installerPackageName); 11921 } 11922 } else { 11923 installerPackageSetting = null; 11924 } 11925 11926 Signature[] callerSignature; 11927 Object obj = mSettings.getUserIdLPr(uid); 11928 if (obj != null) { 11929 if (obj instanceof SharedUserSetting) { 11930 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11931 } else if (obj instanceof PackageSetting) { 11932 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11933 } else { 11934 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11935 } 11936 } else { 11937 throw new SecurityException("Unknown calling UID: " + uid); 11938 } 11939 11940 // Verify: can't set installerPackageName to a package that is 11941 // not signed with the same cert as the caller. 11942 if (installerPackageSetting != null) { 11943 if (compareSignatures(callerSignature, 11944 installerPackageSetting.signatures.mSignatures) 11945 != PackageManager.SIGNATURE_MATCH) { 11946 throw new SecurityException( 11947 "Caller does not have same cert as new installer package " 11948 + installerPackageName); 11949 } 11950 } 11951 11952 // Verify: if target already has an installer package, it must 11953 // be signed with the same cert as the caller. 11954 if (targetPackageSetting.installerPackageName != null) { 11955 PackageSetting setting = mSettings.mPackages.get( 11956 targetPackageSetting.installerPackageName); 11957 // If the currently set package isn't valid, then it's always 11958 // okay to change it. 11959 if (setting != null) { 11960 if (compareSignatures(callerSignature, 11961 setting.signatures.mSignatures) 11962 != PackageManager.SIGNATURE_MATCH) { 11963 throw new SecurityException( 11964 "Caller does not have same cert as old installer package " 11965 + targetPackageSetting.installerPackageName); 11966 } 11967 } 11968 } 11969 11970 // Okay! 11971 targetPackageSetting.installerPackageName = installerPackageName; 11972 if (installerPackageName != null) { 11973 mSettings.mInstallerPackages.add(installerPackageName); 11974 } 11975 scheduleWriteSettingsLocked(); 11976 } 11977 } 11978 11979 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11980 // Queue up an async operation since the package installation may take a little while. 11981 mHandler.post(new Runnable() { 11982 public void run() { 11983 mHandler.removeCallbacks(this); 11984 // Result object to be returned 11985 PackageInstalledInfo res = new PackageInstalledInfo(); 11986 res.setReturnCode(currentStatus); 11987 res.uid = -1; 11988 res.pkg = null; 11989 res.removedInfo = null; 11990 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11991 args.doPreInstall(res.returnCode); 11992 synchronized (mInstallLock) { 11993 installPackageTracedLI(args, res); 11994 } 11995 args.doPostInstall(res.returnCode, res.uid); 11996 } 11997 11998 // A restore should be performed at this point if (a) the install 11999 // succeeded, (b) the operation is not an update, and (c) the new 12000 // package has not opted out of backup participation. 12001 final boolean update = res.removedInfo != null 12002 && res.removedInfo.removedPackage != null; 12003 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12004 boolean doRestore = !update 12005 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12006 12007 // Set up the post-install work request bookkeeping. This will be used 12008 // and cleaned up by the post-install event handling regardless of whether 12009 // there's a restore pass performed. Token values are >= 1. 12010 int token; 12011 if (mNextInstallToken < 0) mNextInstallToken = 1; 12012 token = mNextInstallToken++; 12013 12014 PostInstallData data = new PostInstallData(args, res); 12015 mRunningInstalls.put(token, data); 12016 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12017 12018 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12019 // Pass responsibility to the Backup Manager. It will perform a 12020 // restore if appropriate, then pass responsibility back to the 12021 // Package Manager to run the post-install observer callbacks 12022 // and broadcasts. 12023 IBackupManager bm = IBackupManager.Stub.asInterface( 12024 ServiceManager.getService(Context.BACKUP_SERVICE)); 12025 if (bm != null) { 12026 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12027 + " to BM for possible restore"); 12028 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12029 try { 12030 // TODO: http://b/22388012 12031 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12032 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12033 } else { 12034 doRestore = false; 12035 } 12036 } catch (RemoteException e) { 12037 // can't happen; the backup manager is local 12038 } catch (Exception e) { 12039 Slog.e(TAG, "Exception trying to enqueue restore", e); 12040 doRestore = false; 12041 } 12042 } else { 12043 Slog.e(TAG, "Backup Manager not found!"); 12044 doRestore = false; 12045 } 12046 } 12047 12048 if (!doRestore) { 12049 // No restore possible, or the Backup Manager was mysteriously not 12050 // available -- just fire the post-install work request directly. 12051 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12052 12053 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12054 12055 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12056 mHandler.sendMessage(msg); 12057 } 12058 } 12059 }); 12060 } 12061 12062 /** 12063 * Callback from PackageSettings whenever an app is first transitioned out of the 12064 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12065 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12066 * here whether the app is the target of an ongoing install, and only send the 12067 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12068 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12069 * handling. 12070 */ 12071 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12072 // Serialize this with the rest of the install-process message chain. In the 12073 // restore-at-install case, this Runnable will necessarily run before the 12074 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12075 // are coherent. In the non-restore case, the app has already completed install 12076 // and been launched through some other means, so it is not in a problematic 12077 // state for observers to see the FIRST_LAUNCH signal. 12078 mHandler.post(new Runnable() { 12079 @Override 12080 public void run() { 12081 for (int i = 0; i < mRunningInstalls.size(); i++) { 12082 final PostInstallData data = mRunningInstalls.valueAt(i); 12083 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12084 // right package; but is it for the right user? 12085 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12086 if (userId == data.res.newUsers[uIndex]) { 12087 if (DEBUG_BACKUP) { 12088 Slog.i(TAG, "Package " + pkgName 12089 + " being restored so deferring FIRST_LAUNCH"); 12090 } 12091 return; 12092 } 12093 } 12094 } 12095 } 12096 // didn't find it, so not being restored 12097 if (DEBUG_BACKUP) { 12098 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12099 } 12100 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12101 } 12102 }); 12103 } 12104 12105 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12106 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12107 installerPkg, null, userIds); 12108 } 12109 12110 private abstract class HandlerParams { 12111 private static final int MAX_RETRIES = 4; 12112 12113 /** 12114 * Number of times startCopy() has been attempted and had a non-fatal 12115 * error. 12116 */ 12117 private int mRetries = 0; 12118 12119 /** User handle for the user requesting the information or installation. */ 12120 private final UserHandle mUser; 12121 String traceMethod; 12122 int traceCookie; 12123 12124 HandlerParams(UserHandle user) { 12125 mUser = user; 12126 } 12127 12128 UserHandle getUser() { 12129 return mUser; 12130 } 12131 12132 HandlerParams setTraceMethod(String traceMethod) { 12133 this.traceMethod = traceMethod; 12134 return this; 12135 } 12136 12137 HandlerParams setTraceCookie(int traceCookie) { 12138 this.traceCookie = traceCookie; 12139 return this; 12140 } 12141 12142 final boolean startCopy() { 12143 boolean res; 12144 try { 12145 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12146 12147 if (++mRetries > MAX_RETRIES) { 12148 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12149 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12150 handleServiceError(); 12151 return false; 12152 } else { 12153 handleStartCopy(); 12154 res = true; 12155 } 12156 } catch (RemoteException e) { 12157 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12158 mHandler.sendEmptyMessage(MCS_RECONNECT); 12159 res = false; 12160 } 12161 handleReturnCode(); 12162 return res; 12163 } 12164 12165 final void serviceError() { 12166 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12167 handleServiceError(); 12168 handleReturnCode(); 12169 } 12170 12171 abstract void handleStartCopy() throws RemoteException; 12172 abstract void handleServiceError(); 12173 abstract void handleReturnCode(); 12174 } 12175 12176 class MeasureParams extends HandlerParams { 12177 private final PackageStats mStats; 12178 private boolean mSuccess; 12179 12180 private final IPackageStatsObserver mObserver; 12181 12182 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12183 super(new UserHandle(stats.userHandle)); 12184 mObserver = observer; 12185 mStats = stats; 12186 } 12187 12188 @Override 12189 public String toString() { 12190 return "MeasureParams{" 12191 + Integer.toHexString(System.identityHashCode(this)) 12192 + " " + mStats.packageName + "}"; 12193 } 12194 12195 @Override 12196 void handleStartCopy() throws RemoteException { 12197 synchronized (mInstallLock) { 12198 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12199 } 12200 12201 if (mSuccess) { 12202 final boolean mounted; 12203 if (Environment.isExternalStorageEmulated()) { 12204 mounted = true; 12205 } else { 12206 final String status = Environment.getExternalStorageState(); 12207 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12208 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12209 } 12210 12211 if (mounted) { 12212 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12213 12214 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12215 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12216 12217 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12218 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12219 12220 // Always subtract cache size, since it's a subdirectory 12221 mStats.externalDataSize -= mStats.externalCacheSize; 12222 12223 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12224 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12225 12226 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12227 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12228 } 12229 } 12230 } 12231 12232 @Override 12233 void handleReturnCode() { 12234 if (mObserver != null) { 12235 try { 12236 mObserver.onGetStatsCompleted(mStats, mSuccess); 12237 } catch (RemoteException e) { 12238 Slog.i(TAG, "Observer no longer exists."); 12239 } 12240 } 12241 } 12242 12243 @Override 12244 void handleServiceError() { 12245 Slog.e(TAG, "Could not measure application " + mStats.packageName 12246 + " external storage"); 12247 } 12248 } 12249 12250 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12251 throws RemoteException { 12252 long result = 0; 12253 for (File path : paths) { 12254 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12255 } 12256 return result; 12257 } 12258 12259 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12260 for (File path : paths) { 12261 try { 12262 mcs.clearDirectory(path.getAbsolutePath()); 12263 } catch (RemoteException e) { 12264 } 12265 } 12266 } 12267 12268 static class OriginInfo { 12269 /** 12270 * Location where install is coming from, before it has been 12271 * copied/renamed into place. This could be a single monolithic APK 12272 * file, or a cluster directory. This location may be untrusted. 12273 */ 12274 final File file; 12275 final String cid; 12276 12277 /** 12278 * Flag indicating that {@link #file} or {@link #cid} has already been 12279 * staged, meaning downstream users don't need to defensively copy the 12280 * contents. 12281 */ 12282 final boolean staged; 12283 12284 /** 12285 * Flag indicating that {@link #file} or {@link #cid} is an already 12286 * installed app that is being moved. 12287 */ 12288 final boolean existing; 12289 12290 final String resolvedPath; 12291 final File resolvedFile; 12292 12293 static OriginInfo fromNothing() { 12294 return new OriginInfo(null, null, false, false); 12295 } 12296 12297 static OriginInfo fromUntrustedFile(File file) { 12298 return new OriginInfo(file, null, false, false); 12299 } 12300 12301 static OriginInfo fromExistingFile(File file) { 12302 return new OriginInfo(file, null, false, true); 12303 } 12304 12305 static OriginInfo fromStagedFile(File file) { 12306 return new OriginInfo(file, null, true, false); 12307 } 12308 12309 static OriginInfo fromStagedContainer(String cid) { 12310 return new OriginInfo(null, cid, true, false); 12311 } 12312 12313 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12314 this.file = file; 12315 this.cid = cid; 12316 this.staged = staged; 12317 this.existing = existing; 12318 12319 if (cid != null) { 12320 resolvedPath = PackageHelper.getSdDir(cid); 12321 resolvedFile = new File(resolvedPath); 12322 } else if (file != null) { 12323 resolvedPath = file.getAbsolutePath(); 12324 resolvedFile = file; 12325 } else { 12326 resolvedPath = null; 12327 resolvedFile = null; 12328 } 12329 } 12330 } 12331 12332 static class MoveInfo { 12333 final int moveId; 12334 final String fromUuid; 12335 final String toUuid; 12336 final String packageName; 12337 final String dataAppName; 12338 final int appId; 12339 final String seinfo; 12340 final int targetSdkVersion; 12341 12342 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12343 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12344 this.moveId = moveId; 12345 this.fromUuid = fromUuid; 12346 this.toUuid = toUuid; 12347 this.packageName = packageName; 12348 this.dataAppName = dataAppName; 12349 this.appId = appId; 12350 this.seinfo = seinfo; 12351 this.targetSdkVersion = targetSdkVersion; 12352 } 12353 } 12354 12355 static class VerificationInfo { 12356 /** A constant used to indicate that a uid value is not present. */ 12357 public static final int NO_UID = -1; 12358 12359 /** URI referencing where the package was downloaded from. */ 12360 final Uri originatingUri; 12361 12362 /** HTTP referrer URI associated with the originatingURI. */ 12363 final Uri referrer; 12364 12365 /** UID of the application that the install request originated from. */ 12366 final int originatingUid; 12367 12368 /** UID of application requesting the install */ 12369 final int installerUid; 12370 12371 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12372 this.originatingUri = originatingUri; 12373 this.referrer = referrer; 12374 this.originatingUid = originatingUid; 12375 this.installerUid = installerUid; 12376 } 12377 } 12378 12379 class InstallParams extends HandlerParams { 12380 final OriginInfo origin; 12381 final MoveInfo move; 12382 final IPackageInstallObserver2 observer; 12383 int installFlags; 12384 final String installerPackageName; 12385 final String volumeUuid; 12386 private InstallArgs mArgs; 12387 private int mRet; 12388 final String packageAbiOverride; 12389 final String[] grantedRuntimePermissions; 12390 final VerificationInfo verificationInfo; 12391 final Certificate[][] certificates; 12392 12393 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12394 int installFlags, String installerPackageName, String volumeUuid, 12395 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12396 String[] grantedPermissions, Certificate[][] certificates) { 12397 super(user); 12398 this.origin = origin; 12399 this.move = move; 12400 this.observer = observer; 12401 this.installFlags = installFlags; 12402 this.installerPackageName = installerPackageName; 12403 this.volumeUuid = volumeUuid; 12404 this.verificationInfo = verificationInfo; 12405 this.packageAbiOverride = packageAbiOverride; 12406 this.grantedRuntimePermissions = grantedPermissions; 12407 this.certificates = certificates; 12408 } 12409 12410 @Override 12411 public String toString() { 12412 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12413 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12414 } 12415 12416 private int installLocationPolicy(PackageInfoLite pkgLite) { 12417 String packageName = pkgLite.packageName; 12418 int installLocation = pkgLite.installLocation; 12419 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12420 // reader 12421 synchronized (mPackages) { 12422 // Currently installed package which the new package is attempting to replace or 12423 // null if no such package is installed. 12424 PackageParser.Package installedPkg = mPackages.get(packageName); 12425 // Package which currently owns the data which the new package will own if installed. 12426 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12427 // will be null whereas dataOwnerPkg will contain information about the package 12428 // which was uninstalled while keeping its data. 12429 PackageParser.Package dataOwnerPkg = installedPkg; 12430 if (dataOwnerPkg == null) { 12431 PackageSetting ps = mSettings.mPackages.get(packageName); 12432 if (ps != null) { 12433 dataOwnerPkg = ps.pkg; 12434 } 12435 } 12436 12437 if (dataOwnerPkg != null) { 12438 // If installed, the package will get access to data left on the device by its 12439 // predecessor. As a security measure, this is permited only if this is not a 12440 // version downgrade or if the predecessor package is marked as debuggable and 12441 // a downgrade is explicitly requested. 12442 // 12443 // On debuggable platform builds, downgrades are permitted even for 12444 // non-debuggable packages to make testing easier. Debuggable platform builds do 12445 // not offer security guarantees and thus it's OK to disable some security 12446 // mechanisms to make debugging/testing easier on those builds. However, even on 12447 // debuggable builds downgrades of packages are permitted only if requested via 12448 // installFlags. This is because we aim to keep the behavior of debuggable 12449 // platform builds as close as possible to the behavior of non-debuggable 12450 // platform builds. 12451 final boolean downgradeRequested = 12452 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12453 final boolean packageDebuggable = 12454 (dataOwnerPkg.applicationInfo.flags 12455 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12456 final boolean downgradePermitted = 12457 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12458 if (!downgradePermitted) { 12459 try { 12460 checkDowngrade(dataOwnerPkg, pkgLite); 12461 } catch (PackageManagerException e) { 12462 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12463 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12464 } 12465 } 12466 } 12467 12468 if (installedPkg != null) { 12469 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12470 // Check for updated system application. 12471 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12472 if (onSd) { 12473 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12474 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12475 } 12476 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12477 } else { 12478 if (onSd) { 12479 // Install flag overrides everything. 12480 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12481 } 12482 // If current upgrade specifies particular preference 12483 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12484 // Application explicitly specified internal. 12485 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12486 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12487 // App explictly prefers external. Let policy decide 12488 } else { 12489 // Prefer previous location 12490 if (isExternal(installedPkg)) { 12491 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12492 } 12493 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12494 } 12495 } 12496 } else { 12497 // Invalid install. Return error code 12498 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12499 } 12500 } 12501 } 12502 // All the special cases have been taken care of. 12503 // Return result based on recommended install location. 12504 if (onSd) { 12505 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12506 } 12507 return pkgLite.recommendedInstallLocation; 12508 } 12509 12510 /* 12511 * Invoke remote method to get package information and install 12512 * location values. Override install location based on default 12513 * policy if needed and then create install arguments based 12514 * on the install location. 12515 */ 12516 public void handleStartCopy() throws RemoteException { 12517 int ret = PackageManager.INSTALL_SUCCEEDED; 12518 12519 // If we're already staged, we've firmly committed to an install location 12520 if (origin.staged) { 12521 if (origin.file != null) { 12522 installFlags |= PackageManager.INSTALL_INTERNAL; 12523 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12524 } else if (origin.cid != null) { 12525 installFlags |= PackageManager.INSTALL_EXTERNAL; 12526 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12527 } else { 12528 throw new IllegalStateException("Invalid stage location"); 12529 } 12530 } 12531 12532 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12533 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12534 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12535 PackageInfoLite pkgLite = null; 12536 12537 if (onInt && onSd) { 12538 // Check if both bits are set. 12539 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12540 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12541 } else if (onSd && ephemeral) { 12542 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12543 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12544 } else { 12545 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12546 packageAbiOverride); 12547 12548 if (DEBUG_EPHEMERAL && ephemeral) { 12549 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12550 } 12551 12552 /* 12553 * If we have too little free space, try to free cache 12554 * before giving up. 12555 */ 12556 if (!origin.staged && pkgLite.recommendedInstallLocation 12557 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12558 // TODO: focus freeing disk space on the target device 12559 final StorageManager storage = StorageManager.from(mContext); 12560 final long lowThreshold = storage.getStorageLowBytes( 12561 Environment.getDataDirectory()); 12562 12563 final long sizeBytes = mContainerService.calculateInstalledSize( 12564 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12565 12566 try { 12567 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12568 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12569 installFlags, packageAbiOverride); 12570 } catch (InstallerException e) { 12571 Slog.w(TAG, "Failed to free cache", e); 12572 } 12573 12574 /* 12575 * The cache free must have deleted the file we 12576 * downloaded to install. 12577 * 12578 * TODO: fix the "freeCache" call to not delete 12579 * the file we care about. 12580 */ 12581 if (pkgLite.recommendedInstallLocation 12582 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12583 pkgLite.recommendedInstallLocation 12584 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12585 } 12586 } 12587 } 12588 12589 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12590 int loc = pkgLite.recommendedInstallLocation; 12591 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12592 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12593 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12594 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12595 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12596 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12597 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12598 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12599 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12600 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12601 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12602 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12603 } else { 12604 // Override with defaults if needed. 12605 loc = installLocationPolicy(pkgLite); 12606 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12607 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12608 } else if (!onSd && !onInt) { 12609 // Override install location with flags 12610 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12611 // Set the flag to install on external media. 12612 installFlags |= PackageManager.INSTALL_EXTERNAL; 12613 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12614 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12615 if (DEBUG_EPHEMERAL) { 12616 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12617 } 12618 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12619 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12620 |PackageManager.INSTALL_INTERNAL); 12621 } else { 12622 // Make sure the flag for installing on external 12623 // media is unset 12624 installFlags |= PackageManager.INSTALL_INTERNAL; 12625 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12626 } 12627 } 12628 } 12629 } 12630 12631 final InstallArgs args = createInstallArgs(this); 12632 mArgs = args; 12633 12634 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12635 // TODO: http://b/22976637 12636 // Apps installed for "all" users use the device owner to verify the app 12637 UserHandle verifierUser = getUser(); 12638 if (verifierUser == UserHandle.ALL) { 12639 verifierUser = UserHandle.SYSTEM; 12640 } 12641 12642 /* 12643 * Determine if we have any installed package verifiers. If we 12644 * do, then we'll defer to them to verify the packages. 12645 */ 12646 final int requiredUid = mRequiredVerifierPackage == null ? -1 12647 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12648 verifierUser.getIdentifier()); 12649 if (!origin.existing && requiredUid != -1 12650 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12651 final Intent verification = new Intent( 12652 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12653 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12654 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12655 PACKAGE_MIME_TYPE); 12656 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12657 12658 // Query all live verifiers based on current user state 12659 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12660 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12661 12662 if (DEBUG_VERIFY) { 12663 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12664 + verification.toString() + " with " + pkgLite.verifiers.length 12665 + " optional verifiers"); 12666 } 12667 12668 final int verificationId = mPendingVerificationToken++; 12669 12670 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12671 12672 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12673 installerPackageName); 12674 12675 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12676 installFlags); 12677 12678 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12679 pkgLite.packageName); 12680 12681 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12682 pkgLite.versionCode); 12683 12684 if (verificationInfo != null) { 12685 if (verificationInfo.originatingUri != null) { 12686 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12687 verificationInfo.originatingUri); 12688 } 12689 if (verificationInfo.referrer != null) { 12690 verification.putExtra(Intent.EXTRA_REFERRER, 12691 verificationInfo.referrer); 12692 } 12693 if (verificationInfo.originatingUid >= 0) { 12694 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12695 verificationInfo.originatingUid); 12696 } 12697 if (verificationInfo.installerUid >= 0) { 12698 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12699 verificationInfo.installerUid); 12700 } 12701 } 12702 12703 final PackageVerificationState verificationState = new PackageVerificationState( 12704 requiredUid, args); 12705 12706 mPendingVerification.append(verificationId, verificationState); 12707 12708 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12709 receivers, verificationState); 12710 12711 /* 12712 * If any sufficient verifiers were listed in the package 12713 * manifest, attempt to ask them. 12714 */ 12715 if (sufficientVerifiers != null) { 12716 final int N = sufficientVerifiers.size(); 12717 if (N == 0) { 12718 Slog.i(TAG, "Additional verifiers required, but none installed."); 12719 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12720 } else { 12721 for (int i = 0; i < N; i++) { 12722 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12723 12724 final Intent sufficientIntent = new Intent(verification); 12725 sufficientIntent.setComponent(verifierComponent); 12726 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12727 } 12728 } 12729 } 12730 12731 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12732 mRequiredVerifierPackage, receivers); 12733 if (ret == PackageManager.INSTALL_SUCCEEDED 12734 && mRequiredVerifierPackage != null) { 12735 Trace.asyncTraceBegin( 12736 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12737 /* 12738 * Send the intent to the required verification agent, 12739 * but only start the verification timeout after the 12740 * target BroadcastReceivers have run. 12741 */ 12742 verification.setComponent(requiredVerifierComponent); 12743 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12744 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12745 new BroadcastReceiver() { 12746 @Override 12747 public void onReceive(Context context, Intent intent) { 12748 final Message msg = mHandler 12749 .obtainMessage(CHECK_PENDING_VERIFICATION); 12750 msg.arg1 = verificationId; 12751 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12752 } 12753 }, null, 0, null, null); 12754 12755 /* 12756 * We don't want the copy to proceed until verification 12757 * succeeds, so null out this field. 12758 */ 12759 mArgs = null; 12760 } 12761 } else { 12762 /* 12763 * No package verification is enabled, so immediately start 12764 * the remote call to initiate copy using temporary file. 12765 */ 12766 ret = args.copyApk(mContainerService, true); 12767 } 12768 } 12769 12770 mRet = ret; 12771 } 12772 12773 @Override 12774 void handleReturnCode() { 12775 // If mArgs is null, then MCS couldn't be reached. When it 12776 // reconnects, it will try again to install. At that point, this 12777 // will succeed. 12778 if (mArgs != null) { 12779 processPendingInstall(mArgs, mRet); 12780 } 12781 } 12782 12783 @Override 12784 void handleServiceError() { 12785 mArgs = createInstallArgs(this); 12786 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12787 } 12788 12789 public boolean isForwardLocked() { 12790 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12791 } 12792 } 12793 12794 /** 12795 * Used during creation of InstallArgs 12796 * 12797 * @param installFlags package installation flags 12798 * @return true if should be installed on external storage 12799 */ 12800 private static boolean installOnExternalAsec(int installFlags) { 12801 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12802 return false; 12803 } 12804 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12805 return true; 12806 } 12807 return false; 12808 } 12809 12810 /** 12811 * Used during creation of InstallArgs 12812 * 12813 * @param installFlags package installation flags 12814 * @return true if should be installed as forward locked 12815 */ 12816 private static boolean installForwardLocked(int installFlags) { 12817 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12818 } 12819 12820 private InstallArgs createInstallArgs(InstallParams params) { 12821 if (params.move != null) { 12822 return new MoveInstallArgs(params); 12823 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12824 return new AsecInstallArgs(params); 12825 } else { 12826 return new FileInstallArgs(params); 12827 } 12828 } 12829 12830 /** 12831 * Create args that describe an existing installed package. Typically used 12832 * when cleaning up old installs, or used as a move source. 12833 */ 12834 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12835 String resourcePath, String[] instructionSets) { 12836 final boolean isInAsec; 12837 if (installOnExternalAsec(installFlags)) { 12838 /* Apps on SD card are always in ASEC containers. */ 12839 isInAsec = true; 12840 } else if (installForwardLocked(installFlags) 12841 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12842 /* 12843 * Forward-locked apps are only in ASEC containers if they're the 12844 * new style 12845 */ 12846 isInAsec = true; 12847 } else { 12848 isInAsec = false; 12849 } 12850 12851 if (isInAsec) { 12852 return new AsecInstallArgs(codePath, instructionSets, 12853 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12854 } else { 12855 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12856 } 12857 } 12858 12859 static abstract class InstallArgs { 12860 /** @see InstallParams#origin */ 12861 final OriginInfo origin; 12862 /** @see InstallParams#move */ 12863 final MoveInfo move; 12864 12865 final IPackageInstallObserver2 observer; 12866 // Always refers to PackageManager flags only 12867 final int installFlags; 12868 final String installerPackageName; 12869 final String volumeUuid; 12870 final UserHandle user; 12871 final String abiOverride; 12872 final String[] installGrantPermissions; 12873 /** If non-null, drop an async trace when the install completes */ 12874 final String traceMethod; 12875 final int traceCookie; 12876 final Certificate[][] certificates; 12877 12878 // The list of instruction sets supported by this app. This is currently 12879 // only used during the rmdex() phase to clean up resources. We can get rid of this 12880 // if we move dex files under the common app path. 12881 /* nullable */ String[] instructionSets; 12882 12883 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12884 int installFlags, String installerPackageName, String volumeUuid, 12885 UserHandle user, String[] instructionSets, 12886 String abiOverride, String[] installGrantPermissions, 12887 String traceMethod, int traceCookie, Certificate[][] certificates) { 12888 this.origin = origin; 12889 this.move = move; 12890 this.installFlags = installFlags; 12891 this.observer = observer; 12892 this.installerPackageName = installerPackageName; 12893 this.volumeUuid = volumeUuid; 12894 this.user = user; 12895 this.instructionSets = instructionSets; 12896 this.abiOverride = abiOverride; 12897 this.installGrantPermissions = installGrantPermissions; 12898 this.traceMethod = traceMethod; 12899 this.traceCookie = traceCookie; 12900 this.certificates = certificates; 12901 } 12902 12903 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12904 abstract int doPreInstall(int status); 12905 12906 /** 12907 * Rename package into final resting place. All paths on the given 12908 * scanned package should be updated to reflect the rename. 12909 */ 12910 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12911 abstract int doPostInstall(int status, int uid); 12912 12913 /** @see PackageSettingBase#codePathString */ 12914 abstract String getCodePath(); 12915 /** @see PackageSettingBase#resourcePathString */ 12916 abstract String getResourcePath(); 12917 12918 // Need installer lock especially for dex file removal. 12919 abstract void cleanUpResourcesLI(); 12920 abstract boolean doPostDeleteLI(boolean delete); 12921 12922 /** 12923 * Called before the source arguments are copied. This is used mostly 12924 * for MoveParams when it needs to read the source file to put it in the 12925 * destination. 12926 */ 12927 int doPreCopy() { 12928 return PackageManager.INSTALL_SUCCEEDED; 12929 } 12930 12931 /** 12932 * Called after the source arguments are copied. This is used mostly for 12933 * MoveParams when it needs to read the source file to put it in the 12934 * destination. 12935 */ 12936 int doPostCopy(int uid) { 12937 return PackageManager.INSTALL_SUCCEEDED; 12938 } 12939 12940 protected boolean isFwdLocked() { 12941 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12942 } 12943 12944 protected boolean isExternalAsec() { 12945 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12946 } 12947 12948 protected boolean isEphemeral() { 12949 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12950 } 12951 12952 UserHandle getUser() { 12953 return user; 12954 } 12955 } 12956 12957 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12958 if (!allCodePaths.isEmpty()) { 12959 if (instructionSets == null) { 12960 throw new IllegalStateException("instructionSet == null"); 12961 } 12962 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12963 for (String codePath : allCodePaths) { 12964 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12965 try { 12966 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12967 } catch (InstallerException ignored) { 12968 } 12969 } 12970 } 12971 } 12972 } 12973 12974 /** 12975 * Logic to handle installation of non-ASEC applications, including copying 12976 * and renaming logic. 12977 */ 12978 class FileInstallArgs extends InstallArgs { 12979 private File codeFile; 12980 private File resourceFile; 12981 12982 // Example topology: 12983 // /data/app/com.example/base.apk 12984 // /data/app/com.example/split_foo.apk 12985 // /data/app/com.example/lib/arm/libfoo.so 12986 // /data/app/com.example/lib/arm64/libfoo.so 12987 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12988 12989 /** New install */ 12990 FileInstallArgs(InstallParams params) { 12991 super(params.origin, params.move, params.observer, params.installFlags, 12992 params.installerPackageName, params.volumeUuid, 12993 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12994 params.grantedRuntimePermissions, 12995 params.traceMethod, params.traceCookie, params.certificates); 12996 if (isFwdLocked()) { 12997 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12998 } 12999 } 13000 13001 /** Existing install */ 13002 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13003 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13004 null, null, null, 0, null /*certificates*/); 13005 this.codeFile = (codePath != null) ? new File(codePath) : null; 13006 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13007 } 13008 13009 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13010 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13011 try { 13012 return doCopyApk(imcs, temp); 13013 } finally { 13014 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13015 } 13016 } 13017 13018 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13019 if (origin.staged) { 13020 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13021 codeFile = origin.file; 13022 resourceFile = origin.file; 13023 return PackageManager.INSTALL_SUCCEEDED; 13024 } 13025 13026 try { 13027 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13028 final File tempDir = 13029 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13030 codeFile = tempDir; 13031 resourceFile = tempDir; 13032 } catch (IOException e) { 13033 Slog.w(TAG, "Failed to create copy file: " + e); 13034 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13035 } 13036 13037 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13038 @Override 13039 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13040 if (!FileUtils.isValidExtFilename(name)) { 13041 throw new IllegalArgumentException("Invalid filename: " + name); 13042 } 13043 try { 13044 final File file = new File(codeFile, name); 13045 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13046 O_RDWR | O_CREAT, 0644); 13047 Os.chmod(file.getAbsolutePath(), 0644); 13048 return new ParcelFileDescriptor(fd); 13049 } catch (ErrnoException e) { 13050 throw new RemoteException("Failed to open: " + e.getMessage()); 13051 } 13052 } 13053 }; 13054 13055 int ret = PackageManager.INSTALL_SUCCEEDED; 13056 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13057 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13058 Slog.e(TAG, "Failed to copy package"); 13059 return ret; 13060 } 13061 13062 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13063 NativeLibraryHelper.Handle handle = null; 13064 try { 13065 handle = NativeLibraryHelper.Handle.create(codeFile); 13066 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13067 abiOverride); 13068 } catch (IOException e) { 13069 Slog.e(TAG, "Copying native libraries failed", e); 13070 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13071 } finally { 13072 IoUtils.closeQuietly(handle); 13073 } 13074 13075 return ret; 13076 } 13077 13078 int doPreInstall(int status) { 13079 if (status != PackageManager.INSTALL_SUCCEEDED) { 13080 cleanUp(); 13081 } 13082 return status; 13083 } 13084 13085 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13086 if (status != PackageManager.INSTALL_SUCCEEDED) { 13087 cleanUp(); 13088 return false; 13089 } 13090 13091 final File targetDir = codeFile.getParentFile(); 13092 final File beforeCodeFile = codeFile; 13093 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13094 13095 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13096 try { 13097 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13098 } catch (ErrnoException e) { 13099 Slog.w(TAG, "Failed to rename", e); 13100 return false; 13101 } 13102 13103 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13104 Slog.w(TAG, "Failed to restorecon"); 13105 return false; 13106 } 13107 13108 // Reflect the rename internally 13109 codeFile = afterCodeFile; 13110 resourceFile = afterCodeFile; 13111 13112 // Reflect the rename in scanned details 13113 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13114 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13115 afterCodeFile, pkg.baseCodePath)); 13116 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13117 afterCodeFile, pkg.splitCodePaths)); 13118 13119 // Reflect the rename in app info 13120 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13121 pkg.setApplicationInfoCodePath(pkg.codePath); 13122 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13123 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13124 pkg.setApplicationInfoResourcePath(pkg.codePath); 13125 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13126 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13127 13128 return true; 13129 } 13130 13131 int doPostInstall(int status, int uid) { 13132 if (status != PackageManager.INSTALL_SUCCEEDED) { 13133 cleanUp(); 13134 } 13135 return status; 13136 } 13137 13138 @Override 13139 String getCodePath() { 13140 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13141 } 13142 13143 @Override 13144 String getResourcePath() { 13145 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13146 } 13147 13148 private boolean cleanUp() { 13149 if (codeFile == null || !codeFile.exists()) { 13150 return false; 13151 } 13152 13153 removeCodePathLI(codeFile); 13154 13155 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13156 resourceFile.delete(); 13157 } 13158 13159 return true; 13160 } 13161 13162 void cleanUpResourcesLI() { 13163 // Try enumerating all code paths before deleting 13164 List<String> allCodePaths = Collections.EMPTY_LIST; 13165 if (codeFile != null && codeFile.exists()) { 13166 try { 13167 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13168 allCodePaths = pkg.getAllCodePaths(); 13169 } catch (PackageParserException e) { 13170 // Ignored; we tried our best 13171 } 13172 } 13173 13174 cleanUp(); 13175 removeDexFiles(allCodePaths, instructionSets); 13176 } 13177 13178 boolean doPostDeleteLI(boolean delete) { 13179 // XXX err, shouldn't we respect the delete flag? 13180 cleanUpResourcesLI(); 13181 return true; 13182 } 13183 } 13184 13185 private boolean isAsecExternal(String cid) { 13186 final String asecPath = PackageHelper.getSdFilesystem(cid); 13187 return !asecPath.startsWith(mAsecInternalPath); 13188 } 13189 13190 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13191 PackageManagerException { 13192 if (copyRet < 0) { 13193 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13194 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13195 throw new PackageManagerException(copyRet, message); 13196 } 13197 } 13198 } 13199 13200 /** 13201 * Extract the MountService "container ID" from the full code path of an 13202 * .apk. 13203 */ 13204 static String cidFromCodePath(String fullCodePath) { 13205 int eidx = fullCodePath.lastIndexOf("/"); 13206 String subStr1 = fullCodePath.substring(0, eidx); 13207 int sidx = subStr1.lastIndexOf("/"); 13208 return subStr1.substring(sidx+1, eidx); 13209 } 13210 13211 /** 13212 * Logic to handle installation of ASEC applications, including copying and 13213 * renaming logic. 13214 */ 13215 class AsecInstallArgs extends InstallArgs { 13216 static final String RES_FILE_NAME = "pkg.apk"; 13217 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13218 13219 String cid; 13220 String packagePath; 13221 String resourcePath; 13222 13223 /** New install */ 13224 AsecInstallArgs(InstallParams params) { 13225 super(params.origin, params.move, params.observer, params.installFlags, 13226 params.installerPackageName, params.volumeUuid, 13227 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13228 params.grantedRuntimePermissions, 13229 params.traceMethod, params.traceCookie, params.certificates); 13230 } 13231 13232 /** Existing install */ 13233 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13234 boolean isExternal, boolean isForwardLocked) { 13235 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13236 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13237 instructionSets, null, null, null, 0, null /*certificates*/); 13238 // Hackily pretend we're still looking at a full code path 13239 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13240 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13241 } 13242 13243 // Extract cid from fullCodePath 13244 int eidx = fullCodePath.lastIndexOf("/"); 13245 String subStr1 = fullCodePath.substring(0, eidx); 13246 int sidx = subStr1.lastIndexOf("/"); 13247 cid = subStr1.substring(sidx+1, eidx); 13248 setMountPath(subStr1); 13249 } 13250 13251 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13252 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13253 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13254 instructionSets, null, null, null, 0, null /*certificates*/); 13255 this.cid = cid; 13256 setMountPath(PackageHelper.getSdDir(cid)); 13257 } 13258 13259 void createCopyFile() { 13260 cid = mInstallerService.allocateExternalStageCidLegacy(); 13261 } 13262 13263 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13264 if (origin.staged && origin.cid != null) { 13265 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13266 cid = origin.cid; 13267 setMountPath(PackageHelper.getSdDir(cid)); 13268 return PackageManager.INSTALL_SUCCEEDED; 13269 } 13270 13271 if (temp) { 13272 createCopyFile(); 13273 } else { 13274 /* 13275 * Pre-emptively destroy the container since it's destroyed if 13276 * copying fails due to it existing anyway. 13277 */ 13278 PackageHelper.destroySdDir(cid); 13279 } 13280 13281 final String newMountPath = imcs.copyPackageToContainer( 13282 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13283 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13284 13285 if (newMountPath != null) { 13286 setMountPath(newMountPath); 13287 return PackageManager.INSTALL_SUCCEEDED; 13288 } else { 13289 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13290 } 13291 } 13292 13293 @Override 13294 String getCodePath() { 13295 return packagePath; 13296 } 13297 13298 @Override 13299 String getResourcePath() { 13300 return resourcePath; 13301 } 13302 13303 int doPreInstall(int status) { 13304 if (status != PackageManager.INSTALL_SUCCEEDED) { 13305 // Destroy container 13306 PackageHelper.destroySdDir(cid); 13307 } else { 13308 boolean mounted = PackageHelper.isContainerMounted(cid); 13309 if (!mounted) { 13310 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13311 Process.SYSTEM_UID); 13312 if (newMountPath != null) { 13313 setMountPath(newMountPath); 13314 } else { 13315 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13316 } 13317 } 13318 } 13319 return status; 13320 } 13321 13322 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13323 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13324 String newMountPath = null; 13325 if (PackageHelper.isContainerMounted(cid)) { 13326 // Unmount the container 13327 if (!PackageHelper.unMountSdDir(cid)) { 13328 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13329 return false; 13330 } 13331 } 13332 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13333 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13334 " which might be stale. Will try to clean up."); 13335 // Clean up the stale container and proceed to recreate. 13336 if (!PackageHelper.destroySdDir(newCacheId)) { 13337 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13338 return false; 13339 } 13340 // Successfully cleaned up stale container. Try to rename again. 13341 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13342 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13343 + " inspite of cleaning it up."); 13344 return false; 13345 } 13346 } 13347 if (!PackageHelper.isContainerMounted(newCacheId)) { 13348 Slog.w(TAG, "Mounting container " + newCacheId); 13349 newMountPath = PackageHelper.mountSdDir(newCacheId, 13350 getEncryptKey(), Process.SYSTEM_UID); 13351 } else { 13352 newMountPath = PackageHelper.getSdDir(newCacheId); 13353 } 13354 if (newMountPath == null) { 13355 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13356 return false; 13357 } 13358 Log.i(TAG, "Succesfully renamed " + cid + 13359 " to " + newCacheId + 13360 " at new path: " + newMountPath); 13361 cid = newCacheId; 13362 13363 final File beforeCodeFile = new File(packagePath); 13364 setMountPath(newMountPath); 13365 final File afterCodeFile = new File(packagePath); 13366 13367 // Reflect the rename in scanned details 13368 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13369 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13370 afterCodeFile, pkg.baseCodePath)); 13371 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13372 afterCodeFile, pkg.splitCodePaths)); 13373 13374 // Reflect the rename in app info 13375 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13376 pkg.setApplicationInfoCodePath(pkg.codePath); 13377 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13378 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13379 pkg.setApplicationInfoResourcePath(pkg.codePath); 13380 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13381 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13382 13383 return true; 13384 } 13385 13386 private void setMountPath(String mountPath) { 13387 final File mountFile = new File(mountPath); 13388 13389 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13390 if (monolithicFile.exists()) { 13391 packagePath = monolithicFile.getAbsolutePath(); 13392 if (isFwdLocked()) { 13393 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13394 } else { 13395 resourcePath = packagePath; 13396 } 13397 } else { 13398 packagePath = mountFile.getAbsolutePath(); 13399 resourcePath = packagePath; 13400 } 13401 } 13402 13403 int doPostInstall(int status, int uid) { 13404 if (status != PackageManager.INSTALL_SUCCEEDED) { 13405 cleanUp(); 13406 } else { 13407 final int groupOwner; 13408 final String protectedFile; 13409 if (isFwdLocked()) { 13410 groupOwner = UserHandle.getSharedAppGid(uid); 13411 protectedFile = RES_FILE_NAME; 13412 } else { 13413 groupOwner = -1; 13414 protectedFile = null; 13415 } 13416 13417 if (uid < Process.FIRST_APPLICATION_UID 13418 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13419 Slog.e(TAG, "Failed to finalize " + cid); 13420 PackageHelper.destroySdDir(cid); 13421 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13422 } 13423 13424 boolean mounted = PackageHelper.isContainerMounted(cid); 13425 if (!mounted) { 13426 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13427 } 13428 } 13429 return status; 13430 } 13431 13432 private void cleanUp() { 13433 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13434 13435 // Destroy secure container 13436 PackageHelper.destroySdDir(cid); 13437 } 13438 13439 private List<String> getAllCodePaths() { 13440 final File codeFile = new File(getCodePath()); 13441 if (codeFile != null && codeFile.exists()) { 13442 try { 13443 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13444 return pkg.getAllCodePaths(); 13445 } catch (PackageParserException e) { 13446 // Ignored; we tried our best 13447 } 13448 } 13449 return Collections.EMPTY_LIST; 13450 } 13451 13452 void cleanUpResourcesLI() { 13453 // Enumerate all code paths before deleting 13454 cleanUpResourcesLI(getAllCodePaths()); 13455 } 13456 13457 private void cleanUpResourcesLI(List<String> allCodePaths) { 13458 cleanUp(); 13459 removeDexFiles(allCodePaths, instructionSets); 13460 } 13461 13462 String getPackageName() { 13463 return getAsecPackageName(cid); 13464 } 13465 13466 boolean doPostDeleteLI(boolean delete) { 13467 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13468 final List<String> allCodePaths = getAllCodePaths(); 13469 boolean mounted = PackageHelper.isContainerMounted(cid); 13470 if (mounted) { 13471 // Unmount first 13472 if (PackageHelper.unMountSdDir(cid)) { 13473 mounted = false; 13474 } 13475 } 13476 if (!mounted && delete) { 13477 cleanUpResourcesLI(allCodePaths); 13478 } 13479 return !mounted; 13480 } 13481 13482 @Override 13483 int doPreCopy() { 13484 if (isFwdLocked()) { 13485 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13486 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13487 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13488 } 13489 } 13490 13491 return PackageManager.INSTALL_SUCCEEDED; 13492 } 13493 13494 @Override 13495 int doPostCopy(int uid) { 13496 if (isFwdLocked()) { 13497 if (uid < Process.FIRST_APPLICATION_UID 13498 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13499 RES_FILE_NAME)) { 13500 Slog.e(TAG, "Failed to finalize " + cid); 13501 PackageHelper.destroySdDir(cid); 13502 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13503 } 13504 } 13505 13506 return PackageManager.INSTALL_SUCCEEDED; 13507 } 13508 } 13509 13510 /** 13511 * Logic to handle movement of existing installed applications. 13512 */ 13513 class MoveInstallArgs extends InstallArgs { 13514 private File codeFile; 13515 private File resourceFile; 13516 13517 /** New install */ 13518 MoveInstallArgs(InstallParams params) { 13519 super(params.origin, params.move, params.observer, params.installFlags, 13520 params.installerPackageName, params.volumeUuid, 13521 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13522 params.grantedRuntimePermissions, 13523 params.traceMethod, params.traceCookie, params.certificates); 13524 } 13525 13526 int copyApk(IMediaContainerService imcs, boolean temp) { 13527 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13528 + move.fromUuid + " to " + move.toUuid); 13529 synchronized (mInstaller) { 13530 try { 13531 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13532 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13533 } catch (InstallerException e) { 13534 Slog.w(TAG, "Failed to move app", e); 13535 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13536 } 13537 } 13538 13539 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13540 resourceFile = codeFile; 13541 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13542 13543 return PackageManager.INSTALL_SUCCEEDED; 13544 } 13545 13546 int doPreInstall(int status) { 13547 if (status != PackageManager.INSTALL_SUCCEEDED) { 13548 cleanUp(move.toUuid); 13549 } 13550 return status; 13551 } 13552 13553 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13554 if (status != PackageManager.INSTALL_SUCCEEDED) { 13555 cleanUp(move.toUuid); 13556 return false; 13557 } 13558 13559 // Reflect the move in app info 13560 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13561 pkg.setApplicationInfoCodePath(pkg.codePath); 13562 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13563 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13564 pkg.setApplicationInfoResourcePath(pkg.codePath); 13565 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13566 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13567 13568 return true; 13569 } 13570 13571 int doPostInstall(int status, int uid) { 13572 if (status == PackageManager.INSTALL_SUCCEEDED) { 13573 cleanUp(move.fromUuid); 13574 } else { 13575 cleanUp(move.toUuid); 13576 } 13577 return status; 13578 } 13579 13580 @Override 13581 String getCodePath() { 13582 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13583 } 13584 13585 @Override 13586 String getResourcePath() { 13587 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13588 } 13589 13590 private boolean cleanUp(String volumeUuid) { 13591 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13592 move.dataAppName); 13593 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13594 final int[] userIds = sUserManager.getUserIds(); 13595 synchronized (mInstallLock) { 13596 // Clean up both app data and code 13597 // All package moves are frozen until finished 13598 for (int userId : userIds) { 13599 try { 13600 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13601 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13602 } catch (InstallerException e) { 13603 Slog.w(TAG, String.valueOf(e)); 13604 } 13605 } 13606 removeCodePathLI(codeFile); 13607 } 13608 return true; 13609 } 13610 13611 void cleanUpResourcesLI() { 13612 throw new UnsupportedOperationException(); 13613 } 13614 13615 boolean doPostDeleteLI(boolean delete) { 13616 throw new UnsupportedOperationException(); 13617 } 13618 } 13619 13620 static String getAsecPackageName(String packageCid) { 13621 int idx = packageCid.lastIndexOf("-"); 13622 if (idx == -1) { 13623 return packageCid; 13624 } 13625 return packageCid.substring(0, idx); 13626 } 13627 13628 // Utility method used to create code paths based on package name and available index. 13629 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13630 String idxStr = ""; 13631 int idx = 1; 13632 // Fall back to default value of idx=1 if prefix is not 13633 // part of oldCodePath 13634 if (oldCodePath != null) { 13635 String subStr = oldCodePath; 13636 // Drop the suffix right away 13637 if (suffix != null && subStr.endsWith(suffix)) { 13638 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13639 } 13640 // If oldCodePath already contains prefix find out the 13641 // ending index to either increment or decrement. 13642 int sidx = subStr.lastIndexOf(prefix); 13643 if (sidx != -1) { 13644 subStr = subStr.substring(sidx + prefix.length()); 13645 if (subStr != null) { 13646 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13647 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13648 } 13649 try { 13650 idx = Integer.parseInt(subStr); 13651 if (idx <= 1) { 13652 idx++; 13653 } else { 13654 idx--; 13655 } 13656 } catch(NumberFormatException e) { 13657 } 13658 } 13659 } 13660 } 13661 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13662 return prefix + idxStr; 13663 } 13664 13665 private File getNextCodePath(File targetDir, String packageName) { 13666 int suffix = 1; 13667 File result; 13668 do { 13669 result = new File(targetDir, packageName + "-" + suffix); 13670 suffix++; 13671 } while (result.exists()); 13672 return result; 13673 } 13674 13675 // Utility method that returns the relative package path with respect 13676 // to the installation directory. Like say for /data/data/com.test-1.apk 13677 // string com.test-1 is returned. 13678 static String deriveCodePathName(String codePath) { 13679 if (codePath == null) { 13680 return null; 13681 } 13682 final File codeFile = new File(codePath); 13683 final String name = codeFile.getName(); 13684 if (codeFile.isDirectory()) { 13685 return name; 13686 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13687 final int lastDot = name.lastIndexOf('.'); 13688 return name.substring(0, lastDot); 13689 } else { 13690 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13691 return null; 13692 } 13693 } 13694 13695 static class PackageInstalledInfo { 13696 String name; 13697 int uid; 13698 // The set of users that originally had this package installed. 13699 int[] origUsers; 13700 // The set of users that now have this package installed. 13701 int[] newUsers; 13702 PackageParser.Package pkg; 13703 int returnCode; 13704 String returnMsg; 13705 PackageRemovedInfo removedInfo; 13706 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13707 13708 public void setError(int code, String msg) { 13709 setReturnCode(code); 13710 setReturnMessage(msg); 13711 Slog.w(TAG, msg); 13712 } 13713 13714 public void setError(String msg, PackageParserException e) { 13715 setReturnCode(e.error); 13716 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13717 Slog.w(TAG, msg, e); 13718 } 13719 13720 public void setError(String msg, PackageManagerException e) { 13721 returnCode = e.error; 13722 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13723 Slog.w(TAG, msg, e); 13724 } 13725 13726 public void setReturnCode(int returnCode) { 13727 this.returnCode = returnCode; 13728 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13729 for (int i = 0; i < childCount; i++) { 13730 addedChildPackages.valueAt(i).returnCode = returnCode; 13731 } 13732 } 13733 13734 private void setReturnMessage(String returnMsg) { 13735 this.returnMsg = returnMsg; 13736 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13737 for (int i = 0; i < childCount; i++) { 13738 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13739 } 13740 } 13741 13742 // In some error cases we want to convey more info back to the observer 13743 String origPackage; 13744 String origPermission; 13745 } 13746 13747 /* 13748 * Install a non-existing package. 13749 */ 13750 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13751 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13752 PackageInstalledInfo res) { 13753 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13754 13755 // Remember this for later, in case we need to rollback this install 13756 String pkgName = pkg.packageName; 13757 13758 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13759 13760 synchronized(mPackages) { 13761 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13762 // A package with the same name is already installed, though 13763 // it has been renamed to an older name. The package we 13764 // are trying to install should be installed as an update to 13765 // the existing one, but that has not been requested, so bail. 13766 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13767 + " without first uninstalling package running as " 13768 + mSettings.mRenamedPackages.get(pkgName)); 13769 return; 13770 } 13771 if (mPackages.containsKey(pkgName)) { 13772 // Don't allow installation over an existing package with the same name. 13773 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13774 + " without first uninstalling."); 13775 return; 13776 } 13777 } 13778 13779 try { 13780 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13781 System.currentTimeMillis(), user); 13782 13783 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13784 13785 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13786 prepareAppDataAfterInstallLIF(newPackage); 13787 13788 } else { 13789 // Remove package from internal structures, but keep around any 13790 // data that might have already existed 13791 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13792 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13793 } 13794 } catch (PackageManagerException e) { 13795 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13796 } 13797 13798 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13799 } 13800 13801 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13802 // Can't rotate keys during boot or if sharedUser. 13803 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13804 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13805 return false; 13806 } 13807 // app is using upgradeKeySets; make sure all are valid 13808 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13809 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13810 for (int i = 0; i < upgradeKeySets.length; i++) { 13811 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13812 Slog.wtf(TAG, "Package " 13813 + (oldPs.name != null ? oldPs.name : "<null>") 13814 + " contains upgrade-key-set reference to unknown key-set: " 13815 + upgradeKeySets[i] 13816 + " reverting to signatures check."); 13817 return false; 13818 } 13819 } 13820 return true; 13821 } 13822 13823 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13824 // Upgrade keysets are being used. Determine if new package has a superset of the 13825 // required keys. 13826 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13827 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13828 for (int i = 0; i < upgradeKeySets.length; i++) { 13829 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13830 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13831 return true; 13832 } 13833 } 13834 return false; 13835 } 13836 13837 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13838 try (DigestInputStream digestStream = 13839 new DigestInputStream(new FileInputStream(file), digest)) { 13840 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13841 } 13842 } 13843 13844 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13845 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13846 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13847 13848 final PackageParser.Package oldPackage; 13849 final String pkgName = pkg.packageName; 13850 final int[] allUsers; 13851 final int[] installedUsers; 13852 13853 synchronized(mPackages) { 13854 oldPackage = mPackages.get(pkgName); 13855 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13856 13857 // don't allow upgrade to target a release SDK from a pre-release SDK 13858 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13859 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13860 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13861 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13862 if (oldTargetsPreRelease 13863 && !newTargetsPreRelease 13864 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13865 Slog.w(TAG, "Can't install package targeting released sdk"); 13866 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13867 return; 13868 } 13869 13870 // don't allow an upgrade from full to ephemeral 13871 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13872 if (isEphemeral && !oldIsEphemeral) { 13873 // can't downgrade from full to ephemeral 13874 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13875 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13876 return; 13877 } 13878 13879 // verify signatures are valid 13880 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13881 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13882 if (!checkUpgradeKeySetLP(ps, pkg)) { 13883 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13884 "New package not signed by keys specified by upgrade-keysets: " 13885 + pkgName); 13886 return; 13887 } 13888 } else { 13889 // default to original signature matching 13890 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13891 != PackageManager.SIGNATURE_MATCH) { 13892 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13893 "New package has a different signature: " + pkgName); 13894 return; 13895 } 13896 } 13897 13898 // don't allow a system upgrade unless the upgrade hash matches 13899 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13900 byte[] digestBytes = null; 13901 try { 13902 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13903 updateDigest(digest, new File(pkg.baseCodePath)); 13904 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13905 for (String path : pkg.splitCodePaths) { 13906 updateDigest(digest, new File(path)); 13907 } 13908 } 13909 digestBytes = digest.digest(); 13910 } catch (NoSuchAlgorithmException | IOException e) { 13911 res.setError(INSTALL_FAILED_INVALID_APK, 13912 "Could not compute hash: " + pkgName); 13913 return; 13914 } 13915 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13916 res.setError(INSTALL_FAILED_INVALID_APK, 13917 "New package fails restrict-update check: " + pkgName); 13918 return; 13919 } 13920 // retain upgrade restriction 13921 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13922 } 13923 13924 // Check for shared user id changes 13925 String invalidPackageName = 13926 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13927 if (invalidPackageName != null) { 13928 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13929 "Package " + invalidPackageName + " tried to change user " 13930 + oldPackage.mSharedUserId); 13931 return; 13932 } 13933 13934 // In case of rollback, remember per-user/profile install state 13935 allUsers = sUserManager.getUserIds(); 13936 installedUsers = ps.queryInstalledUsers(allUsers, true); 13937 } 13938 13939 // Update what is removed 13940 res.removedInfo = new PackageRemovedInfo(); 13941 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13942 res.removedInfo.removedPackage = oldPackage.packageName; 13943 res.removedInfo.isUpdate = true; 13944 res.removedInfo.origUsers = installedUsers; 13945 final int childCount = (oldPackage.childPackages != null) 13946 ? oldPackage.childPackages.size() : 0; 13947 for (int i = 0; i < childCount; i++) { 13948 boolean childPackageUpdated = false; 13949 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13950 if (res.addedChildPackages != null) { 13951 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13952 if (childRes != null) { 13953 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13954 childRes.removedInfo.removedPackage = childPkg.packageName; 13955 childRes.removedInfo.isUpdate = true; 13956 childPackageUpdated = true; 13957 } 13958 } 13959 if (!childPackageUpdated) { 13960 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13961 childRemovedRes.removedPackage = childPkg.packageName; 13962 childRemovedRes.isUpdate = false; 13963 childRemovedRes.dataRemoved = true; 13964 synchronized (mPackages) { 13965 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13966 if (childPs != null) { 13967 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13968 } 13969 } 13970 if (res.removedInfo.removedChildPackages == null) { 13971 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13972 } 13973 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13974 } 13975 } 13976 13977 boolean sysPkg = (isSystemApp(oldPackage)); 13978 if (sysPkg) { 13979 // Set the system/privileged flags as needed 13980 final boolean privileged = 13981 (oldPackage.applicationInfo.privateFlags 13982 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13983 final int systemPolicyFlags = policyFlags 13984 | PackageParser.PARSE_IS_SYSTEM 13985 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13986 13987 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13988 user, allUsers, installerPackageName, res); 13989 } else { 13990 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13991 user, allUsers, installerPackageName, res); 13992 } 13993 } 13994 13995 public List<String> getPreviousCodePaths(String packageName) { 13996 final PackageSetting ps = mSettings.mPackages.get(packageName); 13997 final List<String> result = new ArrayList<String>(); 13998 if (ps != null && ps.oldCodePaths != null) { 13999 result.addAll(ps.oldCodePaths); 14000 } 14001 return result; 14002 } 14003 14004 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14005 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14006 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14007 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14008 + deletedPackage); 14009 14010 String pkgName = deletedPackage.packageName; 14011 boolean deletedPkg = true; 14012 boolean addedPkg = false; 14013 boolean updatedSettings = false; 14014 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14015 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14016 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14017 14018 final long origUpdateTime = (pkg.mExtras != null) 14019 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14020 14021 // First delete the existing package while retaining the data directory 14022 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14023 res.removedInfo, true, pkg)) { 14024 // If the existing package wasn't successfully deleted 14025 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14026 deletedPkg = false; 14027 } else { 14028 // Successfully deleted the old package; proceed with replace. 14029 14030 // If deleted package lived in a container, give users a chance to 14031 // relinquish resources before killing. 14032 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14033 if (DEBUG_INSTALL) { 14034 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14035 } 14036 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14037 final ArrayList<String> pkgList = new ArrayList<String>(1); 14038 pkgList.add(deletedPackage.applicationInfo.packageName); 14039 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14040 } 14041 14042 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14043 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14044 clearAppProfilesLIF(pkg); 14045 14046 try { 14047 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14048 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14049 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14050 14051 // Update the in-memory copy of the previous code paths. 14052 PackageSetting ps = mSettings.mPackages.get(pkgName); 14053 if (!killApp) { 14054 if (ps.oldCodePaths == null) { 14055 ps.oldCodePaths = new ArraySet<>(); 14056 } 14057 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14058 if (deletedPackage.splitCodePaths != null) { 14059 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14060 } 14061 } else { 14062 ps.oldCodePaths = null; 14063 } 14064 if (ps.childPackageNames != null) { 14065 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14066 final String childPkgName = ps.childPackageNames.get(i); 14067 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14068 childPs.oldCodePaths = ps.oldCodePaths; 14069 } 14070 } 14071 prepareAppDataAfterInstallLIF(newPackage); 14072 addedPkg = true; 14073 } catch (PackageManagerException e) { 14074 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14075 } 14076 } 14077 14078 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14079 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14080 14081 // Revert all internal state mutations and added folders for the failed install 14082 if (addedPkg) { 14083 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14084 res.removedInfo, true, null); 14085 } 14086 14087 // Restore the old package 14088 if (deletedPkg) { 14089 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14090 File restoreFile = new File(deletedPackage.codePath); 14091 // Parse old package 14092 boolean oldExternal = isExternal(deletedPackage); 14093 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14094 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14095 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14096 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14097 try { 14098 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14099 null); 14100 } catch (PackageManagerException e) { 14101 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14102 + e.getMessage()); 14103 return; 14104 } 14105 14106 synchronized (mPackages) { 14107 // Ensure the installer package name up to date 14108 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14109 14110 // Update permissions for restored package 14111 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14112 14113 mSettings.writeLPr(); 14114 } 14115 14116 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14117 } 14118 } else { 14119 synchronized (mPackages) { 14120 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14121 if (ps != null) { 14122 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14123 if (res.removedInfo.removedChildPackages != null) { 14124 final int childCount = res.removedInfo.removedChildPackages.size(); 14125 // Iterate in reverse as we may modify the collection 14126 for (int i = childCount - 1; i >= 0; i--) { 14127 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14128 if (res.addedChildPackages.containsKey(childPackageName)) { 14129 res.removedInfo.removedChildPackages.removeAt(i); 14130 } else { 14131 PackageRemovedInfo childInfo = res.removedInfo 14132 .removedChildPackages.valueAt(i); 14133 childInfo.removedForAllUsers = mPackages.get( 14134 childInfo.removedPackage) == null; 14135 } 14136 } 14137 } 14138 } 14139 } 14140 } 14141 } 14142 14143 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14144 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14145 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14146 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14147 + ", old=" + deletedPackage); 14148 14149 final boolean disabledSystem; 14150 14151 // Remove existing system package 14152 removePackageLI(deletedPackage, true); 14153 14154 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14155 if (!disabledSystem) { 14156 // We didn't need to disable the .apk as a current system package, 14157 // which means we are replacing another update that is already 14158 // installed. We need to make sure to delete the older one's .apk. 14159 res.removedInfo.args = createInstallArgsForExisting(0, 14160 deletedPackage.applicationInfo.getCodePath(), 14161 deletedPackage.applicationInfo.getResourcePath(), 14162 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14163 } else { 14164 res.removedInfo.args = null; 14165 } 14166 14167 // Successfully disabled the old package. Now proceed with re-installation 14168 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14169 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14170 clearAppProfilesLIF(pkg); 14171 14172 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14173 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14174 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14175 14176 PackageParser.Package newPackage = null; 14177 try { 14178 // Add the package to the internal data structures 14179 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14180 14181 // Set the update and install times 14182 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14183 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14184 System.currentTimeMillis()); 14185 14186 // Update the package dynamic state if succeeded 14187 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14188 // Now that the install succeeded make sure we remove data 14189 // directories for any child package the update removed. 14190 final int deletedChildCount = (deletedPackage.childPackages != null) 14191 ? deletedPackage.childPackages.size() : 0; 14192 final int newChildCount = (newPackage.childPackages != null) 14193 ? newPackage.childPackages.size() : 0; 14194 for (int i = 0; i < deletedChildCount; i++) { 14195 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14196 boolean childPackageDeleted = true; 14197 for (int j = 0; j < newChildCount; j++) { 14198 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14199 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14200 childPackageDeleted = false; 14201 break; 14202 } 14203 } 14204 if (childPackageDeleted) { 14205 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14206 deletedChildPkg.packageName); 14207 if (ps != null && res.removedInfo.removedChildPackages != null) { 14208 PackageRemovedInfo removedChildRes = res.removedInfo 14209 .removedChildPackages.get(deletedChildPkg.packageName); 14210 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14211 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14212 } 14213 } 14214 } 14215 14216 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14217 prepareAppDataAfterInstallLIF(newPackage); 14218 } 14219 } catch (PackageManagerException e) { 14220 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14221 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14222 } 14223 14224 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14225 // Re installation failed. Restore old information 14226 // Remove new pkg information 14227 if (newPackage != null) { 14228 removeInstalledPackageLI(newPackage, true); 14229 } 14230 // Add back the old system package 14231 try { 14232 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14233 } catch (PackageManagerException e) { 14234 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14235 } 14236 14237 synchronized (mPackages) { 14238 if (disabledSystem) { 14239 enableSystemPackageLPw(deletedPackage); 14240 } 14241 14242 // Ensure the installer package name up to date 14243 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14244 14245 // Update permissions for restored package 14246 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14247 14248 mSettings.writeLPr(); 14249 } 14250 14251 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14252 + " after failed upgrade"); 14253 } 14254 } 14255 14256 /** 14257 * Checks whether the parent or any of the child packages have a change shared 14258 * user. For a package to be a valid update the shred users of the parent and 14259 * the children should match. We may later support changing child shared users. 14260 * @param oldPkg The updated package. 14261 * @param newPkg The update package. 14262 * @return The shared user that change between the versions. 14263 */ 14264 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14265 PackageParser.Package newPkg) { 14266 // Check parent shared user 14267 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14268 return newPkg.packageName; 14269 } 14270 // Check child shared users 14271 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14272 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14273 for (int i = 0; i < newChildCount; i++) { 14274 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14275 // If this child was present, did it have the same shared user? 14276 for (int j = 0; j < oldChildCount; j++) { 14277 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14278 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14279 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14280 return newChildPkg.packageName; 14281 } 14282 } 14283 } 14284 return null; 14285 } 14286 14287 private void removeNativeBinariesLI(PackageSetting ps) { 14288 // Remove the lib path for the parent package 14289 if (ps != null) { 14290 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14291 // Remove the lib path for the child packages 14292 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14293 for (int i = 0; i < childCount; i++) { 14294 PackageSetting childPs = null; 14295 synchronized (mPackages) { 14296 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14297 } 14298 if (childPs != null) { 14299 NativeLibraryHelper.removeNativeBinariesLI(childPs 14300 .legacyNativeLibraryPathString); 14301 } 14302 } 14303 } 14304 } 14305 14306 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14307 // Enable the parent package 14308 mSettings.enableSystemPackageLPw(pkg.packageName); 14309 // Enable the child packages 14310 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14311 for (int i = 0; i < childCount; i++) { 14312 PackageParser.Package childPkg = pkg.childPackages.get(i); 14313 mSettings.enableSystemPackageLPw(childPkg.packageName); 14314 } 14315 } 14316 14317 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14318 PackageParser.Package newPkg) { 14319 // Disable the parent package (parent always replaced) 14320 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14321 // Disable the child packages 14322 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14323 for (int i = 0; i < childCount; i++) { 14324 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14325 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14326 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14327 } 14328 return disabled; 14329 } 14330 14331 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14332 String installerPackageName) { 14333 // Enable the parent package 14334 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14335 // Enable the child packages 14336 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14337 for (int i = 0; i < childCount; i++) { 14338 PackageParser.Package childPkg = pkg.childPackages.get(i); 14339 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14340 } 14341 } 14342 14343 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14344 // Collect all used permissions in the UID 14345 ArraySet<String> usedPermissions = new ArraySet<>(); 14346 final int packageCount = su.packages.size(); 14347 for (int i = 0; i < packageCount; i++) { 14348 PackageSetting ps = su.packages.valueAt(i); 14349 if (ps.pkg == null) { 14350 continue; 14351 } 14352 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14353 for (int j = 0; j < requestedPermCount; j++) { 14354 String permission = ps.pkg.requestedPermissions.get(j); 14355 BasePermission bp = mSettings.mPermissions.get(permission); 14356 if (bp != null) { 14357 usedPermissions.add(permission); 14358 } 14359 } 14360 } 14361 14362 PermissionsState permissionsState = su.getPermissionsState(); 14363 // Prune install permissions 14364 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14365 final int installPermCount = installPermStates.size(); 14366 for (int i = installPermCount - 1; i >= 0; i--) { 14367 PermissionState permissionState = installPermStates.get(i); 14368 if (!usedPermissions.contains(permissionState.getName())) { 14369 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14370 if (bp != null) { 14371 permissionsState.revokeInstallPermission(bp); 14372 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14373 PackageManager.MASK_PERMISSION_FLAGS, 0); 14374 } 14375 } 14376 } 14377 14378 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14379 14380 // Prune runtime permissions 14381 for (int userId : allUserIds) { 14382 List<PermissionState> runtimePermStates = permissionsState 14383 .getRuntimePermissionStates(userId); 14384 final int runtimePermCount = runtimePermStates.size(); 14385 for (int i = runtimePermCount - 1; i >= 0; i--) { 14386 PermissionState permissionState = runtimePermStates.get(i); 14387 if (!usedPermissions.contains(permissionState.getName())) { 14388 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14389 if (bp != null) { 14390 permissionsState.revokeRuntimePermission(bp, userId); 14391 permissionsState.updatePermissionFlags(bp, userId, 14392 PackageManager.MASK_PERMISSION_FLAGS, 0); 14393 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14394 runtimePermissionChangedUserIds, userId); 14395 } 14396 } 14397 } 14398 } 14399 14400 return runtimePermissionChangedUserIds; 14401 } 14402 14403 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14404 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14405 // Update the parent package setting 14406 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14407 res, user); 14408 // Update the child packages setting 14409 final int childCount = (newPackage.childPackages != null) 14410 ? newPackage.childPackages.size() : 0; 14411 for (int i = 0; i < childCount; i++) { 14412 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14413 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14414 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14415 childRes.origUsers, childRes, user); 14416 } 14417 } 14418 14419 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14420 String installerPackageName, int[] allUsers, int[] installedForUsers, 14421 PackageInstalledInfo res, UserHandle user) { 14422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14423 14424 String pkgName = newPackage.packageName; 14425 synchronized (mPackages) { 14426 //write settings. the installStatus will be incomplete at this stage. 14427 //note that the new package setting would have already been 14428 //added to mPackages. It hasn't been persisted yet. 14429 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14431 mSettings.writeLPr(); 14432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14433 } 14434 14435 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14436 synchronized (mPackages) { 14437 updatePermissionsLPw(newPackage.packageName, newPackage, 14438 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14439 ? UPDATE_PERMISSIONS_ALL : 0)); 14440 // For system-bundled packages, we assume that installing an upgraded version 14441 // of the package implies that the user actually wants to run that new code, 14442 // so we enable the package. 14443 PackageSetting ps = mSettings.mPackages.get(pkgName); 14444 final int userId = user.getIdentifier(); 14445 if (ps != null) { 14446 if (isSystemApp(newPackage)) { 14447 if (DEBUG_INSTALL) { 14448 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14449 } 14450 // Enable system package for requested users 14451 if (res.origUsers != null) { 14452 for (int origUserId : res.origUsers) { 14453 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14454 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14455 origUserId, installerPackageName); 14456 } 14457 } 14458 } 14459 // Also convey the prior install/uninstall state 14460 if (allUsers != null && installedForUsers != null) { 14461 for (int currentUserId : allUsers) { 14462 final boolean installed = ArrayUtils.contains( 14463 installedForUsers, currentUserId); 14464 if (DEBUG_INSTALL) { 14465 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14466 } 14467 ps.setInstalled(installed, currentUserId); 14468 } 14469 // these install state changes will be persisted in the 14470 // upcoming call to mSettings.writeLPr(). 14471 } 14472 } 14473 // It's implied that when a user requests installation, they want the app to be 14474 // installed and enabled. 14475 if (userId != UserHandle.USER_ALL) { 14476 ps.setInstalled(true, userId); 14477 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14478 } 14479 } 14480 res.name = pkgName; 14481 res.uid = newPackage.applicationInfo.uid; 14482 res.pkg = newPackage; 14483 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14484 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14485 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14486 //to update install status 14487 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14488 mSettings.writeLPr(); 14489 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14490 } 14491 14492 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14493 } 14494 14495 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14496 try { 14497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14498 installPackageLI(args, res); 14499 } finally { 14500 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14501 } 14502 } 14503 14504 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14505 final int installFlags = args.installFlags; 14506 final String installerPackageName = args.installerPackageName; 14507 final String volumeUuid = args.volumeUuid; 14508 final File tmpPackageFile = new File(args.getCodePath()); 14509 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14510 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14511 || (args.volumeUuid != null)); 14512 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14513 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14514 boolean replace = false; 14515 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14516 if (args.move != null) { 14517 // moving a complete application; perform an initial scan on the new install location 14518 scanFlags |= SCAN_INITIAL; 14519 } 14520 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14521 scanFlags |= SCAN_DONT_KILL_APP; 14522 } 14523 14524 // Result object to be returned 14525 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14526 14527 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14528 14529 // Sanity check 14530 if (ephemeral && (forwardLocked || onExternal)) { 14531 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14532 + " external=" + onExternal); 14533 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14534 return; 14535 } 14536 14537 // Retrieve PackageSettings and parse package 14538 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14539 | PackageParser.PARSE_ENFORCE_CODE 14540 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14541 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14542 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14543 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14544 PackageParser pp = new PackageParser(); 14545 pp.setSeparateProcesses(mSeparateProcesses); 14546 pp.setDisplayMetrics(mMetrics); 14547 14548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14549 final PackageParser.Package pkg; 14550 try { 14551 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14552 } catch (PackageParserException e) { 14553 res.setError("Failed parse during installPackageLI", e); 14554 return; 14555 } finally { 14556 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14557 } 14558 14559 // If we are installing a clustered package add results for the children 14560 if (pkg.childPackages != null) { 14561 synchronized (mPackages) { 14562 final int childCount = pkg.childPackages.size(); 14563 for (int i = 0; i < childCount; i++) { 14564 PackageParser.Package childPkg = pkg.childPackages.get(i); 14565 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14566 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14567 childRes.pkg = childPkg; 14568 childRes.name = childPkg.packageName; 14569 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14570 if (childPs != null) { 14571 childRes.origUsers = childPs.queryInstalledUsers( 14572 sUserManager.getUserIds(), true); 14573 } 14574 if ((mPackages.containsKey(childPkg.packageName))) { 14575 childRes.removedInfo = new PackageRemovedInfo(); 14576 childRes.removedInfo.removedPackage = childPkg.packageName; 14577 } 14578 if (res.addedChildPackages == null) { 14579 res.addedChildPackages = new ArrayMap<>(); 14580 } 14581 res.addedChildPackages.put(childPkg.packageName, childRes); 14582 } 14583 } 14584 } 14585 14586 // If package doesn't declare API override, mark that we have an install 14587 // time CPU ABI override. 14588 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14589 pkg.cpuAbiOverride = args.abiOverride; 14590 } 14591 14592 String pkgName = res.name = pkg.packageName; 14593 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14594 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14595 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14596 return; 14597 } 14598 } 14599 14600 try { 14601 // either use what we've been given or parse directly from the APK 14602 if (args.certificates != null) { 14603 try { 14604 PackageParser.populateCertificates(pkg, args.certificates); 14605 } catch (PackageParserException e) { 14606 // there was something wrong with the certificates we were given; 14607 // try to pull them from the APK 14608 PackageParser.collectCertificates(pkg, parseFlags); 14609 } 14610 } else { 14611 PackageParser.collectCertificates(pkg, parseFlags); 14612 } 14613 } catch (PackageParserException e) { 14614 res.setError("Failed collect during installPackageLI", e); 14615 return; 14616 } 14617 14618 // Get rid of all references to package scan path via parser. 14619 pp = null; 14620 String oldCodePath = null; 14621 boolean systemApp = false; 14622 synchronized (mPackages) { 14623 // Check if installing already existing package 14624 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14625 String oldName = mSettings.mRenamedPackages.get(pkgName); 14626 if (pkg.mOriginalPackages != null 14627 && pkg.mOriginalPackages.contains(oldName) 14628 && mPackages.containsKey(oldName)) { 14629 // This package is derived from an original package, 14630 // and this device has been updating from that original 14631 // name. We must continue using the original name, so 14632 // rename the new package here. 14633 pkg.setPackageName(oldName); 14634 pkgName = pkg.packageName; 14635 replace = true; 14636 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14637 + oldName + " pkgName=" + pkgName); 14638 } else if (mPackages.containsKey(pkgName)) { 14639 // This package, under its official name, already exists 14640 // on the device; we should replace it. 14641 replace = true; 14642 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14643 } 14644 14645 // Child packages are installed through the parent package 14646 if (pkg.parentPackage != null) { 14647 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14648 "Package " + pkg.packageName + " is child of package " 14649 + pkg.parentPackage.parentPackage + ". Child packages " 14650 + "can be updated only through the parent package."); 14651 return; 14652 } 14653 14654 if (replace) { 14655 // Prevent apps opting out from runtime permissions 14656 PackageParser.Package oldPackage = mPackages.get(pkgName); 14657 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14658 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14659 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14660 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14661 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14662 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14663 + " doesn't support runtime permissions but the old" 14664 + " target SDK " + oldTargetSdk + " does."); 14665 return; 14666 } 14667 14668 // Prevent installing of child packages 14669 if (oldPackage.parentPackage != null) { 14670 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14671 "Package " + pkg.packageName + " is child of package " 14672 + oldPackage.parentPackage + ". Child packages " 14673 + "can be updated only through the parent package."); 14674 return; 14675 } 14676 } 14677 } 14678 14679 PackageSetting ps = mSettings.mPackages.get(pkgName); 14680 if (ps != null) { 14681 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14682 14683 // Quick sanity check that we're signed correctly if updating; 14684 // we'll check this again later when scanning, but we want to 14685 // bail early here before tripping over redefined permissions. 14686 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14687 if (!checkUpgradeKeySetLP(ps, pkg)) { 14688 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14689 + pkg.packageName + " upgrade keys do not match the " 14690 + "previously installed version"); 14691 return; 14692 } 14693 } else { 14694 try { 14695 verifySignaturesLP(ps, pkg); 14696 } catch (PackageManagerException e) { 14697 res.setError(e.error, e.getMessage()); 14698 return; 14699 } 14700 } 14701 14702 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14703 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14704 systemApp = (ps.pkg.applicationInfo.flags & 14705 ApplicationInfo.FLAG_SYSTEM) != 0; 14706 } 14707 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14708 } 14709 14710 // Check whether the newly-scanned package wants to define an already-defined perm 14711 int N = pkg.permissions.size(); 14712 for (int i = N-1; i >= 0; i--) { 14713 PackageParser.Permission perm = pkg.permissions.get(i); 14714 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14715 if (bp != null) { 14716 // If the defining package is signed with our cert, it's okay. This 14717 // also includes the "updating the same package" case, of course. 14718 // "updating same package" could also involve key-rotation. 14719 final boolean sigsOk; 14720 if (bp.sourcePackage.equals(pkg.packageName) 14721 && (bp.packageSetting instanceof PackageSetting) 14722 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14723 scanFlags))) { 14724 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14725 } else { 14726 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14727 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14728 } 14729 if (!sigsOk) { 14730 // If the owning package is the system itself, we log but allow 14731 // install to proceed; we fail the install on all other permission 14732 // redefinitions. 14733 if (!bp.sourcePackage.equals("android")) { 14734 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14735 + pkg.packageName + " attempting to redeclare permission " 14736 + perm.info.name + " already owned by " + bp.sourcePackage); 14737 res.origPermission = perm.info.name; 14738 res.origPackage = bp.sourcePackage; 14739 return; 14740 } else { 14741 Slog.w(TAG, "Package " + pkg.packageName 14742 + " attempting to redeclare system permission " 14743 + perm.info.name + "; ignoring new declaration"); 14744 pkg.permissions.remove(i); 14745 } 14746 } 14747 } 14748 } 14749 } 14750 14751 if (systemApp) { 14752 if (onExternal) { 14753 // Abort update; system app can't be replaced with app on sdcard 14754 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14755 "Cannot install updates to system apps on sdcard"); 14756 return; 14757 } else if (ephemeral) { 14758 // Abort update; system app can't be replaced with an ephemeral app 14759 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14760 "Cannot update a system app with an ephemeral app"); 14761 return; 14762 } 14763 } 14764 14765 if (args.move != null) { 14766 // We did an in-place move, so dex is ready to roll 14767 scanFlags |= SCAN_NO_DEX; 14768 scanFlags |= SCAN_MOVE; 14769 14770 synchronized (mPackages) { 14771 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14772 if (ps == null) { 14773 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14774 "Missing settings for moved package " + pkgName); 14775 } 14776 14777 // We moved the entire application as-is, so bring over the 14778 // previously derived ABI information. 14779 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14780 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14781 } 14782 14783 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14784 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14785 scanFlags |= SCAN_NO_DEX; 14786 14787 try { 14788 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14789 args.abiOverride : pkg.cpuAbiOverride); 14790 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14791 true /* extract libs */); 14792 } catch (PackageManagerException pme) { 14793 Slog.e(TAG, "Error deriving application ABI", pme); 14794 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14795 return; 14796 } 14797 14798 // Shared libraries for the package need to be updated. 14799 synchronized (mPackages) { 14800 try { 14801 updateSharedLibrariesLPw(pkg, null); 14802 } catch (PackageManagerException e) { 14803 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14804 } 14805 } 14806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14807 // Do not run PackageDexOptimizer through the local performDexOpt 14808 // method because `pkg` is not in `mPackages` yet. 14809 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14810 null /* instructionSets */, false /* checkProfiles */, 14811 getCompilerFilterForReason(REASON_INSTALL)); 14812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14813 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14814 String msg = "Extracting package failed for " + pkgName; 14815 res.setError(INSTALL_FAILED_DEXOPT, msg); 14816 return; 14817 } 14818 14819 // Notify BackgroundDexOptService that the package has been changed. 14820 // If this is an update of a package which used to fail to compile, 14821 // BDOS will remove it from its blacklist. 14822 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14823 } 14824 14825 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14826 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14827 return; 14828 } 14829 14830 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14831 14832 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14833 "installPackageLI")) { 14834 if (replace) { 14835 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14836 installerPackageName, res); 14837 } else { 14838 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14839 args.user, installerPackageName, volumeUuid, res); 14840 } 14841 } 14842 synchronized (mPackages) { 14843 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14844 if (ps != null) { 14845 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14846 } 14847 14848 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14849 for (int i = 0; i < childCount; i++) { 14850 PackageParser.Package childPkg = pkg.childPackages.get(i); 14851 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14852 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14853 if (childPs != null) { 14854 childRes.newUsers = childPs.queryInstalledUsers( 14855 sUserManager.getUserIds(), true); 14856 } 14857 } 14858 } 14859 } 14860 14861 private void startIntentFilterVerifications(int userId, boolean replacing, 14862 PackageParser.Package pkg) { 14863 if (mIntentFilterVerifierComponent == null) { 14864 Slog.w(TAG, "No IntentFilter verification will not be done as " 14865 + "there is no IntentFilterVerifier available!"); 14866 return; 14867 } 14868 14869 final int verifierUid = getPackageUid( 14870 mIntentFilterVerifierComponent.getPackageName(), 14871 MATCH_DEBUG_TRIAGED_MISSING, 14872 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14873 14874 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14875 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14876 mHandler.sendMessage(msg); 14877 14878 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14879 for (int i = 0; i < childCount; i++) { 14880 PackageParser.Package childPkg = pkg.childPackages.get(i); 14881 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14882 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14883 mHandler.sendMessage(msg); 14884 } 14885 } 14886 14887 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14888 PackageParser.Package pkg) { 14889 int size = pkg.activities.size(); 14890 if (size == 0) { 14891 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14892 "No activity, so no need to verify any IntentFilter!"); 14893 return; 14894 } 14895 14896 final boolean hasDomainURLs = hasDomainURLs(pkg); 14897 if (!hasDomainURLs) { 14898 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14899 "No domain URLs, so no need to verify any IntentFilter!"); 14900 return; 14901 } 14902 14903 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14904 + " if any IntentFilter from the " + size 14905 + " Activities needs verification ..."); 14906 14907 int count = 0; 14908 final String packageName = pkg.packageName; 14909 14910 synchronized (mPackages) { 14911 // If this is a new install and we see that we've already run verification for this 14912 // package, we have nothing to do: it means the state was restored from backup. 14913 if (!replacing) { 14914 IntentFilterVerificationInfo ivi = 14915 mSettings.getIntentFilterVerificationLPr(packageName); 14916 if (ivi != null) { 14917 if (DEBUG_DOMAIN_VERIFICATION) { 14918 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14919 + ivi.getStatusString()); 14920 } 14921 return; 14922 } 14923 } 14924 14925 // If any filters need to be verified, then all need to be. 14926 boolean needToVerify = false; 14927 for (PackageParser.Activity a : pkg.activities) { 14928 for (ActivityIntentInfo filter : a.intents) { 14929 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14930 if (DEBUG_DOMAIN_VERIFICATION) { 14931 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14932 } 14933 needToVerify = true; 14934 break; 14935 } 14936 } 14937 } 14938 14939 if (needToVerify) { 14940 final int verificationId = mIntentFilterVerificationToken++; 14941 for (PackageParser.Activity a : pkg.activities) { 14942 for (ActivityIntentInfo filter : a.intents) { 14943 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14945 "Verification needed for IntentFilter:" + filter.toString()); 14946 mIntentFilterVerifier.addOneIntentFilterVerification( 14947 verifierUid, userId, verificationId, filter, packageName); 14948 count++; 14949 } 14950 } 14951 } 14952 } 14953 } 14954 14955 if (count > 0) { 14956 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14957 + " IntentFilter verification" + (count > 1 ? "s" : "") 14958 + " for userId:" + userId); 14959 mIntentFilterVerifier.startVerifications(userId); 14960 } else { 14961 if (DEBUG_DOMAIN_VERIFICATION) { 14962 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14963 } 14964 } 14965 } 14966 14967 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14968 final ComponentName cn = filter.activity.getComponentName(); 14969 final String packageName = cn.getPackageName(); 14970 14971 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14972 packageName); 14973 if (ivi == null) { 14974 return true; 14975 } 14976 int status = ivi.getStatus(); 14977 switch (status) { 14978 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14979 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14980 return true; 14981 14982 default: 14983 // Nothing to do 14984 return false; 14985 } 14986 } 14987 14988 private static boolean isMultiArch(ApplicationInfo info) { 14989 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14990 } 14991 14992 private static boolean isExternal(PackageParser.Package pkg) { 14993 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14994 } 14995 14996 private static boolean isExternal(PackageSetting ps) { 14997 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14998 } 14999 15000 private static boolean isEphemeral(PackageParser.Package pkg) { 15001 return pkg.applicationInfo.isEphemeralApp(); 15002 } 15003 15004 private static boolean isEphemeral(PackageSetting ps) { 15005 return ps.pkg != null && isEphemeral(ps.pkg); 15006 } 15007 15008 private static boolean isSystemApp(PackageParser.Package pkg) { 15009 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15010 } 15011 15012 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15013 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15014 } 15015 15016 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15017 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15018 } 15019 15020 private static boolean isSystemApp(PackageSetting ps) { 15021 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15022 } 15023 15024 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15025 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15026 } 15027 15028 private int packageFlagsToInstallFlags(PackageSetting ps) { 15029 int installFlags = 0; 15030 if (isEphemeral(ps)) { 15031 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15032 } 15033 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15034 // This existing package was an external ASEC install when we have 15035 // the external flag without a UUID 15036 installFlags |= PackageManager.INSTALL_EXTERNAL; 15037 } 15038 if (ps.isForwardLocked()) { 15039 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15040 } 15041 return installFlags; 15042 } 15043 15044 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15045 if (isExternal(pkg)) { 15046 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15047 return StorageManager.UUID_PRIMARY_PHYSICAL; 15048 } else { 15049 return pkg.volumeUuid; 15050 } 15051 } else { 15052 return StorageManager.UUID_PRIVATE_INTERNAL; 15053 } 15054 } 15055 15056 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15057 if (isExternal(pkg)) { 15058 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15059 return mSettings.getExternalVersion(); 15060 } else { 15061 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15062 } 15063 } else { 15064 return mSettings.getInternalVersion(); 15065 } 15066 } 15067 15068 private void deleteTempPackageFiles() { 15069 final FilenameFilter filter = new FilenameFilter() { 15070 public boolean accept(File dir, String name) { 15071 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15072 } 15073 }; 15074 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15075 file.delete(); 15076 } 15077 } 15078 15079 @Override 15080 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15081 int flags) { 15082 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15083 flags); 15084 } 15085 15086 @Override 15087 public void deletePackage(final String packageName, 15088 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15089 mContext.enforceCallingOrSelfPermission( 15090 android.Manifest.permission.DELETE_PACKAGES, null); 15091 Preconditions.checkNotNull(packageName); 15092 Preconditions.checkNotNull(observer); 15093 final int uid = Binder.getCallingUid(); 15094 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15095 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15096 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15097 mContext.enforceCallingOrSelfPermission( 15098 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15099 "deletePackage for user " + userId); 15100 } 15101 15102 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15103 try { 15104 observer.onPackageDeleted(packageName, 15105 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15106 } catch (RemoteException re) { 15107 } 15108 return; 15109 } 15110 15111 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15112 try { 15113 observer.onPackageDeleted(packageName, 15114 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15115 } catch (RemoteException re) { 15116 } 15117 return; 15118 } 15119 15120 if (DEBUG_REMOVE) { 15121 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15122 + " deleteAllUsers: " + deleteAllUsers ); 15123 } 15124 // Queue up an async operation since the package deletion may take a little while. 15125 mHandler.post(new Runnable() { 15126 public void run() { 15127 mHandler.removeCallbacks(this); 15128 int returnCode; 15129 if (!deleteAllUsers) { 15130 returnCode = deletePackageX(packageName, userId, deleteFlags); 15131 } else { 15132 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15133 // If nobody is blocking uninstall, proceed with delete for all users 15134 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15135 returnCode = deletePackageX(packageName, userId, deleteFlags); 15136 } else { 15137 // Otherwise uninstall individually for users with blockUninstalls=false 15138 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15139 for (int userId : users) { 15140 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15141 returnCode = deletePackageX(packageName, userId, userFlags); 15142 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15143 Slog.w(TAG, "Package delete failed for user " + userId 15144 + ", returnCode " + returnCode); 15145 } 15146 } 15147 } 15148 // The app has only been marked uninstalled for certain users. 15149 // We still need to report that delete was blocked 15150 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15151 } 15152 } 15153 try { 15154 observer.onPackageDeleted(packageName, returnCode, null); 15155 } catch (RemoteException e) { 15156 Log.i(TAG, "Observer no longer exists."); 15157 } //end catch 15158 } //end run 15159 }); 15160 } 15161 15162 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15163 int[] result = EMPTY_INT_ARRAY; 15164 for (int userId : userIds) { 15165 if (getBlockUninstallForUser(packageName, userId)) { 15166 result = ArrayUtils.appendInt(result, userId); 15167 } 15168 } 15169 return result; 15170 } 15171 15172 @Override 15173 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15174 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15175 } 15176 15177 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15178 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15179 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15180 try { 15181 if (dpm != null) { 15182 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15183 /* callingUserOnly =*/ false); 15184 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15185 : deviceOwnerComponentName.getPackageName(); 15186 // Does the package contains the device owner? 15187 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15188 // this check is probably not needed, since DO should be registered as a device 15189 // admin on some user too. (Original bug for this: b/17657954) 15190 if (packageName.equals(deviceOwnerPackageName)) { 15191 return true; 15192 } 15193 // Does it contain a device admin for any user? 15194 int[] users; 15195 if (userId == UserHandle.USER_ALL) { 15196 users = sUserManager.getUserIds(); 15197 } else { 15198 users = new int[]{userId}; 15199 } 15200 for (int i = 0; i < users.length; ++i) { 15201 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15202 return true; 15203 } 15204 } 15205 } 15206 } catch (RemoteException e) { 15207 } 15208 return false; 15209 } 15210 15211 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15212 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15213 } 15214 15215 /** 15216 * This method is an internal method that could be get invoked either 15217 * to delete an installed package or to clean up a failed installation. 15218 * After deleting an installed package, a broadcast is sent to notify any 15219 * listeners that the package has been removed. For cleaning up a failed 15220 * installation, the broadcast is not necessary since the package's 15221 * installation wouldn't have sent the initial broadcast either 15222 * The key steps in deleting a package are 15223 * deleting the package information in internal structures like mPackages, 15224 * deleting the packages base directories through installd 15225 * updating mSettings to reflect current status 15226 * persisting settings for later use 15227 * sending a broadcast if necessary 15228 */ 15229 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15230 final PackageRemovedInfo info = new PackageRemovedInfo(); 15231 final boolean res; 15232 15233 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15234 ? UserHandle.ALL : new UserHandle(userId); 15235 15236 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15237 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15238 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15239 } 15240 15241 PackageSetting uninstalledPs = null; 15242 15243 // for the uninstall-updates case and restricted profiles, remember the per- 15244 // user handle installed state 15245 int[] allUsers; 15246 synchronized (mPackages) { 15247 uninstalledPs = mSettings.mPackages.get(packageName); 15248 if (uninstalledPs == null) { 15249 Slog.w(TAG, "Not removing non-existent package " + packageName); 15250 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15251 } 15252 allUsers = sUserManager.getUserIds(); 15253 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15254 } 15255 15256 synchronized (mInstallLock) { 15257 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15258 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15259 "deletePackageX")) { 15260 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15261 deleteFlags | REMOVE_CHATTY, info, true, null); 15262 } 15263 synchronized (mPackages) { 15264 if (res) { 15265 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15266 } 15267 } 15268 } 15269 15270 if (res) { 15271 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15272 info.sendPackageRemovedBroadcasts(killApp); 15273 info.sendSystemPackageUpdatedBroadcasts(); 15274 info.sendSystemPackageAppearedBroadcasts(); 15275 } 15276 // Force a gc here. 15277 Runtime.getRuntime().gc(); 15278 // Delete the resources here after sending the broadcast to let 15279 // other processes clean up before deleting resources. 15280 if (info.args != null) { 15281 synchronized (mInstallLock) { 15282 info.args.doPostDeleteLI(true); 15283 } 15284 } 15285 15286 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15287 } 15288 15289 class PackageRemovedInfo { 15290 String removedPackage; 15291 int uid = -1; 15292 int removedAppId = -1; 15293 int[] origUsers; 15294 int[] removedUsers = null; 15295 boolean isRemovedPackageSystemUpdate = false; 15296 boolean isUpdate; 15297 boolean dataRemoved; 15298 boolean removedForAllUsers; 15299 // Clean up resources deleted packages. 15300 InstallArgs args = null; 15301 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15302 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15303 15304 void sendPackageRemovedBroadcasts(boolean killApp) { 15305 sendPackageRemovedBroadcastInternal(killApp); 15306 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15307 for (int i = 0; i < childCount; i++) { 15308 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15309 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15310 } 15311 } 15312 15313 void sendSystemPackageUpdatedBroadcasts() { 15314 if (isRemovedPackageSystemUpdate) { 15315 sendSystemPackageUpdatedBroadcastsInternal(); 15316 final int childCount = (removedChildPackages != null) 15317 ? removedChildPackages.size() : 0; 15318 for (int i = 0; i < childCount; i++) { 15319 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15320 if (childInfo.isRemovedPackageSystemUpdate) { 15321 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15322 } 15323 } 15324 } 15325 } 15326 15327 void sendSystemPackageAppearedBroadcasts() { 15328 final int packageCount = (appearedChildPackages != null) 15329 ? appearedChildPackages.size() : 0; 15330 for (int i = 0; i < packageCount; i++) { 15331 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15332 for (int userId : installedInfo.newUsers) { 15333 sendPackageAddedForUser(installedInfo.name, true, 15334 UserHandle.getAppId(installedInfo.uid), userId); 15335 } 15336 } 15337 } 15338 15339 private void sendSystemPackageUpdatedBroadcastsInternal() { 15340 Bundle extras = new Bundle(2); 15341 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15342 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15343 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15344 extras, 0, null, null, null); 15345 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15346 extras, 0, null, null, null); 15347 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15348 null, 0, removedPackage, null, null); 15349 } 15350 15351 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15352 Bundle extras = new Bundle(2); 15353 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15354 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15355 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15356 if (isUpdate || isRemovedPackageSystemUpdate) { 15357 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15358 } 15359 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15360 if (removedPackage != null) { 15361 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15362 extras, 0, null, null, removedUsers); 15363 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15364 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15365 removedPackage, extras, 0, null, null, removedUsers); 15366 } 15367 } 15368 if (removedAppId >= 0) { 15369 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15370 removedUsers); 15371 } 15372 } 15373 } 15374 15375 /* 15376 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15377 * flag is not set, the data directory is removed as well. 15378 * make sure this flag is set for partially installed apps. If not its meaningless to 15379 * delete a partially installed application. 15380 */ 15381 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15382 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15383 String packageName = ps.name; 15384 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15385 // Retrieve object to delete permissions for shared user later on 15386 final PackageParser.Package deletedPkg; 15387 final PackageSetting deletedPs; 15388 // reader 15389 synchronized (mPackages) { 15390 deletedPkg = mPackages.get(packageName); 15391 deletedPs = mSettings.mPackages.get(packageName); 15392 if (outInfo != null) { 15393 outInfo.removedPackage = packageName; 15394 outInfo.removedUsers = deletedPs != null 15395 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15396 : null; 15397 } 15398 } 15399 15400 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15401 15402 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15403 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15404 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15405 destroyAppProfilesLIF(deletedPkg); 15406 if (outInfo != null) { 15407 outInfo.dataRemoved = true; 15408 } 15409 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15410 } 15411 15412 // writer 15413 synchronized (mPackages) { 15414 if (deletedPs != null) { 15415 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15416 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15417 clearDefaultBrowserIfNeeded(packageName); 15418 if (outInfo != null) { 15419 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15420 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15421 } 15422 updatePermissionsLPw(deletedPs.name, null, 0); 15423 if (deletedPs.sharedUser != null) { 15424 // Remove permissions associated with package. Since runtime 15425 // permissions are per user we have to kill the removed package 15426 // or packages running under the shared user of the removed 15427 // package if revoking the permissions requested only by the removed 15428 // package is successful and this causes a change in gids. 15429 for (int userId : UserManagerService.getInstance().getUserIds()) { 15430 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15431 userId); 15432 if (userIdToKill == UserHandle.USER_ALL 15433 || userIdToKill >= UserHandle.USER_SYSTEM) { 15434 // If gids changed for this user, kill all affected packages. 15435 mHandler.post(new Runnable() { 15436 @Override 15437 public void run() { 15438 // This has to happen with no lock held. 15439 killApplication(deletedPs.name, deletedPs.appId, 15440 KILL_APP_REASON_GIDS_CHANGED); 15441 } 15442 }); 15443 break; 15444 } 15445 } 15446 } 15447 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15448 } 15449 // make sure to preserve per-user disabled state if this removal was just 15450 // a downgrade of a system app to the factory package 15451 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15452 if (DEBUG_REMOVE) { 15453 Slog.d(TAG, "Propagating install state across downgrade"); 15454 } 15455 for (int userId : allUserHandles) { 15456 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15457 if (DEBUG_REMOVE) { 15458 Slog.d(TAG, " user " + userId + " => " + installed); 15459 } 15460 ps.setInstalled(installed, userId); 15461 } 15462 } 15463 } 15464 // can downgrade to reader 15465 if (writeSettings) { 15466 // Save settings now 15467 mSettings.writeLPr(); 15468 } 15469 } 15470 if (outInfo != null) { 15471 // A user ID was deleted here. Go through all users and remove it 15472 // from KeyStore. 15473 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15474 } 15475 } 15476 15477 static boolean locationIsPrivileged(File path) { 15478 try { 15479 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15480 .getCanonicalPath(); 15481 return path.getCanonicalPath().startsWith(privilegedAppDir); 15482 } catch (IOException e) { 15483 Slog.e(TAG, "Unable to access code path " + path); 15484 } 15485 return false; 15486 } 15487 15488 /* 15489 * Tries to delete system package. 15490 */ 15491 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15492 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15493 boolean writeSettings) { 15494 if (deletedPs.parentPackageName != null) { 15495 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15496 return false; 15497 } 15498 15499 final boolean applyUserRestrictions 15500 = (allUserHandles != null) && (outInfo.origUsers != null); 15501 final PackageSetting disabledPs; 15502 // Confirm if the system package has been updated 15503 // An updated system app can be deleted. This will also have to restore 15504 // the system pkg from system partition 15505 // reader 15506 synchronized (mPackages) { 15507 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15508 } 15509 15510 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15511 + " disabledPs=" + disabledPs); 15512 15513 if (disabledPs == null) { 15514 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15515 return false; 15516 } else if (DEBUG_REMOVE) { 15517 Slog.d(TAG, "Deleting system pkg from data partition"); 15518 } 15519 15520 if (DEBUG_REMOVE) { 15521 if (applyUserRestrictions) { 15522 Slog.d(TAG, "Remembering install states:"); 15523 for (int userId : allUserHandles) { 15524 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15525 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15526 } 15527 } 15528 } 15529 15530 // Delete the updated package 15531 outInfo.isRemovedPackageSystemUpdate = true; 15532 if (outInfo.removedChildPackages != null) { 15533 final int childCount = (deletedPs.childPackageNames != null) 15534 ? deletedPs.childPackageNames.size() : 0; 15535 for (int i = 0; i < childCount; i++) { 15536 String childPackageName = deletedPs.childPackageNames.get(i); 15537 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15538 .contains(childPackageName)) { 15539 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15540 childPackageName); 15541 if (childInfo != null) { 15542 childInfo.isRemovedPackageSystemUpdate = true; 15543 } 15544 } 15545 } 15546 } 15547 15548 if (disabledPs.versionCode < deletedPs.versionCode) { 15549 // Delete data for downgrades 15550 flags &= ~PackageManager.DELETE_KEEP_DATA; 15551 } else { 15552 // Preserve data by setting flag 15553 flags |= PackageManager.DELETE_KEEP_DATA; 15554 } 15555 15556 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15557 outInfo, writeSettings, disabledPs.pkg); 15558 if (!ret) { 15559 return false; 15560 } 15561 15562 // writer 15563 synchronized (mPackages) { 15564 // Reinstate the old system package 15565 enableSystemPackageLPw(disabledPs.pkg); 15566 // Remove any native libraries from the upgraded package. 15567 removeNativeBinariesLI(deletedPs); 15568 } 15569 15570 // Install the system package 15571 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15572 int parseFlags = mDefParseFlags 15573 | PackageParser.PARSE_MUST_BE_APK 15574 | PackageParser.PARSE_IS_SYSTEM 15575 | PackageParser.PARSE_IS_SYSTEM_DIR; 15576 if (locationIsPrivileged(disabledPs.codePath)) { 15577 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15578 } 15579 15580 final PackageParser.Package newPkg; 15581 try { 15582 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15583 } catch (PackageManagerException e) { 15584 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15585 + e.getMessage()); 15586 return false; 15587 } 15588 15589 prepareAppDataAfterInstallLIF(newPkg); 15590 15591 // writer 15592 synchronized (mPackages) { 15593 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15594 15595 // Propagate the permissions state as we do not want to drop on the floor 15596 // runtime permissions. The update permissions method below will take 15597 // care of removing obsolete permissions and grant install permissions. 15598 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15599 updatePermissionsLPw(newPkg.packageName, newPkg, 15600 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15601 15602 if (applyUserRestrictions) { 15603 if (DEBUG_REMOVE) { 15604 Slog.d(TAG, "Propagating install state across reinstall"); 15605 } 15606 for (int userId : allUserHandles) { 15607 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15608 if (DEBUG_REMOVE) { 15609 Slog.d(TAG, " user " + userId + " => " + installed); 15610 } 15611 ps.setInstalled(installed, userId); 15612 15613 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15614 } 15615 // Regardless of writeSettings we need to ensure that this restriction 15616 // state propagation is persisted 15617 mSettings.writeAllUsersPackageRestrictionsLPr(); 15618 } 15619 // can downgrade to reader here 15620 if (writeSettings) { 15621 mSettings.writeLPr(); 15622 } 15623 } 15624 return true; 15625 } 15626 15627 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15628 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15629 PackageRemovedInfo outInfo, boolean writeSettings, 15630 PackageParser.Package replacingPackage) { 15631 synchronized (mPackages) { 15632 if (outInfo != null) { 15633 outInfo.uid = ps.appId; 15634 } 15635 15636 if (outInfo != null && outInfo.removedChildPackages != null) { 15637 final int childCount = (ps.childPackageNames != null) 15638 ? ps.childPackageNames.size() : 0; 15639 for (int i = 0; i < childCount; i++) { 15640 String childPackageName = ps.childPackageNames.get(i); 15641 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15642 if (childPs == null) { 15643 return false; 15644 } 15645 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15646 childPackageName); 15647 if (childInfo != null) { 15648 childInfo.uid = childPs.appId; 15649 } 15650 } 15651 } 15652 } 15653 15654 // Delete package data from internal structures and also remove data if flag is set 15655 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15656 15657 // Delete the child packages data 15658 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15659 for (int i = 0; i < childCount; i++) { 15660 PackageSetting childPs; 15661 synchronized (mPackages) { 15662 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15663 } 15664 if (childPs != null) { 15665 PackageRemovedInfo childOutInfo = (outInfo != null 15666 && outInfo.removedChildPackages != null) 15667 ? outInfo.removedChildPackages.get(childPs.name) : null; 15668 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15669 && (replacingPackage != null 15670 && !replacingPackage.hasChildPackage(childPs.name)) 15671 ? flags & ~DELETE_KEEP_DATA : flags; 15672 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15673 deleteFlags, writeSettings); 15674 } 15675 } 15676 15677 // Delete application code and resources only for parent packages 15678 if (ps.parentPackageName == null) { 15679 if (deleteCodeAndResources && (outInfo != null)) { 15680 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15681 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15682 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15683 } 15684 } 15685 15686 return true; 15687 } 15688 15689 @Override 15690 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15691 int userId) { 15692 mContext.enforceCallingOrSelfPermission( 15693 android.Manifest.permission.DELETE_PACKAGES, null); 15694 synchronized (mPackages) { 15695 PackageSetting ps = mSettings.mPackages.get(packageName); 15696 if (ps == null) { 15697 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15698 return false; 15699 } 15700 if (!ps.getInstalled(userId)) { 15701 // Can't block uninstall for an app that is not installed or enabled. 15702 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15703 return false; 15704 } 15705 ps.setBlockUninstall(blockUninstall, userId); 15706 mSettings.writePackageRestrictionsLPr(userId); 15707 } 15708 return true; 15709 } 15710 15711 @Override 15712 public boolean getBlockUninstallForUser(String packageName, int userId) { 15713 synchronized (mPackages) { 15714 PackageSetting ps = mSettings.mPackages.get(packageName); 15715 if (ps == null) { 15716 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15717 return false; 15718 } 15719 return ps.getBlockUninstall(userId); 15720 } 15721 } 15722 15723 @Override 15724 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15725 int callingUid = Binder.getCallingUid(); 15726 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15727 throw new SecurityException( 15728 "setRequiredForSystemUser can only be run by the system or root"); 15729 } 15730 synchronized (mPackages) { 15731 PackageSetting ps = mSettings.mPackages.get(packageName); 15732 if (ps == null) { 15733 Log.w(TAG, "Package doesn't exist: " + packageName); 15734 return false; 15735 } 15736 if (systemUserApp) { 15737 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15738 } else { 15739 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15740 } 15741 mSettings.writeLPr(); 15742 } 15743 return true; 15744 } 15745 15746 /* 15747 * This method handles package deletion in general 15748 */ 15749 private boolean deletePackageLIF(String packageName, UserHandle user, 15750 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15751 PackageRemovedInfo outInfo, boolean writeSettings, 15752 PackageParser.Package replacingPackage) { 15753 if (packageName == null) { 15754 Slog.w(TAG, "Attempt to delete null packageName."); 15755 return false; 15756 } 15757 15758 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15759 15760 PackageSetting ps; 15761 15762 synchronized (mPackages) { 15763 ps = mSettings.mPackages.get(packageName); 15764 if (ps == null) { 15765 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15766 return false; 15767 } 15768 15769 if (ps.parentPackageName != null && (!isSystemApp(ps) 15770 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15771 if (DEBUG_REMOVE) { 15772 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15773 + ((user == null) ? UserHandle.USER_ALL : user)); 15774 } 15775 final int removedUserId = (user != null) ? user.getIdentifier() 15776 : UserHandle.USER_ALL; 15777 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15778 return false; 15779 } 15780 markPackageUninstalledForUserLPw(ps, user); 15781 scheduleWritePackageRestrictionsLocked(user); 15782 return true; 15783 } 15784 } 15785 15786 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15787 && user.getIdentifier() != UserHandle.USER_ALL)) { 15788 // The caller is asking that the package only be deleted for a single 15789 // user. To do this, we just mark its uninstalled state and delete 15790 // its data. If this is a system app, we only allow this to happen if 15791 // they have set the special DELETE_SYSTEM_APP which requests different 15792 // semantics than normal for uninstalling system apps. 15793 markPackageUninstalledForUserLPw(ps, user); 15794 15795 if (!isSystemApp(ps)) { 15796 // Do not uninstall the APK if an app should be cached 15797 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15798 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15799 // Other user still have this package installed, so all 15800 // we need to do is clear this user's data and save that 15801 // it is uninstalled. 15802 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15803 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15804 return false; 15805 } 15806 scheduleWritePackageRestrictionsLocked(user); 15807 return true; 15808 } else { 15809 // We need to set it back to 'installed' so the uninstall 15810 // broadcasts will be sent correctly. 15811 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15812 ps.setInstalled(true, user.getIdentifier()); 15813 } 15814 } else { 15815 // This is a system app, so we assume that the 15816 // other users still have this package installed, so all 15817 // we need to do is clear this user's data and save that 15818 // it is uninstalled. 15819 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15820 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15821 return false; 15822 } 15823 scheduleWritePackageRestrictionsLocked(user); 15824 return true; 15825 } 15826 } 15827 15828 // If we are deleting a composite package for all users, keep track 15829 // of result for each child. 15830 if (ps.childPackageNames != null && outInfo != null) { 15831 synchronized (mPackages) { 15832 final int childCount = ps.childPackageNames.size(); 15833 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15834 for (int i = 0; i < childCount; i++) { 15835 String childPackageName = ps.childPackageNames.get(i); 15836 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15837 childInfo.removedPackage = childPackageName; 15838 outInfo.removedChildPackages.put(childPackageName, childInfo); 15839 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15840 if (childPs != null) { 15841 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15842 } 15843 } 15844 } 15845 } 15846 15847 boolean ret = false; 15848 if (isSystemApp(ps)) { 15849 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15850 // When an updated system application is deleted we delete the existing resources 15851 // as well and fall back to existing code in system partition 15852 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15853 } else { 15854 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15855 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15856 outInfo, writeSettings, replacingPackage); 15857 } 15858 15859 // Take a note whether we deleted the package for all users 15860 if (outInfo != null) { 15861 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15862 if (outInfo.removedChildPackages != null) { 15863 synchronized (mPackages) { 15864 final int childCount = outInfo.removedChildPackages.size(); 15865 for (int i = 0; i < childCount; i++) { 15866 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15867 if (childInfo != null) { 15868 childInfo.removedForAllUsers = mPackages.get( 15869 childInfo.removedPackage) == null; 15870 } 15871 } 15872 } 15873 } 15874 // If we uninstalled an update to a system app there may be some 15875 // child packages that appeared as they are declared in the system 15876 // app but were not declared in the update. 15877 if (isSystemApp(ps)) { 15878 synchronized (mPackages) { 15879 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15880 final int childCount = (updatedPs.childPackageNames != null) 15881 ? updatedPs.childPackageNames.size() : 0; 15882 for (int i = 0; i < childCount; i++) { 15883 String childPackageName = updatedPs.childPackageNames.get(i); 15884 if (outInfo.removedChildPackages == null 15885 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15886 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15887 if (childPs == null) { 15888 continue; 15889 } 15890 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15891 installRes.name = childPackageName; 15892 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15893 installRes.pkg = mPackages.get(childPackageName); 15894 installRes.uid = childPs.pkg.applicationInfo.uid; 15895 if (outInfo.appearedChildPackages == null) { 15896 outInfo.appearedChildPackages = new ArrayMap<>(); 15897 } 15898 outInfo.appearedChildPackages.put(childPackageName, installRes); 15899 } 15900 } 15901 } 15902 } 15903 } 15904 15905 return ret; 15906 } 15907 15908 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15909 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15910 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15911 for (int nextUserId : userIds) { 15912 if (DEBUG_REMOVE) { 15913 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15914 } 15915 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15916 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15917 false /*hidden*/, false /*suspended*/, null, null, null, 15918 false /*blockUninstall*/, 15919 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15920 } 15921 } 15922 15923 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15924 PackageRemovedInfo outInfo) { 15925 final PackageParser.Package pkg; 15926 synchronized (mPackages) { 15927 pkg = mPackages.get(ps.name); 15928 } 15929 15930 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15931 : new int[] {userId}; 15932 for (int nextUserId : userIds) { 15933 if (DEBUG_REMOVE) { 15934 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15935 + nextUserId); 15936 } 15937 15938 destroyAppDataLIF(pkg, userId, 15939 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15940 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15941 schedulePackageCleaning(ps.name, nextUserId, false); 15942 synchronized (mPackages) { 15943 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15944 scheduleWritePackageRestrictionsLocked(nextUserId); 15945 } 15946 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15947 } 15948 } 15949 15950 if (outInfo != null) { 15951 outInfo.removedPackage = ps.name; 15952 outInfo.removedAppId = ps.appId; 15953 outInfo.removedUsers = userIds; 15954 } 15955 15956 return true; 15957 } 15958 15959 private final class ClearStorageConnection implements ServiceConnection { 15960 IMediaContainerService mContainerService; 15961 15962 @Override 15963 public void onServiceConnected(ComponentName name, IBinder service) { 15964 synchronized (this) { 15965 mContainerService = IMediaContainerService.Stub.asInterface(service); 15966 notifyAll(); 15967 } 15968 } 15969 15970 @Override 15971 public void onServiceDisconnected(ComponentName name) { 15972 } 15973 } 15974 15975 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15976 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15977 15978 final boolean mounted; 15979 if (Environment.isExternalStorageEmulated()) { 15980 mounted = true; 15981 } else { 15982 final String status = Environment.getExternalStorageState(); 15983 15984 mounted = status.equals(Environment.MEDIA_MOUNTED) 15985 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15986 } 15987 15988 if (!mounted) { 15989 return; 15990 } 15991 15992 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15993 int[] users; 15994 if (userId == UserHandle.USER_ALL) { 15995 users = sUserManager.getUserIds(); 15996 } else { 15997 users = new int[] { userId }; 15998 } 15999 final ClearStorageConnection conn = new ClearStorageConnection(); 16000 if (mContext.bindServiceAsUser( 16001 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16002 try { 16003 for (int curUser : users) { 16004 long timeout = SystemClock.uptimeMillis() + 5000; 16005 synchronized (conn) { 16006 long now = SystemClock.uptimeMillis(); 16007 while (conn.mContainerService == null && now < timeout) { 16008 try { 16009 conn.wait(timeout - now); 16010 } catch (InterruptedException e) { 16011 } 16012 } 16013 } 16014 if (conn.mContainerService == null) { 16015 return; 16016 } 16017 16018 final UserEnvironment userEnv = new UserEnvironment(curUser); 16019 clearDirectory(conn.mContainerService, 16020 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16021 if (allData) { 16022 clearDirectory(conn.mContainerService, 16023 userEnv.buildExternalStorageAppDataDirs(packageName)); 16024 clearDirectory(conn.mContainerService, 16025 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16026 } 16027 } 16028 } finally { 16029 mContext.unbindService(conn); 16030 } 16031 } 16032 } 16033 16034 @Override 16035 public void clearApplicationProfileData(String packageName) { 16036 enforceSystemOrRoot("Only the system can clear all profile data"); 16037 16038 final PackageParser.Package pkg; 16039 synchronized (mPackages) { 16040 pkg = mPackages.get(packageName); 16041 } 16042 16043 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16044 synchronized (mInstallLock) { 16045 clearAppProfilesLIF(pkg); 16046 } 16047 } 16048 } 16049 16050 @Override 16051 public void clearApplicationUserData(final String packageName, 16052 final IPackageDataObserver observer, final int userId) { 16053 mContext.enforceCallingOrSelfPermission( 16054 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16055 16056 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16057 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16058 16059 final DevicePolicyManagerInternal dpmi = LocalServices 16060 .getService(DevicePolicyManagerInternal.class); 16061 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16062 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16063 } 16064 // Queue up an async operation since the package deletion may take a little while. 16065 mHandler.post(new Runnable() { 16066 public void run() { 16067 mHandler.removeCallbacks(this); 16068 final boolean succeeded; 16069 try (PackageFreezer freezer = freezePackage(packageName, 16070 "clearApplicationUserData")) { 16071 synchronized (mInstallLock) { 16072 succeeded = clearApplicationUserDataLIF(packageName, userId); 16073 } 16074 clearExternalStorageDataSync(packageName, userId, true); 16075 } 16076 if (succeeded) { 16077 // invoke DeviceStorageMonitor's update method to clear any notifications 16078 DeviceStorageMonitorInternal dsm = LocalServices 16079 .getService(DeviceStorageMonitorInternal.class); 16080 if (dsm != null) { 16081 dsm.checkMemory(); 16082 } 16083 } 16084 if(observer != null) { 16085 try { 16086 observer.onRemoveCompleted(packageName, succeeded); 16087 } catch (RemoteException e) { 16088 Log.i(TAG, "Observer no longer exists."); 16089 } 16090 } //end if observer 16091 } //end run 16092 }); 16093 } 16094 16095 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16096 if (packageName == null) { 16097 Slog.w(TAG, "Attempt to delete null packageName."); 16098 return false; 16099 } 16100 16101 // Try finding details about the requested package 16102 PackageParser.Package pkg; 16103 synchronized (mPackages) { 16104 pkg = mPackages.get(packageName); 16105 if (pkg == null) { 16106 final PackageSetting ps = mSettings.mPackages.get(packageName); 16107 if (ps != null) { 16108 pkg = ps.pkg; 16109 } 16110 } 16111 16112 if (pkg == null) { 16113 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16114 return false; 16115 } 16116 16117 PackageSetting ps = (PackageSetting) pkg.mExtras; 16118 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16119 } 16120 16121 clearAppDataLIF(pkg, userId, 16122 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16123 16124 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16125 removeKeystoreDataIfNeeded(userId, appId); 16126 16127 final UserManager um = mContext.getSystemService(UserManager.class); 16128 final int flags; 16129 if (um.isUserUnlockingOrUnlocked(userId)) { 16130 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16131 } else if (um.isUserRunning(userId)) { 16132 flags = StorageManager.FLAG_STORAGE_DE; 16133 } else { 16134 flags = 0; 16135 } 16136 prepareAppDataContentsLIF(pkg, userId, flags); 16137 16138 return true; 16139 } 16140 16141 /** 16142 * Reverts user permission state changes (permissions and flags) in 16143 * all packages for a given user. 16144 * 16145 * @param userId The device user for which to do a reset. 16146 */ 16147 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16148 final int packageCount = mPackages.size(); 16149 for (int i = 0; i < packageCount; i++) { 16150 PackageParser.Package pkg = mPackages.valueAt(i); 16151 PackageSetting ps = (PackageSetting) pkg.mExtras; 16152 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16153 } 16154 } 16155 16156 /** 16157 * Reverts user permission state changes (permissions and flags). 16158 * 16159 * @param ps The package for which to reset. 16160 * @param userId The device user for which to do a reset. 16161 */ 16162 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16163 final PackageSetting ps, final int userId) { 16164 if (ps.pkg == null) { 16165 return; 16166 } 16167 16168 // These are flags that can change base on user actions. 16169 final int userSettableMask = FLAG_PERMISSION_USER_SET 16170 | FLAG_PERMISSION_USER_FIXED 16171 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16172 | FLAG_PERMISSION_REVIEW_REQUIRED; 16173 16174 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16175 | FLAG_PERMISSION_POLICY_FIXED; 16176 16177 boolean writeInstallPermissions = false; 16178 boolean writeRuntimePermissions = false; 16179 16180 final int permissionCount = ps.pkg.requestedPermissions.size(); 16181 for (int i = 0; i < permissionCount; i++) { 16182 String permission = ps.pkg.requestedPermissions.get(i); 16183 16184 BasePermission bp = mSettings.mPermissions.get(permission); 16185 if (bp == null) { 16186 continue; 16187 } 16188 16189 // If shared user we just reset the state to which only this app contributed. 16190 if (ps.sharedUser != null) { 16191 boolean used = false; 16192 final int packageCount = ps.sharedUser.packages.size(); 16193 for (int j = 0; j < packageCount; j++) { 16194 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16195 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16196 && pkg.pkg.requestedPermissions.contains(permission)) { 16197 used = true; 16198 break; 16199 } 16200 } 16201 if (used) { 16202 continue; 16203 } 16204 } 16205 16206 PermissionsState permissionsState = ps.getPermissionsState(); 16207 16208 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16209 16210 // Always clear the user settable flags. 16211 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16212 bp.name) != null; 16213 // If permission review is enabled and this is a legacy app, mark the 16214 // permission as requiring a review as this is the initial state. 16215 int flags = 0; 16216 if (Build.PERMISSIONS_REVIEW_REQUIRED 16217 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16218 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16219 } 16220 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16221 if (hasInstallState) { 16222 writeInstallPermissions = true; 16223 } else { 16224 writeRuntimePermissions = true; 16225 } 16226 } 16227 16228 // Below is only runtime permission handling. 16229 if (!bp.isRuntime()) { 16230 continue; 16231 } 16232 16233 // Never clobber system or policy. 16234 if ((oldFlags & policyOrSystemFlags) != 0) { 16235 continue; 16236 } 16237 16238 // If this permission was granted by default, make sure it is. 16239 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16240 if (permissionsState.grantRuntimePermission(bp, userId) 16241 != PERMISSION_OPERATION_FAILURE) { 16242 writeRuntimePermissions = true; 16243 } 16244 // If permission review is enabled the permissions for a legacy apps 16245 // are represented as constantly granted runtime ones, so don't revoke. 16246 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16247 // Otherwise, reset the permission. 16248 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16249 switch (revokeResult) { 16250 case PERMISSION_OPERATION_SUCCESS: 16251 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16252 writeRuntimePermissions = true; 16253 final int appId = ps.appId; 16254 mHandler.post(new Runnable() { 16255 @Override 16256 public void run() { 16257 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16258 } 16259 }); 16260 } break; 16261 } 16262 } 16263 } 16264 16265 // Synchronously write as we are taking permissions away. 16266 if (writeRuntimePermissions) { 16267 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16268 } 16269 16270 // Synchronously write as we are taking permissions away. 16271 if (writeInstallPermissions) { 16272 mSettings.writeLPr(); 16273 } 16274 } 16275 16276 /** 16277 * Remove entries from the keystore daemon. Will only remove it if the 16278 * {@code appId} is valid. 16279 */ 16280 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16281 if (appId < 0) { 16282 return; 16283 } 16284 16285 final KeyStore keyStore = KeyStore.getInstance(); 16286 if (keyStore != null) { 16287 if (userId == UserHandle.USER_ALL) { 16288 for (final int individual : sUserManager.getUserIds()) { 16289 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16290 } 16291 } else { 16292 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16293 } 16294 } else { 16295 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16296 } 16297 } 16298 16299 @Override 16300 public void deleteApplicationCacheFiles(final String packageName, 16301 final IPackageDataObserver observer) { 16302 final int userId = UserHandle.getCallingUserId(); 16303 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16304 } 16305 16306 @Override 16307 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16308 final IPackageDataObserver observer) { 16309 mContext.enforceCallingOrSelfPermission( 16310 android.Manifest.permission.DELETE_CACHE_FILES, null); 16311 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16312 /* requireFullPermission= */ true, /* checkShell= */ false, 16313 "delete application cache files"); 16314 16315 final PackageParser.Package pkg; 16316 synchronized (mPackages) { 16317 pkg = mPackages.get(packageName); 16318 } 16319 16320 // Queue up an async operation since the package deletion may take a little while. 16321 mHandler.post(new Runnable() { 16322 public void run() { 16323 synchronized (mInstallLock) { 16324 final int flags = StorageManager.FLAG_STORAGE_DE 16325 | StorageManager.FLAG_STORAGE_CE; 16326 // We're only clearing cache files, so we don't care if the 16327 // app is unfrozen and still able to run 16328 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16329 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16330 } 16331 clearExternalStorageDataSync(packageName, userId, false); 16332 if (observer != null) { 16333 try { 16334 observer.onRemoveCompleted(packageName, true); 16335 } catch (RemoteException e) { 16336 Log.i(TAG, "Observer no longer exists."); 16337 } 16338 } 16339 } 16340 }); 16341 } 16342 16343 @Override 16344 public void getPackageSizeInfo(final String packageName, int userHandle, 16345 final IPackageStatsObserver observer) { 16346 mContext.enforceCallingOrSelfPermission( 16347 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16348 if (packageName == null) { 16349 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16350 } 16351 16352 PackageStats stats = new PackageStats(packageName, userHandle); 16353 16354 /* 16355 * Queue up an async operation since the package measurement may take a 16356 * little while. 16357 */ 16358 Message msg = mHandler.obtainMessage(INIT_COPY); 16359 msg.obj = new MeasureParams(stats, observer); 16360 mHandler.sendMessage(msg); 16361 } 16362 16363 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16364 final PackageSetting ps; 16365 synchronized (mPackages) { 16366 ps = mSettings.mPackages.get(packageName); 16367 if (ps == null) { 16368 Slog.w(TAG, "Failed to find settings for " + packageName); 16369 return false; 16370 } 16371 } 16372 try { 16373 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16374 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16375 ps.getCeDataInode(userId), ps.codePathString, stats); 16376 } catch (InstallerException e) { 16377 Slog.w(TAG, String.valueOf(e)); 16378 return false; 16379 } 16380 16381 // For now, ignore code size of packages on system partition 16382 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16383 stats.codeSize = 0; 16384 } 16385 16386 return true; 16387 } 16388 16389 private int getUidTargetSdkVersionLockedLPr(int uid) { 16390 Object obj = mSettings.getUserIdLPr(uid); 16391 if (obj instanceof SharedUserSetting) { 16392 final SharedUserSetting sus = (SharedUserSetting) obj; 16393 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16394 final Iterator<PackageSetting> it = sus.packages.iterator(); 16395 while (it.hasNext()) { 16396 final PackageSetting ps = it.next(); 16397 if (ps.pkg != null) { 16398 int v = ps.pkg.applicationInfo.targetSdkVersion; 16399 if (v < vers) vers = v; 16400 } 16401 } 16402 return vers; 16403 } else if (obj instanceof PackageSetting) { 16404 final PackageSetting ps = (PackageSetting) obj; 16405 if (ps.pkg != null) { 16406 return ps.pkg.applicationInfo.targetSdkVersion; 16407 } 16408 } 16409 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16410 } 16411 16412 @Override 16413 public void addPreferredActivity(IntentFilter filter, int match, 16414 ComponentName[] set, ComponentName activity, int userId) { 16415 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16416 "Adding preferred"); 16417 } 16418 16419 private void addPreferredActivityInternal(IntentFilter filter, int match, 16420 ComponentName[] set, ComponentName activity, boolean always, int userId, 16421 String opname) { 16422 // writer 16423 int callingUid = Binder.getCallingUid(); 16424 enforceCrossUserPermission(callingUid, userId, 16425 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16426 if (filter.countActions() == 0) { 16427 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16428 return; 16429 } 16430 synchronized (mPackages) { 16431 if (mContext.checkCallingOrSelfPermission( 16432 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16433 != PackageManager.PERMISSION_GRANTED) { 16434 if (getUidTargetSdkVersionLockedLPr(callingUid) 16435 < Build.VERSION_CODES.FROYO) { 16436 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16437 + callingUid); 16438 return; 16439 } 16440 mContext.enforceCallingOrSelfPermission( 16441 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16442 } 16443 16444 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16445 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16446 + userId + ":"); 16447 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16448 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16449 scheduleWritePackageRestrictionsLocked(userId); 16450 } 16451 } 16452 16453 @Override 16454 public void replacePreferredActivity(IntentFilter filter, int match, 16455 ComponentName[] set, ComponentName activity, int userId) { 16456 if (filter.countActions() != 1) { 16457 throw new IllegalArgumentException( 16458 "replacePreferredActivity expects filter to have only 1 action."); 16459 } 16460 if (filter.countDataAuthorities() != 0 16461 || filter.countDataPaths() != 0 16462 || filter.countDataSchemes() > 1 16463 || filter.countDataTypes() != 0) { 16464 throw new IllegalArgumentException( 16465 "replacePreferredActivity expects filter to have no data authorities, " + 16466 "paths, or types; and at most one scheme."); 16467 } 16468 16469 final int callingUid = Binder.getCallingUid(); 16470 enforceCrossUserPermission(callingUid, userId, 16471 true /* requireFullPermission */, false /* checkShell */, 16472 "replace preferred activity"); 16473 synchronized (mPackages) { 16474 if (mContext.checkCallingOrSelfPermission( 16475 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16476 != PackageManager.PERMISSION_GRANTED) { 16477 if (getUidTargetSdkVersionLockedLPr(callingUid) 16478 < Build.VERSION_CODES.FROYO) { 16479 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16480 + Binder.getCallingUid()); 16481 return; 16482 } 16483 mContext.enforceCallingOrSelfPermission( 16484 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16485 } 16486 16487 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16488 if (pir != null) { 16489 // Get all of the existing entries that exactly match this filter. 16490 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16491 if (existing != null && existing.size() == 1) { 16492 PreferredActivity cur = existing.get(0); 16493 if (DEBUG_PREFERRED) { 16494 Slog.i(TAG, "Checking replace of preferred:"); 16495 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16496 if (!cur.mPref.mAlways) { 16497 Slog.i(TAG, " -- CUR; not mAlways!"); 16498 } else { 16499 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16500 Slog.i(TAG, " -- CUR: mSet=" 16501 + Arrays.toString(cur.mPref.mSetComponents)); 16502 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16503 Slog.i(TAG, " -- NEW: mMatch=" 16504 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16505 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16506 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16507 } 16508 } 16509 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16510 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16511 && cur.mPref.sameSet(set)) { 16512 // Setting the preferred activity to what it happens to be already 16513 if (DEBUG_PREFERRED) { 16514 Slog.i(TAG, "Replacing with same preferred activity " 16515 + cur.mPref.mShortComponent + " for user " 16516 + userId + ":"); 16517 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16518 } 16519 return; 16520 } 16521 } 16522 16523 if (existing != null) { 16524 if (DEBUG_PREFERRED) { 16525 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16526 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16527 } 16528 for (int i = 0; i < existing.size(); i++) { 16529 PreferredActivity pa = existing.get(i); 16530 if (DEBUG_PREFERRED) { 16531 Slog.i(TAG, "Removing existing preferred activity " 16532 + pa.mPref.mComponent + ":"); 16533 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16534 } 16535 pir.removeFilter(pa); 16536 } 16537 } 16538 } 16539 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16540 "Replacing preferred"); 16541 } 16542 } 16543 16544 @Override 16545 public void clearPackagePreferredActivities(String packageName) { 16546 final int uid = Binder.getCallingUid(); 16547 // writer 16548 synchronized (mPackages) { 16549 PackageParser.Package pkg = mPackages.get(packageName); 16550 if (pkg == null || pkg.applicationInfo.uid != uid) { 16551 if (mContext.checkCallingOrSelfPermission( 16552 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16553 != PackageManager.PERMISSION_GRANTED) { 16554 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16555 < Build.VERSION_CODES.FROYO) { 16556 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16557 + Binder.getCallingUid()); 16558 return; 16559 } 16560 mContext.enforceCallingOrSelfPermission( 16561 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16562 } 16563 } 16564 16565 int user = UserHandle.getCallingUserId(); 16566 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16567 scheduleWritePackageRestrictionsLocked(user); 16568 } 16569 } 16570 } 16571 16572 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16573 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16574 ArrayList<PreferredActivity> removed = null; 16575 boolean changed = false; 16576 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16577 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16578 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16579 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16580 continue; 16581 } 16582 Iterator<PreferredActivity> it = pir.filterIterator(); 16583 while (it.hasNext()) { 16584 PreferredActivity pa = it.next(); 16585 // Mark entry for removal only if it matches the package name 16586 // and the entry is of type "always". 16587 if (packageName == null || 16588 (pa.mPref.mComponent.getPackageName().equals(packageName) 16589 && pa.mPref.mAlways)) { 16590 if (removed == null) { 16591 removed = new ArrayList<PreferredActivity>(); 16592 } 16593 removed.add(pa); 16594 } 16595 } 16596 if (removed != null) { 16597 for (int j=0; j<removed.size(); j++) { 16598 PreferredActivity pa = removed.get(j); 16599 pir.removeFilter(pa); 16600 } 16601 changed = true; 16602 } 16603 } 16604 return changed; 16605 } 16606 16607 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16608 private void clearIntentFilterVerificationsLPw(int userId) { 16609 final int packageCount = mPackages.size(); 16610 for (int i = 0; i < packageCount; i++) { 16611 PackageParser.Package pkg = mPackages.valueAt(i); 16612 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16613 } 16614 } 16615 16616 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16617 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16618 if (userId == UserHandle.USER_ALL) { 16619 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16620 sUserManager.getUserIds())) { 16621 for (int oneUserId : sUserManager.getUserIds()) { 16622 scheduleWritePackageRestrictionsLocked(oneUserId); 16623 } 16624 } 16625 } else { 16626 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16627 scheduleWritePackageRestrictionsLocked(userId); 16628 } 16629 } 16630 } 16631 16632 void clearDefaultBrowserIfNeeded(String packageName) { 16633 for (int oneUserId : sUserManager.getUserIds()) { 16634 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16635 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16636 if (packageName.equals(defaultBrowserPackageName)) { 16637 setDefaultBrowserPackageName(null, oneUserId); 16638 } 16639 } 16640 } 16641 16642 @Override 16643 public void resetApplicationPreferences(int userId) { 16644 mContext.enforceCallingOrSelfPermission( 16645 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16646 // writer 16647 synchronized (mPackages) { 16648 final long identity = Binder.clearCallingIdentity(); 16649 try { 16650 clearPackagePreferredActivitiesLPw(null, userId); 16651 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16652 // TODO: We have to reset the default SMS and Phone. This requires 16653 // significant refactoring to keep all default apps in the package 16654 // manager (cleaner but more work) or have the services provide 16655 // callbacks to the package manager to request a default app reset. 16656 applyFactoryDefaultBrowserLPw(userId); 16657 clearIntentFilterVerificationsLPw(userId); 16658 primeDomainVerificationsLPw(userId); 16659 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16660 scheduleWritePackageRestrictionsLocked(userId); 16661 } finally { 16662 Binder.restoreCallingIdentity(identity); 16663 } 16664 } 16665 } 16666 16667 @Override 16668 public int getPreferredActivities(List<IntentFilter> outFilters, 16669 List<ComponentName> outActivities, String packageName) { 16670 16671 int num = 0; 16672 final int userId = UserHandle.getCallingUserId(); 16673 // reader 16674 synchronized (mPackages) { 16675 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16676 if (pir != null) { 16677 final Iterator<PreferredActivity> it = pir.filterIterator(); 16678 while (it.hasNext()) { 16679 final PreferredActivity pa = it.next(); 16680 if (packageName == null 16681 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16682 && pa.mPref.mAlways)) { 16683 if (outFilters != null) { 16684 outFilters.add(new IntentFilter(pa)); 16685 } 16686 if (outActivities != null) { 16687 outActivities.add(pa.mPref.mComponent); 16688 } 16689 } 16690 } 16691 } 16692 } 16693 16694 return num; 16695 } 16696 16697 @Override 16698 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16699 int userId) { 16700 int callingUid = Binder.getCallingUid(); 16701 if (callingUid != Process.SYSTEM_UID) { 16702 throw new SecurityException( 16703 "addPersistentPreferredActivity can only be run by the system"); 16704 } 16705 if (filter.countActions() == 0) { 16706 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16707 return; 16708 } 16709 synchronized (mPackages) { 16710 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16711 ":"); 16712 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16713 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16714 new PersistentPreferredActivity(filter, activity)); 16715 scheduleWritePackageRestrictionsLocked(userId); 16716 } 16717 } 16718 16719 @Override 16720 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16721 int callingUid = Binder.getCallingUid(); 16722 if (callingUid != Process.SYSTEM_UID) { 16723 throw new SecurityException( 16724 "clearPackagePersistentPreferredActivities can only be run by the system"); 16725 } 16726 ArrayList<PersistentPreferredActivity> removed = null; 16727 boolean changed = false; 16728 synchronized (mPackages) { 16729 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16730 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16731 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16732 .valueAt(i); 16733 if (userId != thisUserId) { 16734 continue; 16735 } 16736 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16737 while (it.hasNext()) { 16738 PersistentPreferredActivity ppa = it.next(); 16739 // Mark entry for removal only if it matches the package name. 16740 if (ppa.mComponent.getPackageName().equals(packageName)) { 16741 if (removed == null) { 16742 removed = new ArrayList<PersistentPreferredActivity>(); 16743 } 16744 removed.add(ppa); 16745 } 16746 } 16747 if (removed != null) { 16748 for (int j=0; j<removed.size(); j++) { 16749 PersistentPreferredActivity ppa = removed.get(j); 16750 ppir.removeFilter(ppa); 16751 } 16752 changed = true; 16753 } 16754 } 16755 16756 if (changed) { 16757 scheduleWritePackageRestrictionsLocked(userId); 16758 } 16759 } 16760 } 16761 16762 /** 16763 * Common machinery for picking apart a restored XML blob and passing 16764 * it to a caller-supplied functor to be applied to the running system. 16765 */ 16766 private void restoreFromXml(XmlPullParser parser, int userId, 16767 String expectedStartTag, BlobXmlRestorer functor) 16768 throws IOException, XmlPullParserException { 16769 int type; 16770 while ((type = parser.next()) != XmlPullParser.START_TAG 16771 && type != XmlPullParser.END_DOCUMENT) { 16772 } 16773 if (type != XmlPullParser.START_TAG) { 16774 // oops didn't find a start tag?! 16775 if (DEBUG_BACKUP) { 16776 Slog.e(TAG, "Didn't find start tag during restore"); 16777 } 16778 return; 16779 } 16780Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16781 // this is supposed to be TAG_PREFERRED_BACKUP 16782 if (!expectedStartTag.equals(parser.getName())) { 16783 if (DEBUG_BACKUP) { 16784 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16785 } 16786 return; 16787 } 16788 16789 // skip interfering stuff, then we're aligned with the backing implementation 16790 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16791Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16792 functor.apply(parser, userId); 16793 } 16794 16795 private interface BlobXmlRestorer { 16796 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16797 } 16798 16799 /** 16800 * Non-Binder method, support for the backup/restore mechanism: write the 16801 * full set of preferred activities in its canonical XML format. Returns the 16802 * XML output as a byte array, or null if there is none. 16803 */ 16804 @Override 16805 public byte[] getPreferredActivityBackup(int userId) { 16806 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16807 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16808 } 16809 16810 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16811 try { 16812 final XmlSerializer serializer = new FastXmlSerializer(); 16813 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16814 serializer.startDocument(null, true); 16815 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16816 16817 synchronized (mPackages) { 16818 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16819 } 16820 16821 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16822 serializer.endDocument(); 16823 serializer.flush(); 16824 } catch (Exception e) { 16825 if (DEBUG_BACKUP) { 16826 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16827 } 16828 return null; 16829 } 16830 16831 return dataStream.toByteArray(); 16832 } 16833 16834 @Override 16835 public void restorePreferredActivities(byte[] backup, int userId) { 16836 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16837 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16838 } 16839 16840 try { 16841 final XmlPullParser parser = Xml.newPullParser(); 16842 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16843 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16844 new BlobXmlRestorer() { 16845 @Override 16846 public void apply(XmlPullParser parser, int userId) 16847 throws XmlPullParserException, IOException { 16848 synchronized (mPackages) { 16849 mSettings.readPreferredActivitiesLPw(parser, userId); 16850 } 16851 } 16852 } ); 16853 } catch (Exception e) { 16854 if (DEBUG_BACKUP) { 16855 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16856 } 16857 } 16858 } 16859 16860 /** 16861 * Non-Binder method, support for the backup/restore mechanism: write the 16862 * default browser (etc) settings in its canonical XML format. Returns the default 16863 * browser XML representation as a byte array, or null if there is none. 16864 */ 16865 @Override 16866 public byte[] getDefaultAppsBackup(int userId) { 16867 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16868 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16869 } 16870 16871 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16872 try { 16873 final XmlSerializer serializer = new FastXmlSerializer(); 16874 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16875 serializer.startDocument(null, true); 16876 serializer.startTag(null, TAG_DEFAULT_APPS); 16877 16878 synchronized (mPackages) { 16879 mSettings.writeDefaultAppsLPr(serializer, userId); 16880 } 16881 16882 serializer.endTag(null, TAG_DEFAULT_APPS); 16883 serializer.endDocument(); 16884 serializer.flush(); 16885 } catch (Exception e) { 16886 if (DEBUG_BACKUP) { 16887 Slog.e(TAG, "Unable to write default apps for backup", e); 16888 } 16889 return null; 16890 } 16891 16892 return dataStream.toByteArray(); 16893 } 16894 16895 @Override 16896 public void restoreDefaultApps(byte[] backup, int userId) { 16897 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16898 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16899 } 16900 16901 try { 16902 final XmlPullParser parser = Xml.newPullParser(); 16903 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16904 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16905 new BlobXmlRestorer() { 16906 @Override 16907 public void apply(XmlPullParser parser, int userId) 16908 throws XmlPullParserException, IOException { 16909 synchronized (mPackages) { 16910 mSettings.readDefaultAppsLPw(parser, userId); 16911 } 16912 } 16913 } ); 16914 } catch (Exception e) { 16915 if (DEBUG_BACKUP) { 16916 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16917 } 16918 } 16919 } 16920 16921 @Override 16922 public byte[] getIntentFilterVerificationBackup(int userId) { 16923 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16924 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16925 } 16926 16927 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16928 try { 16929 final XmlSerializer serializer = new FastXmlSerializer(); 16930 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16931 serializer.startDocument(null, true); 16932 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16933 16934 synchronized (mPackages) { 16935 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16936 } 16937 16938 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16939 serializer.endDocument(); 16940 serializer.flush(); 16941 } catch (Exception e) { 16942 if (DEBUG_BACKUP) { 16943 Slog.e(TAG, "Unable to write default apps for backup", e); 16944 } 16945 return null; 16946 } 16947 16948 return dataStream.toByteArray(); 16949 } 16950 16951 @Override 16952 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16953 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16954 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16955 } 16956 16957 try { 16958 final XmlPullParser parser = Xml.newPullParser(); 16959 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16960 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16961 new BlobXmlRestorer() { 16962 @Override 16963 public void apply(XmlPullParser parser, int userId) 16964 throws XmlPullParserException, IOException { 16965 synchronized (mPackages) { 16966 mSettings.readAllDomainVerificationsLPr(parser, userId); 16967 mSettings.writeLPr(); 16968 } 16969 } 16970 } ); 16971 } catch (Exception e) { 16972 if (DEBUG_BACKUP) { 16973 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16974 } 16975 } 16976 } 16977 16978 @Override 16979 public byte[] getPermissionGrantBackup(int userId) { 16980 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16981 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16982 } 16983 16984 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16985 try { 16986 final XmlSerializer serializer = new FastXmlSerializer(); 16987 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16988 serializer.startDocument(null, true); 16989 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16990 16991 synchronized (mPackages) { 16992 serializeRuntimePermissionGrantsLPr(serializer, userId); 16993 } 16994 16995 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16996 serializer.endDocument(); 16997 serializer.flush(); 16998 } catch (Exception e) { 16999 if (DEBUG_BACKUP) { 17000 Slog.e(TAG, "Unable to write default apps for backup", e); 17001 } 17002 return null; 17003 } 17004 17005 return dataStream.toByteArray(); 17006 } 17007 17008 @Override 17009 public void restorePermissionGrants(byte[] backup, int userId) { 17010 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17011 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17012 } 17013 17014 try { 17015 final XmlPullParser parser = Xml.newPullParser(); 17016 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17017 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17018 new BlobXmlRestorer() { 17019 @Override 17020 public void apply(XmlPullParser parser, int userId) 17021 throws XmlPullParserException, IOException { 17022 synchronized (mPackages) { 17023 processRestoredPermissionGrantsLPr(parser, userId); 17024 } 17025 } 17026 } ); 17027 } catch (Exception e) { 17028 if (DEBUG_BACKUP) { 17029 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17030 } 17031 } 17032 } 17033 17034 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17035 throws IOException { 17036 serializer.startTag(null, TAG_ALL_GRANTS); 17037 17038 final int N = mSettings.mPackages.size(); 17039 for (int i = 0; i < N; i++) { 17040 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17041 boolean pkgGrantsKnown = false; 17042 17043 PermissionsState packagePerms = ps.getPermissionsState(); 17044 17045 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17046 final int grantFlags = state.getFlags(); 17047 // only look at grants that are not system/policy fixed 17048 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17049 final boolean isGranted = state.isGranted(); 17050 // And only back up the user-twiddled state bits 17051 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17052 final String packageName = mSettings.mPackages.keyAt(i); 17053 if (!pkgGrantsKnown) { 17054 serializer.startTag(null, TAG_GRANT); 17055 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17056 pkgGrantsKnown = true; 17057 } 17058 17059 final boolean userSet = 17060 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17061 final boolean userFixed = 17062 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17063 final boolean revoke = 17064 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17065 17066 serializer.startTag(null, TAG_PERMISSION); 17067 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17068 if (isGranted) { 17069 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17070 } 17071 if (userSet) { 17072 serializer.attribute(null, ATTR_USER_SET, "true"); 17073 } 17074 if (userFixed) { 17075 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17076 } 17077 if (revoke) { 17078 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17079 } 17080 serializer.endTag(null, TAG_PERMISSION); 17081 } 17082 } 17083 } 17084 17085 if (pkgGrantsKnown) { 17086 serializer.endTag(null, TAG_GRANT); 17087 } 17088 } 17089 17090 serializer.endTag(null, TAG_ALL_GRANTS); 17091 } 17092 17093 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17094 throws XmlPullParserException, IOException { 17095 String pkgName = null; 17096 int outerDepth = parser.getDepth(); 17097 int type; 17098 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17099 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17100 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17101 continue; 17102 } 17103 17104 final String tagName = parser.getName(); 17105 if (tagName.equals(TAG_GRANT)) { 17106 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17107 if (DEBUG_BACKUP) { 17108 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17109 } 17110 } else if (tagName.equals(TAG_PERMISSION)) { 17111 17112 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17113 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17114 17115 int newFlagSet = 0; 17116 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17117 newFlagSet |= FLAG_PERMISSION_USER_SET; 17118 } 17119 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17120 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17121 } 17122 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17123 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17124 } 17125 if (DEBUG_BACKUP) { 17126 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17127 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17128 } 17129 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17130 if (ps != null) { 17131 // Already installed so we apply the grant immediately 17132 if (DEBUG_BACKUP) { 17133 Slog.v(TAG, " + already installed; applying"); 17134 } 17135 PermissionsState perms = ps.getPermissionsState(); 17136 BasePermission bp = mSettings.mPermissions.get(permName); 17137 if (bp != null) { 17138 if (isGranted) { 17139 perms.grantRuntimePermission(bp, userId); 17140 } 17141 if (newFlagSet != 0) { 17142 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17143 } 17144 } 17145 } else { 17146 // Need to wait for post-restore install to apply the grant 17147 if (DEBUG_BACKUP) { 17148 Slog.v(TAG, " - not yet installed; saving for later"); 17149 } 17150 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17151 isGranted, newFlagSet, userId); 17152 } 17153 } else { 17154 PackageManagerService.reportSettingsProblem(Log.WARN, 17155 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17156 XmlUtils.skipCurrentTag(parser); 17157 } 17158 } 17159 17160 scheduleWriteSettingsLocked(); 17161 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17162 } 17163 17164 @Override 17165 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17166 int sourceUserId, int targetUserId, int flags) { 17167 mContext.enforceCallingOrSelfPermission( 17168 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17169 int callingUid = Binder.getCallingUid(); 17170 enforceOwnerRights(ownerPackage, callingUid); 17171 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17172 if (intentFilter.countActions() == 0) { 17173 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17174 return; 17175 } 17176 synchronized (mPackages) { 17177 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17178 ownerPackage, targetUserId, flags); 17179 CrossProfileIntentResolver resolver = 17180 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17181 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17182 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17183 if (existing != null) { 17184 int size = existing.size(); 17185 for (int i = 0; i < size; i++) { 17186 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17187 return; 17188 } 17189 } 17190 } 17191 resolver.addFilter(newFilter); 17192 scheduleWritePackageRestrictionsLocked(sourceUserId); 17193 } 17194 } 17195 17196 @Override 17197 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17198 mContext.enforceCallingOrSelfPermission( 17199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17200 int callingUid = Binder.getCallingUid(); 17201 enforceOwnerRights(ownerPackage, callingUid); 17202 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17203 synchronized (mPackages) { 17204 CrossProfileIntentResolver resolver = 17205 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17206 ArraySet<CrossProfileIntentFilter> set = 17207 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17208 for (CrossProfileIntentFilter filter : set) { 17209 if (filter.getOwnerPackage().equals(ownerPackage)) { 17210 resolver.removeFilter(filter); 17211 } 17212 } 17213 scheduleWritePackageRestrictionsLocked(sourceUserId); 17214 } 17215 } 17216 17217 // Enforcing that callingUid is owning pkg on userId 17218 private void enforceOwnerRights(String pkg, int callingUid) { 17219 // The system owns everything. 17220 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17221 return; 17222 } 17223 int callingUserId = UserHandle.getUserId(callingUid); 17224 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17225 if (pi == null) { 17226 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17227 + callingUserId); 17228 } 17229 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17230 throw new SecurityException("Calling uid " + callingUid 17231 + " does not own package " + pkg); 17232 } 17233 } 17234 17235 @Override 17236 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17237 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17238 } 17239 17240 private Intent getHomeIntent() { 17241 Intent intent = new Intent(Intent.ACTION_MAIN); 17242 intent.addCategory(Intent.CATEGORY_HOME); 17243 return intent; 17244 } 17245 17246 private IntentFilter getHomeFilter() { 17247 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17248 filter.addCategory(Intent.CATEGORY_HOME); 17249 filter.addCategory(Intent.CATEGORY_DEFAULT); 17250 return filter; 17251 } 17252 17253 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17254 int userId) { 17255 Intent intent = getHomeIntent(); 17256 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17257 PackageManager.GET_META_DATA, userId); 17258 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17259 true, false, false, userId); 17260 17261 allHomeCandidates.clear(); 17262 if (list != null) { 17263 for (ResolveInfo ri : list) { 17264 allHomeCandidates.add(ri); 17265 } 17266 } 17267 return (preferred == null || preferred.activityInfo == null) 17268 ? null 17269 : new ComponentName(preferred.activityInfo.packageName, 17270 preferred.activityInfo.name); 17271 } 17272 17273 @Override 17274 public void setHomeActivity(ComponentName comp, int userId) { 17275 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17276 getHomeActivitiesAsUser(homeActivities, userId); 17277 17278 boolean found = false; 17279 17280 final int size = homeActivities.size(); 17281 final ComponentName[] set = new ComponentName[size]; 17282 for (int i = 0; i < size; i++) { 17283 final ResolveInfo candidate = homeActivities.get(i); 17284 final ActivityInfo info = candidate.activityInfo; 17285 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17286 set[i] = activityName; 17287 if (!found && activityName.equals(comp)) { 17288 found = true; 17289 } 17290 } 17291 if (!found) { 17292 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17293 + userId); 17294 } 17295 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17296 set, comp, userId); 17297 } 17298 17299 private @Nullable String getSetupWizardPackageName() { 17300 final Intent intent = new Intent(Intent.ACTION_MAIN); 17301 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17302 17303 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17304 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17305 | MATCH_DISABLED_COMPONENTS, 17306 UserHandle.myUserId()); 17307 if (matches.size() == 1) { 17308 return matches.get(0).getComponentInfo().packageName; 17309 } else { 17310 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17311 + ": matches=" + matches); 17312 return null; 17313 } 17314 } 17315 17316 @Override 17317 public void setApplicationEnabledSetting(String appPackageName, 17318 int newState, int flags, int userId, String callingPackage) { 17319 if (!sUserManager.exists(userId)) return; 17320 if (callingPackage == null) { 17321 callingPackage = Integer.toString(Binder.getCallingUid()); 17322 } 17323 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17324 } 17325 17326 @Override 17327 public void setComponentEnabledSetting(ComponentName componentName, 17328 int newState, int flags, int userId) { 17329 if (!sUserManager.exists(userId)) return; 17330 setEnabledSetting(componentName.getPackageName(), 17331 componentName.getClassName(), newState, flags, userId, null); 17332 } 17333 17334 private void setEnabledSetting(final String packageName, String className, int newState, 17335 final int flags, int userId, String callingPackage) { 17336 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17337 || newState == COMPONENT_ENABLED_STATE_ENABLED 17338 || newState == COMPONENT_ENABLED_STATE_DISABLED 17339 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17340 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17341 throw new IllegalArgumentException("Invalid new component state: " 17342 + newState); 17343 } 17344 PackageSetting pkgSetting; 17345 final int uid = Binder.getCallingUid(); 17346 final int permission; 17347 if (uid == Process.SYSTEM_UID) { 17348 permission = PackageManager.PERMISSION_GRANTED; 17349 } else { 17350 permission = mContext.checkCallingOrSelfPermission( 17351 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17352 } 17353 enforceCrossUserPermission(uid, userId, 17354 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17355 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17356 boolean sendNow = false; 17357 boolean isApp = (className == null); 17358 String componentName = isApp ? packageName : className; 17359 int packageUid = -1; 17360 ArrayList<String> components; 17361 17362 // writer 17363 synchronized (mPackages) { 17364 pkgSetting = mSettings.mPackages.get(packageName); 17365 if (pkgSetting == null) { 17366 if (className == null) { 17367 throw new IllegalArgumentException("Unknown package: " + packageName); 17368 } 17369 throw new IllegalArgumentException( 17370 "Unknown component: " + packageName + "/" + className); 17371 } 17372 // Allow root and verify that userId is not being specified by a different user 17373 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17374 throw new SecurityException( 17375 "Permission Denial: attempt to change component state from pid=" 17376 + Binder.getCallingPid() 17377 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17378 } 17379 if (className == null) { 17380 // We're dealing with an application/package level state change 17381 if (pkgSetting.getEnabled(userId) == newState) { 17382 // Nothing to do 17383 return; 17384 } 17385 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17386 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17387 // Don't care about who enables an app. 17388 callingPackage = null; 17389 } 17390 pkgSetting.setEnabled(newState, userId, callingPackage); 17391 // pkgSetting.pkg.mSetEnabled = newState; 17392 } else { 17393 // We're dealing with a component level state change 17394 // First, verify that this is a valid class name. 17395 PackageParser.Package pkg = pkgSetting.pkg; 17396 if (pkg == null || !pkg.hasComponentClassName(className)) { 17397 if (pkg != null && 17398 pkg.applicationInfo.targetSdkVersion >= 17399 Build.VERSION_CODES.JELLY_BEAN) { 17400 throw new IllegalArgumentException("Component class " + className 17401 + " does not exist in " + packageName); 17402 } else { 17403 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17404 + className + " does not exist in " + packageName); 17405 } 17406 } 17407 switch (newState) { 17408 case COMPONENT_ENABLED_STATE_ENABLED: 17409 if (!pkgSetting.enableComponentLPw(className, userId)) { 17410 return; 17411 } 17412 break; 17413 case COMPONENT_ENABLED_STATE_DISABLED: 17414 if (!pkgSetting.disableComponentLPw(className, userId)) { 17415 return; 17416 } 17417 break; 17418 case COMPONENT_ENABLED_STATE_DEFAULT: 17419 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17420 return; 17421 } 17422 break; 17423 default: 17424 Slog.e(TAG, "Invalid new component state: " + newState); 17425 return; 17426 } 17427 } 17428 scheduleWritePackageRestrictionsLocked(userId); 17429 components = mPendingBroadcasts.get(userId, packageName); 17430 final boolean newPackage = components == null; 17431 if (newPackage) { 17432 components = new ArrayList<String>(); 17433 } 17434 if (!components.contains(componentName)) { 17435 components.add(componentName); 17436 } 17437 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17438 sendNow = true; 17439 // Purge entry from pending broadcast list if another one exists already 17440 // since we are sending one right away. 17441 mPendingBroadcasts.remove(userId, packageName); 17442 } else { 17443 if (newPackage) { 17444 mPendingBroadcasts.put(userId, packageName, components); 17445 } 17446 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17447 // Schedule a message 17448 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17449 } 17450 } 17451 } 17452 17453 long callingId = Binder.clearCallingIdentity(); 17454 try { 17455 if (sendNow) { 17456 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17457 sendPackageChangedBroadcast(packageName, 17458 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17459 } 17460 } finally { 17461 Binder.restoreCallingIdentity(callingId); 17462 } 17463 } 17464 17465 @Override 17466 public void flushPackageRestrictionsAsUser(int userId) { 17467 if (!sUserManager.exists(userId)) { 17468 return; 17469 } 17470 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17471 false /* checkShell */, "flushPackageRestrictions"); 17472 synchronized (mPackages) { 17473 mSettings.writePackageRestrictionsLPr(userId); 17474 mDirtyUsers.remove(userId); 17475 if (mDirtyUsers.isEmpty()) { 17476 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17477 } 17478 } 17479 } 17480 17481 private void sendPackageChangedBroadcast(String packageName, 17482 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17483 if (DEBUG_INSTALL) 17484 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17485 + componentNames); 17486 Bundle extras = new Bundle(4); 17487 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17488 String nameList[] = new String[componentNames.size()]; 17489 componentNames.toArray(nameList); 17490 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17491 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17492 extras.putInt(Intent.EXTRA_UID, packageUid); 17493 // If this is not reporting a change of the overall package, then only send it 17494 // to registered receivers. We don't want to launch a swath of apps for every 17495 // little component state change. 17496 final int flags = !componentNames.contains(packageName) 17497 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17498 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17499 new int[] {UserHandle.getUserId(packageUid)}); 17500 } 17501 17502 @Override 17503 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17504 if (!sUserManager.exists(userId)) return; 17505 final int uid = Binder.getCallingUid(); 17506 final int permission = mContext.checkCallingOrSelfPermission( 17507 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17508 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17509 enforceCrossUserPermission(uid, userId, 17510 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17511 // writer 17512 synchronized (mPackages) { 17513 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17514 allowedByPermission, uid, userId)) { 17515 scheduleWritePackageRestrictionsLocked(userId); 17516 } 17517 } 17518 } 17519 17520 @Override 17521 public String getInstallerPackageName(String packageName) { 17522 // reader 17523 synchronized (mPackages) { 17524 return mSettings.getInstallerPackageNameLPr(packageName); 17525 } 17526 } 17527 17528 public boolean isOrphaned(String packageName) { 17529 // reader 17530 synchronized (mPackages) { 17531 return mSettings.isOrphaned(packageName); 17532 } 17533 } 17534 17535 @Override 17536 public int getApplicationEnabledSetting(String packageName, int userId) { 17537 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17538 int uid = Binder.getCallingUid(); 17539 enforceCrossUserPermission(uid, userId, 17540 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17541 // reader 17542 synchronized (mPackages) { 17543 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17544 } 17545 } 17546 17547 @Override 17548 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17549 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17550 int uid = Binder.getCallingUid(); 17551 enforceCrossUserPermission(uid, userId, 17552 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17553 // reader 17554 synchronized (mPackages) { 17555 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17556 } 17557 } 17558 17559 @Override 17560 public void enterSafeMode() { 17561 enforceSystemOrRoot("Only the system can request entering safe mode"); 17562 17563 if (!mSystemReady) { 17564 mSafeMode = true; 17565 } 17566 } 17567 17568 @Override 17569 public void systemReady() { 17570 mSystemReady = true; 17571 17572 // Read the compatibilty setting when the system is ready. 17573 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17574 mContext.getContentResolver(), 17575 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17576 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17577 if (DEBUG_SETTINGS) { 17578 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17579 } 17580 17581 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17582 17583 synchronized (mPackages) { 17584 // Verify that all of the preferred activity components actually 17585 // exist. It is possible for applications to be updated and at 17586 // that point remove a previously declared activity component that 17587 // had been set as a preferred activity. We try to clean this up 17588 // the next time we encounter that preferred activity, but it is 17589 // possible for the user flow to never be able to return to that 17590 // situation so here we do a sanity check to make sure we haven't 17591 // left any junk around. 17592 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17593 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17594 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17595 removed.clear(); 17596 for (PreferredActivity pa : pir.filterSet()) { 17597 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17598 removed.add(pa); 17599 } 17600 } 17601 if (removed.size() > 0) { 17602 for (int r=0; r<removed.size(); r++) { 17603 PreferredActivity pa = removed.get(r); 17604 Slog.w(TAG, "Removing dangling preferred activity: " 17605 + pa.mPref.mComponent); 17606 pir.removeFilter(pa); 17607 } 17608 mSettings.writePackageRestrictionsLPr( 17609 mSettings.mPreferredActivities.keyAt(i)); 17610 } 17611 } 17612 17613 for (int userId : UserManagerService.getInstance().getUserIds()) { 17614 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17615 grantPermissionsUserIds = ArrayUtils.appendInt( 17616 grantPermissionsUserIds, userId); 17617 } 17618 } 17619 } 17620 sUserManager.systemReady(); 17621 17622 // If we upgraded grant all default permissions before kicking off. 17623 for (int userId : grantPermissionsUserIds) { 17624 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17625 } 17626 17627 // Kick off any messages waiting for system ready 17628 if (mPostSystemReadyMessages != null) { 17629 for (Message msg : mPostSystemReadyMessages) { 17630 msg.sendToTarget(); 17631 } 17632 mPostSystemReadyMessages = null; 17633 } 17634 17635 // Watch for external volumes that come and go over time 17636 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17637 storage.registerListener(mStorageListener); 17638 17639 mInstallerService.systemReady(); 17640 mPackageDexOptimizer.systemReady(); 17641 17642 MountServiceInternal mountServiceInternal = LocalServices.getService( 17643 MountServiceInternal.class); 17644 mountServiceInternal.addExternalStoragePolicy( 17645 new MountServiceInternal.ExternalStorageMountPolicy() { 17646 @Override 17647 public int getMountMode(int uid, String packageName) { 17648 if (Process.isIsolated(uid)) { 17649 return Zygote.MOUNT_EXTERNAL_NONE; 17650 } 17651 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17652 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17653 } 17654 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17655 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17656 } 17657 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17658 return Zygote.MOUNT_EXTERNAL_READ; 17659 } 17660 return Zygote.MOUNT_EXTERNAL_WRITE; 17661 } 17662 17663 @Override 17664 public boolean hasExternalStorage(int uid, String packageName) { 17665 return true; 17666 } 17667 }); 17668 17669 // Now that we're mostly running, clean up stale users and apps 17670 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17671 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17672 } 17673 17674 @Override 17675 public boolean isSafeMode() { 17676 return mSafeMode; 17677 } 17678 17679 @Override 17680 public boolean hasSystemUidErrors() { 17681 return mHasSystemUidErrors; 17682 } 17683 17684 static String arrayToString(int[] array) { 17685 StringBuffer buf = new StringBuffer(128); 17686 buf.append('['); 17687 if (array != null) { 17688 for (int i=0; i<array.length; i++) { 17689 if (i > 0) buf.append(", "); 17690 buf.append(array[i]); 17691 } 17692 } 17693 buf.append(']'); 17694 return buf.toString(); 17695 } 17696 17697 static class DumpState { 17698 public static final int DUMP_LIBS = 1 << 0; 17699 public static final int DUMP_FEATURES = 1 << 1; 17700 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17701 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17702 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17703 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17704 public static final int DUMP_PERMISSIONS = 1 << 6; 17705 public static final int DUMP_PACKAGES = 1 << 7; 17706 public static final int DUMP_SHARED_USERS = 1 << 8; 17707 public static final int DUMP_MESSAGES = 1 << 9; 17708 public static final int DUMP_PROVIDERS = 1 << 10; 17709 public static final int DUMP_VERIFIERS = 1 << 11; 17710 public static final int DUMP_PREFERRED = 1 << 12; 17711 public static final int DUMP_PREFERRED_XML = 1 << 13; 17712 public static final int DUMP_KEYSETS = 1 << 14; 17713 public static final int DUMP_VERSION = 1 << 15; 17714 public static final int DUMP_INSTALLS = 1 << 16; 17715 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17716 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17717 public static final int DUMP_FROZEN = 1 << 19; 17718 17719 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17720 17721 private int mTypes; 17722 17723 private int mOptions; 17724 17725 private boolean mTitlePrinted; 17726 17727 private SharedUserSetting mSharedUser; 17728 17729 public boolean isDumping(int type) { 17730 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17731 return true; 17732 } 17733 17734 return (mTypes & type) != 0; 17735 } 17736 17737 public void setDump(int type) { 17738 mTypes |= type; 17739 } 17740 17741 public boolean isOptionEnabled(int option) { 17742 return (mOptions & option) != 0; 17743 } 17744 17745 public void setOptionEnabled(int option) { 17746 mOptions |= option; 17747 } 17748 17749 public boolean onTitlePrinted() { 17750 final boolean printed = mTitlePrinted; 17751 mTitlePrinted = true; 17752 return printed; 17753 } 17754 17755 public boolean getTitlePrinted() { 17756 return mTitlePrinted; 17757 } 17758 17759 public void setTitlePrinted(boolean enabled) { 17760 mTitlePrinted = enabled; 17761 } 17762 17763 public SharedUserSetting getSharedUser() { 17764 return mSharedUser; 17765 } 17766 17767 public void setSharedUser(SharedUserSetting user) { 17768 mSharedUser = user; 17769 } 17770 } 17771 17772 @Override 17773 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17774 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17775 (new PackageManagerShellCommand(this)).exec( 17776 this, in, out, err, args, resultReceiver); 17777 } 17778 17779 @Override 17780 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17781 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17782 != PackageManager.PERMISSION_GRANTED) { 17783 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17784 + Binder.getCallingPid() 17785 + ", uid=" + Binder.getCallingUid() 17786 + " without permission " 17787 + android.Manifest.permission.DUMP); 17788 return; 17789 } 17790 17791 DumpState dumpState = new DumpState(); 17792 boolean fullPreferred = false; 17793 boolean checkin = false; 17794 17795 String packageName = null; 17796 ArraySet<String> permissionNames = null; 17797 17798 int opti = 0; 17799 while (opti < args.length) { 17800 String opt = args[opti]; 17801 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17802 break; 17803 } 17804 opti++; 17805 17806 if ("-a".equals(opt)) { 17807 // Right now we only know how to print all. 17808 } else if ("-h".equals(opt)) { 17809 pw.println("Package manager dump options:"); 17810 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17811 pw.println(" --checkin: dump for a checkin"); 17812 pw.println(" -f: print details of intent filters"); 17813 pw.println(" -h: print this help"); 17814 pw.println(" cmd may be one of:"); 17815 pw.println(" l[ibraries]: list known shared libraries"); 17816 pw.println(" f[eatures]: list device features"); 17817 pw.println(" k[eysets]: print known keysets"); 17818 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17819 pw.println(" perm[issions]: dump permissions"); 17820 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17821 pw.println(" pref[erred]: print preferred package settings"); 17822 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17823 pw.println(" prov[iders]: dump content providers"); 17824 pw.println(" p[ackages]: dump installed packages"); 17825 pw.println(" s[hared-users]: dump shared user IDs"); 17826 pw.println(" m[essages]: print collected runtime messages"); 17827 pw.println(" v[erifiers]: print package verifier info"); 17828 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17829 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17830 pw.println(" version: print database version info"); 17831 pw.println(" write: write current settings now"); 17832 pw.println(" installs: details about install sessions"); 17833 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17834 pw.println(" <package.name>: info about given package"); 17835 return; 17836 } else if ("--checkin".equals(opt)) { 17837 checkin = true; 17838 } else if ("-f".equals(opt)) { 17839 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17840 } else { 17841 pw.println("Unknown argument: " + opt + "; use -h for help"); 17842 } 17843 } 17844 17845 // Is the caller requesting to dump a particular piece of data? 17846 if (opti < args.length) { 17847 String cmd = args[opti]; 17848 opti++; 17849 // Is this a package name? 17850 if ("android".equals(cmd) || cmd.contains(".")) { 17851 packageName = cmd; 17852 // When dumping a single package, we always dump all of its 17853 // filter information since the amount of data will be reasonable. 17854 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17855 } else if ("check-permission".equals(cmd)) { 17856 if (opti >= args.length) { 17857 pw.println("Error: check-permission missing permission argument"); 17858 return; 17859 } 17860 String perm = args[opti]; 17861 opti++; 17862 if (opti >= args.length) { 17863 pw.println("Error: check-permission missing package argument"); 17864 return; 17865 } 17866 String pkg = args[opti]; 17867 opti++; 17868 int user = UserHandle.getUserId(Binder.getCallingUid()); 17869 if (opti < args.length) { 17870 try { 17871 user = Integer.parseInt(args[opti]); 17872 } catch (NumberFormatException e) { 17873 pw.println("Error: check-permission user argument is not a number: " 17874 + args[opti]); 17875 return; 17876 } 17877 } 17878 pw.println(checkPermission(perm, pkg, user)); 17879 return; 17880 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17881 dumpState.setDump(DumpState.DUMP_LIBS); 17882 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17883 dumpState.setDump(DumpState.DUMP_FEATURES); 17884 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17885 if (opti >= args.length) { 17886 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17887 | DumpState.DUMP_SERVICE_RESOLVERS 17888 | DumpState.DUMP_RECEIVER_RESOLVERS 17889 | DumpState.DUMP_CONTENT_RESOLVERS); 17890 } else { 17891 while (opti < args.length) { 17892 String name = args[opti]; 17893 if ("a".equals(name) || "activity".equals(name)) { 17894 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17895 } else if ("s".equals(name) || "service".equals(name)) { 17896 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17897 } else if ("r".equals(name) || "receiver".equals(name)) { 17898 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17899 } else if ("c".equals(name) || "content".equals(name)) { 17900 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17901 } else { 17902 pw.println("Error: unknown resolver table type: " + name); 17903 return; 17904 } 17905 opti++; 17906 } 17907 } 17908 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17909 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17910 } else if ("permission".equals(cmd)) { 17911 if (opti >= args.length) { 17912 pw.println("Error: permission requires permission name"); 17913 return; 17914 } 17915 permissionNames = new ArraySet<>(); 17916 while (opti < args.length) { 17917 permissionNames.add(args[opti]); 17918 opti++; 17919 } 17920 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17921 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17922 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17923 dumpState.setDump(DumpState.DUMP_PREFERRED); 17924 } else if ("preferred-xml".equals(cmd)) { 17925 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17926 if (opti < args.length && "--full".equals(args[opti])) { 17927 fullPreferred = true; 17928 opti++; 17929 } 17930 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17931 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17932 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17933 dumpState.setDump(DumpState.DUMP_PACKAGES); 17934 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17935 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17936 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17937 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17938 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17939 dumpState.setDump(DumpState.DUMP_MESSAGES); 17940 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17941 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17942 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17943 || "intent-filter-verifiers".equals(cmd)) { 17944 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17945 } else if ("version".equals(cmd)) { 17946 dumpState.setDump(DumpState.DUMP_VERSION); 17947 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17948 dumpState.setDump(DumpState.DUMP_KEYSETS); 17949 } else if ("installs".equals(cmd)) { 17950 dumpState.setDump(DumpState.DUMP_INSTALLS); 17951 } else if ("frozen".equals(cmd)) { 17952 dumpState.setDump(DumpState.DUMP_FROZEN); 17953 } else if ("write".equals(cmd)) { 17954 synchronized (mPackages) { 17955 mSettings.writeLPr(); 17956 pw.println("Settings written."); 17957 return; 17958 } 17959 } 17960 } 17961 17962 if (checkin) { 17963 pw.println("vers,1"); 17964 } 17965 17966 // reader 17967 synchronized (mPackages) { 17968 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17969 if (!checkin) { 17970 if (dumpState.onTitlePrinted()) 17971 pw.println(); 17972 pw.println("Database versions:"); 17973 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17974 } 17975 } 17976 17977 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17978 if (!checkin) { 17979 if (dumpState.onTitlePrinted()) 17980 pw.println(); 17981 pw.println("Verifiers:"); 17982 pw.print(" Required: "); 17983 pw.print(mRequiredVerifierPackage); 17984 pw.print(" (uid="); 17985 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17986 UserHandle.USER_SYSTEM)); 17987 pw.println(")"); 17988 } else if (mRequiredVerifierPackage != null) { 17989 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17990 pw.print(","); 17991 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17992 UserHandle.USER_SYSTEM)); 17993 } 17994 } 17995 17996 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17997 packageName == null) { 17998 if (mIntentFilterVerifierComponent != null) { 17999 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18000 if (!checkin) { 18001 if (dumpState.onTitlePrinted()) 18002 pw.println(); 18003 pw.println("Intent Filter Verifier:"); 18004 pw.print(" Using: "); 18005 pw.print(verifierPackageName); 18006 pw.print(" (uid="); 18007 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18008 UserHandle.USER_SYSTEM)); 18009 pw.println(")"); 18010 } else if (verifierPackageName != null) { 18011 pw.print("ifv,"); pw.print(verifierPackageName); 18012 pw.print(","); 18013 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18014 UserHandle.USER_SYSTEM)); 18015 } 18016 } else { 18017 pw.println(); 18018 pw.println("No Intent Filter Verifier available!"); 18019 } 18020 } 18021 18022 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18023 boolean printedHeader = false; 18024 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18025 while (it.hasNext()) { 18026 String name = it.next(); 18027 SharedLibraryEntry ent = mSharedLibraries.get(name); 18028 if (!checkin) { 18029 if (!printedHeader) { 18030 if (dumpState.onTitlePrinted()) 18031 pw.println(); 18032 pw.println("Libraries:"); 18033 printedHeader = true; 18034 } 18035 pw.print(" "); 18036 } else { 18037 pw.print("lib,"); 18038 } 18039 pw.print(name); 18040 if (!checkin) { 18041 pw.print(" -> "); 18042 } 18043 if (ent.path != null) { 18044 if (!checkin) { 18045 pw.print("(jar) "); 18046 pw.print(ent.path); 18047 } else { 18048 pw.print(",jar,"); 18049 pw.print(ent.path); 18050 } 18051 } else { 18052 if (!checkin) { 18053 pw.print("(apk) "); 18054 pw.print(ent.apk); 18055 } else { 18056 pw.print(",apk,"); 18057 pw.print(ent.apk); 18058 } 18059 } 18060 pw.println(); 18061 } 18062 } 18063 18064 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18065 if (dumpState.onTitlePrinted()) 18066 pw.println(); 18067 if (!checkin) { 18068 pw.println("Features:"); 18069 } 18070 18071 for (FeatureInfo feat : mAvailableFeatures.values()) { 18072 if (checkin) { 18073 pw.print("feat,"); 18074 pw.print(feat.name); 18075 pw.print(","); 18076 pw.println(feat.version); 18077 } else { 18078 pw.print(" "); 18079 pw.print(feat.name); 18080 if (feat.version > 0) { 18081 pw.print(" version="); 18082 pw.print(feat.version); 18083 } 18084 pw.println(); 18085 } 18086 } 18087 } 18088 18089 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18090 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18091 : "Activity Resolver Table:", " ", packageName, 18092 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18093 dumpState.setTitlePrinted(true); 18094 } 18095 } 18096 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18097 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18098 : "Receiver Resolver Table:", " ", packageName, 18099 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18100 dumpState.setTitlePrinted(true); 18101 } 18102 } 18103 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18104 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18105 : "Service Resolver Table:", " ", packageName, 18106 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18107 dumpState.setTitlePrinted(true); 18108 } 18109 } 18110 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18111 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18112 : "Provider Resolver Table:", " ", packageName, 18113 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18114 dumpState.setTitlePrinted(true); 18115 } 18116 } 18117 18118 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18119 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18120 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18121 int user = mSettings.mPreferredActivities.keyAt(i); 18122 if (pir.dump(pw, 18123 dumpState.getTitlePrinted() 18124 ? "\nPreferred Activities User " + user + ":" 18125 : "Preferred Activities User " + user + ":", " ", 18126 packageName, true, false)) { 18127 dumpState.setTitlePrinted(true); 18128 } 18129 } 18130 } 18131 18132 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18133 pw.flush(); 18134 FileOutputStream fout = new FileOutputStream(fd); 18135 BufferedOutputStream str = new BufferedOutputStream(fout); 18136 XmlSerializer serializer = new FastXmlSerializer(); 18137 try { 18138 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18139 serializer.startDocument(null, true); 18140 serializer.setFeature( 18141 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18142 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18143 serializer.endDocument(); 18144 serializer.flush(); 18145 } catch (IllegalArgumentException e) { 18146 pw.println("Failed writing: " + e); 18147 } catch (IllegalStateException e) { 18148 pw.println("Failed writing: " + e); 18149 } catch (IOException e) { 18150 pw.println("Failed writing: " + e); 18151 } 18152 } 18153 18154 if (!checkin 18155 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18156 && packageName == null) { 18157 pw.println(); 18158 int count = mSettings.mPackages.size(); 18159 if (count == 0) { 18160 pw.println("No applications!"); 18161 pw.println(); 18162 } else { 18163 final String prefix = " "; 18164 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18165 if (allPackageSettings.size() == 0) { 18166 pw.println("No domain preferred apps!"); 18167 pw.println(); 18168 } else { 18169 pw.println("App verification status:"); 18170 pw.println(); 18171 count = 0; 18172 for (PackageSetting ps : allPackageSettings) { 18173 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18174 if (ivi == null || ivi.getPackageName() == null) continue; 18175 pw.println(prefix + "Package: " + ivi.getPackageName()); 18176 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18177 pw.println(prefix + "Status: " + ivi.getStatusString()); 18178 pw.println(); 18179 count++; 18180 } 18181 if (count == 0) { 18182 pw.println(prefix + "No app verification established."); 18183 pw.println(); 18184 } 18185 for (int userId : sUserManager.getUserIds()) { 18186 pw.println("App linkages for user " + userId + ":"); 18187 pw.println(); 18188 count = 0; 18189 for (PackageSetting ps : allPackageSettings) { 18190 final long status = ps.getDomainVerificationStatusForUser(userId); 18191 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18192 continue; 18193 } 18194 pw.println(prefix + "Package: " + ps.name); 18195 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18196 String statusStr = IntentFilterVerificationInfo. 18197 getStatusStringFromValue(status); 18198 pw.println(prefix + "Status: " + statusStr); 18199 pw.println(); 18200 count++; 18201 } 18202 if (count == 0) { 18203 pw.println(prefix + "No configured app linkages."); 18204 pw.println(); 18205 } 18206 } 18207 } 18208 } 18209 } 18210 18211 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18212 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18213 if (packageName == null && permissionNames == null) { 18214 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18215 if (iperm == 0) { 18216 if (dumpState.onTitlePrinted()) 18217 pw.println(); 18218 pw.println("AppOp Permissions:"); 18219 } 18220 pw.print(" AppOp Permission "); 18221 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18222 pw.println(":"); 18223 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18224 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18225 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18226 } 18227 } 18228 } 18229 } 18230 18231 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18232 boolean printedSomething = false; 18233 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18234 if (packageName != null && !packageName.equals(p.info.packageName)) { 18235 continue; 18236 } 18237 if (!printedSomething) { 18238 if (dumpState.onTitlePrinted()) 18239 pw.println(); 18240 pw.println("Registered ContentProviders:"); 18241 printedSomething = true; 18242 } 18243 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18244 pw.print(" "); pw.println(p.toString()); 18245 } 18246 printedSomething = false; 18247 for (Map.Entry<String, PackageParser.Provider> entry : 18248 mProvidersByAuthority.entrySet()) { 18249 PackageParser.Provider p = entry.getValue(); 18250 if (packageName != null && !packageName.equals(p.info.packageName)) { 18251 continue; 18252 } 18253 if (!printedSomething) { 18254 if (dumpState.onTitlePrinted()) 18255 pw.println(); 18256 pw.println("ContentProvider Authorities:"); 18257 printedSomething = true; 18258 } 18259 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18260 pw.print(" "); pw.println(p.toString()); 18261 if (p.info != null && p.info.applicationInfo != null) { 18262 final String appInfo = p.info.applicationInfo.toString(); 18263 pw.print(" applicationInfo="); pw.println(appInfo); 18264 } 18265 } 18266 } 18267 18268 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18269 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18270 } 18271 18272 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18273 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18274 } 18275 18276 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18277 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18278 } 18279 18280 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18281 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18282 } 18283 18284 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18285 // XXX should handle packageName != null by dumping only install data that 18286 // the given package is involved with. 18287 if (dumpState.onTitlePrinted()) pw.println(); 18288 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18289 } 18290 18291 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18292 // XXX should handle packageName != null by dumping only install data that 18293 // the given package is involved with. 18294 if (dumpState.onTitlePrinted()) pw.println(); 18295 18296 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18297 ipw.println(); 18298 ipw.println("Frozen packages:"); 18299 ipw.increaseIndent(); 18300 if (mFrozenPackages.size() == 0) { 18301 ipw.println("(none)"); 18302 } else { 18303 for (int i = 0; i < mFrozenPackages.size(); i++) { 18304 ipw.println(mFrozenPackages.valueAt(i)); 18305 } 18306 } 18307 ipw.decreaseIndent(); 18308 } 18309 18310 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18311 if (dumpState.onTitlePrinted()) pw.println(); 18312 mSettings.dumpReadMessagesLPr(pw, dumpState); 18313 18314 pw.println(); 18315 pw.println("Package warning messages:"); 18316 BufferedReader in = null; 18317 String line = null; 18318 try { 18319 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18320 while ((line = in.readLine()) != null) { 18321 if (line.contains("ignored: updated version")) continue; 18322 pw.println(line); 18323 } 18324 } catch (IOException ignored) { 18325 } finally { 18326 IoUtils.closeQuietly(in); 18327 } 18328 } 18329 18330 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18331 BufferedReader in = null; 18332 String line = null; 18333 try { 18334 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18335 while ((line = in.readLine()) != null) { 18336 if (line.contains("ignored: updated version")) continue; 18337 pw.print("msg,"); 18338 pw.println(line); 18339 } 18340 } catch (IOException ignored) { 18341 } finally { 18342 IoUtils.closeQuietly(in); 18343 } 18344 } 18345 } 18346 } 18347 18348 private String dumpDomainString(String packageName) { 18349 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18350 .getList(); 18351 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18352 18353 ArraySet<String> result = new ArraySet<>(); 18354 if (iviList.size() > 0) { 18355 for (IntentFilterVerificationInfo ivi : iviList) { 18356 for (String host : ivi.getDomains()) { 18357 result.add(host); 18358 } 18359 } 18360 } 18361 if (filters != null && filters.size() > 0) { 18362 for (IntentFilter filter : filters) { 18363 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18364 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18365 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18366 result.addAll(filter.getHostsList()); 18367 } 18368 } 18369 } 18370 18371 StringBuilder sb = new StringBuilder(result.size() * 16); 18372 for (String domain : result) { 18373 if (sb.length() > 0) sb.append(" "); 18374 sb.append(domain); 18375 } 18376 return sb.toString(); 18377 } 18378 18379 // ------- apps on sdcard specific code ------- 18380 static final boolean DEBUG_SD_INSTALL = false; 18381 18382 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18383 18384 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18385 18386 private boolean mMediaMounted = false; 18387 18388 static String getEncryptKey() { 18389 try { 18390 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18391 SD_ENCRYPTION_KEYSTORE_NAME); 18392 if (sdEncKey == null) { 18393 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18394 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18395 if (sdEncKey == null) { 18396 Slog.e(TAG, "Failed to create encryption keys"); 18397 return null; 18398 } 18399 } 18400 return sdEncKey; 18401 } catch (NoSuchAlgorithmException nsae) { 18402 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18403 return null; 18404 } catch (IOException ioe) { 18405 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18406 return null; 18407 } 18408 } 18409 18410 /* 18411 * Update media status on PackageManager. 18412 */ 18413 @Override 18414 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18415 int callingUid = Binder.getCallingUid(); 18416 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18417 throw new SecurityException("Media status can only be updated by the system"); 18418 } 18419 // reader; this apparently protects mMediaMounted, but should probably 18420 // be a different lock in that case. 18421 synchronized (mPackages) { 18422 Log.i(TAG, "Updating external media status from " 18423 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18424 + (mediaStatus ? "mounted" : "unmounted")); 18425 if (DEBUG_SD_INSTALL) 18426 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18427 + ", mMediaMounted=" + mMediaMounted); 18428 if (mediaStatus == mMediaMounted) { 18429 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18430 : 0, -1); 18431 mHandler.sendMessage(msg); 18432 return; 18433 } 18434 mMediaMounted = mediaStatus; 18435 } 18436 // Queue up an async operation since the package installation may take a 18437 // little while. 18438 mHandler.post(new Runnable() { 18439 public void run() { 18440 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18441 } 18442 }); 18443 } 18444 18445 /** 18446 * Called by MountService when the initial ASECs to scan are available. 18447 * Should block until all the ASEC containers are finished being scanned. 18448 */ 18449 public void scanAvailableAsecs() { 18450 updateExternalMediaStatusInner(true, false, false); 18451 } 18452 18453 /* 18454 * Collect information of applications on external media, map them against 18455 * existing containers and update information based on current mount status. 18456 * Please note that we always have to report status if reportStatus has been 18457 * set to true especially when unloading packages. 18458 */ 18459 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18460 boolean externalStorage) { 18461 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18462 int[] uidArr = EmptyArray.INT; 18463 18464 final String[] list = PackageHelper.getSecureContainerList(); 18465 if (ArrayUtils.isEmpty(list)) { 18466 Log.i(TAG, "No secure containers found"); 18467 } else { 18468 // Process list of secure containers and categorize them 18469 // as active or stale based on their package internal state. 18470 18471 // reader 18472 synchronized (mPackages) { 18473 for (String cid : list) { 18474 // Leave stages untouched for now; installer service owns them 18475 if (PackageInstallerService.isStageName(cid)) continue; 18476 18477 if (DEBUG_SD_INSTALL) 18478 Log.i(TAG, "Processing container " + cid); 18479 String pkgName = getAsecPackageName(cid); 18480 if (pkgName == null) { 18481 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18482 continue; 18483 } 18484 if (DEBUG_SD_INSTALL) 18485 Log.i(TAG, "Looking for pkg : " + pkgName); 18486 18487 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18488 if (ps == null) { 18489 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18490 continue; 18491 } 18492 18493 /* 18494 * Skip packages that are not external if we're unmounting 18495 * external storage. 18496 */ 18497 if (externalStorage && !isMounted && !isExternal(ps)) { 18498 continue; 18499 } 18500 18501 final AsecInstallArgs args = new AsecInstallArgs(cid, 18502 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18503 // The package status is changed only if the code path 18504 // matches between settings and the container id. 18505 if (ps.codePathString != null 18506 && ps.codePathString.startsWith(args.getCodePath())) { 18507 if (DEBUG_SD_INSTALL) { 18508 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18509 + " at code path: " + ps.codePathString); 18510 } 18511 18512 // We do have a valid package installed on sdcard 18513 processCids.put(args, ps.codePathString); 18514 final int uid = ps.appId; 18515 if (uid != -1) { 18516 uidArr = ArrayUtils.appendInt(uidArr, uid); 18517 } 18518 } else { 18519 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18520 + ps.codePathString); 18521 } 18522 } 18523 } 18524 18525 Arrays.sort(uidArr); 18526 } 18527 18528 // Process packages with valid entries. 18529 if (isMounted) { 18530 if (DEBUG_SD_INSTALL) 18531 Log.i(TAG, "Loading packages"); 18532 loadMediaPackages(processCids, uidArr, externalStorage); 18533 startCleaningPackages(); 18534 mInstallerService.onSecureContainersAvailable(); 18535 } else { 18536 if (DEBUG_SD_INSTALL) 18537 Log.i(TAG, "Unloading packages"); 18538 unloadMediaPackages(processCids, uidArr, reportStatus); 18539 } 18540 } 18541 18542 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18543 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18544 final int size = infos.size(); 18545 final String[] packageNames = new String[size]; 18546 final int[] packageUids = new int[size]; 18547 for (int i = 0; i < size; i++) { 18548 final ApplicationInfo info = infos.get(i); 18549 packageNames[i] = info.packageName; 18550 packageUids[i] = info.uid; 18551 } 18552 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18553 finishedReceiver); 18554 } 18555 18556 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18557 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18558 sendResourcesChangedBroadcast(mediaStatus, replacing, 18559 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18560 } 18561 18562 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18563 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18564 int size = pkgList.length; 18565 if (size > 0) { 18566 // Send broadcasts here 18567 Bundle extras = new Bundle(); 18568 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18569 if (uidArr != null) { 18570 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18571 } 18572 if (replacing) { 18573 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18574 } 18575 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18576 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18577 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18578 } 18579 } 18580 18581 /* 18582 * Look at potentially valid container ids from processCids If package 18583 * information doesn't match the one on record or package scanning fails, 18584 * the cid is added to list of removeCids. We currently don't delete stale 18585 * containers. 18586 */ 18587 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18588 boolean externalStorage) { 18589 ArrayList<String> pkgList = new ArrayList<String>(); 18590 Set<AsecInstallArgs> keys = processCids.keySet(); 18591 18592 for (AsecInstallArgs args : keys) { 18593 String codePath = processCids.get(args); 18594 if (DEBUG_SD_INSTALL) 18595 Log.i(TAG, "Loading container : " + args.cid); 18596 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18597 try { 18598 // Make sure there are no container errors first. 18599 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18600 Slog.e(TAG, "Failed to mount cid : " + args.cid 18601 + " when installing from sdcard"); 18602 continue; 18603 } 18604 // Check code path here. 18605 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18606 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18607 + " does not match one in settings " + codePath); 18608 continue; 18609 } 18610 // Parse package 18611 int parseFlags = mDefParseFlags; 18612 if (args.isExternalAsec()) { 18613 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18614 } 18615 if (args.isFwdLocked()) { 18616 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18617 } 18618 18619 synchronized (mInstallLock) { 18620 PackageParser.Package pkg = null; 18621 try { 18622 // Sadly we don't know the package name yet to freeze it 18623 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18624 SCAN_IGNORE_FROZEN, 0, null); 18625 } catch (PackageManagerException e) { 18626 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18627 } 18628 // Scan the package 18629 if (pkg != null) { 18630 /* 18631 * TODO why is the lock being held? doPostInstall is 18632 * called in other places without the lock. This needs 18633 * to be straightened out. 18634 */ 18635 // writer 18636 synchronized (mPackages) { 18637 retCode = PackageManager.INSTALL_SUCCEEDED; 18638 pkgList.add(pkg.packageName); 18639 // Post process args 18640 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18641 pkg.applicationInfo.uid); 18642 } 18643 } else { 18644 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18645 } 18646 } 18647 18648 } finally { 18649 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18650 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18651 } 18652 } 18653 } 18654 // writer 18655 synchronized (mPackages) { 18656 // If the platform SDK has changed since the last time we booted, 18657 // we need to re-grant app permission to catch any new ones that 18658 // appear. This is really a hack, and means that apps can in some 18659 // cases get permissions that the user didn't initially explicitly 18660 // allow... it would be nice to have some better way to handle 18661 // this situation. 18662 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18663 : mSettings.getInternalVersion(); 18664 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18665 : StorageManager.UUID_PRIVATE_INTERNAL; 18666 18667 int updateFlags = UPDATE_PERMISSIONS_ALL; 18668 if (ver.sdkVersion != mSdkVersion) { 18669 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18670 + mSdkVersion + "; regranting permissions for external"); 18671 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18672 } 18673 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18674 18675 // Yay, everything is now upgraded 18676 ver.forceCurrent(); 18677 18678 // can downgrade to reader 18679 // Persist settings 18680 mSettings.writeLPr(); 18681 } 18682 // Send a broadcast to let everyone know we are done processing 18683 if (pkgList.size() > 0) { 18684 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18685 } 18686 } 18687 18688 /* 18689 * Utility method to unload a list of specified containers 18690 */ 18691 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18692 // Just unmount all valid containers. 18693 for (AsecInstallArgs arg : cidArgs) { 18694 synchronized (mInstallLock) { 18695 arg.doPostDeleteLI(false); 18696 } 18697 } 18698 } 18699 18700 /* 18701 * Unload packages mounted on external media. This involves deleting package 18702 * data from internal structures, sending broadcasts about disabled packages, 18703 * gc'ing to free up references, unmounting all secure containers 18704 * corresponding to packages on external media, and posting a 18705 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18706 * that we always have to post this message if status has been requested no 18707 * matter what. 18708 */ 18709 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18710 final boolean reportStatus) { 18711 if (DEBUG_SD_INSTALL) 18712 Log.i(TAG, "unloading media packages"); 18713 ArrayList<String> pkgList = new ArrayList<String>(); 18714 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18715 final Set<AsecInstallArgs> keys = processCids.keySet(); 18716 for (AsecInstallArgs args : keys) { 18717 String pkgName = args.getPackageName(); 18718 if (DEBUG_SD_INSTALL) 18719 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18720 // Delete package internally 18721 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18722 synchronized (mInstallLock) { 18723 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18724 final boolean res; 18725 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18726 "unloadMediaPackages")) { 18727 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18728 null); 18729 } 18730 if (res) { 18731 pkgList.add(pkgName); 18732 } else { 18733 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18734 failedList.add(args); 18735 } 18736 } 18737 } 18738 18739 // reader 18740 synchronized (mPackages) { 18741 // We didn't update the settings after removing each package; 18742 // write them now for all packages. 18743 mSettings.writeLPr(); 18744 } 18745 18746 // We have to absolutely send UPDATED_MEDIA_STATUS only 18747 // after confirming that all the receivers processed the ordered 18748 // broadcast when packages get disabled, force a gc to clean things up. 18749 // and unload all the containers. 18750 if (pkgList.size() > 0) { 18751 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18752 new IIntentReceiver.Stub() { 18753 public void performReceive(Intent intent, int resultCode, String data, 18754 Bundle extras, boolean ordered, boolean sticky, 18755 int sendingUser) throws RemoteException { 18756 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18757 reportStatus ? 1 : 0, 1, keys); 18758 mHandler.sendMessage(msg); 18759 } 18760 }); 18761 } else { 18762 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18763 keys); 18764 mHandler.sendMessage(msg); 18765 } 18766 } 18767 18768 private void loadPrivatePackages(final VolumeInfo vol) { 18769 mHandler.post(new Runnable() { 18770 @Override 18771 public void run() { 18772 loadPrivatePackagesInner(vol); 18773 } 18774 }); 18775 } 18776 18777 private void loadPrivatePackagesInner(VolumeInfo vol) { 18778 final String volumeUuid = vol.fsUuid; 18779 if (TextUtils.isEmpty(volumeUuid)) { 18780 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18781 return; 18782 } 18783 18784 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18785 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18786 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18787 18788 final VersionInfo ver; 18789 final List<PackageSetting> packages; 18790 synchronized (mPackages) { 18791 ver = mSettings.findOrCreateVersion(volumeUuid); 18792 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18793 } 18794 18795 for (PackageSetting ps : packages) { 18796 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18797 synchronized (mInstallLock) { 18798 final PackageParser.Package pkg; 18799 try { 18800 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18801 loaded.add(pkg.applicationInfo); 18802 18803 } catch (PackageManagerException e) { 18804 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18805 } 18806 18807 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18808 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18809 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18810 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18811 } 18812 } 18813 } 18814 18815 // Reconcile app data for all started/unlocked users 18816 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18817 final UserManager um = mContext.getSystemService(UserManager.class); 18818 for (UserInfo user : um.getUsers()) { 18819 final int flags; 18820 if (um.isUserUnlockingOrUnlocked(user.id)) { 18821 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18822 } else if (um.isUserRunning(user.id)) { 18823 flags = StorageManager.FLAG_STORAGE_DE; 18824 } else { 18825 continue; 18826 } 18827 18828 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18829 synchronized (mInstallLock) { 18830 reconcileAppsDataLI(volumeUuid, user.id, flags); 18831 } 18832 } 18833 18834 synchronized (mPackages) { 18835 int updateFlags = UPDATE_PERMISSIONS_ALL; 18836 if (ver.sdkVersion != mSdkVersion) { 18837 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18838 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18839 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18840 } 18841 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18842 18843 // Yay, everything is now upgraded 18844 ver.forceCurrent(); 18845 18846 mSettings.writeLPr(); 18847 } 18848 18849 for (PackageFreezer freezer : freezers) { 18850 freezer.close(); 18851 } 18852 18853 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18854 sendResourcesChangedBroadcast(true, false, loaded, null); 18855 } 18856 18857 private void unloadPrivatePackages(final VolumeInfo vol) { 18858 mHandler.post(new Runnable() { 18859 @Override 18860 public void run() { 18861 unloadPrivatePackagesInner(vol); 18862 } 18863 }); 18864 } 18865 18866 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18867 final String volumeUuid = vol.fsUuid; 18868 if (TextUtils.isEmpty(volumeUuid)) { 18869 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18870 return; 18871 } 18872 18873 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18874 synchronized (mInstallLock) { 18875 synchronized (mPackages) { 18876 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18877 for (PackageSetting ps : packages) { 18878 if (ps.pkg == null) continue; 18879 18880 final ApplicationInfo info = ps.pkg.applicationInfo; 18881 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18882 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18883 18884 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18885 "unloadPrivatePackagesInner")) { 18886 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18887 false, null)) { 18888 unloaded.add(info); 18889 } else { 18890 Slog.w(TAG, "Failed to unload " + ps.codePath); 18891 } 18892 } 18893 } 18894 18895 mSettings.writeLPr(); 18896 } 18897 } 18898 18899 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18900 sendResourcesChangedBroadcast(false, false, unloaded, null); 18901 } 18902 18903 /** 18904 * Prepare storage areas for given user on all mounted devices. 18905 */ 18906 void prepareUserData(int userId, int userSerial, int flags) { 18907 synchronized (mInstallLock) { 18908 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18909 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18910 final String volumeUuid = vol.getFsUuid(); 18911 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18912 } 18913 } 18914 } 18915 18916 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18917 boolean allowRecover) { 18918 // Prepare storage and verify that serial numbers are consistent; if 18919 // there's a mismatch we need to destroy to avoid leaking data 18920 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18921 try { 18922 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18923 18924 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18925 UserManagerService.enforceSerialNumber( 18926 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18927 } 18928 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18929 UserManagerService.enforceSerialNumber( 18930 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18931 } 18932 18933 synchronized (mInstallLock) { 18934 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18935 } 18936 } catch (Exception e) { 18937 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18938 + " because we failed to prepare: " + e); 18939 destroyUserDataLI(volumeUuid, userId, 18940 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18941 18942 if (allowRecover) { 18943 // Try one last time; if we fail again we're really in trouble 18944 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18945 } 18946 } 18947 } 18948 18949 /** 18950 * Destroy storage areas for given user on all mounted devices. 18951 */ 18952 void destroyUserData(int userId, int flags) { 18953 synchronized (mInstallLock) { 18954 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18955 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18956 final String volumeUuid = vol.getFsUuid(); 18957 destroyUserDataLI(volumeUuid, userId, flags); 18958 } 18959 } 18960 } 18961 18962 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18963 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18964 try { 18965 // Clean up app data, profile data, and media data 18966 mInstaller.destroyUserData(volumeUuid, userId, flags); 18967 18968 // Clean up system data 18969 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18970 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18971 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18972 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18973 } 18974 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18975 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18976 } 18977 } 18978 18979 // Data with special labels is now gone, so finish the job 18980 storage.destroyUserStorage(volumeUuid, userId, flags); 18981 18982 } catch (Exception e) { 18983 logCriticalInfo(Log.WARN, 18984 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18985 } 18986 } 18987 18988 /** 18989 * Examine all users present on given mounted volume, and destroy data 18990 * belonging to users that are no longer valid, or whose user ID has been 18991 * recycled. 18992 */ 18993 private void reconcileUsers(String volumeUuid) { 18994 final List<File> files = new ArrayList<>(); 18995 Collections.addAll(files, FileUtils 18996 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18997 Collections.addAll(files, FileUtils 18998 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18999 for (File file : files) { 19000 if (!file.isDirectory()) continue; 19001 19002 final int userId; 19003 final UserInfo info; 19004 try { 19005 userId = Integer.parseInt(file.getName()); 19006 info = sUserManager.getUserInfo(userId); 19007 } catch (NumberFormatException e) { 19008 Slog.w(TAG, "Invalid user directory " + file); 19009 continue; 19010 } 19011 19012 boolean destroyUser = false; 19013 if (info == null) { 19014 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19015 + " because no matching user was found"); 19016 destroyUser = true; 19017 } else if (!mOnlyCore) { 19018 try { 19019 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19020 } catch (IOException e) { 19021 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19022 + " because we failed to enforce serial number: " + e); 19023 destroyUser = true; 19024 } 19025 } 19026 19027 if (destroyUser) { 19028 synchronized (mInstallLock) { 19029 destroyUserDataLI(volumeUuid, userId, 19030 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19031 } 19032 } 19033 } 19034 } 19035 19036 private void assertPackageKnown(String volumeUuid, String packageName) 19037 throws PackageManagerException { 19038 synchronized (mPackages) { 19039 final PackageSetting ps = mSettings.mPackages.get(packageName); 19040 if (ps == null) { 19041 throw new PackageManagerException("Package " + packageName + " is unknown"); 19042 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19043 throw new PackageManagerException( 19044 "Package " + packageName + " found on unknown volume " + volumeUuid 19045 + "; expected volume " + ps.volumeUuid); 19046 } 19047 } 19048 } 19049 19050 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19051 throws PackageManagerException { 19052 synchronized (mPackages) { 19053 final PackageSetting ps = mSettings.mPackages.get(packageName); 19054 if (ps == null) { 19055 throw new PackageManagerException("Package " + packageName + " is unknown"); 19056 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19057 throw new PackageManagerException( 19058 "Package " + packageName + " found on unknown volume " + volumeUuid 19059 + "; expected volume " + ps.volumeUuid); 19060 } else if (!ps.getInstalled(userId)) { 19061 throw new PackageManagerException( 19062 "Package " + packageName + " not installed for user " + userId); 19063 } 19064 } 19065 } 19066 19067 /** 19068 * Examine all apps present on given mounted volume, and destroy apps that 19069 * aren't expected, either due to uninstallation or reinstallation on 19070 * another volume. 19071 */ 19072 private void reconcileApps(String volumeUuid) { 19073 final File[] files = FileUtils 19074 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19075 for (File file : files) { 19076 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19077 && !PackageInstallerService.isStageName(file.getName()); 19078 if (!isPackage) { 19079 // Ignore entries which are not packages 19080 continue; 19081 } 19082 19083 try { 19084 final PackageLite pkg = PackageParser.parsePackageLite(file, 19085 PackageParser.PARSE_MUST_BE_APK); 19086 assertPackageKnown(volumeUuid, pkg.packageName); 19087 19088 } catch (PackageParserException | PackageManagerException e) { 19089 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19090 synchronized (mInstallLock) { 19091 removeCodePathLI(file); 19092 } 19093 } 19094 } 19095 } 19096 19097 /** 19098 * Reconcile all app data for the given user. 19099 * <p> 19100 * Verifies that directories exist and that ownership and labeling is 19101 * correct for all installed apps on all mounted volumes. 19102 */ 19103 void reconcileAppsData(int userId, int flags) { 19104 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19105 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19106 final String volumeUuid = vol.getFsUuid(); 19107 synchronized (mInstallLock) { 19108 reconcileAppsDataLI(volumeUuid, userId, flags); 19109 } 19110 } 19111 } 19112 19113 /** 19114 * Reconcile all app data on given mounted volume. 19115 * <p> 19116 * Destroys app data that isn't expected, either due to uninstallation or 19117 * reinstallation on another volume. 19118 * <p> 19119 * Verifies that directories exist and that ownership and labeling is 19120 * correct for all installed apps. 19121 */ 19122 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19123 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19124 + Integer.toHexString(flags)); 19125 19126 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19127 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19128 19129 boolean restoreconNeeded = false; 19130 19131 // First look for stale data that doesn't belong, and check if things 19132 // have changed since we did our last restorecon 19133 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19134 if (!StorageManager.isUserKeyUnlocked(userId)) { 19135 throw new RuntimeException( 19136 "Yikes, someone asked us to reconcile CE storage while " + userId 19137 + " was still locked; this would have caused massive data loss!"); 19138 } 19139 19140 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19141 19142 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19143 for (File file : files) { 19144 final String packageName = file.getName(); 19145 try { 19146 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19147 } catch (PackageManagerException e) { 19148 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19149 try { 19150 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19151 StorageManager.FLAG_STORAGE_CE, 0); 19152 } catch (InstallerException e2) { 19153 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19154 } 19155 } 19156 } 19157 } 19158 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19159 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19160 19161 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19162 for (File file : files) { 19163 final String packageName = file.getName(); 19164 try { 19165 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19166 } catch (PackageManagerException e) { 19167 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19168 try { 19169 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19170 StorageManager.FLAG_STORAGE_DE, 0); 19171 } catch (InstallerException e2) { 19172 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19173 } 19174 } 19175 } 19176 } 19177 19178 // Ensure that data directories are ready to roll for all packages 19179 // installed for this volume and user 19180 final List<PackageSetting> packages; 19181 synchronized (mPackages) { 19182 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19183 } 19184 int preparedCount = 0; 19185 for (PackageSetting ps : packages) { 19186 final String packageName = ps.name; 19187 if (ps.pkg == null) { 19188 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19189 // TODO: might be due to legacy ASEC apps; we should circle back 19190 // and reconcile again once they're scanned 19191 continue; 19192 } 19193 19194 if (ps.getInstalled(userId)) { 19195 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19196 19197 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19198 // We may have just shuffled around app data directories, so 19199 // prepare them one more time 19200 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19201 } 19202 19203 preparedCount++; 19204 } 19205 } 19206 19207 if (restoreconNeeded) { 19208 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19209 SELinuxMMAC.setRestoreconDone(ceDir); 19210 } 19211 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19212 SELinuxMMAC.setRestoreconDone(deDir); 19213 } 19214 } 19215 19216 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19217 + " packages; restoreconNeeded was " + restoreconNeeded); 19218 } 19219 19220 /** 19221 * Prepare app data for the given app just after it was installed or 19222 * upgraded. This method carefully only touches users that it's installed 19223 * for, and it forces a restorecon to handle any seinfo changes. 19224 * <p> 19225 * Verifies that directories exist and that ownership and labeling is 19226 * correct for all installed apps. If there is an ownership mismatch, it 19227 * will try recovering system apps by wiping data; third-party app data is 19228 * left intact. 19229 * <p> 19230 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19231 */ 19232 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19233 final PackageSetting ps; 19234 synchronized (mPackages) { 19235 ps = mSettings.mPackages.get(pkg.packageName); 19236 mSettings.writeKernelMappingLPr(ps); 19237 } 19238 19239 final UserManager um = mContext.getSystemService(UserManager.class); 19240 for (UserInfo user : um.getUsers()) { 19241 final int flags; 19242 if (um.isUserUnlockingOrUnlocked(user.id)) { 19243 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19244 } else if (um.isUserRunning(user.id)) { 19245 flags = StorageManager.FLAG_STORAGE_DE; 19246 } else { 19247 continue; 19248 } 19249 19250 if (ps.getInstalled(user.id)) { 19251 // Whenever an app changes, force a restorecon of its data 19252 // TODO: when user data is locked, mark that we're still dirty 19253 prepareAppDataLIF(pkg, user.id, flags, true); 19254 } 19255 } 19256 } 19257 19258 /** 19259 * Prepare app data for the given app. 19260 * <p> 19261 * Verifies that directories exist and that ownership and labeling is 19262 * correct for all installed apps. If there is an ownership mismatch, this 19263 * will try recovering system apps by wiping data; third-party app data is 19264 * left intact. 19265 */ 19266 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19267 boolean restoreconNeeded) { 19268 if (pkg == null) { 19269 Slog.wtf(TAG, "Package was null!", new Throwable()); 19270 return; 19271 } 19272 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19273 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19274 for (int i = 0; i < childCount; i++) { 19275 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19276 } 19277 } 19278 19279 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19280 boolean restoreconNeeded) { 19281 if (DEBUG_APP_DATA) { 19282 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19283 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19284 } 19285 19286 final String volumeUuid = pkg.volumeUuid; 19287 final String packageName = pkg.packageName; 19288 final ApplicationInfo app = pkg.applicationInfo; 19289 final int appId = UserHandle.getAppId(app.uid); 19290 19291 Preconditions.checkNotNull(app.seinfo); 19292 19293 try { 19294 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19295 appId, app.seinfo, app.targetSdkVersion); 19296 } catch (InstallerException e) { 19297 if (app.isSystemApp()) { 19298 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19299 + ", but trying to recover: " + e); 19300 destroyAppDataLeafLIF(pkg, userId, flags); 19301 try { 19302 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19303 appId, app.seinfo, app.targetSdkVersion); 19304 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19305 } catch (InstallerException e2) { 19306 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19307 } 19308 } else { 19309 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19310 } 19311 } 19312 19313 if (restoreconNeeded) { 19314 try { 19315 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19316 app.seinfo); 19317 } catch (InstallerException e) { 19318 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19319 } 19320 } 19321 19322 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19323 try { 19324 // CE storage is unlocked right now, so read out the inode and 19325 // remember for use later when it's locked 19326 // TODO: mark this structure as dirty so we persist it! 19327 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19328 StorageManager.FLAG_STORAGE_CE); 19329 synchronized (mPackages) { 19330 final PackageSetting ps = mSettings.mPackages.get(packageName); 19331 if (ps != null) { 19332 ps.setCeDataInode(ceDataInode, userId); 19333 } 19334 } 19335 } catch (InstallerException e) { 19336 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19337 } 19338 } 19339 19340 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19341 } 19342 19343 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19344 if (pkg == null) { 19345 Slog.wtf(TAG, "Package was null!", new Throwable()); 19346 return; 19347 } 19348 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19349 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19350 for (int i = 0; i < childCount; i++) { 19351 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19352 } 19353 } 19354 19355 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19356 final String volumeUuid = pkg.volumeUuid; 19357 final String packageName = pkg.packageName; 19358 final ApplicationInfo app = pkg.applicationInfo; 19359 19360 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19361 // Create a native library symlink only if we have native libraries 19362 // and if the native libraries are 32 bit libraries. We do not provide 19363 // this symlink for 64 bit libraries. 19364 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19365 final String nativeLibPath = app.nativeLibraryDir; 19366 try { 19367 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19368 nativeLibPath, userId); 19369 } catch (InstallerException e) { 19370 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19371 } 19372 } 19373 } 19374 } 19375 19376 /** 19377 * For system apps on non-FBE devices, this method migrates any existing 19378 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19379 * requested by the app. 19380 */ 19381 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19382 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19383 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19384 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19385 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19386 try { 19387 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19388 storageTarget); 19389 } catch (InstallerException e) { 19390 logCriticalInfo(Log.WARN, 19391 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19392 } 19393 return true; 19394 } else { 19395 return false; 19396 } 19397 } 19398 19399 public PackageFreezer freezePackage(String packageName, String killReason) { 19400 return new PackageFreezer(packageName, killReason); 19401 } 19402 19403 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19404 String killReason) { 19405 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19406 return new PackageFreezer(); 19407 } else { 19408 return freezePackage(packageName, killReason); 19409 } 19410 } 19411 19412 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19413 String killReason) { 19414 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19415 return new PackageFreezer(); 19416 } else { 19417 return freezePackage(packageName, killReason); 19418 } 19419 } 19420 19421 /** 19422 * Class that freezes and kills the given package upon creation, and 19423 * unfreezes it upon closing. This is typically used when doing surgery on 19424 * app code/data to prevent the app from running while you're working. 19425 */ 19426 private class PackageFreezer implements AutoCloseable { 19427 private final String mPackageName; 19428 private final PackageFreezer[] mChildren; 19429 19430 private final boolean mWeFroze; 19431 19432 private final AtomicBoolean mClosed = new AtomicBoolean(); 19433 private final CloseGuard mCloseGuard = CloseGuard.get(); 19434 19435 /** 19436 * Create and return a stub freezer that doesn't actually do anything, 19437 * typically used when someone requested 19438 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19439 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19440 */ 19441 public PackageFreezer() { 19442 mPackageName = null; 19443 mChildren = null; 19444 mWeFroze = false; 19445 mCloseGuard.open("close"); 19446 } 19447 19448 public PackageFreezer(String packageName, String killReason) { 19449 synchronized (mPackages) { 19450 mPackageName = packageName; 19451 mWeFroze = mFrozenPackages.add(mPackageName); 19452 19453 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19454 if (ps != null) { 19455 killApplication(ps.name, ps.appId, killReason); 19456 } 19457 19458 final PackageParser.Package p = mPackages.get(packageName); 19459 if (p != null && p.childPackages != null) { 19460 final int N = p.childPackages.size(); 19461 mChildren = new PackageFreezer[N]; 19462 for (int i = 0; i < N; i++) { 19463 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19464 killReason); 19465 } 19466 } else { 19467 mChildren = null; 19468 } 19469 } 19470 mCloseGuard.open("close"); 19471 } 19472 19473 @Override 19474 protected void finalize() throws Throwable { 19475 try { 19476 mCloseGuard.warnIfOpen(); 19477 close(); 19478 } finally { 19479 super.finalize(); 19480 } 19481 } 19482 19483 @Override 19484 public void close() { 19485 mCloseGuard.close(); 19486 if (mClosed.compareAndSet(false, true)) { 19487 synchronized (mPackages) { 19488 if (mWeFroze) { 19489 mFrozenPackages.remove(mPackageName); 19490 } 19491 19492 if (mChildren != null) { 19493 for (PackageFreezer freezer : mChildren) { 19494 freezer.close(); 19495 } 19496 } 19497 } 19498 } 19499 } 19500 } 19501 19502 /** 19503 * Verify that given package is currently frozen. 19504 */ 19505 private void checkPackageFrozen(String packageName) { 19506 synchronized (mPackages) { 19507 if (!mFrozenPackages.contains(packageName)) { 19508 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19509 } 19510 } 19511 } 19512 19513 @Override 19514 public int movePackage(final String packageName, final String volumeUuid) { 19515 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19516 19517 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19518 final int moveId = mNextMoveId.getAndIncrement(); 19519 mHandler.post(new Runnable() { 19520 @Override 19521 public void run() { 19522 try { 19523 movePackageInternal(packageName, volumeUuid, moveId, user); 19524 } catch (PackageManagerException e) { 19525 Slog.w(TAG, "Failed to move " + packageName, e); 19526 mMoveCallbacks.notifyStatusChanged(moveId, 19527 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19528 } 19529 } 19530 }); 19531 return moveId; 19532 } 19533 19534 private void movePackageInternal(final String packageName, final String volumeUuid, 19535 final int moveId, UserHandle user) throws PackageManagerException { 19536 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19537 final PackageManager pm = mContext.getPackageManager(); 19538 19539 final boolean currentAsec; 19540 final String currentVolumeUuid; 19541 final File codeFile; 19542 final String installerPackageName; 19543 final String packageAbiOverride; 19544 final int appId; 19545 final String seinfo; 19546 final String label; 19547 final int targetSdkVersion; 19548 final PackageFreezer freezer; 19549 19550 // reader 19551 synchronized (mPackages) { 19552 final PackageParser.Package pkg = mPackages.get(packageName); 19553 final PackageSetting ps = mSettings.mPackages.get(packageName); 19554 if (pkg == null || ps == null) { 19555 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19556 } 19557 19558 if (pkg.applicationInfo.isSystemApp()) { 19559 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19560 "Cannot move system application"); 19561 } 19562 19563 if (pkg.applicationInfo.isExternalAsec()) { 19564 currentAsec = true; 19565 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19566 } else if (pkg.applicationInfo.isForwardLocked()) { 19567 currentAsec = true; 19568 currentVolumeUuid = "forward_locked"; 19569 } else { 19570 currentAsec = false; 19571 currentVolumeUuid = ps.volumeUuid; 19572 19573 final File probe = new File(pkg.codePath); 19574 final File probeOat = new File(probe, "oat"); 19575 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19576 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19577 "Move only supported for modern cluster style installs"); 19578 } 19579 } 19580 19581 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19582 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19583 "Package already moved to " + volumeUuid); 19584 } 19585 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19586 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19587 "Device admin cannot be moved"); 19588 } 19589 19590 if (mFrozenPackages.contains(packageName)) { 19591 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19592 "Failed to move already frozen package"); 19593 } 19594 19595 codeFile = new File(pkg.codePath); 19596 installerPackageName = ps.installerPackageName; 19597 packageAbiOverride = ps.cpuAbiOverrideString; 19598 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19599 seinfo = pkg.applicationInfo.seinfo; 19600 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19601 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19602 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19603 } 19604 19605 final Bundle extras = new Bundle(); 19606 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19607 extras.putString(Intent.EXTRA_TITLE, label); 19608 mMoveCallbacks.notifyCreated(moveId, extras); 19609 19610 int installFlags; 19611 final boolean moveCompleteApp; 19612 final File measurePath; 19613 19614 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19615 installFlags = INSTALL_INTERNAL; 19616 moveCompleteApp = !currentAsec; 19617 measurePath = Environment.getDataAppDirectory(volumeUuid); 19618 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19619 installFlags = INSTALL_EXTERNAL; 19620 moveCompleteApp = false; 19621 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19622 } else { 19623 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19624 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19625 || !volume.isMountedWritable()) { 19626 freezer.close(); 19627 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19628 "Move location not mounted private volume"); 19629 } 19630 19631 Preconditions.checkState(!currentAsec); 19632 19633 installFlags = INSTALL_INTERNAL; 19634 moveCompleteApp = true; 19635 measurePath = Environment.getDataAppDirectory(volumeUuid); 19636 } 19637 19638 final PackageStats stats = new PackageStats(null, -1); 19639 synchronized (mInstaller) { 19640 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19641 freezer.close(); 19642 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19643 "Failed to measure package size"); 19644 } 19645 } 19646 19647 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19648 + stats.dataSize); 19649 19650 final long startFreeBytes = measurePath.getFreeSpace(); 19651 final long sizeBytes; 19652 if (moveCompleteApp) { 19653 sizeBytes = stats.codeSize + stats.dataSize; 19654 } else { 19655 sizeBytes = stats.codeSize; 19656 } 19657 19658 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19659 freezer.close(); 19660 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19661 "Not enough free space to move"); 19662 } 19663 19664 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19665 19666 final CountDownLatch installedLatch = new CountDownLatch(1); 19667 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19668 @Override 19669 public void onUserActionRequired(Intent intent) throws RemoteException { 19670 throw new IllegalStateException(); 19671 } 19672 19673 @Override 19674 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19675 Bundle extras) throws RemoteException { 19676 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19677 + PackageManager.installStatusToString(returnCode, msg)); 19678 19679 installedLatch.countDown(); 19680 freezer.close(); 19681 19682 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19683 switch (status) { 19684 case PackageInstaller.STATUS_SUCCESS: 19685 mMoveCallbacks.notifyStatusChanged(moveId, 19686 PackageManager.MOVE_SUCCEEDED); 19687 break; 19688 case PackageInstaller.STATUS_FAILURE_STORAGE: 19689 mMoveCallbacks.notifyStatusChanged(moveId, 19690 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19691 break; 19692 default: 19693 mMoveCallbacks.notifyStatusChanged(moveId, 19694 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19695 break; 19696 } 19697 } 19698 }; 19699 19700 final MoveInfo move; 19701 if (moveCompleteApp) { 19702 // Kick off a thread to report progress estimates 19703 new Thread() { 19704 @Override 19705 public void run() { 19706 while (true) { 19707 try { 19708 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19709 break; 19710 } 19711 } catch (InterruptedException ignored) { 19712 } 19713 19714 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19715 final int progress = 10 + (int) MathUtils.constrain( 19716 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19717 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19718 } 19719 } 19720 }.start(); 19721 19722 final String dataAppName = codeFile.getName(); 19723 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19724 dataAppName, appId, seinfo, targetSdkVersion); 19725 } else { 19726 move = null; 19727 } 19728 19729 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19730 19731 final Message msg = mHandler.obtainMessage(INIT_COPY); 19732 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19733 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19734 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19735 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19736 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19737 msg.obj = params; 19738 19739 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19740 System.identityHashCode(msg.obj)); 19741 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19742 System.identityHashCode(msg.obj)); 19743 19744 mHandler.sendMessage(msg); 19745 } 19746 19747 @Override 19748 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19749 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19750 19751 final int realMoveId = mNextMoveId.getAndIncrement(); 19752 final Bundle extras = new Bundle(); 19753 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19754 mMoveCallbacks.notifyCreated(realMoveId, extras); 19755 19756 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19757 @Override 19758 public void onCreated(int moveId, Bundle extras) { 19759 // Ignored 19760 } 19761 19762 @Override 19763 public void onStatusChanged(int moveId, int status, long estMillis) { 19764 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19765 } 19766 }; 19767 19768 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19769 storage.setPrimaryStorageUuid(volumeUuid, callback); 19770 return realMoveId; 19771 } 19772 19773 @Override 19774 public int getMoveStatus(int moveId) { 19775 mContext.enforceCallingOrSelfPermission( 19776 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19777 return mMoveCallbacks.mLastStatus.get(moveId); 19778 } 19779 19780 @Override 19781 public void registerMoveCallback(IPackageMoveObserver callback) { 19782 mContext.enforceCallingOrSelfPermission( 19783 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19784 mMoveCallbacks.register(callback); 19785 } 19786 19787 @Override 19788 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19789 mContext.enforceCallingOrSelfPermission( 19790 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19791 mMoveCallbacks.unregister(callback); 19792 } 19793 19794 @Override 19795 public boolean setInstallLocation(int loc) { 19796 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19797 null); 19798 if (getInstallLocation() == loc) { 19799 return true; 19800 } 19801 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19802 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19803 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19804 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19805 return true; 19806 } 19807 return false; 19808 } 19809 19810 @Override 19811 public int getInstallLocation() { 19812 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19813 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19814 PackageHelper.APP_INSTALL_AUTO); 19815 } 19816 19817 /** Called by UserManagerService */ 19818 void cleanUpUser(UserManagerService userManager, int userHandle) { 19819 synchronized (mPackages) { 19820 mDirtyUsers.remove(userHandle); 19821 mUserNeedsBadging.delete(userHandle); 19822 mSettings.removeUserLPw(userHandle); 19823 mPendingBroadcasts.remove(userHandle); 19824 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19825 removeUnusedPackagesLPw(userManager, userHandle); 19826 } 19827 } 19828 19829 /** 19830 * We're removing userHandle and would like to remove any downloaded packages 19831 * that are no longer in use by any other user. 19832 * @param userHandle the user being removed 19833 */ 19834 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19835 final boolean DEBUG_CLEAN_APKS = false; 19836 int [] users = userManager.getUserIds(); 19837 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19838 while (psit.hasNext()) { 19839 PackageSetting ps = psit.next(); 19840 if (ps.pkg == null) { 19841 continue; 19842 } 19843 final String packageName = ps.pkg.packageName; 19844 // Skip over if system app 19845 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19846 continue; 19847 } 19848 if (DEBUG_CLEAN_APKS) { 19849 Slog.i(TAG, "Checking package " + packageName); 19850 } 19851 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19852 if (keep) { 19853 if (DEBUG_CLEAN_APKS) { 19854 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19855 } 19856 } else { 19857 for (int i = 0; i < users.length; i++) { 19858 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19859 keep = true; 19860 if (DEBUG_CLEAN_APKS) { 19861 Slog.i(TAG, " Keeping package " + packageName + " for user " 19862 + users[i]); 19863 } 19864 break; 19865 } 19866 } 19867 } 19868 if (!keep) { 19869 if (DEBUG_CLEAN_APKS) { 19870 Slog.i(TAG, " Removing package " + packageName); 19871 } 19872 mHandler.post(new Runnable() { 19873 public void run() { 19874 deletePackageX(packageName, userHandle, 0); 19875 } //end run 19876 }); 19877 } 19878 } 19879 } 19880 19881 /** Called by UserManagerService */ 19882 void createNewUser(int userHandle) { 19883 synchronized (mInstallLock) { 19884 mSettings.createNewUserLI(this, mInstaller, userHandle); 19885 } 19886 synchronized (mPackages) { 19887 applyFactoryDefaultBrowserLPw(userHandle); 19888 primeDomainVerificationsLPw(userHandle); 19889 } 19890 } 19891 19892 void newUserCreated(final int userHandle) { 19893 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19894 // If permission review for legacy apps is required, we represent 19895 // dagerous permissions for such apps as always granted runtime 19896 // permissions to keep per user flag state whether review is needed. 19897 // Hence, if a new user is added we have to propagate dangerous 19898 // permission grants for these legacy apps. 19899 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19900 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19901 | UPDATE_PERMISSIONS_REPLACE_ALL); 19902 } 19903 } 19904 19905 @Override 19906 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19907 mContext.enforceCallingOrSelfPermission( 19908 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19909 "Only package verification agents can read the verifier device identity"); 19910 19911 synchronized (mPackages) { 19912 return mSettings.getVerifierDeviceIdentityLPw(); 19913 } 19914 } 19915 19916 @Override 19917 public void setPermissionEnforced(String permission, boolean enforced) { 19918 // TODO: Now that we no longer change GID for storage, this should to away. 19919 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19920 "setPermissionEnforced"); 19921 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19922 synchronized (mPackages) { 19923 if (mSettings.mReadExternalStorageEnforced == null 19924 || mSettings.mReadExternalStorageEnforced != enforced) { 19925 mSettings.mReadExternalStorageEnforced = enforced; 19926 mSettings.writeLPr(); 19927 } 19928 } 19929 // kill any non-foreground processes so we restart them and 19930 // grant/revoke the GID. 19931 final IActivityManager am = ActivityManagerNative.getDefault(); 19932 if (am != null) { 19933 final long token = Binder.clearCallingIdentity(); 19934 try { 19935 am.killProcessesBelowForeground("setPermissionEnforcement"); 19936 } catch (RemoteException e) { 19937 } finally { 19938 Binder.restoreCallingIdentity(token); 19939 } 19940 } 19941 } else { 19942 throw new IllegalArgumentException("No selective enforcement for " + permission); 19943 } 19944 } 19945 19946 @Override 19947 @Deprecated 19948 public boolean isPermissionEnforced(String permission) { 19949 return true; 19950 } 19951 19952 @Override 19953 public boolean isStorageLow() { 19954 final long token = Binder.clearCallingIdentity(); 19955 try { 19956 final DeviceStorageMonitorInternal 19957 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19958 if (dsm != null) { 19959 return dsm.isMemoryLow(); 19960 } else { 19961 return false; 19962 } 19963 } finally { 19964 Binder.restoreCallingIdentity(token); 19965 } 19966 } 19967 19968 @Override 19969 public IPackageInstaller getPackageInstaller() { 19970 return mInstallerService; 19971 } 19972 19973 private boolean userNeedsBadging(int userId) { 19974 int index = mUserNeedsBadging.indexOfKey(userId); 19975 if (index < 0) { 19976 final UserInfo userInfo; 19977 final long token = Binder.clearCallingIdentity(); 19978 try { 19979 userInfo = sUserManager.getUserInfo(userId); 19980 } finally { 19981 Binder.restoreCallingIdentity(token); 19982 } 19983 final boolean b; 19984 if (userInfo != null && userInfo.isManagedProfile()) { 19985 b = true; 19986 } else { 19987 b = false; 19988 } 19989 mUserNeedsBadging.put(userId, b); 19990 return b; 19991 } 19992 return mUserNeedsBadging.valueAt(index); 19993 } 19994 19995 @Override 19996 public KeySet getKeySetByAlias(String packageName, String alias) { 19997 if (packageName == null || alias == null) { 19998 return null; 19999 } 20000 synchronized(mPackages) { 20001 final PackageParser.Package pkg = mPackages.get(packageName); 20002 if (pkg == null) { 20003 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20004 throw new IllegalArgumentException("Unknown package: " + packageName); 20005 } 20006 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20007 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20008 } 20009 } 20010 20011 @Override 20012 public KeySet getSigningKeySet(String packageName) { 20013 if (packageName == null) { 20014 return null; 20015 } 20016 synchronized(mPackages) { 20017 final PackageParser.Package pkg = mPackages.get(packageName); 20018 if (pkg == null) { 20019 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20020 throw new IllegalArgumentException("Unknown package: " + packageName); 20021 } 20022 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20023 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20024 throw new SecurityException("May not access signing KeySet of other apps."); 20025 } 20026 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20027 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20028 } 20029 } 20030 20031 @Override 20032 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20033 if (packageName == null || ks == null) { 20034 return false; 20035 } 20036 synchronized(mPackages) { 20037 final PackageParser.Package pkg = mPackages.get(packageName); 20038 if (pkg == null) { 20039 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20040 throw new IllegalArgumentException("Unknown package: " + packageName); 20041 } 20042 IBinder ksh = ks.getToken(); 20043 if (ksh instanceof KeySetHandle) { 20044 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20045 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20046 } 20047 return false; 20048 } 20049 } 20050 20051 @Override 20052 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20053 if (packageName == null || ks == null) { 20054 return false; 20055 } 20056 synchronized(mPackages) { 20057 final PackageParser.Package pkg = mPackages.get(packageName); 20058 if (pkg == null) { 20059 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20060 throw new IllegalArgumentException("Unknown package: " + packageName); 20061 } 20062 IBinder ksh = ks.getToken(); 20063 if (ksh instanceof KeySetHandle) { 20064 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20065 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20066 } 20067 return false; 20068 } 20069 } 20070 20071 private void deletePackageIfUnusedLPr(final String packageName) { 20072 PackageSetting ps = mSettings.mPackages.get(packageName); 20073 if (ps == null) { 20074 return; 20075 } 20076 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20077 // TODO Implement atomic delete if package is unused 20078 // It is currently possible that the package will be deleted even if it is installed 20079 // after this method returns. 20080 mHandler.post(new Runnable() { 20081 public void run() { 20082 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20083 } 20084 }); 20085 } 20086 } 20087 20088 /** 20089 * Check and throw if the given before/after packages would be considered a 20090 * downgrade. 20091 */ 20092 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20093 throws PackageManagerException { 20094 if (after.versionCode < before.mVersionCode) { 20095 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20096 "Update version code " + after.versionCode + " is older than current " 20097 + before.mVersionCode); 20098 } else if (after.versionCode == before.mVersionCode) { 20099 if (after.baseRevisionCode < before.baseRevisionCode) { 20100 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20101 "Update base revision code " + after.baseRevisionCode 20102 + " is older than current " + before.baseRevisionCode); 20103 } 20104 20105 if (!ArrayUtils.isEmpty(after.splitNames)) { 20106 for (int i = 0; i < after.splitNames.length; i++) { 20107 final String splitName = after.splitNames[i]; 20108 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20109 if (j != -1) { 20110 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20111 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20112 "Update split " + splitName + " revision code " 20113 + after.splitRevisionCodes[i] + " is older than current " 20114 + before.splitRevisionCodes[j]); 20115 } 20116 } 20117 } 20118 } 20119 } 20120 } 20121 20122 private static class MoveCallbacks extends Handler { 20123 private static final int MSG_CREATED = 1; 20124 private static final int MSG_STATUS_CHANGED = 2; 20125 20126 private final RemoteCallbackList<IPackageMoveObserver> 20127 mCallbacks = new RemoteCallbackList<>(); 20128 20129 private final SparseIntArray mLastStatus = new SparseIntArray(); 20130 20131 public MoveCallbacks(Looper looper) { 20132 super(looper); 20133 } 20134 20135 public void register(IPackageMoveObserver callback) { 20136 mCallbacks.register(callback); 20137 } 20138 20139 public void unregister(IPackageMoveObserver callback) { 20140 mCallbacks.unregister(callback); 20141 } 20142 20143 @Override 20144 public void handleMessage(Message msg) { 20145 final SomeArgs args = (SomeArgs) msg.obj; 20146 final int n = mCallbacks.beginBroadcast(); 20147 for (int i = 0; i < n; i++) { 20148 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20149 try { 20150 invokeCallback(callback, msg.what, args); 20151 } catch (RemoteException ignored) { 20152 } 20153 } 20154 mCallbacks.finishBroadcast(); 20155 args.recycle(); 20156 } 20157 20158 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20159 throws RemoteException { 20160 switch (what) { 20161 case MSG_CREATED: { 20162 callback.onCreated(args.argi1, (Bundle) args.arg2); 20163 break; 20164 } 20165 case MSG_STATUS_CHANGED: { 20166 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20167 break; 20168 } 20169 } 20170 } 20171 20172 private void notifyCreated(int moveId, Bundle extras) { 20173 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20174 20175 final SomeArgs args = SomeArgs.obtain(); 20176 args.argi1 = moveId; 20177 args.arg2 = extras; 20178 obtainMessage(MSG_CREATED, args).sendToTarget(); 20179 } 20180 20181 private void notifyStatusChanged(int moveId, int status) { 20182 notifyStatusChanged(moveId, status, -1); 20183 } 20184 20185 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20186 Slog.v(TAG, "Move " + moveId + " status " + status); 20187 20188 final SomeArgs args = SomeArgs.obtain(); 20189 args.argi1 = moveId; 20190 args.argi2 = status; 20191 args.arg3 = estMillis; 20192 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20193 20194 synchronized (mLastStatus) { 20195 mLastStatus.put(moveId, status); 20196 } 20197 } 20198 } 20199 20200 private final static class OnPermissionChangeListeners extends Handler { 20201 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20202 20203 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20204 new RemoteCallbackList<>(); 20205 20206 public OnPermissionChangeListeners(Looper looper) { 20207 super(looper); 20208 } 20209 20210 @Override 20211 public void handleMessage(Message msg) { 20212 switch (msg.what) { 20213 case MSG_ON_PERMISSIONS_CHANGED: { 20214 final int uid = msg.arg1; 20215 handleOnPermissionsChanged(uid); 20216 } break; 20217 } 20218 } 20219 20220 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20221 mPermissionListeners.register(listener); 20222 20223 } 20224 20225 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20226 mPermissionListeners.unregister(listener); 20227 } 20228 20229 public void onPermissionsChanged(int uid) { 20230 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20231 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20232 } 20233 } 20234 20235 private void handleOnPermissionsChanged(int uid) { 20236 final int count = mPermissionListeners.beginBroadcast(); 20237 try { 20238 for (int i = 0; i < count; i++) { 20239 IOnPermissionsChangeListener callback = mPermissionListeners 20240 .getBroadcastItem(i); 20241 try { 20242 callback.onPermissionsChanged(uid); 20243 } catch (RemoteException e) { 20244 Log.e(TAG, "Permission listener is dead", e); 20245 } 20246 } 20247 } finally { 20248 mPermissionListeners.finishBroadcast(); 20249 } 20250 } 20251 } 20252 20253 private class PackageManagerInternalImpl extends PackageManagerInternal { 20254 @Override 20255 public void setLocationPackagesProvider(PackagesProvider provider) { 20256 synchronized (mPackages) { 20257 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20258 } 20259 } 20260 20261 @Override 20262 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20263 synchronized (mPackages) { 20264 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20265 } 20266 } 20267 20268 @Override 20269 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20270 synchronized (mPackages) { 20271 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20272 } 20273 } 20274 20275 @Override 20276 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20277 synchronized (mPackages) { 20278 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20279 } 20280 } 20281 20282 @Override 20283 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20284 synchronized (mPackages) { 20285 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20286 } 20287 } 20288 20289 @Override 20290 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20291 synchronized (mPackages) { 20292 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20293 } 20294 } 20295 20296 @Override 20297 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20298 synchronized (mPackages) { 20299 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20300 packageName, userId); 20301 } 20302 } 20303 20304 @Override 20305 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20306 synchronized (mPackages) { 20307 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20308 packageName, userId); 20309 } 20310 } 20311 20312 @Override 20313 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20314 synchronized (mPackages) { 20315 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20316 packageName, userId); 20317 } 20318 } 20319 20320 @Override 20321 public void setKeepUninstalledPackages(final List<String> packageList) { 20322 Preconditions.checkNotNull(packageList); 20323 List<String> removedFromList = null; 20324 synchronized (mPackages) { 20325 if (mKeepUninstalledPackages != null) { 20326 final int packagesCount = mKeepUninstalledPackages.size(); 20327 for (int i = 0; i < packagesCount; i++) { 20328 String oldPackage = mKeepUninstalledPackages.get(i); 20329 if (packageList != null && packageList.contains(oldPackage)) { 20330 continue; 20331 } 20332 if (removedFromList == null) { 20333 removedFromList = new ArrayList<>(); 20334 } 20335 removedFromList.add(oldPackage); 20336 } 20337 } 20338 mKeepUninstalledPackages = new ArrayList<>(packageList); 20339 if (removedFromList != null) { 20340 final int removedCount = removedFromList.size(); 20341 for (int i = 0; i < removedCount; i++) { 20342 deletePackageIfUnusedLPr(removedFromList.get(i)); 20343 } 20344 } 20345 } 20346 } 20347 20348 @Override 20349 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20350 synchronized (mPackages) { 20351 // If we do not support permission review, done. 20352 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20353 return false; 20354 } 20355 20356 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20357 if (packageSetting == null) { 20358 return false; 20359 } 20360 20361 // Permission review applies only to apps not supporting the new permission model. 20362 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20363 return false; 20364 } 20365 20366 // Legacy apps have the permission and get user consent on launch. 20367 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20368 return permissionsState.isPermissionReviewRequired(userId); 20369 } 20370 } 20371 20372 @Override 20373 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20374 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20375 } 20376 20377 @Override 20378 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20379 int userId) { 20380 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20381 } 20382 } 20383 20384 @Override 20385 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20386 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20387 synchronized (mPackages) { 20388 final long identity = Binder.clearCallingIdentity(); 20389 try { 20390 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20391 packageNames, userId); 20392 } finally { 20393 Binder.restoreCallingIdentity(identity); 20394 } 20395 } 20396 } 20397 20398 private static void enforceSystemOrPhoneCaller(String tag) { 20399 int callingUid = Binder.getCallingUid(); 20400 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20401 throw new SecurityException( 20402 "Cannot call " + tag + " from UID " + callingUid); 20403 } 20404 } 20405 20406 boolean isHistoricalPackageUsageAvailable() { 20407 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20408 } 20409 20410 /** 20411 * Return a <b>copy</b> of the collection of packages known to the package manager. 20412 * @return A copy of the values of mPackages. 20413 */ 20414 Collection<PackageParser.Package> getPackages() { 20415 synchronized (mPackages) { 20416 return new ArrayList<>(mPackages.values()); 20417 } 20418 } 20419 20420 /** 20421 * Logs process start information (including base APK hash) to the security log. 20422 * @hide 20423 */ 20424 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20425 String apkFile, int pid) { 20426 if (!SecurityLog.isLoggingEnabled()) { 20427 return; 20428 } 20429 Bundle data = new Bundle(); 20430 data.putLong("startTimestamp", System.currentTimeMillis()); 20431 data.putString("processName", processName); 20432 data.putInt("uid", uid); 20433 data.putString("seinfo", seinfo); 20434 data.putString("apkFile", apkFile); 20435 data.putInt("pid", pid); 20436 Message msg = mProcessLoggingHandler.obtainMessage( 20437 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20438 msg.setData(data); 20439 mProcessLoggingHandler.sendMessage(msg); 20440 } 20441} 20442