PackageManagerService.java revision 0dc591b48d96c7b5ac809197c2fb758dccec15a2
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.security.KeyStore; 199import android.security.SystemKeyStore; 200import android.system.ErrnoException; 201import android.system.Os; 202import android.text.TextUtils; 203import android.text.format.DateUtils; 204import android.util.ArrayMap; 205import android.util.ArraySet; 206import android.util.AtomicFile; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.util.jar.StrictJarFile; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.os.IParcelFileDescriptorFactory; 229import com.android.internal.os.InstallerConnection.InstallerException; 230import com.android.internal.os.SomeArgs; 231import com.android.internal.os.Zygote; 232import com.android.internal.telephony.CarrierAppUtils; 233import com.android.internal.util.ArrayUtils; 234import com.android.internal.util.FastPrintWriter; 235import com.android.internal.util.FastXmlSerializer; 236import com.android.internal.util.IndentingPrintWriter; 237import com.android.internal.util.Preconditions; 238import com.android.internal.util.XmlUtils; 239import com.android.server.EventLogTags; 240import com.android.server.FgThread; 241import com.android.server.IntentResolver; 242import com.android.server.LocalServices; 243import com.android.server.ServiceThread; 244import com.android.server.SystemConfig; 245import com.android.server.Watchdog; 246import com.android.server.pm.PermissionsState.PermissionState; 247import com.android.server.pm.Settings.DatabaseVersion; 248import com.android.server.pm.Settings.VersionInfo; 249import com.android.server.storage.DeviceStorageMonitorInternal; 250 251import dalvik.system.CloseGuard; 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.Certificate; 281import java.security.cert.CertificateEncodingException; 282import java.security.cert.CertificateException; 283import java.text.SimpleDateFormat; 284import java.util.ArrayList; 285import java.util.Arrays; 286import java.util.Collection; 287import java.util.Collections; 288import java.util.Comparator; 289import java.util.Date; 290import java.util.HashSet; 291import java.util.Iterator; 292import java.util.List; 293import java.util.Map; 294import java.util.Objects; 295import java.util.Set; 296import java.util.concurrent.CountDownLatch; 297import java.util.concurrent.TimeUnit; 298import java.util.concurrent.atomic.AtomicBoolean; 299import java.util.concurrent.atomic.AtomicInteger; 300import java.util.concurrent.atomic.AtomicLong; 301 302/** 303 * Keep track of all those APKs everywhere. 304 * <p> 305 * Internally there are two important locks: 306 * <ul> 307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 308 * and other related state. It is a fine-grained lock that should only be held 309 * momentarily, as it's one of the most contended locks in the system. 310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 311 * operations typically involve heavy lifting of application data on disk. Since 312 * {@code installd} is single-threaded, and it's operations can often be slow, 313 * this lock should never be acquired while already holding {@link #mPackages}. 314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 315 * holding {@link #mInstallLock}. 316 * </ul> 317 * Many internal methods rely on the caller to hold the appropriate locks, and 318 * this contract is expressed through method name suffixes: 319 * <ul> 320 * <li>fooLI(): the caller must hold {@link #mInstallLock} 321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 322 * being modified must be frozen 323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 325 * </ul> 326 * <p> 327 * Because this class is very central to the platform's security; please run all 328 * CTS and unit tests whenever making modifications: 329 * 330 * <pre> 331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 333 * </pre> 334 */ 335public class PackageManagerService extends IPackageManager.Stub { 336 static final String TAG = "PackageManager"; 337 static final boolean DEBUG_SETTINGS = false; 338 static final boolean DEBUG_PREFERRED = false; 339 static final boolean DEBUG_UPGRADE = false; 340 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 341 private static final boolean DEBUG_BACKUP = false; 342 private static final boolean DEBUG_INSTALL = false; 343 private static final boolean DEBUG_REMOVE = false; 344 private static final boolean DEBUG_BROADCASTS = false; 345 private static final boolean DEBUG_SHOW_INFO = false; 346 private static final boolean DEBUG_PACKAGE_INFO = false; 347 private static final boolean DEBUG_INTENT_MATCHING = false; 348 private static final boolean DEBUG_PACKAGE_SCANNING = false; 349 private static final boolean DEBUG_VERIFY = false; 350 private static final boolean DEBUG_FILTERS = false; 351 352 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 353 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 354 // user, but by default initialize to this. 355 static final boolean DEBUG_DEXOPT = false; 356 357 private static final boolean DEBUG_ABI_SELECTION = false; 358 private static final boolean DEBUG_EPHEMERAL = false; 359 private static final boolean DEBUG_TRIAGED_MISSING = false; 360 private static final boolean DEBUG_APP_DATA = false; 361 362 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 363 364 private static final boolean DISABLE_EPHEMERAL_APPS = true; 365 366 private static final int RADIO_UID = Process.PHONE_UID; 367 private static final int LOG_UID = Process.LOG_UID; 368 private static final int NFC_UID = Process.NFC_UID; 369 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 370 private static final int SHELL_UID = Process.SHELL_UID; 371 372 // Cap the size of permission trees that 3rd party apps can define 373 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 374 375 // Suffix used during package installation when copying/moving 376 // package apks to install directory. 377 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 378 379 static final int SCAN_NO_DEX = 1<<1; 380 static final int SCAN_FORCE_DEX = 1<<2; 381 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 382 static final int SCAN_NEW_INSTALL = 1<<4; 383 static final int SCAN_NO_PATHS = 1<<5; 384 static final int SCAN_UPDATE_TIME = 1<<6; 385 static final int SCAN_DEFER_DEX = 1<<7; 386 static final int SCAN_BOOTING = 1<<8; 387 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 388 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 389 static final int SCAN_REPLACING = 1<<11; 390 static final int SCAN_REQUIRE_KNOWN = 1<<12; 391 static final int SCAN_MOVE = 1<<13; 392 static final int SCAN_INITIAL = 1<<14; 393 static final int SCAN_CHECK_ONLY = 1<<15; 394 static final int SCAN_DONT_KILL_APP = 1<<17; 395 static final int SCAN_IGNORE_FROZEN = 1<<18; 396 397 static final int REMOVE_CHATTY = 1<<16; 398 399 private static final int[] EMPTY_INT_ARRAY = new int[0]; 400 401 /** 402 * Timeout (in milliseconds) after which the watchdog should declare that 403 * our handler thread is wedged. The usual default for such things is one 404 * minute but we sometimes do very lengthy I/O operations on this thread, 405 * such as installing multi-gigabyte applications, so ours needs to be longer. 406 */ 407 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 408 409 /** 410 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 411 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 412 * settings entry if available, otherwise we use the hardcoded default. If it's been 413 * more than this long since the last fstrim, we force one during the boot sequence. 414 * 415 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 416 * one gets run at the next available charging+idle time. This final mandatory 417 * no-fstrim check kicks in only of the other scheduling criteria is never met. 418 */ 419 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 420 421 /** 422 * Whether verification is enabled by default. 423 */ 424 private static final boolean DEFAULT_VERIFY_ENABLE = true; 425 426 /** 427 * The default maximum time to wait for the verification agent to return in 428 * milliseconds. 429 */ 430 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 431 432 /** 433 * The default response for package verification timeout. 434 * 435 * This can be either PackageManager.VERIFICATION_ALLOW or 436 * PackageManager.VERIFICATION_REJECT. 437 */ 438 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 439 440 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 441 442 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 443 DEFAULT_CONTAINER_PACKAGE, 444 "com.android.defcontainer.DefaultContainerService"); 445 446 private static final String KILL_APP_REASON_GIDS_CHANGED = 447 "permission grant or revoke changed gids"; 448 449 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 450 "permissions revoked"; 451 452 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 453 454 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 455 456 /** Permission grant: not grant the permission. */ 457 private static final int GRANT_DENIED = 1; 458 459 /** Permission grant: grant the permission as an install permission. */ 460 private static final int GRANT_INSTALL = 2; 461 462 /** Permission grant: grant the permission as a runtime one. */ 463 private static final int GRANT_RUNTIME = 3; 464 465 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 466 private static final int GRANT_UPGRADE = 4; 467 468 /** Canonical intent used to identify what counts as a "web browser" app */ 469 private static final Intent sBrowserIntent; 470 static { 471 sBrowserIntent = new Intent(); 472 sBrowserIntent.setAction(Intent.ACTION_VIEW); 473 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 474 sBrowserIntent.setData(Uri.parse("http:")); 475 } 476 477 /** 478 * The set of all protected actions [i.e. those actions for which a high priority 479 * intent filter is disallowed]. 480 */ 481 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 482 static { 483 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 485 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 486 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 487 } 488 489 // Compilation reasons. 490 public static final int REASON_FIRST_BOOT = 0; 491 public static final int REASON_BOOT = 1; 492 public static final int REASON_INSTALL = 2; 493 public static final int REASON_BACKGROUND_DEXOPT = 3; 494 public static final int REASON_AB_OTA = 4; 495 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 496 public static final int REASON_SHARED_APK = 6; 497 public static final int REASON_FORCED_DEXOPT = 7; 498 499 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 500 501 /** Special library name that skips shared libraries check during compilation. */ 502 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 503 504 final ServiceThread mHandlerThread; 505 506 final PackageHandler mHandler; 507 508 private final ProcessLoggingHandler mProcessLoggingHandler; 509 510 /** 511 * Messages for {@link #mHandler} that need to wait for system ready before 512 * being dispatched. 513 */ 514 private ArrayList<Message> mPostSystemReadyMessages; 515 516 final int mSdkVersion = Build.VERSION.SDK_INT; 517 518 final Context mContext; 519 final boolean mFactoryTest; 520 final boolean mOnlyCore; 521 final DisplayMetrics mMetrics; 522 final int mDefParseFlags; 523 final String[] mSeparateProcesses; 524 final boolean mIsUpgrade; 525 final boolean mIsPreNUpgrade; 526 527 /** The location for ASEC container files on internal storage. */ 528 final String mAsecInternalPath; 529 530 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 531 // LOCK HELD. Can be called with mInstallLock held. 532 @GuardedBy("mInstallLock") 533 final Installer mInstaller; 534 535 /** Directory where installed third-party apps stored */ 536 final File mAppInstallDir; 537 final File mEphemeralInstallDir; 538 539 /** 540 * Directory to which applications installed internally have their 541 * 32 bit native libraries copied. 542 */ 543 private File mAppLib32InstallDir; 544 545 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 546 // apps. 547 final File mDrmAppPrivateInstallDir; 548 549 // ---------------------------------------------------------------- 550 551 // Lock for state used when installing and doing other long running 552 // operations. Methods that must be called with this lock held have 553 // the suffix "LI". 554 final Object mInstallLock = new Object(); 555 556 // ---------------------------------------------------------------- 557 558 // Keys are String (package name), values are Package. This also serves 559 // as the lock for the global state. Methods that must be called with 560 // this lock held have the prefix "LP". 561 @GuardedBy("mPackages") 562 final ArrayMap<String, PackageParser.Package> mPackages = 563 new ArrayMap<String, PackageParser.Package>(); 564 565 final ArrayMap<String, Set<String>> mKnownCodebase = 566 new ArrayMap<String, Set<String>>(); 567 568 // Tracks available target package names -> overlay package paths. 569 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 570 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 571 572 /** 573 * Tracks new system packages [received in an OTA] that we expect to 574 * find updated user-installed versions. Keys are package name, values 575 * are package location. 576 */ 577 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 578 /** 579 * Tracks high priority intent filters for protected actions. During boot, certain 580 * filter actions are protected and should never be allowed to have a high priority 581 * intent filter for them. However, there is one, and only one exception -- the 582 * setup wizard. It must be able to define a high priority intent filter for these 583 * actions to ensure there are no escapes from the wizard. We need to delay processing 584 * of these during boot as we need to look at all of the system packages in order 585 * to know which component is the setup wizard. 586 */ 587 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 588 /** 589 * Whether or not processing protected filters should be deferred. 590 */ 591 private boolean mDeferProtectedFilters = true; 592 593 /** 594 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 595 */ 596 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 597 /** 598 * Whether or not system app permissions should be promoted from install to runtime. 599 */ 600 boolean mPromoteSystemApps; 601 602 @GuardedBy("mPackages") 603 final Settings mSettings; 604 605 /** 606 * Set of package names that are currently "frozen", which means active 607 * surgery is being done on the code/data for that package. The platform 608 * will refuse to launch frozen packages to avoid race conditions. 609 * 610 * @see PackageFreezer 611 */ 612 @GuardedBy("mPackages") 613 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 614 615 boolean mRestoredSettings; 616 617 // System configuration read by SystemConfig. 618 final int[] mGlobalGids; 619 final SparseArray<ArraySet<String>> mSystemPermissions; 620 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 621 622 // If mac_permissions.xml was found for seinfo labeling. 623 boolean mFoundPolicyFile; 624 625 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 626 627 public static final class SharedLibraryEntry { 628 public final String path; 629 public final String apk; 630 631 SharedLibraryEntry(String _path, String _apk) { 632 path = _path; 633 apk = _apk; 634 } 635 } 636 637 // Currently known shared libraries. 638 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 639 new ArrayMap<String, SharedLibraryEntry>(); 640 641 // All available activities, for your resolving pleasure. 642 final ActivityIntentResolver mActivities = 643 new ActivityIntentResolver(); 644 645 // All available receivers, for your resolving pleasure. 646 final ActivityIntentResolver mReceivers = 647 new ActivityIntentResolver(); 648 649 // All available services, for your resolving pleasure. 650 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 651 652 // All available providers, for your resolving pleasure. 653 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 654 655 // Mapping from provider base names (first directory in content URI codePath) 656 // to the provider information. 657 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 658 new ArrayMap<String, PackageParser.Provider>(); 659 660 // Mapping from instrumentation class names to info about them. 661 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 662 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 663 664 // Mapping from permission names to info about them. 665 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 666 new ArrayMap<String, PackageParser.PermissionGroup>(); 667 668 // Packages whose data we have transfered into another package, thus 669 // should no longer exist. 670 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 671 672 // Broadcast actions that are only available to the system. 673 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 674 675 /** List of packages waiting for verification. */ 676 final SparseArray<PackageVerificationState> mPendingVerification 677 = new SparseArray<PackageVerificationState>(); 678 679 /** Set of packages associated with each app op permission. */ 680 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 681 682 final PackageInstallerService mInstallerService; 683 684 private final PackageDexOptimizer mPackageDexOptimizer; 685 686 private AtomicInteger mNextMoveId = new AtomicInteger(); 687 private final MoveCallbacks mMoveCallbacks; 688 689 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 690 691 // Cache of users who need badging. 692 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 693 694 /** Token for keys in mPendingVerification. */ 695 private int mPendingVerificationToken = 0; 696 697 volatile boolean mSystemReady; 698 volatile boolean mSafeMode; 699 volatile boolean mHasSystemUidErrors; 700 701 ApplicationInfo mAndroidApplication; 702 final ActivityInfo mResolveActivity = new ActivityInfo(); 703 final ResolveInfo mResolveInfo = new ResolveInfo(); 704 ComponentName mResolveComponentName; 705 PackageParser.Package mPlatformPackage; 706 ComponentName mCustomResolverComponentName; 707 708 boolean mResolverReplaced = false; 709 710 private final @Nullable ComponentName mIntentFilterVerifierComponent; 711 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 712 713 private int mIntentFilterVerificationToken = 0; 714 715 /** Component that knows whether or not an ephemeral application exists */ 716 final ComponentName mEphemeralResolverComponent; 717 /** The service connection to the ephemeral resolver */ 718 final EphemeralResolverConnection mEphemeralResolverConnection; 719 720 /** Component used to install ephemeral applications */ 721 final ComponentName mEphemeralInstallerComponent; 722 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 723 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 724 725 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 726 = new SparseArray<IntentFilterVerificationState>(); 727 728 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 729 new DefaultPermissionGrantPolicy(this); 730 731 // List of packages names to keep cached, even if they are uninstalled for all users 732 private List<String> mKeepUninstalledPackages; 733 734 private static class IFVerificationParams { 735 PackageParser.Package pkg; 736 boolean replacing; 737 int userId; 738 int verifierUid; 739 740 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 741 int _userId, int _verifierUid) { 742 pkg = _pkg; 743 replacing = _replacing; 744 userId = _userId; 745 replacing = _replacing; 746 verifierUid = _verifierUid; 747 } 748 } 749 750 private interface IntentFilterVerifier<T extends IntentFilter> { 751 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 752 T filter, String packageName); 753 void startVerifications(int userId); 754 void receiveVerificationResponse(int verificationId); 755 } 756 757 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 758 private Context mContext; 759 private ComponentName mIntentFilterVerifierComponent; 760 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 761 762 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 763 mContext = context; 764 mIntentFilterVerifierComponent = verifierComponent; 765 } 766 767 private String getDefaultScheme() { 768 return IntentFilter.SCHEME_HTTPS; 769 } 770 771 @Override 772 public void startVerifications(int userId) { 773 // Launch verifications requests 774 int count = mCurrentIntentFilterVerifications.size(); 775 for (int n=0; n<count; n++) { 776 int verificationId = mCurrentIntentFilterVerifications.get(n); 777 final IntentFilterVerificationState ivs = 778 mIntentFilterVerificationStates.get(verificationId); 779 780 String packageName = ivs.getPackageName(); 781 782 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 783 final int filterCount = filters.size(); 784 ArraySet<String> domainsSet = new ArraySet<>(); 785 for (int m=0; m<filterCount; m++) { 786 PackageParser.ActivityIntentInfo filter = filters.get(m); 787 domainsSet.addAll(filter.getHostsList()); 788 } 789 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 790 synchronized (mPackages) { 791 if (mSettings.createIntentFilterVerificationIfNeededLPw( 792 packageName, domainsList) != null) { 793 scheduleWriteSettingsLocked(); 794 } 795 } 796 sendVerificationRequest(userId, verificationId, ivs); 797 } 798 mCurrentIntentFilterVerifications.clear(); 799 } 800 801 private void sendVerificationRequest(int userId, int verificationId, 802 IntentFilterVerificationState ivs) { 803 804 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 805 verificationIntent.putExtra( 806 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 807 verificationId); 808 verificationIntent.putExtra( 809 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 810 getDefaultScheme()); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 813 ivs.getHostsString()); 814 verificationIntent.putExtra( 815 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 816 ivs.getPackageName()); 817 verificationIntent.setComponent(mIntentFilterVerifierComponent); 818 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 819 820 UserHandle user = new UserHandle(userId); 821 mContext.sendBroadcastAsUser(verificationIntent, user); 822 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 823 "Sending IntentFilter verification broadcast"); 824 } 825 826 public void receiveVerificationResponse(int verificationId) { 827 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 828 829 final boolean verified = ivs.isVerified(); 830 831 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 832 final int count = filters.size(); 833 if (DEBUG_DOMAIN_VERIFICATION) { 834 Slog.i(TAG, "Received verification response " + verificationId 835 + " for " + count + " filters, verified=" + verified); 836 } 837 for (int n=0; n<count; n++) { 838 PackageParser.ActivityIntentInfo filter = filters.get(n); 839 filter.setVerified(verified); 840 841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 842 + " verified with result:" + verified + " and hosts:" 843 + ivs.getHostsString()); 844 } 845 846 mIntentFilterVerificationStates.remove(verificationId); 847 848 final String packageName = ivs.getPackageName(); 849 IntentFilterVerificationInfo ivi = null; 850 851 synchronized (mPackages) { 852 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 853 } 854 if (ivi == null) { 855 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 856 + verificationId + " packageName:" + packageName); 857 return; 858 } 859 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 860 "Updating IntentFilterVerificationInfo for package " + packageName 861 +" verificationId:" + verificationId); 862 863 synchronized (mPackages) { 864 if (verified) { 865 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 866 } else { 867 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 868 } 869 scheduleWriteSettingsLocked(); 870 871 final int userId = ivs.getUserId(); 872 if (userId != UserHandle.USER_ALL) { 873 final int userStatus = 874 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 875 876 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 877 boolean needUpdate = false; 878 879 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 880 // already been set by the User thru the Disambiguation dialog 881 switch (userStatus) { 882 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 883 if (verified) { 884 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 885 } else { 886 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 887 } 888 needUpdate = true; 889 break; 890 891 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 892 if (verified) { 893 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 894 needUpdate = true; 895 } 896 break; 897 898 default: 899 // Nothing to do 900 } 901 902 if (needUpdate) { 903 mSettings.updateIntentFilterVerificationStatusLPw( 904 packageName, updatedStatus, userId); 905 scheduleWritePackageRestrictionsLocked(userId); 906 } 907 } 908 } 909 } 910 911 @Override 912 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 913 ActivityIntentInfo filter, String packageName) { 914 if (!hasValidDomains(filter)) { 915 return false; 916 } 917 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 918 if (ivs == null) { 919 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 920 packageName); 921 } 922 if (DEBUG_DOMAIN_VERIFICATION) { 923 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 924 } 925 ivs.addFilter(filter); 926 return true; 927 } 928 929 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 930 int userId, int verificationId, String packageName) { 931 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 932 verifierUid, userId, packageName); 933 ivs.setPendingState(); 934 synchronized (mPackages) { 935 mIntentFilterVerificationStates.append(verificationId, ivs); 936 mCurrentIntentFilterVerifications.add(verificationId); 937 } 938 return ivs; 939 } 940 } 941 942 private static boolean hasValidDomains(ActivityIntentInfo filter) { 943 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 944 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 945 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 946 } 947 948 // Set of pending broadcasts for aggregating enable/disable of components. 949 static class PendingPackageBroadcasts { 950 // for each user id, a map of <package name -> components within that package> 951 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 952 953 public PendingPackageBroadcasts() { 954 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 955 } 956 957 public ArrayList<String> get(int userId, String packageName) { 958 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 959 return packages.get(packageName); 960 } 961 962 public void put(int userId, String packageName, ArrayList<String> components) { 963 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 964 packages.put(packageName, components); 965 } 966 967 public void remove(int userId, String packageName) { 968 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 969 if (packages != null) { 970 packages.remove(packageName); 971 } 972 } 973 974 public void remove(int userId) { 975 mUidMap.remove(userId); 976 } 977 978 public int userIdCount() { 979 return mUidMap.size(); 980 } 981 982 public int userIdAt(int n) { 983 return mUidMap.keyAt(n); 984 } 985 986 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 987 return mUidMap.get(userId); 988 } 989 990 public int size() { 991 // total number of pending broadcast entries across all userIds 992 int num = 0; 993 for (int i = 0; i< mUidMap.size(); i++) { 994 num += mUidMap.valueAt(i).size(); 995 } 996 return num; 997 } 998 999 public void clear() { 1000 mUidMap.clear(); 1001 } 1002 1003 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1004 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1005 if (map == null) { 1006 map = new ArrayMap<String, ArrayList<String>>(); 1007 mUidMap.put(userId, map); 1008 } 1009 return map; 1010 } 1011 } 1012 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1013 1014 // Service Connection to remote media container service to copy 1015 // package uri's from external media onto secure containers 1016 // or internal storage. 1017 private IMediaContainerService mContainerService = null; 1018 1019 static final int SEND_PENDING_BROADCAST = 1; 1020 static final int MCS_BOUND = 3; 1021 static final int END_COPY = 4; 1022 static final int INIT_COPY = 5; 1023 static final int MCS_UNBIND = 6; 1024 static final int START_CLEANING_PACKAGE = 7; 1025 static final int FIND_INSTALL_LOC = 8; 1026 static final int POST_INSTALL = 9; 1027 static final int MCS_RECONNECT = 10; 1028 static final int MCS_GIVE_UP = 11; 1029 static final int UPDATED_MEDIA_STATUS = 12; 1030 static final int WRITE_SETTINGS = 13; 1031 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1032 static final int PACKAGE_VERIFIED = 15; 1033 static final int CHECK_PENDING_VERIFICATION = 16; 1034 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1035 static final int INTENT_FILTER_VERIFIED = 18; 1036 1037 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1038 1039 // Delay time in millisecs 1040 static final int BROADCAST_DELAY = 10 * 1000; 1041 1042 static UserManagerService sUserManager; 1043 1044 // Stores a list of users whose package restrictions file needs to be updated 1045 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1046 1047 final private DefaultContainerConnection mDefContainerConn = 1048 new DefaultContainerConnection(); 1049 class DefaultContainerConnection implements ServiceConnection { 1050 public void onServiceConnected(ComponentName name, IBinder service) { 1051 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1052 IMediaContainerService imcs = 1053 IMediaContainerService.Stub.asInterface(service); 1054 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1055 } 1056 1057 public void onServiceDisconnected(ComponentName name) { 1058 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1059 } 1060 } 1061 1062 // Recordkeeping of restore-after-install operations that are currently in flight 1063 // between the Package Manager and the Backup Manager 1064 static class PostInstallData { 1065 public InstallArgs args; 1066 public PackageInstalledInfo res; 1067 1068 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1069 args = _a; 1070 res = _r; 1071 } 1072 } 1073 1074 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1075 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1076 1077 // XML tags for backup/restore of various bits of state 1078 private static final String TAG_PREFERRED_BACKUP = "pa"; 1079 private static final String TAG_DEFAULT_APPS = "da"; 1080 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1081 1082 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1083 private static final String TAG_ALL_GRANTS = "rt-grants"; 1084 private static final String TAG_GRANT = "grant"; 1085 private static final String ATTR_PACKAGE_NAME = "pkg"; 1086 1087 private static final String TAG_PERMISSION = "perm"; 1088 private static final String ATTR_PERMISSION_NAME = "name"; 1089 private static final String ATTR_IS_GRANTED = "g"; 1090 private static final String ATTR_USER_SET = "set"; 1091 private static final String ATTR_USER_FIXED = "fixed"; 1092 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1093 1094 // System/policy permission grants are not backed up 1095 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1096 FLAG_PERMISSION_POLICY_FIXED 1097 | FLAG_PERMISSION_SYSTEM_FIXED 1098 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1099 1100 // And we back up these user-adjusted states 1101 private static final int USER_RUNTIME_GRANT_MASK = 1102 FLAG_PERMISSION_USER_SET 1103 | FLAG_PERMISSION_USER_FIXED 1104 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1105 1106 final @Nullable String mRequiredVerifierPackage; 1107 final @NonNull String mRequiredInstallerPackage; 1108 final @Nullable String mSetupWizardPackage; 1109 final @NonNull String mServicesSystemSharedLibraryPackageName; 1110 final @NonNull String mSharedSystemSharedLibraryPackageName; 1111 1112 private final PackageUsage mPackageUsage = new PackageUsage(); 1113 1114 private class PackageUsage { 1115 private static final int WRITE_INTERVAL 1116 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1117 1118 private final Object mFileLock = new Object(); 1119 private final AtomicLong mLastWritten = new AtomicLong(0); 1120 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1121 1122 private boolean mIsHistoricalPackageUsageAvailable = true; 1123 1124 boolean isHistoricalPackageUsageAvailable() { 1125 return mIsHistoricalPackageUsageAvailable; 1126 } 1127 1128 void write(boolean force) { 1129 if (force) { 1130 writeInternal(); 1131 return; 1132 } 1133 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1134 && !DEBUG_DEXOPT) { 1135 return; 1136 } 1137 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1138 new Thread("PackageUsage_DiskWriter") { 1139 @Override 1140 public void run() { 1141 try { 1142 writeInternal(); 1143 } finally { 1144 mBackgroundWriteRunning.set(false); 1145 } 1146 } 1147 }.start(); 1148 } 1149 } 1150 1151 private void writeInternal() { 1152 synchronized (mPackages) { 1153 synchronized (mFileLock) { 1154 AtomicFile file = getFile(); 1155 FileOutputStream f = null; 1156 try { 1157 f = file.startWrite(); 1158 BufferedOutputStream out = new BufferedOutputStream(f); 1159 FileUtils.setPermissions(file.getBaseFile().getPath(), 1160 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1161 StringBuilder sb = new StringBuilder(); 1162 1163 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1164 sb.append('\n'); 1165 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1166 1167 for (PackageParser.Package pkg : mPackages.values()) { 1168 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1169 continue; 1170 } 1171 sb.setLength(0); 1172 sb.append(pkg.packageName); 1173 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1174 sb.append(' '); 1175 sb.append(usageTimeInMillis); 1176 } 1177 sb.append('\n'); 1178 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1179 } 1180 out.flush(); 1181 file.finishWrite(f); 1182 } catch (IOException e) { 1183 if (f != null) { 1184 file.failWrite(f); 1185 } 1186 Log.e(TAG, "Failed to write package usage times", e); 1187 } 1188 } 1189 } 1190 mLastWritten.set(SystemClock.elapsedRealtime()); 1191 } 1192 1193 void readLP() { 1194 synchronized (mFileLock) { 1195 AtomicFile file = getFile(); 1196 BufferedInputStream in = null; 1197 try { 1198 in = new BufferedInputStream(file.openRead()); 1199 StringBuffer sb = new StringBuffer(); 1200 1201 String firstLine = readLine(in, sb); 1202 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1203 readVersion1LP(in, sb); 1204 } else { 1205 readVersion0LP(in, sb, firstLine); 1206 } 1207 } catch (FileNotFoundException expected) { 1208 mIsHistoricalPackageUsageAvailable = false; 1209 } catch (IOException e) { 1210 Log.w(TAG, "Failed to read package usage times", e); 1211 } finally { 1212 IoUtils.closeQuietly(in); 1213 } 1214 } 1215 mLastWritten.set(SystemClock.elapsedRealtime()); 1216 } 1217 1218 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1219 throws IOException { 1220 // Initial version of the file had no version number and stored one 1221 // package-timestamp pair per line. 1222 // Note that the first line has already been read from the InputStream. 1223 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1224 String[] tokens = line.split(" "); 1225 if (tokens.length != 2) { 1226 throw new IOException("Failed to parse " + line + 1227 " as package-timestamp pair."); 1228 } 1229 1230 String packageName = tokens[0]; 1231 PackageParser.Package pkg = mPackages.get(packageName); 1232 if (pkg == null) { 1233 continue; 1234 } 1235 1236 long timestamp = parseAsLong(tokens[1]); 1237 for (int reason = 0; 1238 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1239 reason++) { 1240 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1241 } 1242 } 1243 } 1244 1245 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1246 // Version 1 of the file started with the corresponding version 1247 // number and then stored a package name and eight timestamps per line. 1248 String line; 1249 while ((line = readLine(in, sb)) != null) { 1250 String[] tokens = line.split(" "); 1251 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1252 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1253 } 1254 1255 String packageName = tokens[0]; 1256 PackageParser.Package pkg = mPackages.get(packageName); 1257 if (pkg == null) { 1258 continue; 1259 } 1260 1261 for (int reason = 0; 1262 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1263 reason++) { 1264 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1265 } 1266 } 1267 } 1268 1269 private long parseAsLong(String token) throws IOException { 1270 try { 1271 return Long.parseLong(token); 1272 } catch (NumberFormatException e) { 1273 throw new IOException("Failed to parse " + token + " as a long.", e); 1274 } 1275 } 1276 1277 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1278 return readToken(in, sb, '\n'); 1279 } 1280 1281 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1282 throws IOException { 1283 sb.setLength(0); 1284 while (true) { 1285 int ch = in.read(); 1286 if (ch == -1) { 1287 if (sb.length() == 0) { 1288 return null; 1289 } 1290 throw new IOException("Unexpected EOF"); 1291 } 1292 if (ch == endOfToken) { 1293 return sb.toString(); 1294 } 1295 sb.append((char)ch); 1296 } 1297 } 1298 1299 private AtomicFile getFile() { 1300 File dataDir = Environment.getDataDirectory(); 1301 File systemDir = new File(dataDir, "system"); 1302 File fname = new File(systemDir, "package-usage.list"); 1303 return new AtomicFile(fname); 1304 } 1305 1306 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1307 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1308 } 1309 1310 class PackageHandler extends Handler { 1311 private boolean mBound = false; 1312 final ArrayList<HandlerParams> mPendingInstalls = 1313 new ArrayList<HandlerParams>(); 1314 1315 private boolean connectToService() { 1316 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1317 " DefaultContainerService"); 1318 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1319 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1320 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1321 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1322 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1323 mBound = true; 1324 return true; 1325 } 1326 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1327 return false; 1328 } 1329 1330 private void disconnectService() { 1331 mContainerService = null; 1332 mBound = false; 1333 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1334 mContext.unbindService(mDefContainerConn); 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 } 1337 1338 PackageHandler(Looper looper) { 1339 super(looper); 1340 } 1341 1342 public void handleMessage(Message msg) { 1343 try { 1344 doHandleMessage(msg); 1345 } finally { 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1347 } 1348 } 1349 1350 void doHandleMessage(Message msg) { 1351 switch (msg.what) { 1352 case INIT_COPY: { 1353 HandlerParams params = (HandlerParams) msg.obj; 1354 int idx = mPendingInstalls.size(); 1355 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1356 // If a bind was already initiated we dont really 1357 // need to do anything. The pending install 1358 // will be processed later on. 1359 if (!mBound) { 1360 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1361 System.identityHashCode(mHandler)); 1362 // If this is the only one pending we might 1363 // have to bind to the service again. 1364 if (!connectToService()) { 1365 Slog.e(TAG, "Failed to bind to media container service"); 1366 params.serviceError(); 1367 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1368 System.identityHashCode(mHandler)); 1369 if (params.traceMethod != null) { 1370 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1371 params.traceCookie); 1372 } 1373 return; 1374 } else { 1375 // Once we bind to the service, the first 1376 // pending request will be processed. 1377 mPendingInstalls.add(idx, params); 1378 } 1379 } else { 1380 mPendingInstalls.add(idx, params); 1381 // Already bound to the service. Just make 1382 // sure we trigger off processing the first request. 1383 if (idx == 0) { 1384 mHandler.sendEmptyMessage(MCS_BOUND); 1385 } 1386 } 1387 break; 1388 } 1389 case MCS_BOUND: { 1390 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1391 if (msg.obj != null) { 1392 mContainerService = (IMediaContainerService) msg.obj; 1393 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1394 System.identityHashCode(mHandler)); 1395 } 1396 if (mContainerService == null) { 1397 if (!mBound) { 1398 // Something seriously wrong since we are not bound and we are not 1399 // waiting for connection. Bail out. 1400 Slog.e(TAG, "Cannot bind to media container service"); 1401 for (HandlerParams params : mPendingInstalls) { 1402 // Indicate service bind error 1403 params.serviceError(); 1404 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1405 System.identityHashCode(params)); 1406 if (params.traceMethod != null) { 1407 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1408 params.traceMethod, params.traceCookie); 1409 } 1410 return; 1411 } 1412 mPendingInstalls.clear(); 1413 } else { 1414 Slog.w(TAG, "Waiting to connect to media container service"); 1415 } 1416 } else if (mPendingInstalls.size() > 0) { 1417 HandlerParams params = mPendingInstalls.get(0); 1418 if (params != null) { 1419 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1420 System.identityHashCode(params)); 1421 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1422 if (params.startCopy()) { 1423 // We are done... look for more work or to 1424 // go idle. 1425 if (DEBUG_SD_INSTALL) Log.i(TAG, 1426 "Checking for more work or unbind..."); 1427 // Delete pending install 1428 if (mPendingInstalls.size() > 0) { 1429 mPendingInstalls.remove(0); 1430 } 1431 if (mPendingInstalls.size() == 0) { 1432 if (mBound) { 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, 1434 "Posting delayed MCS_UNBIND"); 1435 removeMessages(MCS_UNBIND); 1436 Message ubmsg = obtainMessage(MCS_UNBIND); 1437 // Unbind after a little delay, to avoid 1438 // continual thrashing. 1439 sendMessageDelayed(ubmsg, 10000); 1440 } 1441 } else { 1442 // There are more pending requests in queue. 1443 // Just post MCS_BOUND message to trigger processing 1444 // of next pending install. 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, 1446 "Posting MCS_BOUND for next work"); 1447 mHandler.sendEmptyMessage(MCS_BOUND); 1448 } 1449 } 1450 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1451 } 1452 } else { 1453 // Should never happen ideally. 1454 Slog.w(TAG, "Empty queue"); 1455 } 1456 break; 1457 } 1458 case MCS_RECONNECT: { 1459 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1460 if (mPendingInstalls.size() > 0) { 1461 if (mBound) { 1462 disconnectService(); 1463 } 1464 if (!connectToService()) { 1465 Slog.e(TAG, "Failed to bind to media container service"); 1466 for (HandlerParams params : mPendingInstalls) { 1467 // Indicate service bind error 1468 params.serviceError(); 1469 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1470 System.identityHashCode(params)); 1471 } 1472 mPendingInstalls.clear(); 1473 } 1474 } 1475 break; 1476 } 1477 case MCS_UNBIND: { 1478 // If there is no actual work left, then time to unbind. 1479 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1480 1481 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1482 if (mBound) { 1483 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1484 1485 disconnectService(); 1486 } 1487 } else if (mPendingInstalls.size() > 0) { 1488 // There are more pending requests in queue. 1489 // Just post MCS_BOUND message to trigger processing 1490 // of next pending install. 1491 mHandler.sendEmptyMessage(MCS_BOUND); 1492 } 1493 1494 break; 1495 } 1496 case MCS_GIVE_UP: { 1497 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1498 HandlerParams params = mPendingInstalls.remove(0); 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1500 System.identityHashCode(params)); 1501 break; 1502 } 1503 case SEND_PENDING_BROADCAST: { 1504 String packages[]; 1505 ArrayList<String> components[]; 1506 int size = 0; 1507 int uids[]; 1508 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1509 synchronized (mPackages) { 1510 if (mPendingBroadcasts == null) { 1511 return; 1512 } 1513 size = mPendingBroadcasts.size(); 1514 if (size <= 0) { 1515 // Nothing to be done. Just return 1516 return; 1517 } 1518 packages = new String[size]; 1519 components = new ArrayList[size]; 1520 uids = new int[size]; 1521 int i = 0; // filling out the above arrays 1522 1523 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1524 int packageUserId = mPendingBroadcasts.userIdAt(n); 1525 Iterator<Map.Entry<String, ArrayList<String>>> it 1526 = mPendingBroadcasts.packagesForUserId(packageUserId) 1527 .entrySet().iterator(); 1528 while (it.hasNext() && i < size) { 1529 Map.Entry<String, ArrayList<String>> ent = it.next(); 1530 packages[i] = ent.getKey(); 1531 components[i] = ent.getValue(); 1532 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1533 uids[i] = (ps != null) 1534 ? UserHandle.getUid(packageUserId, ps.appId) 1535 : -1; 1536 i++; 1537 } 1538 } 1539 size = i; 1540 mPendingBroadcasts.clear(); 1541 } 1542 // Send broadcasts 1543 for (int i = 0; i < size; i++) { 1544 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1545 } 1546 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1547 break; 1548 } 1549 case START_CLEANING_PACKAGE: { 1550 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1551 final String packageName = (String)msg.obj; 1552 final int userId = msg.arg1; 1553 final boolean andCode = msg.arg2 != 0; 1554 synchronized (mPackages) { 1555 if (userId == UserHandle.USER_ALL) { 1556 int[] users = sUserManager.getUserIds(); 1557 for (int user : users) { 1558 mSettings.addPackageToCleanLPw( 1559 new PackageCleanItem(user, packageName, andCode)); 1560 } 1561 } else { 1562 mSettings.addPackageToCleanLPw( 1563 new PackageCleanItem(userId, packageName, andCode)); 1564 } 1565 } 1566 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1567 startCleaningPackages(); 1568 } break; 1569 case POST_INSTALL: { 1570 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1571 1572 PostInstallData data = mRunningInstalls.get(msg.arg1); 1573 final boolean didRestore = (msg.arg2 != 0); 1574 mRunningInstalls.delete(msg.arg1); 1575 1576 if (data != null) { 1577 InstallArgs args = data.args; 1578 PackageInstalledInfo parentRes = data.res; 1579 1580 final boolean grantPermissions = (args.installFlags 1581 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1582 final boolean killApp = (args.installFlags 1583 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1584 final String[] grantedPermissions = args.installGrantPermissions; 1585 1586 // Handle the parent package 1587 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1588 grantedPermissions, didRestore, args.installerPackageName, 1589 args.observer); 1590 1591 // Handle the child packages 1592 final int childCount = (parentRes.addedChildPackages != null) 1593 ? parentRes.addedChildPackages.size() : 0; 1594 for (int i = 0; i < childCount; i++) { 1595 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1596 handlePackagePostInstall(childRes, grantPermissions, killApp, 1597 grantedPermissions, false, args.installerPackageName, 1598 args.observer); 1599 } 1600 1601 // Log tracing if needed 1602 if (args.traceMethod != null) { 1603 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1604 args.traceCookie); 1605 } 1606 } else { 1607 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1608 } 1609 1610 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1611 } break; 1612 case UPDATED_MEDIA_STATUS: { 1613 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1614 boolean reportStatus = msg.arg1 == 1; 1615 boolean doGc = msg.arg2 == 1; 1616 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1617 if (doGc) { 1618 // Force a gc to clear up stale containers. 1619 Runtime.getRuntime().gc(); 1620 } 1621 if (msg.obj != null) { 1622 @SuppressWarnings("unchecked") 1623 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1624 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1625 // Unload containers 1626 unloadAllContainers(args); 1627 } 1628 if (reportStatus) { 1629 try { 1630 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1631 PackageHelper.getMountService().finishMediaUpdate(); 1632 } catch (RemoteException e) { 1633 Log.e(TAG, "MountService not running?"); 1634 } 1635 } 1636 } break; 1637 case WRITE_SETTINGS: { 1638 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1639 synchronized (mPackages) { 1640 removeMessages(WRITE_SETTINGS); 1641 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1642 mSettings.writeLPr(); 1643 mDirtyUsers.clear(); 1644 } 1645 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1646 } break; 1647 case WRITE_PACKAGE_RESTRICTIONS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1651 for (int userId : mDirtyUsers) { 1652 mSettings.writePackageRestrictionsLPr(userId); 1653 } 1654 mDirtyUsers.clear(); 1655 } 1656 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1657 } break; 1658 case CHECK_PENDING_VERIFICATION: { 1659 final int verificationId = msg.arg1; 1660 final PackageVerificationState state = mPendingVerification.get(verificationId); 1661 1662 if ((state != null) && !state.timeoutExtended()) { 1663 final InstallArgs args = state.getInstallArgs(); 1664 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1665 1666 Slog.i(TAG, "Verification timed out for " + originUri); 1667 mPendingVerification.remove(verificationId); 1668 1669 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1670 1671 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1672 Slog.i(TAG, "Continuing with installation of " + originUri); 1673 state.setVerifierResponse(Binder.getCallingUid(), 1674 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1675 broadcastPackageVerified(verificationId, originUri, 1676 PackageManager.VERIFICATION_ALLOW, 1677 state.getInstallArgs().getUser()); 1678 try { 1679 ret = args.copyApk(mContainerService, true); 1680 } catch (RemoteException e) { 1681 Slog.e(TAG, "Could not contact the ContainerService"); 1682 } 1683 } else { 1684 broadcastPackageVerified(verificationId, originUri, 1685 PackageManager.VERIFICATION_REJECT, 1686 state.getInstallArgs().getUser()); 1687 } 1688 1689 Trace.asyncTraceEnd( 1690 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1691 1692 processPendingInstall(args, ret); 1693 mHandler.sendEmptyMessage(MCS_UNBIND); 1694 } 1695 break; 1696 } 1697 case PACKAGE_VERIFIED: { 1698 final int verificationId = msg.arg1; 1699 1700 final PackageVerificationState state = mPendingVerification.get(verificationId); 1701 if (state == null) { 1702 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1703 break; 1704 } 1705 1706 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1707 1708 state.setVerifierResponse(response.callerUid, response.code); 1709 1710 if (state.isVerificationComplete()) { 1711 mPendingVerification.remove(verificationId); 1712 1713 final InstallArgs args = state.getInstallArgs(); 1714 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1715 1716 int ret; 1717 if (state.isInstallAllowed()) { 1718 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1719 broadcastPackageVerified(verificationId, originUri, 1720 response.code, state.getInstallArgs().getUser()); 1721 try { 1722 ret = args.copyApk(mContainerService, true); 1723 } catch (RemoteException e) { 1724 Slog.e(TAG, "Could not contact the ContainerService"); 1725 } 1726 } else { 1727 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1728 } 1729 1730 Trace.asyncTraceEnd( 1731 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1732 1733 processPendingInstall(args, ret); 1734 mHandler.sendEmptyMessage(MCS_UNBIND); 1735 } 1736 1737 break; 1738 } 1739 case START_INTENT_FILTER_VERIFICATIONS: { 1740 IFVerificationParams params = (IFVerificationParams) msg.obj; 1741 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1742 params.replacing, params.pkg); 1743 break; 1744 } 1745 case INTENT_FILTER_VERIFIED: { 1746 final int verificationId = msg.arg1; 1747 1748 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1749 verificationId); 1750 if (state == null) { 1751 Slog.w(TAG, "Invalid IntentFilter verification token " 1752 + verificationId + " received"); 1753 break; 1754 } 1755 1756 final int userId = state.getUserId(); 1757 1758 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1759 "Processing IntentFilter verification with token:" 1760 + verificationId + " and userId:" + userId); 1761 1762 final IntentFilterVerificationResponse response = 1763 (IntentFilterVerificationResponse) msg.obj; 1764 1765 state.setVerifierResponse(response.callerUid, response.code); 1766 1767 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1768 "IntentFilter verification with token:" + verificationId 1769 + " and userId:" + userId 1770 + " is settings verifier response with response code:" 1771 + response.code); 1772 1773 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1774 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1775 + response.getFailedDomainsString()); 1776 } 1777 1778 if (state.isVerificationComplete()) { 1779 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1780 } else { 1781 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1782 "IntentFilter verification with token:" + verificationId 1783 + " was not said to be complete"); 1784 } 1785 1786 break; 1787 } 1788 } 1789 } 1790 } 1791 1792 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1793 boolean killApp, String[] grantedPermissions, 1794 boolean launchedForRestore, String installerPackage, 1795 IPackageInstallObserver2 installObserver) { 1796 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1797 // Send the removed broadcasts 1798 if (res.removedInfo != null) { 1799 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1800 } 1801 1802 // Now that we successfully installed the package, grant runtime 1803 // permissions if requested before broadcasting the install. 1804 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1805 >= Build.VERSION_CODES.M) { 1806 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1807 } 1808 1809 final boolean update = res.removedInfo != null 1810 && res.removedInfo.removedPackage != null; 1811 1812 // If this is the first time we have child packages for a disabled privileged 1813 // app that had no children, we grant requested runtime permissions to the new 1814 // children if the parent on the system image had them already granted. 1815 if (res.pkg.parentPackage != null) { 1816 synchronized (mPackages) { 1817 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1818 } 1819 } 1820 1821 synchronized (mPackages) { 1822 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1823 } 1824 1825 final String packageName = res.pkg.applicationInfo.packageName; 1826 Bundle extras = new Bundle(1); 1827 extras.putInt(Intent.EXTRA_UID, res.uid); 1828 1829 // Determine the set of users who are adding this package for 1830 // the first time vs. those who are seeing an update. 1831 int[] firstUsers = EMPTY_INT_ARRAY; 1832 int[] updateUsers = EMPTY_INT_ARRAY; 1833 if (res.origUsers == null || res.origUsers.length == 0) { 1834 firstUsers = res.newUsers; 1835 } else { 1836 for (int newUser : res.newUsers) { 1837 boolean isNew = true; 1838 for (int origUser : res.origUsers) { 1839 if (origUser == newUser) { 1840 isNew = false; 1841 break; 1842 } 1843 } 1844 if (isNew) { 1845 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1846 } else { 1847 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1848 } 1849 } 1850 } 1851 1852 // Send installed broadcasts if the install/update is not ephemeral 1853 if (!isEphemeral(res.pkg)) { 1854 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1855 1856 // Send added for users that see the package for the first time 1857 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1858 extras, 0 /*flags*/, null /*targetPackage*/, 1859 null /*finishedReceiver*/, firstUsers); 1860 1861 // Send added for users that don't see the package for the first time 1862 if (update) { 1863 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1864 } 1865 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1866 extras, 0 /*flags*/, null /*targetPackage*/, 1867 null /*finishedReceiver*/, updateUsers); 1868 1869 // Send replaced for users that don't see the package for the first time 1870 if (update) { 1871 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1872 packageName, extras, 0 /*flags*/, 1873 null /*targetPackage*/, null /*finishedReceiver*/, 1874 updateUsers); 1875 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1876 null /*package*/, null /*extras*/, 0 /*flags*/, 1877 packageName /*targetPackage*/, 1878 null /*finishedReceiver*/, updateUsers); 1879 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1880 // First-install and we did a restore, so we're responsible for the 1881 // first-launch broadcast. 1882 if (DEBUG_BACKUP) { 1883 Slog.i(TAG, "Post-restore of " + packageName 1884 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1885 } 1886 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1887 } 1888 1889 // Send broadcast package appeared if forward locked/external for all users 1890 // treat asec-hosted packages like removable media on upgrade 1891 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1892 if (DEBUG_INSTALL) { 1893 Slog.i(TAG, "upgrading pkg " + res.pkg 1894 + " is ASEC-hosted -> AVAILABLE"); 1895 } 1896 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1897 ArrayList<String> pkgList = new ArrayList<>(1); 1898 pkgList.add(packageName); 1899 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1900 } 1901 } 1902 1903 // Work that needs to happen on first install within each user 1904 if (firstUsers != null && firstUsers.length > 0) { 1905 synchronized (mPackages) { 1906 for (int userId : firstUsers) { 1907 // If this app is a browser and it's newly-installed for some 1908 // users, clear any default-browser state in those users. The 1909 // app's nature doesn't depend on the user, so we can just check 1910 // its browser nature in any user and generalize. 1911 if (packageIsBrowser(packageName, userId)) { 1912 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1913 } 1914 1915 // We may also need to apply pending (restored) runtime 1916 // permission grants within these users. 1917 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1918 } 1919 } 1920 } 1921 1922 // Log current value of "unknown sources" setting 1923 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1924 getUnknownSourcesSettings()); 1925 1926 // Force a gc to clear up things 1927 Runtime.getRuntime().gc(); 1928 1929 // Remove the replaced package's older resources safely now 1930 // We delete after a gc for applications on sdcard. 1931 if (res.removedInfo != null && res.removedInfo.args != null) { 1932 synchronized (mInstallLock) { 1933 res.removedInfo.args.doPostDeleteLI(true); 1934 } 1935 } 1936 } 1937 1938 // If someone is watching installs - notify them 1939 if (installObserver != null) { 1940 try { 1941 Bundle extras = extrasForInstallResult(res); 1942 installObserver.onPackageInstalled(res.name, res.returnCode, 1943 res.returnMsg, extras); 1944 } catch (RemoteException e) { 1945 Slog.i(TAG, "Observer no longer exists."); 1946 } 1947 } 1948 } 1949 1950 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1951 PackageParser.Package pkg) { 1952 if (pkg.parentPackage == null) { 1953 return; 1954 } 1955 if (pkg.requestedPermissions == null) { 1956 return; 1957 } 1958 final PackageSetting disabledSysParentPs = mSettings 1959 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1960 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1961 || !disabledSysParentPs.isPrivileged() 1962 || (disabledSysParentPs.childPackageNames != null 1963 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1964 return; 1965 } 1966 final int[] allUserIds = sUserManager.getUserIds(); 1967 final int permCount = pkg.requestedPermissions.size(); 1968 for (int i = 0; i < permCount; i++) { 1969 String permission = pkg.requestedPermissions.get(i); 1970 BasePermission bp = mSettings.mPermissions.get(permission); 1971 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1972 continue; 1973 } 1974 for (int userId : allUserIds) { 1975 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1976 permission, userId)) { 1977 grantRuntimePermission(pkg.packageName, permission, userId); 1978 } 1979 } 1980 } 1981 } 1982 1983 private StorageEventListener mStorageListener = new StorageEventListener() { 1984 @Override 1985 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1986 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1987 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1988 final String volumeUuid = vol.getFsUuid(); 1989 1990 // Clean up any users or apps that were removed or recreated 1991 // while this volume was missing 1992 reconcileUsers(volumeUuid); 1993 reconcileApps(volumeUuid); 1994 1995 // Clean up any install sessions that expired or were 1996 // cancelled while this volume was missing 1997 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1998 1999 loadPrivatePackages(vol); 2000 2001 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2002 unloadPrivatePackages(vol); 2003 } 2004 } 2005 2006 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2007 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2008 updateExternalMediaStatus(true, false); 2009 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2010 updateExternalMediaStatus(false, false); 2011 } 2012 } 2013 } 2014 2015 @Override 2016 public void onVolumeForgotten(String fsUuid) { 2017 if (TextUtils.isEmpty(fsUuid)) { 2018 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2019 return; 2020 } 2021 2022 // Remove any apps installed on the forgotten volume 2023 synchronized (mPackages) { 2024 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2025 for (PackageSetting ps : packages) { 2026 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2027 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2028 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2029 } 2030 2031 mSettings.onVolumeForgotten(fsUuid); 2032 mSettings.writeLPr(); 2033 } 2034 } 2035 }; 2036 2037 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2038 String[] grantedPermissions) { 2039 for (int userId : userIds) { 2040 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2041 } 2042 2043 // We could have touched GID membership, so flush out packages.list 2044 synchronized (mPackages) { 2045 mSettings.writePackageListLPr(); 2046 } 2047 } 2048 2049 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2050 String[] grantedPermissions) { 2051 SettingBase sb = (SettingBase) pkg.mExtras; 2052 if (sb == null) { 2053 return; 2054 } 2055 2056 PermissionsState permissionsState = sb.getPermissionsState(); 2057 2058 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2059 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2060 2061 for (String permission : pkg.requestedPermissions) { 2062 final BasePermission bp; 2063 synchronized (mPackages) { 2064 bp = mSettings.mPermissions.get(permission); 2065 } 2066 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2067 && (grantedPermissions == null 2068 || ArrayUtils.contains(grantedPermissions, permission))) { 2069 final int flags = permissionsState.getPermissionFlags(permission, userId); 2070 // Installer cannot change immutable permissions. 2071 if ((flags & immutableFlags) == 0) { 2072 grantRuntimePermission(pkg.packageName, permission, userId); 2073 } 2074 } 2075 } 2076 } 2077 2078 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2079 Bundle extras = null; 2080 switch (res.returnCode) { 2081 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2082 extras = new Bundle(); 2083 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2084 res.origPermission); 2085 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2086 res.origPackage); 2087 break; 2088 } 2089 case PackageManager.INSTALL_SUCCEEDED: { 2090 extras = new Bundle(); 2091 extras.putBoolean(Intent.EXTRA_REPLACING, 2092 res.removedInfo != null && res.removedInfo.removedPackage != null); 2093 break; 2094 } 2095 } 2096 return extras; 2097 } 2098 2099 void scheduleWriteSettingsLocked() { 2100 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2101 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2102 } 2103 } 2104 2105 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2106 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2107 scheduleWritePackageRestrictionsLocked(userId); 2108 } 2109 2110 void scheduleWritePackageRestrictionsLocked(int userId) { 2111 final int[] userIds = (userId == UserHandle.USER_ALL) 2112 ? sUserManager.getUserIds() : new int[]{userId}; 2113 for (int nextUserId : userIds) { 2114 if (!sUserManager.exists(nextUserId)) return; 2115 mDirtyUsers.add(nextUserId); 2116 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2117 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2118 } 2119 } 2120 } 2121 2122 public static PackageManagerService main(Context context, Installer installer, 2123 boolean factoryTest, boolean onlyCore) { 2124 // Self-check for initial settings. 2125 PackageManagerServiceCompilerMapping.checkProperties(); 2126 2127 PackageManagerService m = new PackageManagerService(context, installer, 2128 factoryTest, onlyCore); 2129 m.enableSystemUserPackages(); 2130 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2131 // disabled after already being started. 2132 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2133 UserHandle.USER_SYSTEM); 2134 ServiceManager.addService("package", m); 2135 return m; 2136 } 2137 2138 private void enableSystemUserPackages() { 2139 if (!UserManager.isSplitSystemUser()) { 2140 return; 2141 } 2142 // For system user, enable apps based on the following conditions: 2143 // - app is whitelisted or belong to one of these groups: 2144 // -- system app which has no launcher icons 2145 // -- system app which has INTERACT_ACROSS_USERS permission 2146 // -- system IME app 2147 // - app is not in the blacklist 2148 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2149 Set<String> enableApps = new ArraySet<>(); 2150 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2151 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2152 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2153 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2154 enableApps.addAll(wlApps); 2155 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2156 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2157 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2158 enableApps.removeAll(blApps); 2159 Log.i(TAG, "Applications installed for system user: " + enableApps); 2160 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2161 UserHandle.SYSTEM); 2162 final int allAppsSize = allAps.size(); 2163 synchronized (mPackages) { 2164 for (int i = 0; i < allAppsSize; i++) { 2165 String pName = allAps.get(i); 2166 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2167 // Should not happen, but we shouldn't be failing if it does 2168 if (pkgSetting == null) { 2169 continue; 2170 } 2171 boolean install = enableApps.contains(pName); 2172 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2173 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2174 + " for system user"); 2175 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2176 } 2177 } 2178 } 2179 } 2180 2181 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2182 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2183 Context.DISPLAY_SERVICE); 2184 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2185 } 2186 2187 public PackageManagerService(Context context, Installer installer, 2188 boolean factoryTest, boolean onlyCore) { 2189 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2190 SystemClock.uptimeMillis()); 2191 2192 if (mSdkVersion <= 0) { 2193 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2194 } 2195 2196 mContext = context; 2197 mFactoryTest = factoryTest; 2198 mOnlyCore = onlyCore; 2199 mMetrics = new DisplayMetrics(); 2200 mSettings = new Settings(mPackages); 2201 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2202 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2203 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2204 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2205 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2206 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2207 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2208 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2209 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2210 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2211 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 2214 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2215 if (separateProcesses != null && separateProcesses.length() > 0) { 2216 if ("*".equals(separateProcesses)) { 2217 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2218 mSeparateProcesses = null; 2219 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2220 } else { 2221 mDefParseFlags = 0; 2222 mSeparateProcesses = separateProcesses.split(","); 2223 Slog.w(TAG, "Running with debug.separate_processes: " 2224 + separateProcesses); 2225 } 2226 } else { 2227 mDefParseFlags = 0; 2228 mSeparateProcesses = null; 2229 } 2230 2231 mInstaller = installer; 2232 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2233 "*dexopt*"); 2234 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2235 2236 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2237 FgThread.get().getLooper()); 2238 2239 getDefaultDisplayMetrics(context, mMetrics); 2240 2241 SystemConfig systemConfig = SystemConfig.getInstance(); 2242 mGlobalGids = systemConfig.getGlobalGids(); 2243 mSystemPermissions = systemConfig.getSystemPermissions(); 2244 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2245 2246 synchronized (mInstallLock) { 2247 // writer 2248 synchronized (mPackages) { 2249 mHandlerThread = new ServiceThread(TAG, 2250 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2251 mHandlerThread.start(); 2252 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2253 mProcessLoggingHandler = new ProcessLoggingHandler(); 2254 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2255 2256 File dataDir = Environment.getDataDirectory(); 2257 mAppInstallDir = new File(dataDir, "app"); 2258 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2259 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2260 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2261 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2262 2263 sUserManager = new UserManagerService(context, this, mPackages); 2264 2265 // Propagate permission configuration in to package manager. 2266 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2267 = systemConfig.getPermissions(); 2268 for (int i=0; i<permConfig.size(); i++) { 2269 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2270 BasePermission bp = mSettings.mPermissions.get(perm.name); 2271 if (bp == null) { 2272 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2273 mSettings.mPermissions.put(perm.name, bp); 2274 } 2275 if (perm.gids != null) { 2276 bp.setGids(perm.gids, perm.perUser); 2277 } 2278 } 2279 2280 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2281 for (int i=0; i<libConfig.size(); i++) { 2282 mSharedLibraries.put(libConfig.keyAt(i), 2283 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2284 } 2285 2286 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2287 2288 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2289 2290 String customResolverActivity = Resources.getSystem().getString( 2291 R.string.config_customResolverActivity); 2292 if (TextUtils.isEmpty(customResolverActivity)) { 2293 customResolverActivity = null; 2294 } else { 2295 mCustomResolverComponentName = ComponentName.unflattenFromString( 2296 customResolverActivity); 2297 } 2298 2299 long startTime = SystemClock.uptimeMillis(); 2300 2301 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2302 startTime); 2303 2304 // Set flag to monitor and not change apk file paths when 2305 // scanning install directories. 2306 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2307 2308 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2309 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2310 2311 if (bootClassPath == null) { 2312 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2313 } 2314 2315 if (systemServerClassPath == null) { 2316 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2317 } 2318 2319 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2320 final String[] dexCodeInstructionSets = 2321 getDexCodeInstructionSets( 2322 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2323 2324 /** 2325 * Ensure all external libraries have had dexopt run on them. 2326 */ 2327 if (mSharedLibraries.size() > 0) { 2328 // NOTE: For now, we're compiling these system "shared libraries" 2329 // (and framework jars) into all available architectures. It's possible 2330 // to compile them only when we come across an app that uses them (there's 2331 // already logic for that in scanPackageLI) but that adds some complexity. 2332 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2333 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2334 final String lib = libEntry.path; 2335 if (lib == null) { 2336 continue; 2337 } 2338 2339 try { 2340 // Shared libraries do not have profiles so we perform a full 2341 // AOT compilation (if needed). 2342 int dexoptNeeded = DexFile.getDexOptNeeded( 2343 lib, dexCodeInstructionSet, 2344 getCompilerFilterForReason(REASON_SHARED_APK), 2345 false /* newProfile */); 2346 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2347 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2348 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2349 getCompilerFilterForReason(REASON_SHARED_APK), 2350 StorageManager.UUID_PRIVATE_INTERNAL, 2351 SKIP_SHARED_LIBRARY_CHECK); 2352 } 2353 } catch (FileNotFoundException e) { 2354 Slog.w(TAG, "Library not found: " + lib); 2355 } catch (IOException | InstallerException e) { 2356 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2357 + e.getMessage()); 2358 } 2359 } 2360 } 2361 } 2362 2363 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2364 2365 final VersionInfo ver = mSettings.getInternalVersion(); 2366 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2367 2368 // when upgrading from pre-M, promote system app permissions from install to runtime 2369 mPromoteSystemApps = 2370 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2371 2372 // save off the names of pre-existing system packages prior to scanning; we don't 2373 // want to automatically grant runtime permissions for new system apps 2374 if (mPromoteSystemApps) { 2375 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2376 while (pkgSettingIter.hasNext()) { 2377 PackageSetting ps = pkgSettingIter.next(); 2378 if (isSystemApp(ps)) { 2379 mExistingSystemPackages.add(ps.name); 2380 } 2381 } 2382 } 2383 2384 // When upgrading from pre-N, we need to handle package extraction like first boot, 2385 // as there is no profiling data available. 2386 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2387 mSettings.setNWorkDone(); 2388 2389 // Collect vendor overlay packages. 2390 // (Do this before scanning any apps.) 2391 // For security and version matching reason, only consider 2392 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2393 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2394 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2395 | PackageParser.PARSE_IS_SYSTEM 2396 | PackageParser.PARSE_IS_SYSTEM_DIR 2397 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2398 2399 // Find base frameworks (resource packages without code). 2400 scanDirTracedLI(frameworkDir, mDefParseFlags 2401 | PackageParser.PARSE_IS_SYSTEM 2402 | PackageParser.PARSE_IS_SYSTEM_DIR 2403 | PackageParser.PARSE_IS_PRIVILEGED, 2404 scanFlags | SCAN_NO_DEX, 0); 2405 2406 // Collected privileged system packages. 2407 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2408 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2409 | PackageParser.PARSE_IS_SYSTEM 2410 | PackageParser.PARSE_IS_SYSTEM_DIR 2411 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2412 2413 // Collect ordinary system packages. 2414 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2415 scanDirTracedLI(systemAppDir, mDefParseFlags 2416 | PackageParser.PARSE_IS_SYSTEM 2417 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2418 2419 // Collect all vendor packages. 2420 File vendorAppDir = new File("/vendor/app"); 2421 try { 2422 vendorAppDir = vendorAppDir.getCanonicalFile(); 2423 } catch (IOException e) { 2424 // failed to look up canonical path, continue with original one 2425 } 2426 scanDirTracedLI(vendorAppDir, mDefParseFlags 2427 | PackageParser.PARSE_IS_SYSTEM 2428 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2429 2430 // Collect all OEM packages. 2431 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2432 scanDirTracedLI(oemAppDir, mDefParseFlags 2433 | PackageParser.PARSE_IS_SYSTEM 2434 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2435 2436 // Prune any system packages that no longer exist. 2437 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2438 if (!mOnlyCore) { 2439 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2440 while (psit.hasNext()) { 2441 PackageSetting ps = psit.next(); 2442 2443 /* 2444 * If this is not a system app, it can't be a 2445 * disable system app. 2446 */ 2447 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2448 continue; 2449 } 2450 2451 /* 2452 * If the package is scanned, it's not erased. 2453 */ 2454 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2455 if (scannedPkg != null) { 2456 /* 2457 * If the system app is both scanned and in the 2458 * disabled packages list, then it must have been 2459 * added via OTA. Remove it from the currently 2460 * scanned package so the previously user-installed 2461 * application can be scanned. 2462 */ 2463 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2464 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2465 + ps.name + "; removing system app. Last known codePath=" 2466 + ps.codePathString + ", installStatus=" + ps.installStatus 2467 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2468 + scannedPkg.mVersionCode); 2469 removePackageLI(scannedPkg, true); 2470 mExpectingBetter.put(ps.name, ps.codePath); 2471 } 2472 2473 continue; 2474 } 2475 2476 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2477 psit.remove(); 2478 logCriticalInfo(Log.WARN, "System package " + ps.name 2479 + " no longer exists; it's data will be wiped"); 2480 // Actual deletion of code and data will be handled by later 2481 // reconciliation step 2482 } else { 2483 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2484 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2485 possiblyDeletedUpdatedSystemApps.add(ps.name); 2486 } 2487 } 2488 } 2489 } 2490 2491 //look for any incomplete package installations 2492 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2493 for (int i = 0; i < deletePkgsList.size(); i++) { 2494 // Actual deletion of code and data will be handled by later 2495 // reconciliation step 2496 final String packageName = deletePkgsList.get(i).name; 2497 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2498 synchronized (mPackages) { 2499 mSettings.removePackageLPw(packageName); 2500 } 2501 } 2502 2503 //delete tmp files 2504 deleteTempPackageFiles(); 2505 2506 // Remove any shared userIDs that have no associated packages 2507 mSettings.pruneSharedUsersLPw(); 2508 2509 if (!mOnlyCore) { 2510 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2511 SystemClock.uptimeMillis()); 2512 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2513 2514 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2515 | PackageParser.PARSE_FORWARD_LOCK, 2516 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2517 2518 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2519 | PackageParser.PARSE_IS_EPHEMERAL, 2520 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2521 2522 /** 2523 * Remove disable package settings for any updated system 2524 * apps that were removed via an OTA. If they're not a 2525 * previously-updated app, remove them completely. 2526 * Otherwise, just revoke their system-level permissions. 2527 */ 2528 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2529 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2530 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2531 2532 String msg; 2533 if (deletedPkg == null) { 2534 msg = "Updated system package " + deletedAppName 2535 + " no longer exists; it's data will be wiped"; 2536 // Actual deletion of code and data will be handled by later 2537 // reconciliation step 2538 } else { 2539 msg = "Updated system app + " + deletedAppName 2540 + " no longer present; removing system privileges for " 2541 + deletedAppName; 2542 2543 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2544 2545 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2546 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2547 } 2548 logCriticalInfo(Log.WARN, msg); 2549 } 2550 2551 /** 2552 * Make sure all system apps that we expected to appear on 2553 * the userdata partition actually showed up. If they never 2554 * appeared, crawl back and revive the system version. 2555 */ 2556 for (int i = 0; i < mExpectingBetter.size(); i++) { 2557 final String packageName = mExpectingBetter.keyAt(i); 2558 if (!mPackages.containsKey(packageName)) { 2559 final File scanFile = mExpectingBetter.valueAt(i); 2560 2561 logCriticalInfo(Log.WARN, "Expected better " + packageName 2562 + " but never showed up; reverting to system"); 2563 2564 int reparseFlags = mDefParseFlags; 2565 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2566 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2567 | PackageParser.PARSE_IS_SYSTEM_DIR 2568 | PackageParser.PARSE_IS_PRIVILEGED; 2569 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2570 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2571 | PackageParser.PARSE_IS_SYSTEM_DIR; 2572 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2573 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2574 | PackageParser.PARSE_IS_SYSTEM_DIR; 2575 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2576 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2577 | PackageParser.PARSE_IS_SYSTEM_DIR; 2578 } else { 2579 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2580 continue; 2581 } 2582 2583 mSettings.enableSystemPackageLPw(packageName); 2584 2585 try { 2586 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2587 } catch (PackageManagerException e) { 2588 Slog.e(TAG, "Failed to parse original system package: " 2589 + e.getMessage()); 2590 } 2591 } 2592 } 2593 } 2594 mExpectingBetter.clear(); 2595 2596 // Resolve protected action filters. Only the setup wizard is allowed to 2597 // have a high priority filter for these actions. 2598 mSetupWizardPackage = getSetupWizardPackageName(); 2599 if (mProtectedFilters.size() > 0) { 2600 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2601 Slog.i(TAG, "No setup wizard;" 2602 + " All protected intents capped to priority 0"); 2603 } 2604 for (ActivityIntentInfo filter : mProtectedFilters) { 2605 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2606 if (DEBUG_FILTERS) { 2607 Slog.i(TAG, "Found setup wizard;" 2608 + " allow priority " + filter.getPriority() + ";" 2609 + " package: " + filter.activity.info.packageName 2610 + " activity: " + filter.activity.className 2611 + " priority: " + filter.getPriority()); 2612 } 2613 // skip setup wizard; allow it to keep the high priority filter 2614 continue; 2615 } 2616 Slog.w(TAG, "Protected action; cap priority to 0;" 2617 + " package: " + filter.activity.info.packageName 2618 + " activity: " + filter.activity.className 2619 + " origPrio: " + filter.getPriority()); 2620 filter.setPriority(0); 2621 } 2622 } 2623 mDeferProtectedFilters = false; 2624 mProtectedFilters.clear(); 2625 2626 // Now that we know all of the shared libraries, update all clients to have 2627 // the correct library paths. 2628 updateAllSharedLibrariesLPw(); 2629 2630 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2631 // NOTE: We ignore potential failures here during a system scan (like 2632 // the rest of the commands above) because there's precious little we 2633 // can do about it. A settings error is reported, though. 2634 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2635 false /* boot complete */); 2636 } 2637 2638 // Now that we know all the packages we are keeping, 2639 // read and update their last usage times. 2640 mPackageUsage.readLP(); 2641 2642 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2643 SystemClock.uptimeMillis()); 2644 Slog.i(TAG, "Time to scan packages: " 2645 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2646 + " seconds"); 2647 2648 // If the platform SDK has changed since the last time we booted, 2649 // we need to re-grant app permission to catch any new ones that 2650 // appear. This is really a hack, and means that apps can in some 2651 // cases get permissions that the user didn't initially explicitly 2652 // allow... it would be nice to have some better way to handle 2653 // this situation. 2654 int updateFlags = UPDATE_PERMISSIONS_ALL; 2655 if (ver.sdkVersion != mSdkVersion) { 2656 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2657 + mSdkVersion + "; regranting permissions for internal storage"); 2658 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2659 } 2660 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2661 ver.sdkVersion = mSdkVersion; 2662 2663 // If this is the first boot or an update from pre-M, and it is a normal 2664 // boot, then we need to initialize the default preferred apps across 2665 // all defined users. 2666 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2667 for (UserInfo user : sUserManager.getUsers(true)) { 2668 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2669 applyFactoryDefaultBrowserLPw(user.id); 2670 primeDomainVerificationsLPw(user.id); 2671 } 2672 } 2673 2674 // Prepare storage for system user really early during boot, 2675 // since core system apps like SettingsProvider and SystemUI 2676 // can't wait for user to start 2677 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2678 StorageManager.FLAG_STORAGE_DE); 2679 2680 // If this is first boot after an OTA, and a normal boot, then 2681 // we need to clear code cache directories. 2682 if (mIsUpgrade && !onlyCore) { 2683 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2684 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2685 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2686 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2687 // No apps are running this early, so no need to freeze 2688 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2689 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2690 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2691 } 2692 clearAppProfilesLIF(ps.pkg); 2693 } 2694 ver.fingerprint = Build.FINGERPRINT; 2695 } 2696 2697 checkDefaultBrowser(); 2698 2699 // clear only after permissions and other defaults have been updated 2700 mExistingSystemPackages.clear(); 2701 mPromoteSystemApps = false; 2702 2703 // All the changes are done during package scanning. 2704 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2705 2706 // can downgrade to reader 2707 mSettings.writeLPr(); 2708 2709 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2710 SystemClock.uptimeMillis()); 2711 2712 if (!mOnlyCore) { 2713 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2714 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2715 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2716 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2717 mIntentFilterVerifierComponent); 2718 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2719 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2720 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2721 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2722 } else { 2723 mRequiredVerifierPackage = null; 2724 mRequiredInstallerPackage = null; 2725 mIntentFilterVerifierComponent = null; 2726 mIntentFilterVerifier = null; 2727 mServicesSystemSharedLibraryPackageName = null; 2728 mSharedSystemSharedLibraryPackageName = null; 2729 } 2730 2731 mInstallerService = new PackageInstallerService(context, this); 2732 2733 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2734 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2735 // both the installer and resolver must be present to enable ephemeral 2736 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2737 if (DEBUG_EPHEMERAL) { 2738 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2739 + " installer:" + ephemeralInstallerComponent); 2740 } 2741 mEphemeralResolverComponent = ephemeralResolverComponent; 2742 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2743 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2744 mEphemeralResolverConnection = 2745 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2746 } else { 2747 if (DEBUG_EPHEMERAL) { 2748 final String missingComponent = 2749 (ephemeralResolverComponent == null) 2750 ? (ephemeralInstallerComponent == null) 2751 ? "resolver and installer" 2752 : "resolver" 2753 : "installer"; 2754 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2755 } 2756 mEphemeralResolverComponent = null; 2757 mEphemeralInstallerComponent = null; 2758 mEphemeralResolverConnection = null; 2759 } 2760 2761 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2762 } // synchronized (mPackages) 2763 } // synchronized (mInstallLock) 2764 2765 // Now after opening every single application zip, make sure they 2766 // are all flushed. Not really needed, but keeps things nice and 2767 // tidy. 2768 Runtime.getRuntime().gc(); 2769 2770 // The initial scanning above does many calls into installd while 2771 // holding the mPackages lock, but we're mostly interested in yelling 2772 // once we have a booted system. 2773 mInstaller.setWarnIfHeld(mPackages); 2774 2775 // Expose private service for system components to use. 2776 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2777 } 2778 2779 @Override 2780 public boolean isFirstBoot() { 2781 return !mRestoredSettings; 2782 } 2783 2784 @Override 2785 public boolean isOnlyCoreApps() { 2786 return mOnlyCore; 2787 } 2788 2789 @Override 2790 public boolean isUpgrade() { 2791 return mIsUpgrade; 2792 } 2793 2794 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2795 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2796 2797 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2798 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2799 UserHandle.USER_SYSTEM); 2800 if (matches.size() == 1) { 2801 return matches.get(0).getComponentInfo().packageName; 2802 } else { 2803 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2804 return null; 2805 } 2806 } 2807 2808 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2809 synchronized (mPackages) { 2810 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2811 if (libraryEntry == null) { 2812 throw new IllegalStateException("Missing required shared library:" + libraryName); 2813 } 2814 return libraryEntry.apk; 2815 } 2816 } 2817 2818 private @NonNull String getRequiredInstallerLPr() { 2819 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2820 intent.addCategory(Intent.CATEGORY_DEFAULT); 2821 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2822 2823 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2824 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2825 UserHandle.USER_SYSTEM); 2826 if (matches.size() == 1) { 2827 ResolveInfo resolveInfo = matches.get(0); 2828 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2829 throw new RuntimeException("The installer must be a privileged app"); 2830 } 2831 return matches.get(0).getComponentInfo().packageName; 2832 } else { 2833 throw new RuntimeException("There must be exactly one installer; found " + matches); 2834 } 2835 } 2836 2837 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2838 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2839 2840 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2841 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2842 UserHandle.USER_SYSTEM); 2843 ResolveInfo best = null; 2844 final int N = matches.size(); 2845 for (int i = 0; i < N; i++) { 2846 final ResolveInfo cur = matches.get(i); 2847 final String packageName = cur.getComponentInfo().packageName; 2848 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2849 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2850 continue; 2851 } 2852 2853 if (best == null || cur.priority > best.priority) { 2854 best = cur; 2855 } 2856 } 2857 2858 if (best != null) { 2859 return best.getComponentInfo().getComponentName(); 2860 } else { 2861 throw new RuntimeException("There must be at least one intent filter verifier"); 2862 } 2863 } 2864 2865 private @Nullable ComponentName getEphemeralResolverLPr() { 2866 final String[] packageArray = 2867 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2868 if (packageArray.length == 0) { 2869 if (DEBUG_EPHEMERAL) { 2870 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2871 } 2872 return null; 2873 } 2874 2875 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2876 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2877 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2878 UserHandle.USER_SYSTEM); 2879 2880 final int N = resolvers.size(); 2881 if (N == 0) { 2882 if (DEBUG_EPHEMERAL) { 2883 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2884 } 2885 return null; 2886 } 2887 2888 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2889 for (int i = 0; i < N; i++) { 2890 final ResolveInfo info = resolvers.get(i); 2891 2892 if (info.serviceInfo == null) { 2893 continue; 2894 } 2895 2896 final String packageName = info.serviceInfo.packageName; 2897 if (!possiblePackages.contains(packageName)) { 2898 if (DEBUG_EPHEMERAL) { 2899 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2900 + " pkg: " + packageName + ", info:" + info); 2901 } 2902 continue; 2903 } 2904 2905 if (DEBUG_EPHEMERAL) { 2906 Slog.v(TAG, "Ephemeral resolver found;" 2907 + " pkg: " + packageName + ", info:" + info); 2908 } 2909 return new ComponentName(packageName, info.serviceInfo.name); 2910 } 2911 if (DEBUG_EPHEMERAL) { 2912 Slog.v(TAG, "Ephemeral resolver NOT found"); 2913 } 2914 return null; 2915 } 2916 2917 private @Nullable ComponentName getEphemeralInstallerLPr() { 2918 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2919 intent.addCategory(Intent.CATEGORY_DEFAULT); 2920 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2921 2922 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2923 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2924 UserHandle.USER_SYSTEM); 2925 if (matches.size() == 0) { 2926 return null; 2927 } else if (matches.size() == 1) { 2928 return matches.get(0).getComponentInfo().getComponentName(); 2929 } else { 2930 throw new RuntimeException( 2931 "There must be at most one ephemeral installer; found " + matches); 2932 } 2933 } 2934 2935 private void primeDomainVerificationsLPw(int userId) { 2936 if (DEBUG_DOMAIN_VERIFICATION) { 2937 Slog.d(TAG, "Priming domain verifications in user " + userId); 2938 } 2939 2940 SystemConfig systemConfig = SystemConfig.getInstance(); 2941 ArraySet<String> packages = systemConfig.getLinkedApps(); 2942 ArraySet<String> domains = new ArraySet<String>(); 2943 2944 for (String packageName : packages) { 2945 PackageParser.Package pkg = mPackages.get(packageName); 2946 if (pkg != null) { 2947 if (!pkg.isSystemApp()) { 2948 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2949 continue; 2950 } 2951 2952 domains.clear(); 2953 for (PackageParser.Activity a : pkg.activities) { 2954 for (ActivityIntentInfo filter : a.intents) { 2955 if (hasValidDomains(filter)) { 2956 domains.addAll(filter.getHostsList()); 2957 } 2958 } 2959 } 2960 2961 if (domains.size() > 0) { 2962 if (DEBUG_DOMAIN_VERIFICATION) { 2963 Slog.v(TAG, " + " + packageName); 2964 } 2965 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2966 // state w.r.t. the formal app-linkage "no verification attempted" state; 2967 // and then 'always' in the per-user state actually used for intent resolution. 2968 final IntentFilterVerificationInfo ivi; 2969 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2970 new ArrayList<String>(domains)); 2971 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2972 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2973 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2974 } else { 2975 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2976 + "' does not handle web links"); 2977 } 2978 } else { 2979 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2980 } 2981 } 2982 2983 scheduleWritePackageRestrictionsLocked(userId); 2984 scheduleWriteSettingsLocked(); 2985 } 2986 2987 private void applyFactoryDefaultBrowserLPw(int userId) { 2988 // The default browser app's package name is stored in a string resource, 2989 // with a product-specific overlay used for vendor customization. 2990 String browserPkg = mContext.getResources().getString( 2991 com.android.internal.R.string.default_browser); 2992 if (!TextUtils.isEmpty(browserPkg)) { 2993 // non-empty string => required to be a known package 2994 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2995 if (ps == null) { 2996 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2997 browserPkg = null; 2998 } else { 2999 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3000 } 3001 } 3002 3003 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3004 // default. If there's more than one, just leave everything alone. 3005 if (browserPkg == null) { 3006 calculateDefaultBrowserLPw(userId); 3007 } 3008 } 3009 3010 private void calculateDefaultBrowserLPw(int userId) { 3011 List<String> allBrowsers = resolveAllBrowserApps(userId); 3012 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3013 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3014 } 3015 3016 private List<String> resolveAllBrowserApps(int userId) { 3017 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3018 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3019 PackageManager.MATCH_ALL, userId); 3020 3021 final int count = list.size(); 3022 List<String> result = new ArrayList<String>(count); 3023 for (int i=0; i<count; i++) { 3024 ResolveInfo info = list.get(i); 3025 if (info.activityInfo == null 3026 || !info.handleAllWebDataURI 3027 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3028 || result.contains(info.activityInfo.packageName)) { 3029 continue; 3030 } 3031 result.add(info.activityInfo.packageName); 3032 } 3033 3034 return result; 3035 } 3036 3037 private boolean packageIsBrowser(String packageName, int userId) { 3038 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3039 PackageManager.MATCH_ALL, userId); 3040 final int N = list.size(); 3041 for (int i = 0; i < N; i++) { 3042 ResolveInfo info = list.get(i); 3043 if (packageName.equals(info.activityInfo.packageName)) { 3044 return true; 3045 } 3046 } 3047 return false; 3048 } 3049 3050 private void checkDefaultBrowser() { 3051 final int myUserId = UserHandle.myUserId(); 3052 final String packageName = getDefaultBrowserPackageName(myUserId); 3053 if (packageName != null) { 3054 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3055 if (info == null) { 3056 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3057 synchronized (mPackages) { 3058 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3059 } 3060 } 3061 } 3062 } 3063 3064 @Override 3065 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3066 throws RemoteException { 3067 try { 3068 return super.onTransact(code, data, reply, flags); 3069 } catch (RuntimeException e) { 3070 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3071 Slog.wtf(TAG, "Package Manager Crash", e); 3072 } 3073 throw e; 3074 } 3075 } 3076 3077 static int[] appendInts(int[] cur, int[] add) { 3078 if (add == null) return cur; 3079 if (cur == null) return add; 3080 final int N = add.length; 3081 for (int i=0; i<N; i++) { 3082 cur = appendInt(cur, add[i]); 3083 } 3084 return cur; 3085 } 3086 3087 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3088 if (!sUserManager.exists(userId)) return null; 3089 if (ps == null) { 3090 return null; 3091 } 3092 final PackageParser.Package p = ps.pkg; 3093 if (p == null) { 3094 return null; 3095 } 3096 3097 final PermissionsState permissionsState = ps.getPermissionsState(); 3098 3099 final int[] gids = permissionsState.computeGids(userId); 3100 final Set<String> permissions = permissionsState.getPermissions(userId); 3101 final PackageUserState state = ps.readUserState(userId); 3102 3103 return PackageParser.generatePackageInfo(p, gids, flags, 3104 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3105 } 3106 3107 @Override 3108 public void checkPackageStartable(String packageName, int userId) { 3109 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3110 3111 synchronized (mPackages) { 3112 final PackageSetting ps = mSettings.mPackages.get(packageName); 3113 if (ps == null) { 3114 throw new SecurityException("Package " + packageName + " was not found!"); 3115 } 3116 3117 if (!ps.getInstalled(userId)) { 3118 throw new SecurityException( 3119 "Package " + packageName + " was not installed for user " + userId + "!"); 3120 } 3121 3122 if (mSafeMode && !ps.isSystem()) { 3123 throw new SecurityException("Package " + packageName + " not a system app!"); 3124 } 3125 3126 if (mFrozenPackages.contains(packageName)) { 3127 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3128 } 3129 3130 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3131 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3132 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3133 } 3134 } 3135 } 3136 3137 @Override 3138 public boolean isPackageAvailable(String packageName, int userId) { 3139 if (!sUserManager.exists(userId)) return false; 3140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3141 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3142 synchronized (mPackages) { 3143 PackageParser.Package p = mPackages.get(packageName); 3144 if (p != null) { 3145 final PackageSetting ps = (PackageSetting) p.mExtras; 3146 if (ps != null) { 3147 final PackageUserState state = ps.readUserState(userId); 3148 if (state != null) { 3149 return PackageParser.isAvailable(state); 3150 } 3151 } 3152 } 3153 } 3154 return false; 3155 } 3156 3157 @Override 3158 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3159 if (!sUserManager.exists(userId)) return null; 3160 flags = updateFlagsForPackage(flags, userId, packageName); 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3162 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3163 // reader 3164 synchronized (mPackages) { 3165 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3166 PackageParser.Package p = null; 3167 if (matchFactoryOnly) { 3168 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3169 if (ps != null) { 3170 return generatePackageInfo(ps, flags, userId); 3171 } 3172 } 3173 if (p == null) { 3174 p = mPackages.get(packageName); 3175 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3176 return null; 3177 } 3178 } 3179 if (DEBUG_PACKAGE_INFO) 3180 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3181 if (p != null) { 3182 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3183 } 3184 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3185 final PackageSetting ps = mSettings.mPackages.get(packageName); 3186 return generatePackageInfo(ps, flags, userId); 3187 } 3188 } 3189 return null; 3190 } 3191 3192 @Override 3193 public String[] currentToCanonicalPackageNames(String[] names) { 3194 String[] out = new String[names.length]; 3195 // reader 3196 synchronized (mPackages) { 3197 for (int i=names.length-1; i>=0; i--) { 3198 PackageSetting ps = mSettings.mPackages.get(names[i]); 3199 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3200 } 3201 } 3202 return out; 3203 } 3204 3205 @Override 3206 public String[] canonicalToCurrentPackageNames(String[] names) { 3207 String[] out = new String[names.length]; 3208 // reader 3209 synchronized (mPackages) { 3210 for (int i=names.length-1; i>=0; i--) { 3211 String cur = mSettings.mRenamedPackages.get(names[i]); 3212 out[i] = cur != null ? cur : names[i]; 3213 } 3214 } 3215 return out; 3216 } 3217 3218 @Override 3219 public int getPackageUid(String packageName, int flags, int userId) { 3220 if (!sUserManager.exists(userId)) return -1; 3221 flags = updateFlagsForPackage(flags, userId, packageName); 3222 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3223 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3224 3225 // reader 3226 synchronized (mPackages) { 3227 final PackageParser.Package p = mPackages.get(packageName); 3228 if (p != null && p.isMatch(flags)) { 3229 return UserHandle.getUid(userId, p.applicationInfo.uid); 3230 } 3231 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3232 final PackageSetting ps = mSettings.mPackages.get(packageName); 3233 if (ps != null && ps.isMatch(flags)) { 3234 return UserHandle.getUid(userId, ps.appId); 3235 } 3236 } 3237 } 3238 3239 return -1; 3240 } 3241 3242 @Override 3243 public int[] getPackageGids(String packageName, int flags, int userId) { 3244 if (!sUserManager.exists(userId)) return null; 3245 flags = updateFlagsForPackage(flags, userId, packageName); 3246 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3247 false /* requireFullPermission */, false /* checkShell */, 3248 "getPackageGids"); 3249 3250 // reader 3251 synchronized (mPackages) { 3252 final PackageParser.Package p = mPackages.get(packageName); 3253 if (p != null && p.isMatch(flags)) { 3254 PackageSetting ps = (PackageSetting) p.mExtras; 3255 return ps.getPermissionsState().computeGids(userId); 3256 } 3257 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3258 final PackageSetting ps = mSettings.mPackages.get(packageName); 3259 if (ps != null && ps.isMatch(flags)) { 3260 return ps.getPermissionsState().computeGids(userId); 3261 } 3262 } 3263 } 3264 3265 return null; 3266 } 3267 3268 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3269 if (bp.perm != null) { 3270 return PackageParser.generatePermissionInfo(bp.perm, flags); 3271 } 3272 PermissionInfo pi = new PermissionInfo(); 3273 pi.name = bp.name; 3274 pi.packageName = bp.sourcePackage; 3275 pi.nonLocalizedLabel = bp.name; 3276 pi.protectionLevel = bp.protectionLevel; 3277 return pi; 3278 } 3279 3280 @Override 3281 public PermissionInfo getPermissionInfo(String name, int flags) { 3282 // reader 3283 synchronized (mPackages) { 3284 final BasePermission p = mSettings.mPermissions.get(name); 3285 if (p != null) { 3286 return generatePermissionInfo(p, flags); 3287 } 3288 return null; 3289 } 3290 } 3291 3292 @Override 3293 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3294 int flags) { 3295 // reader 3296 synchronized (mPackages) { 3297 if (group != null && !mPermissionGroups.containsKey(group)) { 3298 // This is thrown as NameNotFoundException 3299 return null; 3300 } 3301 3302 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3303 for (BasePermission p : mSettings.mPermissions.values()) { 3304 if (group == null) { 3305 if (p.perm == null || p.perm.info.group == null) { 3306 out.add(generatePermissionInfo(p, flags)); 3307 } 3308 } else { 3309 if (p.perm != null && group.equals(p.perm.info.group)) { 3310 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3311 } 3312 } 3313 } 3314 return new ParceledListSlice<>(out); 3315 } 3316 } 3317 3318 @Override 3319 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3320 // reader 3321 synchronized (mPackages) { 3322 return PackageParser.generatePermissionGroupInfo( 3323 mPermissionGroups.get(name), flags); 3324 } 3325 } 3326 3327 @Override 3328 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3329 // reader 3330 synchronized (mPackages) { 3331 final int N = mPermissionGroups.size(); 3332 ArrayList<PermissionGroupInfo> out 3333 = new ArrayList<PermissionGroupInfo>(N); 3334 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3335 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3336 } 3337 return new ParceledListSlice<>(out); 3338 } 3339 } 3340 3341 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3342 int userId) { 3343 if (!sUserManager.exists(userId)) return null; 3344 PackageSetting ps = mSettings.mPackages.get(packageName); 3345 if (ps != null) { 3346 if (ps.pkg == null) { 3347 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3348 if (pInfo != null) { 3349 return pInfo.applicationInfo; 3350 } 3351 return null; 3352 } 3353 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3354 ps.readUserState(userId), userId); 3355 } 3356 return null; 3357 } 3358 3359 @Override 3360 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3361 if (!sUserManager.exists(userId)) return null; 3362 flags = updateFlagsForApplication(flags, userId, packageName); 3363 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3364 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3365 // writer 3366 synchronized (mPackages) { 3367 PackageParser.Package p = mPackages.get(packageName); 3368 if (DEBUG_PACKAGE_INFO) Log.v( 3369 TAG, "getApplicationInfo " + packageName 3370 + ": " + p); 3371 if (p != null) { 3372 PackageSetting ps = mSettings.mPackages.get(packageName); 3373 if (ps == null) return null; 3374 // Note: isEnabledLP() does not apply here - always return info 3375 return PackageParser.generateApplicationInfo( 3376 p, flags, ps.readUserState(userId), userId); 3377 } 3378 if ("android".equals(packageName)||"system".equals(packageName)) { 3379 return mAndroidApplication; 3380 } 3381 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3382 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3383 } 3384 } 3385 return null; 3386 } 3387 3388 @Override 3389 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3390 final IPackageDataObserver observer) { 3391 mContext.enforceCallingOrSelfPermission( 3392 android.Manifest.permission.CLEAR_APP_CACHE, null); 3393 // Queue up an async operation since clearing cache may take a little while. 3394 mHandler.post(new Runnable() { 3395 public void run() { 3396 mHandler.removeCallbacks(this); 3397 boolean success = true; 3398 synchronized (mInstallLock) { 3399 try { 3400 mInstaller.freeCache(volumeUuid, freeStorageSize); 3401 } catch (InstallerException e) { 3402 Slog.w(TAG, "Couldn't clear application caches: " + e); 3403 success = false; 3404 } 3405 } 3406 if (observer != null) { 3407 try { 3408 observer.onRemoveCompleted(null, success); 3409 } catch (RemoteException e) { 3410 Slog.w(TAG, "RemoveException when invoking call back"); 3411 } 3412 } 3413 } 3414 }); 3415 } 3416 3417 @Override 3418 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3419 final IntentSender pi) { 3420 mContext.enforceCallingOrSelfPermission( 3421 android.Manifest.permission.CLEAR_APP_CACHE, null); 3422 // Queue up an async operation since clearing cache may take a little while. 3423 mHandler.post(new Runnable() { 3424 public void run() { 3425 mHandler.removeCallbacks(this); 3426 boolean success = true; 3427 synchronized (mInstallLock) { 3428 try { 3429 mInstaller.freeCache(volumeUuid, freeStorageSize); 3430 } catch (InstallerException e) { 3431 Slog.w(TAG, "Couldn't clear application caches: " + e); 3432 success = false; 3433 } 3434 } 3435 if(pi != null) { 3436 try { 3437 // Callback via pending intent 3438 int code = success ? 1 : 0; 3439 pi.sendIntent(null, code, null, 3440 null, null); 3441 } catch (SendIntentException e1) { 3442 Slog.i(TAG, "Failed to send pending intent"); 3443 } 3444 } 3445 } 3446 }); 3447 } 3448 3449 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3450 synchronized (mInstallLock) { 3451 try { 3452 mInstaller.freeCache(volumeUuid, freeStorageSize); 3453 } catch (InstallerException e) { 3454 throw new IOException("Failed to free enough space", e); 3455 } 3456 } 3457 } 3458 3459 /** 3460 * Update given flags based on encryption status of current user. 3461 */ 3462 private int updateFlags(int flags, int userId) { 3463 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3464 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3465 // Caller expressed an explicit opinion about what encryption 3466 // aware/unaware components they want to see, so fall through and 3467 // give them what they want 3468 } else { 3469 // Caller expressed no opinion, so match based on user state 3470 if (StorageManager.isUserKeyUnlocked(userId)) { 3471 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3472 } else { 3473 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3474 } 3475 } 3476 return flags; 3477 } 3478 3479 /** 3480 * Update given flags when being used to request {@link PackageInfo}. 3481 */ 3482 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3483 boolean triaged = true; 3484 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3485 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3486 // Caller is asking for component details, so they'd better be 3487 // asking for specific encryption matching behavior, or be triaged 3488 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3489 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3490 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3491 triaged = false; 3492 } 3493 } 3494 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3495 | PackageManager.MATCH_SYSTEM_ONLY 3496 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3497 triaged = false; 3498 } 3499 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3500 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3501 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3502 } 3503 return updateFlags(flags, userId); 3504 } 3505 3506 /** 3507 * Update given flags when being used to request {@link ApplicationInfo}. 3508 */ 3509 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3510 return updateFlagsForPackage(flags, userId, cookie); 3511 } 3512 3513 /** 3514 * Update given flags when being used to request {@link ComponentInfo}. 3515 */ 3516 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3517 if (cookie instanceof Intent) { 3518 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3519 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3520 } 3521 } 3522 3523 boolean triaged = true; 3524 // Caller is asking for component details, so they'd better be 3525 // asking for specific encryption matching behavior, or be triaged 3526 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3527 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3528 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3529 triaged = false; 3530 } 3531 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3532 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3533 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3534 } 3535 3536 return updateFlags(flags, userId); 3537 } 3538 3539 /** 3540 * Update given flags when being used to request {@link ResolveInfo}. 3541 */ 3542 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3543 // Safe mode means we shouldn't match any third-party components 3544 if (mSafeMode) { 3545 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3546 } 3547 3548 return updateFlagsForComponent(flags, userId, cookie); 3549 } 3550 3551 @Override 3552 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3553 if (!sUserManager.exists(userId)) return null; 3554 flags = updateFlagsForComponent(flags, userId, component); 3555 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3556 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3557 synchronized (mPackages) { 3558 PackageParser.Activity a = mActivities.mActivities.get(component); 3559 3560 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3561 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3562 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3563 if (ps == null) return null; 3564 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3565 userId); 3566 } 3567 if (mResolveComponentName.equals(component)) { 3568 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3569 new PackageUserState(), userId); 3570 } 3571 } 3572 return null; 3573 } 3574 3575 @Override 3576 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3577 String resolvedType) { 3578 synchronized (mPackages) { 3579 if (component.equals(mResolveComponentName)) { 3580 // The resolver supports EVERYTHING! 3581 return true; 3582 } 3583 PackageParser.Activity a = mActivities.mActivities.get(component); 3584 if (a == null) { 3585 return false; 3586 } 3587 for (int i=0; i<a.intents.size(); i++) { 3588 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3589 intent.getData(), intent.getCategories(), TAG) >= 0) { 3590 return true; 3591 } 3592 } 3593 return false; 3594 } 3595 } 3596 3597 @Override 3598 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3599 if (!sUserManager.exists(userId)) return null; 3600 flags = updateFlagsForComponent(flags, userId, component); 3601 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3602 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3603 synchronized (mPackages) { 3604 PackageParser.Activity a = mReceivers.mActivities.get(component); 3605 if (DEBUG_PACKAGE_INFO) Log.v( 3606 TAG, "getReceiverInfo " + component + ": " + a); 3607 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3608 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3609 if (ps == null) return null; 3610 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3611 userId); 3612 } 3613 } 3614 return null; 3615 } 3616 3617 @Override 3618 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3619 if (!sUserManager.exists(userId)) return null; 3620 flags = updateFlagsForComponent(flags, userId, component); 3621 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3622 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3623 synchronized (mPackages) { 3624 PackageParser.Service s = mServices.mServices.get(component); 3625 if (DEBUG_PACKAGE_INFO) Log.v( 3626 TAG, "getServiceInfo " + component + ": " + s); 3627 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3628 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3629 if (ps == null) return null; 3630 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3631 userId); 3632 } 3633 } 3634 return null; 3635 } 3636 3637 @Override 3638 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3639 if (!sUserManager.exists(userId)) return null; 3640 flags = updateFlagsForComponent(flags, userId, component); 3641 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3642 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3643 synchronized (mPackages) { 3644 PackageParser.Provider p = mProviders.mProviders.get(component); 3645 if (DEBUG_PACKAGE_INFO) Log.v( 3646 TAG, "getProviderInfo " + component + ": " + p); 3647 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3648 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3649 if (ps == null) return null; 3650 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3651 userId); 3652 } 3653 } 3654 return null; 3655 } 3656 3657 @Override 3658 public String[] getSystemSharedLibraryNames() { 3659 Set<String> libSet; 3660 synchronized (mPackages) { 3661 libSet = mSharedLibraries.keySet(); 3662 int size = libSet.size(); 3663 if (size > 0) { 3664 String[] libs = new String[size]; 3665 libSet.toArray(libs); 3666 return libs; 3667 } 3668 } 3669 return null; 3670 } 3671 3672 @Override 3673 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3674 synchronized (mPackages) { 3675 return mServicesSystemSharedLibraryPackageName; 3676 } 3677 } 3678 3679 @Override 3680 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3681 synchronized (mPackages) { 3682 return mSharedSystemSharedLibraryPackageName; 3683 } 3684 } 3685 3686 @Override 3687 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3688 synchronized (mPackages) { 3689 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3690 3691 final FeatureInfo fi = new FeatureInfo(); 3692 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3693 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3694 res.add(fi); 3695 3696 return new ParceledListSlice<>(res); 3697 } 3698 } 3699 3700 @Override 3701 public boolean hasSystemFeature(String name, int version) { 3702 synchronized (mPackages) { 3703 final FeatureInfo feat = mAvailableFeatures.get(name); 3704 if (feat == null) { 3705 return false; 3706 } else { 3707 return feat.version >= version; 3708 } 3709 } 3710 } 3711 3712 @Override 3713 public int checkPermission(String permName, String pkgName, int userId) { 3714 if (!sUserManager.exists(userId)) { 3715 return PackageManager.PERMISSION_DENIED; 3716 } 3717 3718 synchronized (mPackages) { 3719 final PackageParser.Package p = mPackages.get(pkgName); 3720 if (p != null && p.mExtras != null) { 3721 final PackageSetting ps = (PackageSetting) p.mExtras; 3722 final PermissionsState permissionsState = ps.getPermissionsState(); 3723 if (permissionsState.hasPermission(permName, userId)) { 3724 return PackageManager.PERMISSION_GRANTED; 3725 } 3726 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3727 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3728 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3729 return PackageManager.PERMISSION_GRANTED; 3730 } 3731 } 3732 } 3733 3734 return PackageManager.PERMISSION_DENIED; 3735 } 3736 3737 @Override 3738 public int checkUidPermission(String permName, int uid) { 3739 final int userId = UserHandle.getUserId(uid); 3740 3741 if (!sUserManager.exists(userId)) { 3742 return PackageManager.PERMISSION_DENIED; 3743 } 3744 3745 synchronized (mPackages) { 3746 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3747 if (obj != null) { 3748 final SettingBase ps = (SettingBase) obj; 3749 final PermissionsState permissionsState = ps.getPermissionsState(); 3750 if (permissionsState.hasPermission(permName, userId)) { 3751 return PackageManager.PERMISSION_GRANTED; 3752 } 3753 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3754 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3755 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3756 return PackageManager.PERMISSION_GRANTED; 3757 } 3758 } else { 3759 ArraySet<String> perms = mSystemPermissions.get(uid); 3760 if (perms != null) { 3761 if (perms.contains(permName)) { 3762 return PackageManager.PERMISSION_GRANTED; 3763 } 3764 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3765 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3766 return PackageManager.PERMISSION_GRANTED; 3767 } 3768 } 3769 } 3770 } 3771 3772 return PackageManager.PERMISSION_DENIED; 3773 } 3774 3775 @Override 3776 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3777 if (UserHandle.getCallingUserId() != userId) { 3778 mContext.enforceCallingPermission( 3779 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3780 "isPermissionRevokedByPolicy for user " + userId); 3781 } 3782 3783 if (checkPermission(permission, packageName, userId) 3784 == PackageManager.PERMISSION_GRANTED) { 3785 return false; 3786 } 3787 3788 final long identity = Binder.clearCallingIdentity(); 3789 try { 3790 final int flags = getPermissionFlags(permission, packageName, userId); 3791 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3792 } finally { 3793 Binder.restoreCallingIdentity(identity); 3794 } 3795 } 3796 3797 @Override 3798 public String getPermissionControllerPackageName() { 3799 synchronized (mPackages) { 3800 return mRequiredInstallerPackage; 3801 } 3802 } 3803 3804 /** 3805 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3806 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3807 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3808 * @param message the message to log on security exception 3809 */ 3810 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3811 boolean checkShell, String message) { 3812 if (userId < 0) { 3813 throw new IllegalArgumentException("Invalid userId " + userId); 3814 } 3815 if (checkShell) { 3816 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3817 } 3818 if (userId == UserHandle.getUserId(callingUid)) return; 3819 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3820 if (requireFullPermission) { 3821 mContext.enforceCallingOrSelfPermission( 3822 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3823 } else { 3824 try { 3825 mContext.enforceCallingOrSelfPermission( 3826 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3827 } catch (SecurityException se) { 3828 mContext.enforceCallingOrSelfPermission( 3829 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3830 } 3831 } 3832 } 3833 } 3834 3835 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3836 if (callingUid == Process.SHELL_UID) { 3837 if (userHandle >= 0 3838 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3839 throw new SecurityException("Shell does not have permission to access user " 3840 + userHandle); 3841 } else if (userHandle < 0) { 3842 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3843 + Debug.getCallers(3)); 3844 } 3845 } 3846 } 3847 3848 private BasePermission findPermissionTreeLP(String permName) { 3849 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3850 if (permName.startsWith(bp.name) && 3851 permName.length() > bp.name.length() && 3852 permName.charAt(bp.name.length()) == '.') { 3853 return bp; 3854 } 3855 } 3856 return null; 3857 } 3858 3859 private BasePermission checkPermissionTreeLP(String permName) { 3860 if (permName != null) { 3861 BasePermission bp = findPermissionTreeLP(permName); 3862 if (bp != null) { 3863 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3864 return bp; 3865 } 3866 throw new SecurityException("Calling uid " 3867 + Binder.getCallingUid() 3868 + " is not allowed to add to permission tree " 3869 + bp.name + " owned by uid " + bp.uid); 3870 } 3871 } 3872 throw new SecurityException("No permission tree found for " + permName); 3873 } 3874 3875 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3876 if (s1 == null) { 3877 return s2 == null; 3878 } 3879 if (s2 == null) { 3880 return false; 3881 } 3882 if (s1.getClass() != s2.getClass()) { 3883 return false; 3884 } 3885 return s1.equals(s2); 3886 } 3887 3888 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3889 if (pi1.icon != pi2.icon) return false; 3890 if (pi1.logo != pi2.logo) return false; 3891 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3892 if (!compareStrings(pi1.name, pi2.name)) return false; 3893 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3894 // We'll take care of setting this one. 3895 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3896 // These are not currently stored in settings. 3897 //if (!compareStrings(pi1.group, pi2.group)) return false; 3898 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3899 //if (pi1.labelRes != pi2.labelRes) return false; 3900 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3901 return true; 3902 } 3903 3904 int permissionInfoFootprint(PermissionInfo info) { 3905 int size = info.name.length(); 3906 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3907 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3908 return size; 3909 } 3910 3911 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3912 int size = 0; 3913 for (BasePermission perm : mSettings.mPermissions.values()) { 3914 if (perm.uid == tree.uid) { 3915 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3916 } 3917 } 3918 return size; 3919 } 3920 3921 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3922 // We calculate the max size of permissions defined by this uid and throw 3923 // if that plus the size of 'info' would exceed our stated maximum. 3924 if (tree.uid != Process.SYSTEM_UID) { 3925 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3926 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3927 throw new SecurityException("Permission tree size cap exceeded"); 3928 } 3929 } 3930 } 3931 3932 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3933 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3934 throw new SecurityException("Label must be specified in permission"); 3935 } 3936 BasePermission tree = checkPermissionTreeLP(info.name); 3937 BasePermission bp = mSettings.mPermissions.get(info.name); 3938 boolean added = bp == null; 3939 boolean changed = true; 3940 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3941 if (added) { 3942 enforcePermissionCapLocked(info, tree); 3943 bp = new BasePermission(info.name, tree.sourcePackage, 3944 BasePermission.TYPE_DYNAMIC); 3945 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3946 throw new SecurityException( 3947 "Not allowed to modify non-dynamic permission " 3948 + info.name); 3949 } else { 3950 if (bp.protectionLevel == fixedLevel 3951 && bp.perm.owner.equals(tree.perm.owner) 3952 && bp.uid == tree.uid 3953 && comparePermissionInfos(bp.perm.info, info)) { 3954 changed = false; 3955 } 3956 } 3957 bp.protectionLevel = fixedLevel; 3958 info = new PermissionInfo(info); 3959 info.protectionLevel = fixedLevel; 3960 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3961 bp.perm.info.packageName = tree.perm.info.packageName; 3962 bp.uid = tree.uid; 3963 if (added) { 3964 mSettings.mPermissions.put(info.name, bp); 3965 } 3966 if (changed) { 3967 if (!async) { 3968 mSettings.writeLPr(); 3969 } else { 3970 scheduleWriteSettingsLocked(); 3971 } 3972 } 3973 return added; 3974 } 3975 3976 @Override 3977 public boolean addPermission(PermissionInfo info) { 3978 synchronized (mPackages) { 3979 return addPermissionLocked(info, false); 3980 } 3981 } 3982 3983 @Override 3984 public boolean addPermissionAsync(PermissionInfo info) { 3985 synchronized (mPackages) { 3986 return addPermissionLocked(info, true); 3987 } 3988 } 3989 3990 @Override 3991 public void removePermission(String name) { 3992 synchronized (mPackages) { 3993 checkPermissionTreeLP(name); 3994 BasePermission bp = mSettings.mPermissions.get(name); 3995 if (bp != null) { 3996 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3997 throw new SecurityException( 3998 "Not allowed to modify non-dynamic permission " 3999 + name); 4000 } 4001 mSettings.mPermissions.remove(name); 4002 mSettings.writeLPr(); 4003 } 4004 } 4005 } 4006 4007 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4008 BasePermission bp) { 4009 int index = pkg.requestedPermissions.indexOf(bp.name); 4010 if (index == -1) { 4011 throw new SecurityException("Package " + pkg.packageName 4012 + " has not requested permission " + bp.name); 4013 } 4014 if (!bp.isRuntime() && !bp.isDevelopment()) { 4015 throw new SecurityException("Permission " + bp.name 4016 + " is not a changeable permission type"); 4017 } 4018 } 4019 4020 @Override 4021 public void grantRuntimePermission(String packageName, String name, final int userId) { 4022 if (!sUserManager.exists(userId)) { 4023 Log.e(TAG, "No such user:" + userId); 4024 return; 4025 } 4026 4027 mContext.enforceCallingOrSelfPermission( 4028 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4029 "grantRuntimePermission"); 4030 4031 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4032 true /* requireFullPermission */, true /* checkShell */, 4033 "grantRuntimePermission"); 4034 4035 final int uid; 4036 final SettingBase sb; 4037 4038 synchronized (mPackages) { 4039 final PackageParser.Package pkg = mPackages.get(packageName); 4040 if (pkg == null) { 4041 throw new IllegalArgumentException("Unknown package: " + packageName); 4042 } 4043 4044 final BasePermission bp = mSettings.mPermissions.get(name); 4045 if (bp == null) { 4046 throw new IllegalArgumentException("Unknown permission: " + name); 4047 } 4048 4049 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4050 4051 // If a permission review is required for legacy apps we represent 4052 // their permissions as always granted runtime ones since we need 4053 // to keep the review required permission flag per user while an 4054 // install permission's state is shared across all users. 4055 if (Build.PERMISSIONS_REVIEW_REQUIRED 4056 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4057 && bp.isRuntime()) { 4058 return; 4059 } 4060 4061 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4062 sb = (SettingBase) pkg.mExtras; 4063 if (sb == null) { 4064 throw new IllegalArgumentException("Unknown package: " + packageName); 4065 } 4066 4067 final PermissionsState permissionsState = sb.getPermissionsState(); 4068 4069 final int flags = permissionsState.getPermissionFlags(name, userId); 4070 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4071 throw new SecurityException("Cannot grant system fixed permission " 4072 + name + " for package " + packageName); 4073 } 4074 4075 if (bp.isDevelopment()) { 4076 // Development permissions must be handled specially, since they are not 4077 // normal runtime permissions. For now they apply to all users. 4078 if (permissionsState.grantInstallPermission(bp) != 4079 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4080 scheduleWriteSettingsLocked(); 4081 } 4082 return; 4083 } 4084 4085 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4086 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4087 return; 4088 } 4089 4090 final int result = permissionsState.grantRuntimePermission(bp, userId); 4091 switch (result) { 4092 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4093 return; 4094 } 4095 4096 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4097 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4098 mHandler.post(new Runnable() { 4099 @Override 4100 public void run() { 4101 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4102 } 4103 }); 4104 } 4105 break; 4106 } 4107 4108 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4109 4110 // Not critical if that is lost - app has to request again. 4111 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4112 } 4113 4114 // Only need to do this if user is initialized. Otherwise it's a new user 4115 // and there are no processes running as the user yet and there's no need 4116 // to make an expensive call to remount processes for the changed permissions. 4117 if (READ_EXTERNAL_STORAGE.equals(name) 4118 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4119 final long token = Binder.clearCallingIdentity(); 4120 try { 4121 if (sUserManager.isInitialized(userId)) { 4122 MountServiceInternal mountServiceInternal = LocalServices.getService( 4123 MountServiceInternal.class); 4124 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4125 } 4126 } finally { 4127 Binder.restoreCallingIdentity(token); 4128 } 4129 } 4130 } 4131 4132 @Override 4133 public void revokeRuntimePermission(String packageName, String name, int userId) { 4134 if (!sUserManager.exists(userId)) { 4135 Log.e(TAG, "No such user:" + userId); 4136 return; 4137 } 4138 4139 mContext.enforceCallingOrSelfPermission( 4140 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4141 "revokeRuntimePermission"); 4142 4143 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4144 true /* requireFullPermission */, true /* checkShell */, 4145 "revokeRuntimePermission"); 4146 4147 final int appId; 4148 4149 synchronized (mPackages) { 4150 final PackageParser.Package pkg = mPackages.get(packageName); 4151 if (pkg == null) { 4152 throw new IllegalArgumentException("Unknown package: " + packageName); 4153 } 4154 4155 final BasePermission bp = mSettings.mPermissions.get(name); 4156 if (bp == null) { 4157 throw new IllegalArgumentException("Unknown permission: " + name); 4158 } 4159 4160 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4161 4162 // If a permission review is required for legacy apps we represent 4163 // their permissions as always granted runtime ones since we need 4164 // to keep the review required permission flag per user while an 4165 // install permission's state is shared across all users. 4166 if (Build.PERMISSIONS_REVIEW_REQUIRED 4167 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4168 && bp.isRuntime()) { 4169 return; 4170 } 4171 4172 SettingBase sb = (SettingBase) pkg.mExtras; 4173 if (sb == null) { 4174 throw new IllegalArgumentException("Unknown package: " + packageName); 4175 } 4176 4177 final PermissionsState permissionsState = sb.getPermissionsState(); 4178 4179 final int flags = permissionsState.getPermissionFlags(name, userId); 4180 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4181 throw new SecurityException("Cannot revoke system fixed permission " 4182 + name + " for package " + packageName); 4183 } 4184 4185 if (bp.isDevelopment()) { 4186 // Development permissions must be handled specially, since they are not 4187 // normal runtime permissions. For now they apply to all users. 4188 if (permissionsState.revokeInstallPermission(bp) != 4189 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4190 scheduleWriteSettingsLocked(); 4191 } 4192 return; 4193 } 4194 4195 if (permissionsState.revokeRuntimePermission(bp, userId) == 4196 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4197 return; 4198 } 4199 4200 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4201 4202 // Critical, after this call app should never have the permission. 4203 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4204 4205 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4206 } 4207 4208 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4209 } 4210 4211 @Override 4212 public void resetRuntimePermissions() { 4213 mContext.enforceCallingOrSelfPermission( 4214 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4215 "revokeRuntimePermission"); 4216 4217 int callingUid = Binder.getCallingUid(); 4218 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4219 mContext.enforceCallingOrSelfPermission( 4220 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4221 "resetRuntimePermissions"); 4222 } 4223 4224 synchronized (mPackages) { 4225 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4226 for (int userId : UserManagerService.getInstance().getUserIds()) { 4227 final int packageCount = mPackages.size(); 4228 for (int i = 0; i < packageCount; i++) { 4229 PackageParser.Package pkg = mPackages.valueAt(i); 4230 if (!(pkg.mExtras instanceof PackageSetting)) { 4231 continue; 4232 } 4233 PackageSetting ps = (PackageSetting) pkg.mExtras; 4234 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4235 } 4236 } 4237 } 4238 } 4239 4240 @Override 4241 public int getPermissionFlags(String name, String packageName, int userId) { 4242 if (!sUserManager.exists(userId)) { 4243 return 0; 4244 } 4245 4246 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4247 4248 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4249 true /* requireFullPermission */, false /* checkShell */, 4250 "getPermissionFlags"); 4251 4252 synchronized (mPackages) { 4253 final PackageParser.Package pkg = mPackages.get(packageName); 4254 if (pkg == null) { 4255 throw new IllegalArgumentException("Unknown package: " + packageName); 4256 } 4257 4258 final BasePermission bp = mSettings.mPermissions.get(name); 4259 if (bp == null) { 4260 throw new IllegalArgumentException("Unknown permission: " + name); 4261 } 4262 4263 SettingBase sb = (SettingBase) pkg.mExtras; 4264 if (sb == null) { 4265 throw new IllegalArgumentException("Unknown package: " + packageName); 4266 } 4267 4268 PermissionsState permissionsState = sb.getPermissionsState(); 4269 return permissionsState.getPermissionFlags(name, userId); 4270 } 4271 } 4272 4273 @Override 4274 public void updatePermissionFlags(String name, String packageName, int flagMask, 4275 int flagValues, int userId) { 4276 if (!sUserManager.exists(userId)) { 4277 return; 4278 } 4279 4280 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4281 4282 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4283 true /* requireFullPermission */, true /* checkShell */, 4284 "updatePermissionFlags"); 4285 4286 // Only the system can change these flags and nothing else. 4287 if (getCallingUid() != Process.SYSTEM_UID) { 4288 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4289 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4290 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4291 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4292 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4293 } 4294 4295 synchronized (mPackages) { 4296 final PackageParser.Package pkg = mPackages.get(packageName); 4297 if (pkg == null) { 4298 throw new IllegalArgumentException("Unknown package: " + packageName); 4299 } 4300 4301 final BasePermission bp = mSettings.mPermissions.get(name); 4302 if (bp == null) { 4303 throw new IllegalArgumentException("Unknown permission: " + name); 4304 } 4305 4306 SettingBase sb = (SettingBase) pkg.mExtras; 4307 if (sb == null) { 4308 throw new IllegalArgumentException("Unknown package: " + packageName); 4309 } 4310 4311 PermissionsState permissionsState = sb.getPermissionsState(); 4312 4313 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4314 4315 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4316 // Install and runtime permissions are stored in different places, 4317 // so figure out what permission changed and persist the change. 4318 if (permissionsState.getInstallPermissionState(name) != null) { 4319 scheduleWriteSettingsLocked(); 4320 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4321 || hadState) { 4322 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4323 } 4324 } 4325 } 4326 } 4327 4328 /** 4329 * Update the permission flags for all packages and runtime permissions of a user in order 4330 * to allow device or profile owner to remove POLICY_FIXED. 4331 */ 4332 @Override 4333 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4334 if (!sUserManager.exists(userId)) { 4335 return; 4336 } 4337 4338 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4339 4340 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4341 true /* requireFullPermission */, true /* checkShell */, 4342 "updatePermissionFlagsForAllApps"); 4343 4344 // Only the system can change system fixed flags. 4345 if (getCallingUid() != Process.SYSTEM_UID) { 4346 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4347 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4348 } 4349 4350 synchronized (mPackages) { 4351 boolean changed = false; 4352 final int packageCount = mPackages.size(); 4353 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4354 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4355 SettingBase sb = (SettingBase) pkg.mExtras; 4356 if (sb == null) { 4357 continue; 4358 } 4359 PermissionsState permissionsState = sb.getPermissionsState(); 4360 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4361 userId, flagMask, flagValues); 4362 } 4363 if (changed) { 4364 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4365 } 4366 } 4367 } 4368 4369 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4370 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4371 != PackageManager.PERMISSION_GRANTED 4372 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4373 != PackageManager.PERMISSION_GRANTED) { 4374 throw new SecurityException(message + " requires " 4375 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4376 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4377 } 4378 } 4379 4380 @Override 4381 public boolean shouldShowRequestPermissionRationale(String permissionName, 4382 String packageName, int userId) { 4383 if (UserHandle.getCallingUserId() != userId) { 4384 mContext.enforceCallingPermission( 4385 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4386 "canShowRequestPermissionRationale for user " + userId); 4387 } 4388 4389 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4390 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4391 return false; 4392 } 4393 4394 if (checkPermission(permissionName, packageName, userId) 4395 == PackageManager.PERMISSION_GRANTED) { 4396 return false; 4397 } 4398 4399 final int flags; 4400 4401 final long identity = Binder.clearCallingIdentity(); 4402 try { 4403 flags = getPermissionFlags(permissionName, 4404 packageName, userId); 4405 } finally { 4406 Binder.restoreCallingIdentity(identity); 4407 } 4408 4409 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4410 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4411 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4412 4413 if ((flags & fixedFlags) != 0) { 4414 return false; 4415 } 4416 4417 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4418 } 4419 4420 @Override 4421 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4422 mContext.enforceCallingOrSelfPermission( 4423 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4424 "addOnPermissionsChangeListener"); 4425 4426 synchronized (mPackages) { 4427 mOnPermissionChangeListeners.addListenerLocked(listener); 4428 } 4429 } 4430 4431 @Override 4432 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4433 synchronized (mPackages) { 4434 mOnPermissionChangeListeners.removeListenerLocked(listener); 4435 } 4436 } 4437 4438 @Override 4439 public boolean isProtectedBroadcast(String actionName) { 4440 synchronized (mPackages) { 4441 if (mProtectedBroadcasts.contains(actionName)) { 4442 return true; 4443 } else if (actionName != null) { 4444 // TODO: remove these terrible hacks 4445 if (actionName.startsWith("android.net.netmon.lingerExpired") 4446 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4447 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4448 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4449 return true; 4450 } 4451 } 4452 } 4453 return false; 4454 } 4455 4456 @Override 4457 public int checkSignatures(String pkg1, String pkg2) { 4458 synchronized (mPackages) { 4459 final PackageParser.Package p1 = mPackages.get(pkg1); 4460 final PackageParser.Package p2 = mPackages.get(pkg2); 4461 if (p1 == null || p1.mExtras == null 4462 || p2 == null || p2.mExtras == null) { 4463 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4464 } 4465 return compareSignatures(p1.mSignatures, p2.mSignatures); 4466 } 4467 } 4468 4469 @Override 4470 public int checkUidSignatures(int uid1, int uid2) { 4471 // Map to base uids. 4472 uid1 = UserHandle.getAppId(uid1); 4473 uid2 = UserHandle.getAppId(uid2); 4474 // reader 4475 synchronized (mPackages) { 4476 Signature[] s1; 4477 Signature[] s2; 4478 Object obj = mSettings.getUserIdLPr(uid1); 4479 if (obj != null) { 4480 if (obj instanceof SharedUserSetting) { 4481 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4482 } else if (obj instanceof PackageSetting) { 4483 s1 = ((PackageSetting)obj).signatures.mSignatures; 4484 } else { 4485 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4486 } 4487 } else { 4488 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4489 } 4490 obj = mSettings.getUserIdLPr(uid2); 4491 if (obj != null) { 4492 if (obj instanceof SharedUserSetting) { 4493 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4494 } else if (obj instanceof PackageSetting) { 4495 s2 = ((PackageSetting)obj).signatures.mSignatures; 4496 } else { 4497 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4498 } 4499 } else { 4500 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4501 } 4502 return compareSignatures(s1, s2); 4503 } 4504 } 4505 4506 /** 4507 * This method should typically only be used when granting or revoking 4508 * permissions, since the app may immediately restart after this call. 4509 * <p> 4510 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4511 * guard your work against the app being relaunched. 4512 */ 4513 private void killUid(int appId, int userId, String reason) { 4514 final long identity = Binder.clearCallingIdentity(); 4515 try { 4516 IActivityManager am = ActivityManagerNative.getDefault(); 4517 if (am != null) { 4518 try { 4519 am.killUid(appId, userId, reason); 4520 } catch (RemoteException e) { 4521 /* ignore - same process */ 4522 } 4523 } 4524 } finally { 4525 Binder.restoreCallingIdentity(identity); 4526 } 4527 } 4528 4529 /** 4530 * Compares two sets of signatures. Returns: 4531 * <br /> 4532 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4533 * <br /> 4534 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4535 * <br /> 4536 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4537 * <br /> 4538 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4539 * <br /> 4540 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4541 */ 4542 static int compareSignatures(Signature[] s1, Signature[] s2) { 4543 if (s1 == null) { 4544 return s2 == null 4545 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4546 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4547 } 4548 4549 if (s2 == null) { 4550 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4551 } 4552 4553 if (s1.length != s2.length) { 4554 return PackageManager.SIGNATURE_NO_MATCH; 4555 } 4556 4557 // Since both signature sets are of size 1, we can compare without HashSets. 4558 if (s1.length == 1) { 4559 return s1[0].equals(s2[0]) ? 4560 PackageManager.SIGNATURE_MATCH : 4561 PackageManager.SIGNATURE_NO_MATCH; 4562 } 4563 4564 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4565 for (Signature sig : s1) { 4566 set1.add(sig); 4567 } 4568 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4569 for (Signature sig : s2) { 4570 set2.add(sig); 4571 } 4572 // Make sure s2 contains all signatures in s1. 4573 if (set1.equals(set2)) { 4574 return PackageManager.SIGNATURE_MATCH; 4575 } 4576 return PackageManager.SIGNATURE_NO_MATCH; 4577 } 4578 4579 /** 4580 * If the database version for this type of package (internal storage or 4581 * external storage) is less than the version where package signatures 4582 * were updated, return true. 4583 */ 4584 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4585 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4586 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4587 } 4588 4589 /** 4590 * Used for backward compatibility to make sure any packages with 4591 * certificate chains get upgraded to the new style. {@code existingSigs} 4592 * will be in the old format (since they were stored on disk from before the 4593 * system upgrade) and {@code scannedSigs} will be in the newer format. 4594 */ 4595 private int compareSignaturesCompat(PackageSignatures existingSigs, 4596 PackageParser.Package scannedPkg) { 4597 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4598 return PackageManager.SIGNATURE_NO_MATCH; 4599 } 4600 4601 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4602 for (Signature sig : existingSigs.mSignatures) { 4603 existingSet.add(sig); 4604 } 4605 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4606 for (Signature sig : scannedPkg.mSignatures) { 4607 try { 4608 Signature[] chainSignatures = sig.getChainSignatures(); 4609 for (Signature chainSig : chainSignatures) { 4610 scannedCompatSet.add(chainSig); 4611 } 4612 } catch (CertificateEncodingException e) { 4613 scannedCompatSet.add(sig); 4614 } 4615 } 4616 /* 4617 * Make sure the expanded scanned set contains all signatures in the 4618 * existing one. 4619 */ 4620 if (scannedCompatSet.equals(existingSet)) { 4621 // Migrate the old signatures to the new scheme. 4622 existingSigs.assignSignatures(scannedPkg.mSignatures); 4623 // The new KeySets will be re-added later in the scanning process. 4624 synchronized (mPackages) { 4625 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4626 } 4627 return PackageManager.SIGNATURE_MATCH; 4628 } 4629 return PackageManager.SIGNATURE_NO_MATCH; 4630 } 4631 4632 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4633 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4634 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4635 } 4636 4637 private int compareSignaturesRecover(PackageSignatures existingSigs, 4638 PackageParser.Package scannedPkg) { 4639 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4640 return PackageManager.SIGNATURE_NO_MATCH; 4641 } 4642 4643 String msg = null; 4644 try { 4645 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4646 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4647 + scannedPkg.packageName); 4648 return PackageManager.SIGNATURE_MATCH; 4649 } 4650 } catch (CertificateException e) { 4651 msg = e.getMessage(); 4652 } 4653 4654 logCriticalInfo(Log.INFO, 4655 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4656 return PackageManager.SIGNATURE_NO_MATCH; 4657 } 4658 4659 @Override 4660 public List<String> getAllPackages() { 4661 synchronized (mPackages) { 4662 return new ArrayList<String>(mPackages.keySet()); 4663 } 4664 } 4665 4666 @Override 4667 public String[] getPackagesForUid(int uid) { 4668 uid = UserHandle.getAppId(uid); 4669 // reader 4670 synchronized (mPackages) { 4671 Object obj = mSettings.getUserIdLPr(uid); 4672 if (obj instanceof SharedUserSetting) { 4673 final SharedUserSetting sus = (SharedUserSetting) obj; 4674 final int N = sus.packages.size(); 4675 final String[] res = new String[N]; 4676 final Iterator<PackageSetting> it = sus.packages.iterator(); 4677 int i = 0; 4678 while (it.hasNext()) { 4679 res[i++] = it.next().name; 4680 } 4681 return res; 4682 } else if (obj instanceof PackageSetting) { 4683 final PackageSetting ps = (PackageSetting) obj; 4684 return new String[] { ps.name }; 4685 } 4686 } 4687 return null; 4688 } 4689 4690 @Override 4691 public String getNameForUid(int uid) { 4692 // reader 4693 synchronized (mPackages) { 4694 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4695 if (obj instanceof SharedUserSetting) { 4696 final SharedUserSetting sus = (SharedUserSetting) obj; 4697 return sus.name + ":" + sus.userId; 4698 } else if (obj instanceof PackageSetting) { 4699 final PackageSetting ps = (PackageSetting) obj; 4700 return ps.name; 4701 } 4702 } 4703 return null; 4704 } 4705 4706 @Override 4707 public int getUidForSharedUser(String sharedUserName) { 4708 if(sharedUserName == null) { 4709 return -1; 4710 } 4711 // reader 4712 synchronized (mPackages) { 4713 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4714 if (suid == null) { 4715 return -1; 4716 } 4717 return suid.userId; 4718 } 4719 } 4720 4721 @Override 4722 public int getFlagsForUid(int uid) { 4723 synchronized (mPackages) { 4724 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4725 if (obj instanceof SharedUserSetting) { 4726 final SharedUserSetting sus = (SharedUserSetting) obj; 4727 return sus.pkgFlags; 4728 } else if (obj instanceof PackageSetting) { 4729 final PackageSetting ps = (PackageSetting) obj; 4730 return ps.pkgFlags; 4731 } 4732 } 4733 return 0; 4734 } 4735 4736 @Override 4737 public int getPrivateFlagsForUid(int uid) { 4738 synchronized (mPackages) { 4739 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4740 if (obj instanceof SharedUserSetting) { 4741 final SharedUserSetting sus = (SharedUserSetting) obj; 4742 return sus.pkgPrivateFlags; 4743 } else if (obj instanceof PackageSetting) { 4744 final PackageSetting ps = (PackageSetting) obj; 4745 return ps.pkgPrivateFlags; 4746 } 4747 } 4748 return 0; 4749 } 4750 4751 @Override 4752 public boolean isUidPrivileged(int uid) { 4753 uid = UserHandle.getAppId(uid); 4754 // reader 4755 synchronized (mPackages) { 4756 Object obj = mSettings.getUserIdLPr(uid); 4757 if (obj instanceof SharedUserSetting) { 4758 final SharedUserSetting sus = (SharedUserSetting) obj; 4759 final Iterator<PackageSetting> it = sus.packages.iterator(); 4760 while (it.hasNext()) { 4761 if (it.next().isPrivileged()) { 4762 return true; 4763 } 4764 } 4765 } else if (obj instanceof PackageSetting) { 4766 final PackageSetting ps = (PackageSetting) obj; 4767 return ps.isPrivileged(); 4768 } 4769 } 4770 return false; 4771 } 4772 4773 @Override 4774 public String[] getAppOpPermissionPackages(String permissionName) { 4775 synchronized (mPackages) { 4776 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4777 if (pkgs == null) { 4778 return null; 4779 } 4780 return pkgs.toArray(new String[pkgs.size()]); 4781 } 4782 } 4783 4784 @Override 4785 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4786 int flags, int userId) { 4787 try { 4788 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4789 4790 if (!sUserManager.exists(userId)) return null; 4791 flags = updateFlagsForResolve(flags, userId, intent); 4792 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4793 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4794 4795 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4796 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4797 flags, userId); 4798 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4799 4800 final ResolveInfo bestChoice = 4801 chooseBestActivity(intent, resolvedType, flags, query, userId); 4802 4803 if (isEphemeralAllowed(intent, query, userId)) { 4804 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4805 final EphemeralResolveInfo ai = 4806 getEphemeralResolveInfo(intent, resolvedType, userId); 4807 if (ai != null) { 4808 if (DEBUG_EPHEMERAL) { 4809 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4810 } 4811 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4812 bestChoice.ephemeralResolveInfo = ai; 4813 } 4814 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4815 } 4816 return bestChoice; 4817 } finally { 4818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4819 } 4820 } 4821 4822 @Override 4823 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4824 IntentFilter filter, int match, ComponentName activity) { 4825 final int userId = UserHandle.getCallingUserId(); 4826 if (DEBUG_PREFERRED) { 4827 Log.v(TAG, "setLastChosenActivity intent=" + intent 4828 + " resolvedType=" + resolvedType 4829 + " flags=" + flags 4830 + " filter=" + filter 4831 + " match=" + match 4832 + " activity=" + activity); 4833 filter.dump(new PrintStreamPrinter(System.out), " "); 4834 } 4835 intent.setComponent(null); 4836 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4837 userId); 4838 // Find any earlier preferred or last chosen entries and nuke them 4839 findPreferredActivity(intent, resolvedType, 4840 flags, query, 0, false, true, false, userId); 4841 // Add the new activity as the last chosen for this filter 4842 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4843 "Setting last chosen"); 4844 } 4845 4846 @Override 4847 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4848 final int userId = UserHandle.getCallingUserId(); 4849 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4850 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4851 userId); 4852 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4853 false, false, false, userId); 4854 } 4855 4856 4857 private boolean isEphemeralAllowed( 4858 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4859 // Short circuit and return early if possible. 4860 if (DISABLE_EPHEMERAL_APPS) { 4861 return false; 4862 } 4863 final int callingUser = UserHandle.getCallingUserId(); 4864 if (callingUser != UserHandle.USER_SYSTEM) { 4865 return false; 4866 } 4867 if (mEphemeralResolverConnection == null) { 4868 return false; 4869 } 4870 if (intent.getComponent() != null) { 4871 return false; 4872 } 4873 if (intent.getPackage() != null) { 4874 return false; 4875 } 4876 final boolean isWebUri = hasWebURI(intent); 4877 if (!isWebUri) { 4878 return false; 4879 } 4880 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4881 synchronized (mPackages) { 4882 final int count = resolvedActivites.size(); 4883 for (int n = 0; n < count; n++) { 4884 ResolveInfo info = resolvedActivites.get(n); 4885 String packageName = info.activityInfo.packageName; 4886 PackageSetting ps = mSettings.mPackages.get(packageName); 4887 if (ps != null) { 4888 // Try to get the status from User settings first 4889 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4890 int status = (int) (packedStatus >> 32); 4891 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4892 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4893 if (DEBUG_EPHEMERAL) { 4894 Slog.v(TAG, "DENY ephemeral apps;" 4895 + " pkg: " + packageName + ", status: " + status); 4896 } 4897 return false; 4898 } 4899 } 4900 } 4901 } 4902 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4903 return true; 4904 } 4905 4906 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4907 int userId) { 4908 MessageDigest digest = null; 4909 try { 4910 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4911 } catch (NoSuchAlgorithmException e) { 4912 // If we can't create a digest, ignore ephemeral apps. 4913 return null; 4914 } 4915 4916 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4917 final byte[] digestBytes = digest.digest(hostBytes); 4918 int shaPrefix = 4919 digestBytes[0] << 24 4920 | digestBytes[1] << 16 4921 | digestBytes[2] << 8 4922 | digestBytes[3] << 0; 4923 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4924 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4925 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4926 // No hash prefix match; there are no ephemeral apps for this domain. 4927 return null; 4928 } 4929 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4930 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4931 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4932 continue; 4933 } 4934 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4935 // No filters; this should never happen. 4936 if (filters.isEmpty()) { 4937 continue; 4938 } 4939 // We have a domain match; resolve the filters to see if anything matches. 4940 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4941 for (int j = filters.size() - 1; j >= 0; --j) { 4942 final EphemeralResolveIntentInfo intentInfo = 4943 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4944 ephemeralResolver.addFilter(intentInfo); 4945 } 4946 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4947 intent, resolvedType, false /*defaultOnly*/, userId); 4948 if (!matchedResolveInfoList.isEmpty()) { 4949 return matchedResolveInfoList.get(0); 4950 } 4951 } 4952 // Hash or filter mis-match; no ephemeral apps for this domain. 4953 return null; 4954 } 4955 4956 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4957 int flags, List<ResolveInfo> query, int userId) { 4958 if (query != null) { 4959 final int N = query.size(); 4960 if (N == 1) { 4961 return query.get(0); 4962 } else if (N > 1) { 4963 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4964 // If there is more than one activity with the same priority, 4965 // then let the user decide between them. 4966 ResolveInfo r0 = query.get(0); 4967 ResolveInfo r1 = query.get(1); 4968 if (DEBUG_INTENT_MATCHING || debug) { 4969 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4970 + r1.activityInfo.name + "=" + r1.priority); 4971 } 4972 // If the first activity has a higher priority, or a different 4973 // default, then it is always desirable to pick it. 4974 if (r0.priority != r1.priority 4975 || r0.preferredOrder != r1.preferredOrder 4976 || r0.isDefault != r1.isDefault) { 4977 return query.get(0); 4978 } 4979 // If we have saved a preference for a preferred activity for 4980 // this Intent, use that. 4981 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4982 flags, query, r0.priority, true, false, debug, userId); 4983 if (ri != null) { 4984 return ri; 4985 } 4986 ri = new ResolveInfo(mResolveInfo); 4987 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4988 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4989 ri.activityInfo.applicationInfo = new ApplicationInfo( 4990 ri.activityInfo.applicationInfo); 4991 if (userId != 0) { 4992 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4993 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4994 } 4995 // Make sure that the resolver is displayable in car mode 4996 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4997 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4998 return ri; 4999 } 5000 } 5001 return null; 5002 } 5003 5004 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5005 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5006 final int N = query.size(); 5007 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5008 .get(userId); 5009 // Get the list of persistent preferred activities that handle the intent 5010 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5011 List<PersistentPreferredActivity> pprefs = ppir != null 5012 ? ppir.queryIntent(intent, resolvedType, 5013 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5014 : null; 5015 if (pprefs != null && pprefs.size() > 0) { 5016 final int M = pprefs.size(); 5017 for (int i=0; i<M; i++) { 5018 final PersistentPreferredActivity ppa = pprefs.get(i); 5019 if (DEBUG_PREFERRED || debug) { 5020 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5021 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5022 + "\n component=" + ppa.mComponent); 5023 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5024 } 5025 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5026 flags | MATCH_DISABLED_COMPONENTS, userId); 5027 if (DEBUG_PREFERRED || debug) { 5028 Slog.v(TAG, "Found persistent preferred activity:"); 5029 if (ai != null) { 5030 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5031 } else { 5032 Slog.v(TAG, " null"); 5033 } 5034 } 5035 if (ai == null) { 5036 // This previously registered persistent preferred activity 5037 // component is no longer known. Ignore it and do NOT remove it. 5038 continue; 5039 } 5040 for (int j=0; j<N; j++) { 5041 final ResolveInfo ri = query.get(j); 5042 if (!ri.activityInfo.applicationInfo.packageName 5043 .equals(ai.applicationInfo.packageName)) { 5044 continue; 5045 } 5046 if (!ri.activityInfo.name.equals(ai.name)) { 5047 continue; 5048 } 5049 // Found a persistent preference that can handle the intent. 5050 if (DEBUG_PREFERRED || debug) { 5051 Slog.v(TAG, "Returning persistent preferred activity: " + 5052 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5053 } 5054 return ri; 5055 } 5056 } 5057 } 5058 return null; 5059 } 5060 5061 // TODO: handle preferred activities missing while user has amnesia 5062 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5063 List<ResolveInfo> query, int priority, boolean always, 5064 boolean removeMatches, boolean debug, int userId) { 5065 if (!sUserManager.exists(userId)) return null; 5066 flags = updateFlagsForResolve(flags, userId, intent); 5067 // writer 5068 synchronized (mPackages) { 5069 if (intent.getSelector() != null) { 5070 intent = intent.getSelector(); 5071 } 5072 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5073 5074 // Try to find a matching persistent preferred activity. 5075 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5076 debug, userId); 5077 5078 // If a persistent preferred activity matched, use it. 5079 if (pri != null) { 5080 return pri; 5081 } 5082 5083 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5084 // Get the list of preferred activities that handle the intent 5085 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5086 List<PreferredActivity> prefs = pir != null 5087 ? pir.queryIntent(intent, resolvedType, 5088 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5089 : null; 5090 if (prefs != null && prefs.size() > 0) { 5091 boolean changed = false; 5092 try { 5093 // First figure out how good the original match set is. 5094 // We will only allow preferred activities that came 5095 // from the same match quality. 5096 int match = 0; 5097 5098 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5099 5100 final int N = query.size(); 5101 for (int j=0; j<N; j++) { 5102 final ResolveInfo ri = query.get(j); 5103 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5104 + ": 0x" + Integer.toHexString(match)); 5105 if (ri.match > match) { 5106 match = ri.match; 5107 } 5108 } 5109 5110 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5111 + Integer.toHexString(match)); 5112 5113 match &= IntentFilter.MATCH_CATEGORY_MASK; 5114 final int M = prefs.size(); 5115 for (int i=0; i<M; i++) { 5116 final PreferredActivity pa = prefs.get(i); 5117 if (DEBUG_PREFERRED || debug) { 5118 Slog.v(TAG, "Checking PreferredActivity ds=" 5119 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5120 + "\n component=" + pa.mPref.mComponent); 5121 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5122 } 5123 if (pa.mPref.mMatch != match) { 5124 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5125 + Integer.toHexString(pa.mPref.mMatch)); 5126 continue; 5127 } 5128 // If it's not an "always" type preferred activity and that's what we're 5129 // looking for, skip it. 5130 if (always && !pa.mPref.mAlways) { 5131 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5132 continue; 5133 } 5134 final ActivityInfo ai = getActivityInfo( 5135 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5136 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5137 userId); 5138 if (DEBUG_PREFERRED || debug) { 5139 Slog.v(TAG, "Found preferred activity:"); 5140 if (ai != null) { 5141 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5142 } else { 5143 Slog.v(TAG, " null"); 5144 } 5145 } 5146 if (ai == null) { 5147 // This previously registered preferred activity 5148 // component is no longer known. Most likely an update 5149 // to the app was installed and in the new version this 5150 // component no longer exists. Clean it up by removing 5151 // it from the preferred activities list, and skip it. 5152 Slog.w(TAG, "Removing dangling preferred activity: " 5153 + pa.mPref.mComponent); 5154 pir.removeFilter(pa); 5155 changed = true; 5156 continue; 5157 } 5158 for (int j=0; j<N; j++) { 5159 final ResolveInfo ri = query.get(j); 5160 if (!ri.activityInfo.applicationInfo.packageName 5161 .equals(ai.applicationInfo.packageName)) { 5162 continue; 5163 } 5164 if (!ri.activityInfo.name.equals(ai.name)) { 5165 continue; 5166 } 5167 5168 if (removeMatches) { 5169 pir.removeFilter(pa); 5170 changed = true; 5171 if (DEBUG_PREFERRED) { 5172 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5173 } 5174 break; 5175 } 5176 5177 // Okay we found a previously set preferred or last chosen app. 5178 // If the result set is different from when this 5179 // was created, we need to clear it and re-ask the 5180 // user their preference, if we're looking for an "always" type entry. 5181 if (always && !pa.mPref.sameSet(query)) { 5182 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5183 + intent + " type " + resolvedType); 5184 if (DEBUG_PREFERRED) { 5185 Slog.v(TAG, "Removing preferred activity since set changed " 5186 + pa.mPref.mComponent); 5187 } 5188 pir.removeFilter(pa); 5189 // Re-add the filter as a "last chosen" entry (!always) 5190 PreferredActivity lastChosen = new PreferredActivity( 5191 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5192 pir.addFilter(lastChosen); 5193 changed = true; 5194 return null; 5195 } 5196 5197 // Yay! Either the set matched or we're looking for the last chosen 5198 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5199 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5200 return ri; 5201 } 5202 } 5203 } finally { 5204 if (changed) { 5205 if (DEBUG_PREFERRED) { 5206 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5207 } 5208 scheduleWritePackageRestrictionsLocked(userId); 5209 } 5210 } 5211 } 5212 } 5213 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5214 return null; 5215 } 5216 5217 /* 5218 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5219 */ 5220 @Override 5221 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5222 int targetUserId) { 5223 mContext.enforceCallingOrSelfPermission( 5224 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5225 List<CrossProfileIntentFilter> matches = 5226 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5227 if (matches != null) { 5228 int size = matches.size(); 5229 for (int i = 0; i < size; i++) { 5230 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5231 } 5232 } 5233 if (hasWebURI(intent)) { 5234 // cross-profile app linking works only towards the parent. 5235 final UserInfo parent = getProfileParent(sourceUserId); 5236 synchronized(mPackages) { 5237 int flags = updateFlagsForResolve(0, parent.id, intent); 5238 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5239 intent, resolvedType, flags, sourceUserId, parent.id); 5240 return xpDomainInfo != null; 5241 } 5242 } 5243 return false; 5244 } 5245 5246 private UserInfo getProfileParent(int userId) { 5247 final long identity = Binder.clearCallingIdentity(); 5248 try { 5249 return sUserManager.getProfileParent(userId); 5250 } finally { 5251 Binder.restoreCallingIdentity(identity); 5252 } 5253 } 5254 5255 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5256 String resolvedType, int userId) { 5257 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5258 if (resolver != null) { 5259 return resolver.queryIntent(intent, resolvedType, false, userId); 5260 } 5261 return null; 5262 } 5263 5264 @Override 5265 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5266 String resolvedType, int flags, int userId) { 5267 try { 5268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5269 5270 return new ParceledListSlice<>( 5271 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5272 } finally { 5273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5274 } 5275 } 5276 5277 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5278 String resolvedType, int flags, int userId) { 5279 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5280 flags = updateFlagsForResolve(flags, userId, intent); 5281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5282 false /* requireFullPermission */, false /* checkShell */, 5283 "query intent activities"); 5284 ComponentName comp = intent.getComponent(); 5285 if (comp == null) { 5286 if (intent.getSelector() != null) { 5287 intent = intent.getSelector(); 5288 comp = intent.getComponent(); 5289 } 5290 } 5291 5292 if (comp != null) { 5293 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5294 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5295 if (ai != null) { 5296 final ResolveInfo ri = new ResolveInfo(); 5297 ri.activityInfo = ai; 5298 list.add(ri); 5299 } 5300 return list; 5301 } 5302 5303 // reader 5304 synchronized (mPackages) { 5305 final String pkgName = intent.getPackage(); 5306 if (pkgName == null) { 5307 List<CrossProfileIntentFilter> matchingFilters = 5308 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5309 // Check for results that need to skip the current profile. 5310 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5311 resolvedType, flags, userId); 5312 if (xpResolveInfo != null) { 5313 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5314 result.add(xpResolveInfo); 5315 return filterIfNotSystemUser(result, userId); 5316 } 5317 5318 // Check for results in the current profile. 5319 List<ResolveInfo> result = mActivities.queryIntent( 5320 intent, resolvedType, flags, userId); 5321 result = filterIfNotSystemUser(result, userId); 5322 5323 // Check for cross profile results. 5324 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5325 xpResolveInfo = queryCrossProfileIntents( 5326 matchingFilters, intent, resolvedType, flags, userId, 5327 hasNonNegativePriorityResult); 5328 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5329 boolean isVisibleToUser = filterIfNotSystemUser( 5330 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5331 if (isVisibleToUser) { 5332 result.add(xpResolveInfo); 5333 Collections.sort(result, mResolvePrioritySorter); 5334 } 5335 } 5336 if (hasWebURI(intent)) { 5337 CrossProfileDomainInfo xpDomainInfo = null; 5338 final UserInfo parent = getProfileParent(userId); 5339 if (parent != null) { 5340 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5341 flags, userId, parent.id); 5342 } 5343 if (xpDomainInfo != null) { 5344 if (xpResolveInfo != null) { 5345 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5346 // in the result. 5347 result.remove(xpResolveInfo); 5348 } 5349 if (result.size() == 0) { 5350 result.add(xpDomainInfo.resolveInfo); 5351 return result; 5352 } 5353 } else if (result.size() <= 1) { 5354 return result; 5355 } 5356 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5357 xpDomainInfo, userId); 5358 Collections.sort(result, mResolvePrioritySorter); 5359 } 5360 return result; 5361 } 5362 final PackageParser.Package pkg = mPackages.get(pkgName); 5363 if (pkg != null) { 5364 return filterIfNotSystemUser( 5365 mActivities.queryIntentForPackage( 5366 intent, resolvedType, flags, pkg.activities, userId), 5367 userId); 5368 } 5369 return new ArrayList<ResolveInfo>(); 5370 } 5371 } 5372 5373 private static class CrossProfileDomainInfo { 5374 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5375 ResolveInfo resolveInfo; 5376 /* Best domain verification status of the activities found in the other profile */ 5377 int bestDomainVerificationStatus; 5378 } 5379 5380 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5381 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5382 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5383 sourceUserId)) { 5384 return null; 5385 } 5386 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5387 resolvedType, flags, parentUserId); 5388 5389 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5390 return null; 5391 } 5392 CrossProfileDomainInfo result = null; 5393 int size = resultTargetUser.size(); 5394 for (int i = 0; i < size; i++) { 5395 ResolveInfo riTargetUser = resultTargetUser.get(i); 5396 // Intent filter verification is only for filters that specify a host. So don't return 5397 // those that handle all web uris. 5398 if (riTargetUser.handleAllWebDataURI) { 5399 continue; 5400 } 5401 String packageName = riTargetUser.activityInfo.packageName; 5402 PackageSetting ps = mSettings.mPackages.get(packageName); 5403 if (ps == null) { 5404 continue; 5405 } 5406 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5407 int status = (int)(verificationState >> 32); 5408 if (result == null) { 5409 result = new CrossProfileDomainInfo(); 5410 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5411 sourceUserId, parentUserId); 5412 result.bestDomainVerificationStatus = status; 5413 } else { 5414 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5415 result.bestDomainVerificationStatus); 5416 } 5417 } 5418 // Don't consider matches with status NEVER across profiles. 5419 if (result != null && result.bestDomainVerificationStatus 5420 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5421 return null; 5422 } 5423 return result; 5424 } 5425 5426 /** 5427 * Verification statuses are ordered from the worse to the best, except for 5428 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5429 */ 5430 private int bestDomainVerificationStatus(int status1, int status2) { 5431 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5432 return status2; 5433 } 5434 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5435 return status1; 5436 } 5437 return (int) MathUtils.max(status1, status2); 5438 } 5439 5440 private boolean isUserEnabled(int userId) { 5441 long callingId = Binder.clearCallingIdentity(); 5442 try { 5443 UserInfo userInfo = sUserManager.getUserInfo(userId); 5444 return userInfo != null && userInfo.isEnabled(); 5445 } finally { 5446 Binder.restoreCallingIdentity(callingId); 5447 } 5448 } 5449 5450 /** 5451 * Filter out activities with systemUserOnly flag set, when current user is not System. 5452 * 5453 * @return filtered list 5454 */ 5455 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5456 if (userId == UserHandle.USER_SYSTEM) { 5457 return resolveInfos; 5458 } 5459 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5460 ResolveInfo info = resolveInfos.get(i); 5461 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5462 resolveInfos.remove(i); 5463 } 5464 } 5465 return resolveInfos; 5466 } 5467 5468 /** 5469 * @param resolveInfos list of resolve infos in descending priority order 5470 * @return if the list contains a resolve info with non-negative priority 5471 */ 5472 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5473 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5474 } 5475 5476 private static boolean hasWebURI(Intent intent) { 5477 if (intent.getData() == null) { 5478 return false; 5479 } 5480 final String scheme = intent.getScheme(); 5481 if (TextUtils.isEmpty(scheme)) { 5482 return false; 5483 } 5484 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5485 } 5486 5487 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5488 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5489 int userId) { 5490 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5491 5492 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5493 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5494 candidates.size()); 5495 } 5496 5497 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5498 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5499 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5500 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5501 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5502 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5503 5504 synchronized (mPackages) { 5505 final int count = candidates.size(); 5506 // First, try to use linked apps. Partition the candidates into four lists: 5507 // one for the final results, one for the "do not use ever", one for "undefined status" 5508 // and finally one for "browser app type". 5509 for (int n=0; n<count; n++) { 5510 ResolveInfo info = candidates.get(n); 5511 String packageName = info.activityInfo.packageName; 5512 PackageSetting ps = mSettings.mPackages.get(packageName); 5513 if (ps != null) { 5514 // Add to the special match all list (Browser use case) 5515 if (info.handleAllWebDataURI) { 5516 matchAllList.add(info); 5517 continue; 5518 } 5519 // Try to get the status from User settings first 5520 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5521 int status = (int)(packedStatus >> 32); 5522 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5523 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5524 if (DEBUG_DOMAIN_VERIFICATION) { 5525 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5526 + " : linkgen=" + linkGeneration); 5527 } 5528 // Use link-enabled generation as preferredOrder, i.e. 5529 // prefer newly-enabled over earlier-enabled. 5530 info.preferredOrder = linkGeneration; 5531 alwaysList.add(info); 5532 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5533 if (DEBUG_DOMAIN_VERIFICATION) { 5534 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5535 } 5536 neverList.add(info); 5537 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5538 if (DEBUG_DOMAIN_VERIFICATION) { 5539 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5540 } 5541 alwaysAskList.add(info); 5542 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5543 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5544 if (DEBUG_DOMAIN_VERIFICATION) { 5545 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5546 } 5547 undefinedList.add(info); 5548 } 5549 } 5550 } 5551 5552 // We'll want to include browser possibilities in a few cases 5553 boolean includeBrowser = false; 5554 5555 // First try to add the "always" resolution(s) for the current user, if any 5556 if (alwaysList.size() > 0) { 5557 result.addAll(alwaysList); 5558 } else { 5559 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5560 result.addAll(undefinedList); 5561 // Maybe add one for the other profile. 5562 if (xpDomainInfo != null && ( 5563 xpDomainInfo.bestDomainVerificationStatus 5564 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5565 result.add(xpDomainInfo.resolveInfo); 5566 } 5567 includeBrowser = true; 5568 } 5569 5570 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5571 // If there were 'always' entries their preferred order has been set, so we also 5572 // back that off to make the alternatives equivalent 5573 if (alwaysAskList.size() > 0) { 5574 for (ResolveInfo i : result) { 5575 i.preferredOrder = 0; 5576 } 5577 result.addAll(alwaysAskList); 5578 includeBrowser = true; 5579 } 5580 5581 if (includeBrowser) { 5582 // Also add browsers (all of them or only the default one) 5583 if (DEBUG_DOMAIN_VERIFICATION) { 5584 Slog.v(TAG, " ...including browsers in candidate set"); 5585 } 5586 if ((matchFlags & MATCH_ALL) != 0) { 5587 result.addAll(matchAllList); 5588 } else { 5589 // Browser/generic handling case. If there's a default browser, go straight 5590 // to that (but only if there is no other higher-priority match). 5591 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5592 int maxMatchPrio = 0; 5593 ResolveInfo defaultBrowserMatch = null; 5594 final int numCandidates = matchAllList.size(); 5595 for (int n = 0; n < numCandidates; n++) { 5596 ResolveInfo info = matchAllList.get(n); 5597 // track the highest overall match priority... 5598 if (info.priority > maxMatchPrio) { 5599 maxMatchPrio = info.priority; 5600 } 5601 // ...and the highest-priority default browser match 5602 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5603 if (defaultBrowserMatch == null 5604 || (defaultBrowserMatch.priority < info.priority)) { 5605 if (debug) { 5606 Slog.v(TAG, "Considering default browser match " + info); 5607 } 5608 defaultBrowserMatch = info; 5609 } 5610 } 5611 } 5612 if (defaultBrowserMatch != null 5613 && defaultBrowserMatch.priority >= maxMatchPrio 5614 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5615 { 5616 if (debug) { 5617 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5618 } 5619 result.add(defaultBrowserMatch); 5620 } else { 5621 result.addAll(matchAllList); 5622 } 5623 } 5624 5625 // If there is nothing selected, add all candidates and remove the ones that the user 5626 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5627 if (result.size() == 0) { 5628 result.addAll(candidates); 5629 result.removeAll(neverList); 5630 } 5631 } 5632 } 5633 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5634 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5635 result.size()); 5636 for (ResolveInfo info : result) { 5637 Slog.v(TAG, " + " + info.activityInfo); 5638 } 5639 } 5640 return result; 5641 } 5642 5643 // Returns a packed value as a long: 5644 // 5645 // high 'int'-sized word: link status: undefined/ask/never/always. 5646 // low 'int'-sized word: relative priority among 'always' results. 5647 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5648 long result = ps.getDomainVerificationStatusForUser(userId); 5649 // if none available, get the master status 5650 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5651 if (ps.getIntentFilterVerificationInfo() != null) { 5652 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5653 } 5654 } 5655 return result; 5656 } 5657 5658 private ResolveInfo querySkipCurrentProfileIntents( 5659 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5660 int flags, int sourceUserId) { 5661 if (matchingFilters != null) { 5662 int size = matchingFilters.size(); 5663 for (int i = 0; i < size; i ++) { 5664 CrossProfileIntentFilter filter = matchingFilters.get(i); 5665 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5666 // Checking if there are activities in the target user that can handle the 5667 // intent. 5668 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5669 resolvedType, flags, sourceUserId); 5670 if (resolveInfo != null) { 5671 return resolveInfo; 5672 } 5673 } 5674 } 5675 } 5676 return null; 5677 } 5678 5679 // Return matching ResolveInfo in target user if any. 5680 private ResolveInfo queryCrossProfileIntents( 5681 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5682 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5683 if (matchingFilters != null) { 5684 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5685 // match the same intent. For performance reasons, it is better not to 5686 // run queryIntent twice for the same userId 5687 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5688 int size = matchingFilters.size(); 5689 for (int i = 0; i < size; i++) { 5690 CrossProfileIntentFilter filter = matchingFilters.get(i); 5691 int targetUserId = filter.getTargetUserId(); 5692 boolean skipCurrentProfile = 5693 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5694 boolean skipCurrentProfileIfNoMatchFound = 5695 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5696 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5697 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5698 // Checking if there are activities in the target user that can handle the 5699 // intent. 5700 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5701 resolvedType, flags, sourceUserId); 5702 if (resolveInfo != null) return resolveInfo; 5703 alreadyTriedUserIds.put(targetUserId, true); 5704 } 5705 } 5706 } 5707 return null; 5708 } 5709 5710 /** 5711 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5712 * will forward the intent to the filter's target user. 5713 * Otherwise, returns null. 5714 */ 5715 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5716 String resolvedType, int flags, int sourceUserId) { 5717 int targetUserId = filter.getTargetUserId(); 5718 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5719 resolvedType, flags, targetUserId); 5720 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5721 // If all the matches in the target profile are suspended, return null. 5722 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5723 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5724 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5725 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5726 targetUserId); 5727 } 5728 } 5729 } 5730 return null; 5731 } 5732 5733 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5734 int sourceUserId, int targetUserId) { 5735 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5736 long ident = Binder.clearCallingIdentity(); 5737 boolean targetIsProfile; 5738 try { 5739 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5740 } finally { 5741 Binder.restoreCallingIdentity(ident); 5742 } 5743 String className; 5744 if (targetIsProfile) { 5745 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5746 } else { 5747 className = FORWARD_INTENT_TO_PARENT; 5748 } 5749 ComponentName forwardingActivityComponentName = new ComponentName( 5750 mAndroidApplication.packageName, className); 5751 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5752 sourceUserId); 5753 if (!targetIsProfile) { 5754 forwardingActivityInfo.showUserIcon = targetUserId; 5755 forwardingResolveInfo.noResourceId = true; 5756 } 5757 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5758 forwardingResolveInfo.priority = 0; 5759 forwardingResolveInfo.preferredOrder = 0; 5760 forwardingResolveInfo.match = 0; 5761 forwardingResolveInfo.isDefault = true; 5762 forwardingResolveInfo.filter = filter; 5763 forwardingResolveInfo.targetUserId = targetUserId; 5764 return forwardingResolveInfo; 5765 } 5766 5767 @Override 5768 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5769 Intent[] specifics, String[] specificTypes, Intent intent, 5770 String resolvedType, int flags, int userId) { 5771 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5772 specificTypes, intent, resolvedType, flags, userId)); 5773 } 5774 5775 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5776 Intent[] specifics, String[] specificTypes, Intent intent, 5777 String resolvedType, int flags, int userId) { 5778 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5779 flags = updateFlagsForResolve(flags, userId, intent); 5780 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5781 false /* requireFullPermission */, false /* checkShell */, 5782 "query intent activity options"); 5783 final String resultsAction = intent.getAction(); 5784 5785 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5786 | PackageManager.GET_RESOLVED_FILTER, userId); 5787 5788 if (DEBUG_INTENT_MATCHING) { 5789 Log.v(TAG, "Query " + intent + ": " + results); 5790 } 5791 5792 int specificsPos = 0; 5793 int N; 5794 5795 // todo: note that the algorithm used here is O(N^2). This 5796 // isn't a problem in our current environment, but if we start running 5797 // into situations where we have more than 5 or 10 matches then this 5798 // should probably be changed to something smarter... 5799 5800 // First we go through and resolve each of the specific items 5801 // that were supplied, taking care of removing any corresponding 5802 // duplicate items in the generic resolve list. 5803 if (specifics != null) { 5804 for (int i=0; i<specifics.length; i++) { 5805 final Intent sintent = specifics[i]; 5806 if (sintent == null) { 5807 continue; 5808 } 5809 5810 if (DEBUG_INTENT_MATCHING) { 5811 Log.v(TAG, "Specific #" + i + ": " + sintent); 5812 } 5813 5814 String action = sintent.getAction(); 5815 if (resultsAction != null && resultsAction.equals(action)) { 5816 // If this action was explicitly requested, then don't 5817 // remove things that have it. 5818 action = null; 5819 } 5820 5821 ResolveInfo ri = null; 5822 ActivityInfo ai = null; 5823 5824 ComponentName comp = sintent.getComponent(); 5825 if (comp == null) { 5826 ri = resolveIntent( 5827 sintent, 5828 specificTypes != null ? specificTypes[i] : null, 5829 flags, userId); 5830 if (ri == null) { 5831 continue; 5832 } 5833 if (ri == mResolveInfo) { 5834 // ACK! Must do something better with this. 5835 } 5836 ai = ri.activityInfo; 5837 comp = new ComponentName(ai.applicationInfo.packageName, 5838 ai.name); 5839 } else { 5840 ai = getActivityInfo(comp, flags, userId); 5841 if (ai == null) { 5842 continue; 5843 } 5844 } 5845 5846 // Look for any generic query activities that are duplicates 5847 // of this specific one, and remove them from the results. 5848 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5849 N = results.size(); 5850 int j; 5851 for (j=specificsPos; j<N; j++) { 5852 ResolveInfo sri = results.get(j); 5853 if ((sri.activityInfo.name.equals(comp.getClassName()) 5854 && sri.activityInfo.applicationInfo.packageName.equals( 5855 comp.getPackageName())) 5856 || (action != null && sri.filter.matchAction(action))) { 5857 results.remove(j); 5858 if (DEBUG_INTENT_MATCHING) Log.v( 5859 TAG, "Removing duplicate item from " + j 5860 + " due to specific " + specificsPos); 5861 if (ri == null) { 5862 ri = sri; 5863 } 5864 j--; 5865 N--; 5866 } 5867 } 5868 5869 // Add this specific item to its proper place. 5870 if (ri == null) { 5871 ri = new ResolveInfo(); 5872 ri.activityInfo = ai; 5873 } 5874 results.add(specificsPos, ri); 5875 ri.specificIndex = i; 5876 specificsPos++; 5877 } 5878 } 5879 5880 // Now we go through the remaining generic results and remove any 5881 // duplicate actions that are found here. 5882 N = results.size(); 5883 for (int i=specificsPos; i<N-1; i++) { 5884 final ResolveInfo rii = results.get(i); 5885 if (rii.filter == null) { 5886 continue; 5887 } 5888 5889 // Iterate over all of the actions of this result's intent 5890 // filter... typically this should be just one. 5891 final Iterator<String> it = rii.filter.actionsIterator(); 5892 if (it == null) { 5893 continue; 5894 } 5895 while (it.hasNext()) { 5896 final String action = it.next(); 5897 if (resultsAction != null && resultsAction.equals(action)) { 5898 // If this action was explicitly requested, then don't 5899 // remove things that have it. 5900 continue; 5901 } 5902 for (int j=i+1; j<N; j++) { 5903 final ResolveInfo rij = results.get(j); 5904 if (rij.filter != null && rij.filter.hasAction(action)) { 5905 results.remove(j); 5906 if (DEBUG_INTENT_MATCHING) Log.v( 5907 TAG, "Removing duplicate item from " + j 5908 + " due to action " + action + " at " + i); 5909 j--; 5910 N--; 5911 } 5912 } 5913 } 5914 5915 // If the caller didn't request filter information, drop it now 5916 // so we don't have to marshall/unmarshall it. 5917 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5918 rii.filter = null; 5919 } 5920 } 5921 5922 // Filter out the caller activity if so requested. 5923 if (caller != null) { 5924 N = results.size(); 5925 for (int i=0; i<N; i++) { 5926 ActivityInfo ainfo = results.get(i).activityInfo; 5927 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5928 && caller.getClassName().equals(ainfo.name)) { 5929 results.remove(i); 5930 break; 5931 } 5932 } 5933 } 5934 5935 // If the caller didn't request filter information, 5936 // drop them now so we don't have to 5937 // marshall/unmarshall it. 5938 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5939 N = results.size(); 5940 for (int i=0; i<N; i++) { 5941 results.get(i).filter = null; 5942 } 5943 } 5944 5945 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5946 return results; 5947 } 5948 5949 @Override 5950 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5951 String resolvedType, int flags, int userId) { 5952 return new ParceledListSlice<>( 5953 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5954 } 5955 5956 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5957 String resolvedType, int flags, int userId) { 5958 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5959 flags = updateFlagsForResolve(flags, userId, intent); 5960 ComponentName comp = intent.getComponent(); 5961 if (comp == null) { 5962 if (intent.getSelector() != null) { 5963 intent = intent.getSelector(); 5964 comp = intent.getComponent(); 5965 } 5966 } 5967 if (comp != null) { 5968 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5969 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5970 if (ai != null) { 5971 ResolveInfo ri = new ResolveInfo(); 5972 ri.activityInfo = ai; 5973 list.add(ri); 5974 } 5975 return list; 5976 } 5977 5978 // reader 5979 synchronized (mPackages) { 5980 String pkgName = intent.getPackage(); 5981 if (pkgName == null) { 5982 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5983 } 5984 final PackageParser.Package pkg = mPackages.get(pkgName); 5985 if (pkg != null) { 5986 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5987 userId); 5988 } 5989 return Collections.emptyList(); 5990 } 5991 } 5992 5993 @Override 5994 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5995 if (!sUserManager.exists(userId)) return null; 5996 flags = updateFlagsForResolve(flags, userId, intent); 5997 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5998 if (query != null) { 5999 if (query.size() >= 1) { 6000 // If there is more than one service with the same priority, 6001 // just arbitrarily pick the first one. 6002 return query.get(0); 6003 } 6004 } 6005 return null; 6006 } 6007 6008 @Override 6009 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6010 String resolvedType, int flags, int userId) { 6011 return new ParceledListSlice<>( 6012 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6013 } 6014 6015 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6016 String resolvedType, int flags, int userId) { 6017 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6018 flags = updateFlagsForResolve(flags, userId, intent); 6019 ComponentName comp = intent.getComponent(); 6020 if (comp == null) { 6021 if (intent.getSelector() != null) { 6022 intent = intent.getSelector(); 6023 comp = intent.getComponent(); 6024 } 6025 } 6026 if (comp != null) { 6027 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6028 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6029 if (si != null) { 6030 final ResolveInfo ri = new ResolveInfo(); 6031 ri.serviceInfo = si; 6032 list.add(ri); 6033 } 6034 return list; 6035 } 6036 6037 // reader 6038 synchronized (mPackages) { 6039 String pkgName = intent.getPackage(); 6040 if (pkgName == null) { 6041 return mServices.queryIntent(intent, resolvedType, flags, userId); 6042 } 6043 final PackageParser.Package pkg = mPackages.get(pkgName); 6044 if (pkg != null) { 6045 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6046 userId); 6047 } 6048 return Collections.emptyList(); 6049 } 6050 } 6051 6052 @Override 6053 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6054 String resolvedType, int flags, int userId) { 6055 return new ParceledListSlice<>( 6056 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6057 } 6058 6059 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6060 Intent intent, String resolvedType, int flags, int userId) { 6061 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6062 flags = updateFlagsForResolve(flags, userId, intent); 6063 ComponentName comp = intent.getComponent(); 6064 if (comp == null) { 6065 if (intent.getSelector() != null) { 6066 intent = intent.getSelector(); 6067 comp = intent.getComponent(); 6068 } 6069 } 6070 if (comp != null) { 6071 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6072 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6073 if (pi != null) { 6074 final ResolveInfo ri = new ResolveInfo(); 6075 ri.providerInfo = pi; 6076 list.add(ri); 6077 } 6078 return list; 6079 } 6080 6081 // reader 6082 synchronized (mPackages) { 6083 String pkgName = intent.getPackage(); 6084 if (pkgName == null) { 6085 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6086 } 6087 final PackageParser.Package pkg = mPackages.get(pkgName); 6088 if (pkg != null) { 6089 return mProviders.queryIntentForPackage( 6090 intent, resolvedType, flags, pkg.providers, userId); 6091 } 6092 return Collections.emptyList(); 6093 } 6094 } 6095 6096 @Override 6097 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6098 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6099 flags = updateFlagsForPackage(flags, userId, null); 6100 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6101 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6102 true /* requireFullPermission */, false /* checkShell */, 6103 "get installed packages"); 6104 6105 // writer 6106 synchronized (mPackages) { 6107 ArrayList<PackageInfo> list; 6108 if (listUninstalled) { 6109 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6110 for (PackageSetting ps : mSettings.mPackages.values()) { 6111 final PackageInfo pi; 6112 if (ps.pkg != null) { 6113 pi = generatePackageInfo(ps, flags, userId); 6114 } else { 6115 pi = generatePackageInfo(ps, flags, userId); 6116 } 6117 if (pi != null) { 6118 list.add(pi); 6119 } 6120 } 6121 } else { 6122 list = new ArrayList<PackageInfo>(mPackages.size()); 6123 for (PackageParser.Package p : mPackages.values()) { 6124 final PackageInfo pi = 6125 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6126 if (pi != null) { 6127 list.add(pi); 6128 } 6129 } 6130 } 6131 6132 return new ParceledListSlice<PackageInfo>(list); 6133 } 6134 } 6135 6136 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6137 String[] permissions, boolean[] tmp, int flags, int userId) { 6138 int numMatch = 0; 6139 final PermissionsState permissionsState = ps.getPermissionsState(); 6140 for (int i=0; i<permissions.length; i++) { 6141 final String permission = permissions[i]; 6142 if (permissionsState.hasPermission(permission, userId)) { 6143 tmp[i] = true; 6144 numMatch++; 6145 } else { 6146 tmp[i] = false; 6147 } 6148 } 6149 if (numMatch == 0) { 6150 return; 6151 } 6152 final PackageInfo pi; 6153 if (ps.pkg != null) { 6154 pi = generatePackageInfo(ps, flags, userId); 6155 } else { 6156 pi = generatePackageInfo(ps, flags, userId); 6157 } 6158 // The above might return null in cases of uninstalled apps or install-state 6159 // skew across users/profiles. 6160 if (pi != null) { 6161 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6162 if (numMatch == permissions.length) { 6163 pi.requestedPermissions = permissions; 6164 } else { 6165 pi.requestedPermissions = new String[numMatch]; 6166 numMatch = 0; 6167 for (int i=0; i<permissions.length; i++) { 6168 if (tmp[i]) { 6169 pi.requestedPermissions[numMatch] = permissions[i]; 6170 numMatch++; 6171 } 6172 } 6173 } 6174 } 6175 list.add(pi); 6176 } 6177 } 6178 6179 @Override 6180 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6181 String[] permissions, int flags, int userId) { 6182 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6183 flags = updateFlagsForPackage(flags, userId, permissions); 6184 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6185 6186 // writer 6187 synchronized (mPackages) { 6188 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6189 boolean[] tmpBools = new boolean[permissions.length]; 6190 if (listUninstalled) { 6191 for (PackageSetting ps : mSettings.mPackages.values()) { 6192 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6193 } 6194 } else { 6195 for (PackageParser.Package pkg : mPackages.values()) { 6196 PackageSetting ps = (PackageSetting)pkg.mExtras; 6197 if (ps != null) { 6198 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6199 userId); 6200 } 6201 } 6202 } 6203 6204 return new ParceledListSlice<PackageInfo>(list); 6205 } 6206 } 6207 6208 @Override 6209 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6210 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6211 flags = updateFlagsForApplication(flags, userId, null); 6212 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6213 6214 // writer 6215 synchronized (mPackages) { 6216 ArrayList<ApplicationInfo> list; 6217 if (listUninstalled) { 6218 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6219 for (PackageSetting ps : mSettings.mPackages.values()) { 6220 ApplicationInfo ai; 6221 if (ps.pkg != null) { 6222 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6223 ps.readUserState(userId), userId); 6224 } else { 6225 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6226 } 6227 if (ai != null) { 6228 list.add(ai); 6229 } 6230 } 6231 } else { 6232 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6233 for (PackageParser.Package p : mPackages.values()) { 6234 if (p.mExtras != null) { 6235 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6236 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6237 if (ai != null) { 6238 list.add(ai); 6239 } 6240 } 6241 } 6242 } 6243 6244 return new ParceledListSlice<ApplicationInfo>(list); 6245 } 6246 } 6247 6248 @Override 6249 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6250 if (DISABLE_EPHEMERAL_APPS) { 6251 return null; 6252 } 6253 6254 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6255 "getEphemeralApplications"); 6256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6257 true /* requireFullPermission */, false /* checkShell */, 6258 "getEphemeralApplications"); 6259 synchronized (mPackages) { 6260 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6261 .getEphemeralApplicationsLPw(userId); 6262 if (ephemeralApps != null) { 6263 return new ParceledListSlice<>(ephemeralApps); 6264 } 6265 } 6266 return null; 6267 } 6268 6269 @Override 6270 public boolean isEphemeralApplication(String packageName, int userId) { 6271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6272 true /* requireFullPermission */, false /* checkShell */, 6273 "isEphemeral"); 6274 if (DISABLE_EPHEMERAL_APPS) { 6275 return false; 6276 } 6277 6278 if (!isCallerSameApp(packageName)) { 6279 return false; 6280 } 6281 synchronized (mPackages) { 6282 PackageParser.Package pkg = mPackages.get(packageName); 6283 if (pkg != null) { 6284 return pkg.applicationInfo.isEphemeralApp(); 6285 } 6286 } 6287 return false; 6288 } 6289 6290 @Override 6291 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6292 if (DISABLE_EPHEMERAL_APPS) { 6293 return null; 6294 } 6295 6296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6297 true /* requireFullPermission */, false /* checkShell */, 6298 "getCookie"); 6299 if (!isCallerSameApp(packageName)) { 6300 return null; 6301 } 6302 synchronized (mPackages) { 6303 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6304 packageName, userId); 6305 } 6306 } 6307 6308 @Override 6309 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6310 if (DISABLE_EPHEMERAL_APPS) { 6311 return true; 6312 } 6313 6314 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6315 true /* requireFullPermission */, true /* checkShell */, 6316 "setCookie"); 6317 if (!isCallerSameApp(packageName)) { 6318 return false; 6319 } 6320 synchronized (mPackages) { 6321 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6322 packageName, cookie, userId); 6323 } 6324 } 6325 6326 @Override 6327 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6328 if (DISABLE_EPHEMERAL_APPS) { 6329 return null; 6330 } 6331 6332 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6333 "getEphemeralApplicationIcon"); 6334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6335 true /* requireFullPermission */, false /* checkShell */, 6336 "getEphemeralApplicationIcon"); 6337 synchronized (mPackages) { 6338 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6339 packageName, userId); 6340 } 6341 } 6342 6343 private boolean isCallerSameApp(String packageName) { 6344 PackageParser.Package pkg = mPackages.get(packageName); 6345 return pkg != null 6346 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6347 } 6348 6349 @Override 6350 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6351 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6352 } 6353 6354 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6355 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6356 6357 // reader 6358 synchronized (mPackages) { 6359 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6360 final int userId = UserHandle.getCallingUserId(); 6361 while (i.hasNext()) { 6362 final PackageParser.Package p = i.next(); 6363 if (p.applicationInfo == null) continue; 6364 6365 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6366 && !p.applicationInfo.isDirectBootAware(); 6367 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6368 && p.applicationInfo.isDirectBootAware(); 6369 6370 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6371 && (!mSafeMode || isSystemApp(p)) 6372 && (matchesUnaware || matchesAware)) { 6373 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6374 if (ps != null) { 6375 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6376 ps.readUserState(userId), userId); 6377 if (ai != null) { 6378 finalList.add(ai); 6379 } 6380 } 6381 } 6382 } 6383 } 6384 6385 return finalList; 6386 } 6387 6388 @Override 6389 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6390 if (!sUserManager.exists(userId)) return null; 6391 flags = updateFlagsForComponent(flags, userId, name); 6392 // reader 6393 synchronized (mPackages) { 6394 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6395 PackageSetting ps = provider != null 6396 ? mSettings.mPackages.get(provider.owner.packageName) 6397 : null; 6398 return ps != null 6399 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6400 ? PackageParser.generateProviderInfo(provider, flags, 6401 ps.readUserState(userId), userId) 6402 : null; 6403 } 6404 } 6405 6406 /** 6407 * @deprecated 6408 */ 6409 @Deprecated 6410 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6411 // reader 6412 synchronized (mPackages) { 6413 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6414 .entrySet().iterator(); 6415 final int userId = UserHandle.getCallingUserId(); 6416 while (i.hasNext()) { 6417 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6418 PackageParser.Provider p = entry.getValue(); 6419 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6420 6421 if (ps != null && p.syncable 6422 && (!mSafeMode || (p.info.applicationInfo.flags 6423 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6424 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6425 ps.readUserState(userId), userId); 6426 if (info != null) { 6427 outNames.add(entry.getKey()); 6428 outInfo.add(info); 6429 } 6430 } 6431 } 6432 } 6433 } 6434 6435 @Override 6436 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6437 int uid, int flags) { 6438 final int userId = processName != null ? UserHandle.getUserId(uid) 6439 : UserHandle.getCallingUserId(); 6440 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6441 flags = updateFlagsForComponent(flags, userId, processName); 6442 6443 ArrayList<ProviderInfo> finalList = null; 6444 // reader 6445 synchronized (mPackages) { 6446 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6447 while (i.hasNext()) { 6448 final PackageParser.Provider p = i.next(); 6449 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6450 if (ps != null && p.info.authority != null 6451 && (processName == null 6452 || (p.info.processName.equals(processName) 6453 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6454 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6455 if (finalList == null) { 6456 finalList = new ArrayList<ProviderInfo>(3); 6457 } 6458 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6459 ps.readUserState(userId), userId); 6460 if (info != null) { 6461 finalList.add(info); 6462 } 6463 } 6464 } 6465 } 6466 6467 if (finalList != null) { 6468 Collections.sort(finalList, mProviderInitOrderSorter); 6469 return new ParceledListSlice<ProviderInfo>(finalList); 6470 } 6471 6472 return ParceledListSlice.emptyList(); 6473 } 6474 6475 @Override 6476 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6477 // reader 6478 synchronized (mPackages) { 6479 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6480 return PackageParser.generateInstrumentationInfo(i, flags); 6481 } 6482 } 6483 6484 @Override 6485 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6486 String targetPackage, int flags) { 6487 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6488 } 6489 6490 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6491 int flags) { 6492 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6493 6494 // reader 6495 synchronized (mPackages) { 6496 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6497 while (i.hasNext()) { 6498 final PackageParser.Instrumentation p = i.next(); 6499 if (targetPackage == null 6500 || targetPackage.equals(p.info.targetPackage)) { 6501 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6502 flags); 6503 if (ii != null) { 6504 finalList.add(ii); 6505 } 6506 } 6507 } 6508 } 6509 6510 return finalList; 6511 } 6512 6513 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6514 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6515 if (overlays == null) { 6516 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6517 return; 6518 } 6519 for (PackageParser.Package opkg : overlays.values()) { 6520 // Not much to do if idmap fails: we already logged the error 6521 // and we certainly don't want to abort installation of pkg simply 6522 // because an overlay didn't fit properly. For these reasons, 6523 // ignore the return value of createIdmapForPackagePairLI. 6524 createIdmapForPackagePairLI(pkg, opkg); 6525 } 6526 } 6527 6528 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6529 PackageParser.Package opkg) { 6530 if (!opkg.mTrustedOverlay) { 6531 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6532 opkg.baseCodePath + ": overlay not trusted"); 6533 return false; 6534 } 6535 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6536 if (overlaySet == null) { 6537 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6538 opkg.baseCodePath + " but target package has no known overlays"); 6539 return false; 6540 } 6541 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6542 // TODO: generate idmap for split APKs 6543 try { 6544 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6545 } catch (InstallerException e) { 6546 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6547 + opkg.baseCodePath); 6548 return false; 6549 } 6550 PackageParser.Package[] overlayArray = 6551 overlaySet.values().toArray(new PackageParser.Package[0]); 6552 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6553 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6554 return p1.mOverlayPriority - p2.mOverlayPriority; 6555 } 6556 }; 6557 Arrays.sort(overlayArray, cmp); 6558 6559 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6560 int i = 0; 6561 for (PackageParser.Package p : overlayArray) { 6562 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6563 } 6564 return true; 6565 } 6566 6567 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6569 try { 6570 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6571 } finally { 6572 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6573 } 6574 } 6575 6576 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6577 final File[] files = dir.listFiles(); 6578 if (ArrayUtils.isEmpty(files)) { 6579 Log.d(TAG, "No files in app dir " + dir); 6580 return; 6581 } 6582 6583 if (DEBUG_PACKAGE_SCANNING) { 6584 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6585 + " flags=0x" + Integer.toHexString(parseFlags)); 6586 } 6587 6588 for (File file : files) { 6589 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6590 && !PackageInstallerService.isStageName(file.getName()); 6591 if (!isPackage) { 6592 // Ignore entries which are not packages 6593 continue; 6594 } 6595 try { 6596 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6597 scanFlags, currentTime, null); 6598 } catch (PackageManagerException e) { 6599 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6600 6601 // Delete invalid userdata apps 6602 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6603 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6604 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6605 removeCodePathLI(file); 6606 } 6607 } 6608 } 6609 } 6610 6611 private static File getSettingsProblemFile() { 6612 File dataDir = Environment.getDataDirectory(); 6613 File systemDir = new File(dataDir, "system"); 6614 File fname = new File(systemDir, "uiderrors.txt"); 6615 return fname; 6616 } 6617 6618 static void reportSettingsProblem(int priority, String msg) { 6619 logCriticalInfo(priority, msg); 6620 } 6621 6622 static void logCriticalInfo(int priority, String msg) { 6623 Slog.println(priority, TAG, msg); 6624 EventLogTags.writePmCriticalInfo(msg); 6625 try { 6626 File fname = getSettingsProblemFile(); 6627 FileOutputStream out = new FileOutputStream(fname, true); 6628 PrintWriter pw = new FastPrintWriter(out); 6629 SimpleDateFormat formatter = new SimpleDateFormat(); 6630 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6631 pw.println(dateString + ": " + msg); 6632 pw.close(); 6633 FileUtils.setPermissions( 6634 fname.toString(), 6635 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6636 -1, -1); 6637 } catch (java.io.IOException e) { 6638 } 6639 } 6640 6641 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6642 final int policyFlags) throws PackageManagerException { 6643 if (ps != null 6644 && ps.codePath.equals(srcFile) 6645 && ps.timeStamp == srcFile.lastModified() 6646 && !isCompatSignatureUpdateNeeded(pkg) 6647 && !isRecoverSignatureUpdateNeeded(pkg)) { 6648 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6649 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6650 ArraySet<PublicKey> signingKs; 6651 synchronized (mPackages) { 6652 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6653 } 6654 if (ps.signatures.mSignatures != null 6655 && ps.signatures.mSignatures.length != 0 6656 && signingKs != null) { 6657 // Optimization: reuse the existing cached certificates 6658 // if the package appears to be unchanged. 6659 pkg.mSignatures = ps.signatures.mSignatures; 6660 pkg.mSigningKeys = signingKs; 6661 return; 6662 } 6663 6664 Slog.w(TAG, "PackageSetting for " + ps.name 6665 + " is missing signatures. Collecting certs again to recover them."); 6666 } else { 6667 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6668 } 6669 6670 try { 6671 PackageParser.collectCertificates(pkg, policyFlags); 6672 } catch (PackageParserException e) { 6673 throw PackageManagerException.from(e); 6674 } 6675 } 6676 6677 /** 6678 * Traces a package scan. 6679 * @see #scanPackageLI(File, int, int, long, UserHandle) 6680 */ 6681 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6682 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6683 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6684 try { 6685 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6686 } finally { 6687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6688 } 6689 } 6690 6691 /** 6692 * Scans a package and returns the newly parsed package. 6693 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6694 */ 6695 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6696 long currentTime, UserHandle user) throws PackageManagerException { 6697 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6698 PackageParser pp = new PackageParser(); 6699 pp.setSeparateProcesses(mSeparateProcesses); 6700 pp.setOnlyCoreApps(mOnlyCore); 6701 pp.setDisplayMetrics(mMetrics); 6702 6703 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6704 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6705 } 6706 6707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6708 final PackageParser.Package pkg; 6709 try { 6710 pkg = pp.parsePackage(scanFile, parseFlags); 6711 } catch (PackageParserException e) { 6712 throw PackageManagerException.from(e); 6713 } finally { 6714 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6715 } 6716 6717 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6718 } 6719 6720 /** 6721 * Scans a package and returns the newly parsed package. 6722 * @throws PackageManagerException on a parse error. 6723 */ 6724 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6725 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6726 throws PackageManagerException { 6727 // If the package has children and this is the first dive in the function 6728 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6729 // packages (parent and children) would be successfully scanned before the 6730 // actual scan since scanning mutates internal state and we want to atomically 6731 // install the package and its children. 6732 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6733 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6734 scanFlags |= SCAN_CHECK_ONLY; 6735 } 6736 } else { 6737 scanFlags &= ~SCAN_CHECK_ONLY; 6738 } 6739 6740 // Scan the parent 6741 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6742 scanFlags, currentTime, user); 6743 6744 // Scan the children 6745 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6746 for (int i = 0; i < childCount; i++) { 6747 PackageParser.Package childPackage = pkg.childPackages.get(i); 6748 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6749 currentTime, user); 6750 } 6751 6752 6753 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6754 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6755 } 6756 6757 return scannedPkg; 6758 } 6759 6760 /** 6761 * Scans a package and returns the newly parsed package. 6762 * @throws PackageManagerException on a parse error. 6763 */ 6764 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6765 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6766 throws PackageManagerException { 6767 PackageSetting ps = null; 6768 PackageSetting updatedPkg; 6769 // reader 6770 synchronized (mPackages) { 6771 // Look to see if we already know about this package. 6772 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6773 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6774 // This package has been renamed to its original name. Let's 6775 // use that. 6776 ps = mSettings.peekPackageLPr(oldName); 6777 } 6778 // If there was no original package, see one for the real package name. 6779 if (ps == null) { 6780 ps = mSettings.peekPackageLPr(pkg.packageName); 6781 } 6782 // Check to see if this package could be hiding/updating a system 6783 // package. Must look for it either under the original or real 6784 // package name depending on our state. 6785 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6786 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6787 6788 // If this is a package we don't know about on the system partition, we 6789 // may need to remove disabled child packages on the system partition 6790 // or may need to not add child packages if the parent apk is updated 6791 // on the data partition and no longer defines this child package. 6792 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6793 // If this is a parent package for an updated system app and this system 6794 // app got an OTA update which no longer defines some of the child packages 6795 // we have to prune them from the disabled system packages. 6796 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6797 if (disabledPs != null) { 6798 final int scannedChildCount = (pkg.childPackages != null) 6799 ? pkg.childPackages.size() : 0; 6800 final int disabledChildCount = disabledPs.childPackageNames != null 6801 ? disabledPs.childPackageNames.size() : 0; 6802 for (int i = 0; i < disabledChildCount; i++) { 6803 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6804 boolean disabledPackageAvailable = false; 6805 for (int j = 0; j < scannedChildCount; j++) { 6806 PackageParser.Package childPkg = pkg.childPackages.get(j); 6807 if (childPkg.packageName.equals(disabledChildPackageName)) { 6808 disabledPackageAvailable = true; 6809 break; 6810 } 6811 } 6812 if (!disabledPackageAvailable) { 6813 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6814 } 6815 } 6816 } 6817 } 6818 } 6819 6820 boolean updatedPkgBetter = false; 6821 // First check if this is a system package that may involve an update 6822 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6823 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6824 // it needs to drop FLAG_PRIVILEGED. 6825 if (locationIsPrivileged(scanFile)) { 6826 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6827 } else { 6828 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6829 } 6830 6831 if (ps != null && !ps.codePath.equals(scanFile)) { 6832 // The path has changed from what was last scanned... check the 6833 // version of the new path against what we have stored to determine 6834 // what to do. 6835 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6836 if (pkg.mVersionCode <= ps.versionCode) { 6837 // The system package has been updated and the code path does not match 6838 // Ignore entry. Skip it. 6839 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6840 + " ignored: updated version " + ps.versionCode 6841 + " better than this " + pkg.mVersionCode); 6842 if (!updatedPkg.codePath.equals(scanFile)) { 6843 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6844 + ps.name + " changing from " + updatedPkg.codePathString 6845 + " to " + scanFile); 6846 updatedPkg.codePath = scanFile; 6847 updatedPkg.codePathString = scanFile.toString(); 6848 updatedPkg.resourcePath = scanFile; 6849 updatedPkg.resourcePathString = scanFile.toString(); 6850 } 6851 updatedPkg.pkg = pkg; 6852 updatedPkg.versionCode = pkg.mVersionCode; 6853 6854 // Update the disabled system child packages to point to the package too. 6855 final int childCount = updatedPkg.childPackageNames != null 6856 ? updatedPkg.childPackageNames.size() : 0; 6857 for (int i = 0; i < childCount; i++) { 6858 String childPackageName = updatedPkg.childPackageNames.get(i); 6859 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6860 childPackageName); 6861 if (updatedChildPkg != null) { 6862 updatedChildPkg.pkg = pkg; 6863 updatedChildPkg.versionCode = pkg.mVersionCode; 6864 } 6865 } 6866 6867 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6868 + scanFile + " ignored: updated version " + ps.versionCode 6869 + " better than this " + pkg.mVersionCode); 6870 } else { 6871 // The current app on the system partition is better than 6872 // what we have updated to on the data partition; switch 6873 // back to the system partition version. 6874 // At this point, its safely assumed that package installation for 6875 // apps in system partition will go through. If not there won't be a working 6876 // version of the app 6877 // writer 6878 synchronized (mPackages) { 6879 // Just remove the loaded entries from package lists. 6880 mPackages.remove(ps.name); 6881 } 6882 6883 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6884 + " reverting from " + ps.codePathString 6885 + ": new version " + pkg.mVersionCode 6886 + " better than installed " + ps.versionCode); 6887 6888 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6889 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6890 synchronized (mInstallLock) { 6891 args.cleanUpResourcesLI(); 6892 } 6893 synchronized (mPackages) { 6894 mSettings.enableSystemPackageLPw(ps.name); 6895 } 6896 updatedPkgBetter = true; 6897 } 6898 } 6899 } 6900 6901 if (updatedPkg != null) { 6902 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6903 // initially 6904 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6905 6906 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6907 // flag set initially 6908 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6909 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6910 } 6911 } 6912 6913 // Verify certificates against what was last scanned 6914 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6915 6916 /* 6917 * A new system app appeared, but we already had a non-system one of the 6918 * same name installed earlier. 6919 */ 6920 boolean shouldHideSystemApp = false; 6921 if (updatedPkg == null && ps != null 6922 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6923 /* 6924 * Check to make sure the signatures match first. If they don't, 6925 * wipe the installed application and its data. 6926 */ 6927 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6928 != PackageManager.SIGNATURE_MATCH) { 6929 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6930 + " signatures don't match existing userdata copy; removing"); 6931 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6932 "scanPackageInternalLI")) { 6933 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6934 } 6935 ps = null; 6936 } else { 6937 /* 6938 * If the newly-added system app is an older version than the 6939 * already installed version, hide it. It will be scanned later 6940 * and re-added like an update. 6941 */ 6942 if (pkg.mVersionCode <= ps.versionCode) { 6943 shouldHideSystemApp = true; 6944 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6945 + " but new version " + pkg.mVersionCode + " better than installed " 6946 + ps.versionCode + "; hiding system"); 6947 } else { 6948 /* 6949 * The newly found system app is a newer version that the 6950 * one previously installed. Simply remove the 6951 * already-installed application and replace it with our own 6952 * while keeping the application data. 6953 */ 6954 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6955 + " reverting from " + ps.codePathString + ": new version " 6956 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6957 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6958 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6959 synchronized (mInstallLock) { 6960 args.cleanUpResourcesLI(); 6961 } 6962 } 6963 } 6964 } 6965 6966 // The apk is forward locked (not public) if its code and resources 6967 // are kept in different files. (except for app in either system or 6968 // vendor path). 6969 // TODO grab this value from PackageSettings 6970 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6971 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6972 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6973 } 6974 } 6975 6976 // TODO: extend to support forward-locked splits 6977 String resourcePath = null; 6978 String baseResourcePath = null; 6979 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6980 if (ps != null && ps.resourcePathString != null) { 6981 resourcePath = ps.resourcePathString; 6982 baseResourcePath = ps.resourcePathString; 6983 } else { 6984 // Should not happen at all. Just log an error. 6985 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6986 } 6987 } else { 6988 resourcePath = pkg.codePath; 6989 baseResourcePath = pkg.baseCodePath; 6990 } 6991 6992 // Set application objects path explicitly. 6993 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6994 pkg.setApplicationInfoCodePath(pkg.codePath); 6995 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6996 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6997 pkg.setApplicationInfoResourcePath(resourcePath); 6998 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6999 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7000 7001 // Note that we invoke the following method only if we are about to unpack an application 7002 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7003 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7004 7005 /* 7006 * If the system app should be overridden by a previously installed 7007 * data, hide the system app now and let the /data/app scan pick it up 7008 * again. 7009 */ 7010 if (shouldHideSystemApp) { 7011 synchronized (mPackages) { 7012 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7013 } 7014 } 7015 7016 return scannedPkg; 7017 } 7018 7019 private static String fixProcessName(String defProcessName, 7020 String processName, int uid) { 7021 if (processName == null) { 7022 return defProcessName; 7023 } 7024 return processName; 7025 } 7026 7027 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7028 throws PackageManagerException { 7029 if (pkgSetting.signatures.mSignatures != null) { 7030 // Already existing package. Make sure signatures match 7031 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7032 == PackageManager.SIGNATURE_MATCH; 7033 if (!match) { 7034 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7035 == PackageManager.SIGNATURE_MATCH; 7036 } 7037 if (!match) { 7038 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7039 == PackageManager.SIGNATURE_MATCH; 7040 } 7041 if (!match) { 7042 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7043 + pkg.packageName + " signatures do not match the " 7044 + "previously installed version; ignoring!"); 7045 } 7046 } 7047 7048 // Check for shared user signatures 7049 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7050 // Already existing package. Make sure signatures match 7051 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7052 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7053 if (!match) { 7054 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7055 == PackageManager.SIGNATURE_MATCH; 7056 } 7057 if (!match) { 7058 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7059 == PackageManager.SIGNATURE_MATCH; 7060 } 7061 if (!match) { 7062 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7063 "Package " + pkg.packageName 7064 + " has no signatures that match those in shared user " 7065 + pkgSetting.sharedUser.name + "; ignoring!"); 7066 } 7067 } 7068 } 7069 7070 /** 7071 * Enforces that only the system UID or root's UID can call a method exposed 7072 * via Binder. 7073 * 7074 * @param message used as message if SecurityException is thrown 7075 * @throws SecurityException if the caller is not system or root 7076 */ 7077 private static final void enforceSystemOrRoot(String message) { 7078 final int uid = Binder.getCallingUid(); 7079 if (uid != Process.SYSTEM_UID && uid != 0) { 7080 throw new SecurityException(message); 7081 } 7082 } 7083 7084 @Override 7085 public void performFstrimIfNeeded() { 7086 enforceSystemOrRoot("Only the system can request fstrim"); 7087 7088 // Before everything else, see whether we need to fstrim. 7089 try { 7090 IMountService ms = PackageHelper.getMountService(); 7091 if (ms != null) { 7092 final boolean isUpgrade = isUpgrade(); 7093 boolean doTrim = isUpgrade; 7094 if (doTrim) { 7095 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7096 } else { 7097 final long interval = android.provider.Settings.Global.getLong( 7098 mContext.getContentResolver(), 7099 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7100 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7101 if (interval > 0) { 7102 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7103 if (timeSinceLast > interval) { 7104 doTrim = true; 7105 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7106 + "; running immediately"); 7107 } 7108 } 7109 } 7110 if (doTrim) { 7111 if (!isFirstBoot()) { 7112 try { 7113 ActivityManagerNative.getDefault().showBootMessage( 7114 mContext.getResources().getString( 7115 R.string.android_upgrading_fstrim), true); 7116 } catch (RemoteException e) { 7117 } 7118 } 7119 ms.runMaintenance(); 7120 } 7121 } else { 7122 Slog.e(TAG, "Mount service unavailable!"); 7123 } 7124 } catch (RemoteException e) { 7125 // Can't happen; MountService is local 7126 } 7127 } 7128 7129 @Override 7130 public void updatePackagesIfNeeded() { 7131 enforceSystemOrRoot("Only the system can request package update"); 7132 7133 // We need to re-extract after an OTA. 7134 boolean causeUpgrade = isUpgrade(); 7135 7136 // First boot or factory reset. 7137 // Note: we also handle devices that are upgrading to N right now as if it is their 7138 // first boot, as they do not have profile data. 7139 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7140 7141 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7142 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7143 7144 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7145 return; 7146 } 7147 7148 List<PackageParser.Package> pkgs; 7149 synchronized (mPackages) { 7150 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7151 } 7152 7153 int curr = 0; 7154 int total = pkgs.size(); 7155 for (PackageParser.Package pkg : pkgs) { 7156 curr++; 7157 7158 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7159 if (DEBUG_DEXOPT) { 7160 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7161 } 7162 continue; 7163 } 7164 7165 if (DEBUG_DEXOPT) { 7166 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7167 } 7168 7169 if (!isFirstBoot()) { 7170 try { 7171 ActivityManagerNative.getDefault().showBootMessage( 7172 mContext.getResources().getString(R.string.android_upgrading_apk, 7173 curr, total), true); 7174 } catch (RemoteException e) { 7175 } 7176 } 7177 7178 performDexOpt(pkg.packageName, 7179 null /* instructionSet */, 7180 true /* checkProfiles */, 7181 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7182 false /* force */); 7183 } 7184 } 7185 7186 @Override 7187 public void notifyPackageUse(String packageName, int reason) { 7188 synchronized (mPackages) { 7189 PackageParser.Package p = mPackages.get(packageName); 7190 if (p == null) { 7191 return; 7192 } 7193 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7194 } 7195 } 7196 7197 // TODO: this is not used nor needed. Delete it. 7198 @Override 7199 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7200 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7201 getFullCompilerFilter(), false /* force */); 7202 } 7203 7204 @Override 7205 public boolean performDexOpt(String packageName, String instructionSet, 7206 boolean checkProfiles, int compileReason, boolean force) { 7207 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7208 getCompilerFilterForReason(compileReason), force); 7209 } 7210 7211 @Override 7212 public boolean performDexOptMode(String packageName, String instructionSet, 7213 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7214 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7215 targetCompilerFilter, force); 7216 } 7217 7218 private boolean performDexOptTraced(String packageName, String instructionSet, 7219 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7221 try { 7222 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7223 targetCompilerFilter, force); 7224 } finally { 7225 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7226 } 7227 } 7228 7229 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7230 // if the package can now be considered up to date for the given filter. 7231 private boolean performDexOptInternal(String packageName, String instructionSet, 7232 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7233 PackageParser.Package p; 7234 final String targetInstructionSet; 7235 synchronized (mPackages) { 7236 p = mPackages.get(packageName); 7237 if (p == null) { 7238 return false; 7239 } 7240 mPackageUsage.write(false); 7241 7242 targetInstructionSet = instructionSet != null ? instructionSet : 7243 getPrimaryInstructionSet(p.applicationInfo); 7244 } 7245 long callingId = Binder.clearCallingIdentity(); 7246 try { 7247 synchronized (mInstallLock) { 7248 final String[] instructionSets = new String[] { targetInstructionSet }; 7249 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7250 checkProfiles, targetCompilerFilter, force); 7251 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7252 } 7253 } finally { 7254 Binder.restoreCallingIdentity(callingId); 7255 } 7256 } 7257 7258 public ArraySet<String> getOptimizablePackages() { 7259 ArraySet<String> pkgs = new ArraySet<String>(); 7260 synchronized (mPackages) { 7261 for (PackageParser.Package p : mPackages.values()) { 7262 if (PackageDexOptimizer.canOptimizePackage(p)) { 7263 pkgs.add(p.packageName); 7264 } 7265 } 7266 } 7267 return pkgs; 7268 } 7269 7270 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7271 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7272 boolean force) { 7273 // Select the dex optimizer based on the force parameter. 7274 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7275 // allocate an object here. 7276 PackageDexOptimizer pdo = force 7277 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7278 : mPackageDexOptimizer; 7279 7280 // Optimize all dependencies first. Note: we ignore the return value and march on 7281 // on errors. 7282 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7283 if (!deps.isEmpty()) { 7284 for (PackageParser.Package depPackage : deps) { 7285 // TODO: Analyze and investigate if we (should) profile libraries. 7286 // Currently this will do a full compilation of the library by default. 7287 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7288 false /* checkProfiles */, 7289 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7290 } 7291 } 7292 7293 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7294 targetCompilerFilter); 7295 } 7296 7297 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7298 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7299 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7300 Set<String> collectedNames = new HashSet<>(); 7301 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7302 7303 retValue.remove(p); 7304 7305 return retValue; 7306 } else { 7307 return Collections.emptyList(); 7308 } 7309 } 7310 7311 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7312 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7313 if (!collectedNames.contains(p.packageName)) { 7314 collectedNames.add(p.packageName); 7315 collected.add(p); 7316 7317 if (p.usesLibraries != null) { 7318 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7319 } 7320 if (p.usesOptionalLibraries != null) { 7321 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7322 collectedNames); 7323 } 7324 } 7325 } 7326 7327 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7328 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7329 for (String libName : libs) { 7330 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7331 if (libPkg != null) { 7332 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7333 } 7334 } 7335 } 7336 7337 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7338 synchronized (mPackages) { 7339 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7340 if (lib != null && lib.apk != null) { 7341 return mPackages.get(lib.apk); 7342 } 7343 } 7344 return null; 7345 } 7346 7347 public void shutdown() { 7348 mPackageUsage.write(true); 7349 } 7350 7351 @Override 7352 public void forceDexOpt(String packageName) { 7353 enforceSystemOrRoot("forceDexOpt"); 7354 7355 PackageParser.Package pkg; 7356 synchronized (mPackages) { 7357 pkg = mPackages.get(packageName); 7358 if (pkg == null) { 7359 throw new IllegalArgumentException("Unknown package: " + packageName); 7360 } 7361 } 7362 7363 synchronized (mInstallLock) { 7364 final String[] instructionSets = new String[] { 7365 getPrimaryInstructionSet(pkg.applicationInfo) }; 7366 7367 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7368 7369 // Whoever is calling forceDexOpt wants a fully compiled package. 7370 // Don't use profiles since that may cause compilation to be skipped. 7371 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7372 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7373 true /* force */); 7374 7375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7376 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7377 throw new IllegalStateException("Failed to dexopt: " + res); 7378 } 7379 } 7380 } 7381 7382 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7383 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7384 Slog.w(TAG, "Unable to update from " + oldPkg.name 7385 + " to " + newPkg.packageName 7386 + ": old package not in system partition"); 7387 return false; 7388 } else if (mPackages.get(oldPkg.name) != null) { 7389 Slog.w(TAG, "Unable to update from " + oldPkg.name 7390 + " to " + newPkg.packageName 7391 + ": old package still exists"); 7392 return false; 7393 } 7394 return true; 7395 } 7396 7397 void removeCodePathLI(File codePath) { 7398 if (codePath.isDirectory()) { 7399 try { 7400 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7401 } catch (InstallerException e) { 7402 Slog.w(TAG, "Failed to remove code path", e); 7403 } 7404 } else { 7405 codePath.delete(); 7406 } 7407 } 7408 7409 private int[] resolveUserIds(int userId) { 7410 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7411 } 7412 7413 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7414 if (pkg == null) { 7415 Slog.wtf(TAG, "Package was null!", new Throwable()); 7416 return; 7417 } 7418 clearAppDataLeafLIF(pkg, userId, flags); 7419 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7420 for (int i = 0; i < childCount; i++) { 7421 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7422 } 7423 } 7424 7425 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7426 final PackageSetting ps; 7427 synchronized (mPackages) { 7428 ps = mSettings.mPackages.get(pkg.packageName); 7429 } 7430 for (int realUserId : resolveUserIds(userId)) { 7431 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7432 try { 7433 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7434 ceDataInode); 7435 } catch (InstallerException e) { 7436 Slog.w(TAG, String.valueOf(e)); 7437 } 7438 } 7439 } 7440 7441 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7442 if (pkg == null) { 7443 Slog.wtf(TAG, "Package was null!", new Throwable()); 7444 return; 7445 } 7446 destroyAppDataLeafLIF(pkg, userId, flags); 7447 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7448 for (int i = 0; i < childCount; i++) { 7449 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7450 } 7451 } 7452 7453 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7454 final PackageSetting ps; 7455 synchronized (mPackages) { 7456 ps = mSettings.mPackages.get(pkg.packageName); 7457 } 7458 for (int realUserId : resolveUserIds(userId)) { 7459 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7460 try { 7461 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7462 ceDataInode); 7463 } catch (InstallerException e) { 7464 Slog.w(TAG, String.valueOf(e)); 7465 } 7466 } 7467 } 7468 7469 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7470 if (pkg == null) { 7471 Slog.wtf(TAG, "Package was null!", new Throwable()); 7472 return; 7473 } 7474 destroyAppProfilesLeafLIF(pkg); 7475 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7476 for (int i = 0; i < childCount; i++) { 7477 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7478 } 7479 } 7480 7481 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7482 try { 7483 mInstaller.destroyAppProfiles(pkg.packageName); 7484 } catch (InstallerException e) { 7485 Slog.w(TAG, String.valueOf(e)); 7486 } 7487 } 7488 7489 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7490 if (pkg == null) { 7491 Slog.wtf(TAG, "Package was null!", new Throwable()); 7492 return; 7493 } 7494 clearAppProfilesLeafLIF(pkg); 7495 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7496 for (int i = 0; i < childCount; i++) { 7497 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7498 } 7499 } 7500 7501 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7502 try { 7503 mInstaller.clearAppProfiles(pkg.packageName); 7504 } catch (InstallerException e) { 7505 Slog.w(TAG, String.valueOf(e)); 7506 } 7507 } 7508 7509 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7510 long lastUpdateTime) { 7511 // Set parent install/update time 7512 PackageSetting ps = (PackageSetting) pkg.mExtras; 7513 if (ps != null) { 7514 ps.firstInstallTime = firstInstallTime; 7515 ps.lastUpdateTime = lastUpdateTime; 7516 } 7517 // Set children install/update time 7518 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7519 for (int i = 0; i < childCount; i++) { 7520 PackageParser.Package childPkg = pkg.childPackages.get(i); 7521 ps = (PackageSetting) childPkg.mExtras; 7522 if (ps != null) { 7523 ps.firstInstallTime = firstInstallTime; 7524 ps.lastUpdateTime = lastUpdateTime; 7525 } 7526 } 7527 } 7528 7529 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7530 PackageParser.Package changingLib) { 7531 if (file.path != null) { 7532 usesLibraryFiles.add(file.path); 7533 return; 7534 } 7535 PackageParser.Package p = mPackages.get(file.apk); 7536 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7537 // If we are doing this while in the middle of updating a library apk, 7538 // then we need to make sure to use that new apk for determining the 7539 // dependencies here. (We haven't yet finished committing the new apk 7540 // to the package manager state.) 7541 if (p == null || p.packageName.equals(changingLib.packageName)) { 7542 p = changingLib; 7543 } 7544 } 7545 if (p != null) { 7546 usesLibraryFiles.addAll(p.getAllCodePaths()); 7547 } 7548 } 7549 7550 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7551 PackageParser.Package changingLib) throws PackageManagerException { 7552 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7553 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7554 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7555 for (int i=0; i<N; i++) { 7556 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7557 if (file == null) { 7558 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7559 "Package " + pkg.packageName + " requires unavailable shared library " 7560 + pkg.usesLibraries.get(i) + "; failing!"); 7561 } 7562 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7563 } 7564 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7565 for (int i=0; i<N; i++) { 7566 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7567 if (file == null) { 7568 Slog.w(TAG, "Package " + pkg.packageName 7569 + " desires unavailable shared library " 7570 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7571 } else { 7572 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7573 } 7574 } 7575 N = usesLibraryFiles.size(); 7576 if (N > 0) { 7577 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7578 } else { 7579 pkg.usesLibraryFiles = null; 7580 } 7581 } 7582 } 7583 7584 private static boolean hasString(List<String> list, List<String> which) { 7585 if (list == null) { 7586 return false; 7587 } 7588 for (int i=list.size()-1; i>=0; i--) { 7589 for (int j=which.size()-1; j>=0; j--) { 7590 if (which.get(j).equals(list.get(i))) { 7591 return true; 7592 } 7593 } 7594 } 7595 return false; 7596 } 7597 7598 private void updateAllSharedLibrariesLPw() { 7599 for (PackageParser.Package pkg : mPackages.values()) { 7600 try { 7601 updateSharedLibrariesLPw(pkg, null); 7602 } catch (PackageManagerException e) { 7603 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7604 } 7605 } 7606 } 7607 7608 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7609 PackageParser.Package changingPkg) { 7610 ArrayList<PackageParser.Package> res = null; 7611 for (PackageParser.Package pkg : mPackages.values()) { 7612 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7613 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7614 if (res == null) { 7615 res = new ArrayList<PackageParser.Package>(); 7616 } 7617 res.add(pkg); 7618 try { 7619 updateSharedLibrariesLPw(pkg, changingPkg); 7620 } catch (PackageManagerException e) { 7621 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7622 } 7623 } 7624 } 7625 return res; 7626 } 7627 7628 /** 7629 * Derive the value of the {@code cpuAbiOverride} based on the provided 7630 * value and an optional stored value from the package settings. 7631 */ 7632 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7633 String cpuAbiOverride = null; 7634 7635 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7636 cpuAbiOverride = null; 7637 } else if (abiOverride != null) { 7638 cpuAbiOverride = abiOverride; 7639 } else if (settings != null) { 7640 cpuAbiOverride = settings.cpuAbiOverrideString; 7641 } 7642 7643 return cpuAbiOverride; 7644 } 7645 7646 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7647 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7648 throws PackageManagerException { 7649 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7650 // If the package has children and this is the first dive in the function 7651 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7652 // whether all packages (parent and children) would be successfully scanned 7653 // before the actual scan since scanning mutates internal state and we want 7654 // to atomically install the package and its children. 7655 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7656 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7657 scanFlags |= SCAN_CHECK_ONLY; 7658 } 7659 } else { 7660 scanFlags &= ~SCAN_CHECK_ONLY; 7661 } 7662 7663 final PackageParser.Package scannedPkg; 7664 try { 7665 // Scan the parent 7666 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7667 // Scan the children 7668 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7669 for (int i = 0; i < childCount; i++) { 7670 PackageParser.Package childPkg = pkg.childPackages.get(i); 7671 scanPackageLI(childPkg, policyFlags, 7672 scanFlags, currentTime, user); 7673 } 7674 } finally { 7675 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7676 } 7677 7678 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7679 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7680 } 7681 7682 return scannedPkg; 7683 } 7684 7685 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7686 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7687 boolean success = false; 7688 try { 7689 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7690 currentTime, user); 7691 success = true; 7692 return res; 7693 } finally { 7694 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7695 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7696 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7697 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7698 destroyAppProfilesLIF(pkg); 7699 } 7700 } 7701 } 7702 7703 /** 7704 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7705 */ 7706 private static boolean apkHasCode(String fileName) { 7707 StrictJarFile jarFile = null; 7708 try { 7709 jarFile = new StrictJarFile(fileName, 7710 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7711 return jarFile.findEntry("classes.dex") != null; 7712 } catch (IOException ignore) { 7713 } finally { 7714 try { 7715 jarFile.close(); 7716 } catch (IOException ignore) {} 7717 } 7718 return false; 7719 } 7720 7721 /** 7722 * Enforces code policy for the package. This ensures that if an APK has 7723 * declared hasCode="true" in its manifest that the APK actually contains 7724 * code. 7725 * 7726 * @throws PackageManagerException If bytecode could not be found when it should exist 7727 */ 7728 private static void enforceCodePolicy(PackageParser.Package pkg) 7729 throws PackageManagerException { 7730 final boolean shouldHaveCode = 7731 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7732 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7733 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7734 "Package " + pkg.baseCodePath + " code is missing"); 7735 } 7736 7737 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7738 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7739 final boolean splitShouldHaveCode = 7740 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7741 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7742 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7743 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7744 } 7745 } 7746 } 7747 } 7748 7749 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7750 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7751 throws PackageManagerException { 7752 final File scanFile = new File(pkg.codePath); 7753 if (pkg.applicationInfo.getCodePath() == null || 7754 pkg.applicationInfo.getResourcePath() == null) { 7755 // Bail out. The resource and code paths haven't been set. 7756 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7757 "Code and resource paths haven't been set correctly"); 7758 } 7759 7760 // Apply policy 7761 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7762 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7763 if (pkg.applicationInfo.isDirectBootAware()) { 7764 // we're direct boot aware; set for all components 7765 for (PackageParser.Service s : pkg.services) { 7766 s.info.encryptionAware = s.info.directBootAware = true; 7767 } 7768 for (PackageParser.Provider p : pkg.providers) { 7769 p.info.encryptionAware = p.info.directBootAware = true; 7770 } 7771 for (PackageParser.Activity a : pkg.activities) { 7772 a.info.encryptionAware = a.info.directBootAware = true; 7773 } 7774 for (PackageParser.Activity r : pkg.receivers) { 7775 r.info.encryptionAware = r.info.directBootAware = true; 7776 } 7777 } 7778 } else { 7779 // Only allow system apps to be flagged as core apps. 7780 pkg.coreApp = false; 7781 // clear flags not applicable to regular apps 7782 pkg.applicationInfo.privateFlags &= 7783 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7784 pkg.applicationInfo.privateFlags &= 7785 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7786 } 7787 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7788 7789 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7790 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7791 } 7792 7793 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7794 enforceCodePolicy(pkg); 7795 } 7796 7797 if (mCustomResolverComponentName != null && 7798 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7799 setUpCustomResolverActivity(pkg); 7800 } 7801 7802 if (pkg.packageName.equals("android")) { 7803 synchronized (mPackages) { 7804 if (mAndroidApplication != null) { 7805 Slog.w(TAG, "*************************************************"); 7806 Slog.w(TAG, "Core android package being redefined. Skipping."); 7807 Slog.w(TAG, " file=" + scanFile); 7808 Slog.w(TAG, "*************************************************"); 7809 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7810 "Core android package being redefined. Skipping."); 7811 } 7812 7813 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7814 // Set up information for our fall-back user intent resolution activity. 7815 mPlatformPackage = pkg; 7816 pkg.mVersionCode = mSdkVersion; 7817 mAndroidApplication = pkg.applicationInfo; 7818 7819 if (!mResolverReplaced) { 7820 mResolveActivity.applicationInfo = mAndroidApplication; 7821 mResolveActivity.name = ResolverActivity.class.getName(); 7822 mResolveActivity.packageName = mAndroidApplication.packageName; 7823 mResolveActivity.processName = "system:ui"; 7824 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7825 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7826 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7827 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7828 mResolveActivity.exported = true; 7829 mResolveActivity.enabled = true; 7830 mResolveInfo.activityInfo = mResolveActivity; 7831 mResolveInfo.priority = 0; 7832 mResolveInfo.preferredOrder = 0; 7833 mResolveInfo.match = 0; 7834 mResolveComponentName = new ComponentName( 7835 mAndroidApplication.packageName, mResolveActivity.name); 7836 } 7837 } 7838 } 7839 } 7840 7841 if (DEBUG_PACKAGE_SCANNING) { 7842 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7843 Log.d(TAG, "Scanning package " + pkg.packageName); 7844 } 7845 7846 synchronized (mPackages) { 7847 if (mPackages.containsKey(pkg.packageName) 7848 || mSharedLibraries.containsKey(pkg.packageName)) { 7849 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7850 "Application package " + pkg.packageName 7851 + " already installed. Skipping duplicate."); 7852 } 7853 7854 // If we're only installing presumed-existing packages, require that the 7855 // scanned APK is both already known and at the path previously established 7856 // for it. Previously unknown packages we pick up normally, but if we have an 7857 // a priori expectation about this package's install presence, enforce it. 7858 // With a singular exception for new system packages. When an OTA contains 7859 // a new system package, we allow the codepath to change from a system location 7860 // to the user-installed location. If we don't allow this change, any newer, 7861 // user-installed version of the application will be ignored. 7862 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7863 if (mExpectingBetter.containsKey(pkg.packageName)) { 7864 logCriticalInfo(Log.WARN, 7865 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7866 } else { 7867 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7868 if (known != null) { 7869 if (DEBUG_PACKAGE_SCANNING) { 7870 Log.d(TAG, "Examining " + pkg.codePath 7871 + " and requiring known paths " + known.codePathString 7872 + " & " + known.resourcePathString); 7873 } 7874 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7875 || !pkg.applicationInfo.getResourcePath().equals( 7876 known.resourcePathString)) { 7877 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7878 "Application package " + pkg.packageName 7879 + " found at " + pkg.applicationInfo.getCodePath() 7880 + " but expected at " + known.codePathString 7881 + "; ignoring."); 7882 } 7883 } 7884 } 7885 } 7886 } 7887 7888 // Initialize package source and resource directories 7889 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7890 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7891 7892 SharedUserSetting suid = null; 7893 PackageSetting pkgSetting = null; 7894 7895 if (!isSystemApp(pkg)) { 7896 // Only system apps can use these features. 7897 pkg.mOriginalPackages = null; 7898 pkg.mRealPackage = null; 7899 pkg.mAdoptPermissions = null; 7900 } 7901 7902 // Getting the package setting may have a side-effect, so if we 7903 // are only checking if scan would succeed, stash a copy of the 7904 // old setting to restore at the end. 7905 PackageSetting nonMutatedPs = null; 7906 7907 // writer 7908 synchronized (mPackages) { 7909 if (pkg.mSharedUserId != null) { 7910 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7911 if (suid == null) { 7912 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7913 "Creating application package " + pkg.packageName 7914 + " for shared user failed"); 7915 } 7916 if (DEBUG_PACKAGE_SCANNING) { 7917 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7918 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7919 + "): packages=" + suid.packages); 7920 } 7921 } 7922 7923 // Check if we are renaming from an original package name. 7924 PackageSetting origPackage = null; 7925 String realName = null; 7926 if (pkg.mOriginalPackages != null) { 7927 // This package may need to be renamed to a previously 7928 // installed name. Let's check on that... 7929 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7930 if (pkg.mOriginalPackages.contains(renamed)) { 7931 // This package had originally been installed as the 7932 // original name, and we have already taken care of 7933 // transitioning to the new one. Just update the new 7934 // one to continue using the old name. 7935 realName = pkg.mRealPackage; 7936 if (!pkg.packageName.equals(renamed)) { 7937 // Callers into this function may have already taken 7938 // care of renaming the package; only do it here if 7939 // it is not already done. 7940 pkg.setPackageName(renamed); 7941 } 7942 7943 } else { 7944 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7945 if ((origPackage = mSettings.peekPackageLPr( 7946 pkg.mOriginalPackages.get(i))) != null) { 7947 // We do have the package already installed under its 7948 // original name... should we use it? 7949 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7950 // New package is not compatible with original. 7951 origPackage = null; 7952 continue; 7953 } else if (origPackage.sharedUser != null) { 7954 // Make sure uid is compatible between packages. 7955 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7956 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7957 + " to " + pkg.packageName + ": old uid " 7958 + origPackage.sharedUser.name 7959 + " differs from " + pkg.mSharedUserId); 7960 origPackage = null; 7961 continue; 7962 } 7963 // TODO: Add case when shared user id is added [b/28144775] 7964 } else { 7965 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7966 + pkg.packageName + " to old name " + origPackage.name); 7967 } 7968 break; 7969 } 7970 } 7971 } 7972 } 7973 7974 if (mTransferedPackages.contains(pkg.packageName)) { 7975 Slog.w(TAG, "Package " + pkg.packageName 7976 + " was transferred to another, but its .apk remains"); 7977 } 7978 7979 // See comments in nonMutatedPs declaration 7980 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7981 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7982 if (foundPs != null) { 7983 nonMutatedPs = new PackageSetting(foundPs); 7984 } 7985 } 7986 7987 // Just create the setting, don't add it yet. For already existing packages 7988 // the PkgSetting exists already and doesn't have to be created. 7989 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7990 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7991 pkg.applicationInfo.primaryCpuAbi, 7992 pkg.applicationInfo.secondaryCpuAbi, 7993 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7994 user, false); 7995 if (pkgSetting == null) { 7996 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7997 "Creating application package " + pkg.packageName + " failed"); 7998 } 7999 8000 if (pkgSetting.origPackage != null) { 8001 // If we are first transitioning from an original package, 8002 // fix up the new package's name now. We need to do this after 8003 // looking up the package under its new name, so getPackageLP 8004 // can take care of fiddling things correctly. 8005 pkg.setPackageName(origPackage.name); 8006 8007 // File a report about this. 8008 String msg = "New package " + pkgSetting.realName 8009 + " renamed to replace old package " + pkgSetting.name; 8010 reportSettingsProblem(Log.WARN, msg); 8011 8012 // Make a note of it. 8013 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8014 mTransferedPackages.add(origPackage.name); 8015 } 8016 8017 // No longer need to retain this. 8018 pkgSetting.origPackage = null; 8019 } 8020 8021 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8022 // Make a note of it. 8023 mTransferedPackages.add(pkg.packageName); 8024 } 8025 8026 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8027 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8028 } 8029 8030 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8031 // Check all shared libraries and map to their actual file path. 8032 // We only do this here for apps not on a system dir, because those 8033 // are the only ones that can fail an install due to this. We 8034 // will take care of the system apps by updating all of their 8035 // library paths after the scan is done. 8036 updateSharedLibrariesLPw(pkg, null); 8037 } 8038 8039 if (mFoundPolicyFile) { 8040 SELinuxMMAC.assignSeinfoValue(pkg); 8041 } 8042 8043 pkg.applicationInfo.uid = pkgSetting.appId; 8044 pkg.mExtras = pkgSetting; 8045 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8046 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8047 // We just determined the app is signed correctly, so bring 8048 // over the latest parsed certs. 8049 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8050 } else { 8051 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8052 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8053 "Package " + pkg.packageName + " upgrade keys do not match the " 8054 + "previously installed version"); 8055 } else { 8056 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8057 String msg = "System package " + pkg.packageName 8058 + " signature changed; retaining data."; 8059 reportSettingsProblem(Log.WARN, msg); 8060 } 8061 } 8062 } else { 8063 try { 8064 verifySignaturesLP(pkgSetting, pkg); 8065 // We just determined the app is signed correctly, so bring 8066 // over the latest parsed certs. 8067 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8068 } catch (PackageManagerException e) { 8069 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8070 throw e; 8071 } 8072 // The signature has changed, but this package is in the system 8073 // image... let's recover! 8074 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8075 // However... if this package is part of a shared user, but it 8076 // doesn't match the signature of the shared user, let's fail. 8077 // What this means is that you can't change the signatures 8078 // associated with an overall shared user, which doesn't seem all 8079 // that unreasonable. 8080 if (pkgSetting.sharedUser != null) { 8081 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8082 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8083 throw new PackageManagerException( 8084 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8085 "Signature mismatch for shared user: " 8086 + pkgSetting.sharedUser); 8087 } 8088 } 8089 // File a report about this. 8090 String msg = "System package " + pkg.packageName 8091 + " signature changed; retaining data."; 8092 reportSettingsProblem(Log.WARN, msg); 8093 } 8094 } 8095 // Verify that this new package doesn't have any content providers 8096 // that conflict with existing packages. Only do this if the 8097 // package isn't already installed, since we don't want to break 8098 // things that are installed. 8099 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8100 final int N = pkg.providers.size(); 8101 int i; 8102 for (i=0; i<N; i++) { 8103 PackageParser.Provider p = pkg.providers.get(i); 8104 if (p.info.authority != null) { 8105 String names[] = p.info.authority.split(";"); 8106 for (int j = 0; j < names.length; j++) { 8107 if (mProvidersByAuthority.containsKey(names[j])) { 8108 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8109 final String otherPackageName = 8110 ((other != null && other.getComponentName() != null) ? 8111 other.getComponentName().getPackageName() : "?"); 8112 throw new PackageManagerException( 8113 INSTALL_FAILED_CONFLICTING_PROVIDER, 8114 "Can't install because provider name " + names[j] 8115 + " (in package " + pkg.applicationInfo.packageName 8116 + ") is already used by " + otherPackageName); 8117 } 8118 } 8119 } 8120 } 8121 } 8122 8123 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8124 // This package wants to adopt ownership of permissions from 8125 // another package. 8126 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8127 final String origName = pkg.mAdoptPermissions.get(i); 8128 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8129 if (orig != null) { 8130 if (verifyPackageUpdateLPr(orig, pkg)) { 8131 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8132 + pkg.packageName); 8133 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8134 } 8135 } 8136 } 8137 } 8138 } 8139 8140 final String pkgName = pkg.packageName; 8141 8142 final long scanFileTime = scanFile.lastModified(); 8143 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8144 pkg.applicationInfo.processName = fixProcessName( 8145 pkg.applicationInfo.packageName, 8146 pkg.applicationInfo.processName, 8147 pkg.applicationInfo.uid); 8148 8149 if (pkg != mPlatformPackage) { 8150 // Get all of our default paths setup 8151 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8152 } 8153 8154 final String path = scanFile.getPath(); 8155 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8156 8157 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8158 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8159 8160 // Some system apps still use directory structure for native libraries 8161 // in which case we might end up not detecting abi solely based on apk 8162 // structure. Try to detect abi based on directory structure. 8163 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8164 pkg.applicationInfo.primaryCpuAbi == null) { 8165 setBundledAppAbisAndRoots(pkg, pkgSetting); 8166 setNativeLibraryPaths(pkg); 8167 } 8168 8169 } else { 8170 if ((scanFlags & SCAN_MOVE) != 0) { 8171 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8172 // but we already have this packages package info in the PackageSetting. We just 8173 // use that and derive the native library path based on the new codepath. 8174 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8175 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8176 } 8177 8178 // Set native library paths again. For moves, the path will be updated based on the 8179 // ABIs we've determined above. For non-moves, the path will be updated based on the 8180 // ABIs we determined during compilation, but the path will depend on the final 8181 // package path (after the rename away from the stage path). 8182 setNativeLibraryPaths(pkg); 8183 } 8184 8185 // This is a special case for the "system" package, where the ABI is 8186 // dictated by the zygote configuration (and init.rc). We should keep track 8187 // of this ABI so that we can deal with "normal" applications that run under 8188 // the same UID correctly. 8189 if (mPlatformPackage == pkg) { 8190 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8191 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8192 } 8193 8194 // If there's a mismatch between the abi-override in the package setting 8195 // and the abiOverride specified for the install. Warn about this because we 8196 // would've already compiled the app without taking the package setting into 8197 // account. 8198 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8199 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8200 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8201 " for package " + pkg.packageName); 8202 } 8203 } 8204 8205 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8206 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8207 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8208 8209 // Copy the derived override back to the parsed package, so that we can 8210 // update the package settings accordingly. 8211 pkg.cpuAbiOverride = cpuAbiOverride; 8212 8213 if (DEBUG_ABI_SELECTION) { 8214 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8215 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8216 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8217 } 8218 8219 // Push the derived path down into PackageSettings so we know what to 8220 // clean up at uninstall time. 8221 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8222 8223 if (DEBUG_ABI_SELECTION) { 8224 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8225 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8226 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8227 } 8228 8229 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8230 // We don't do this here during boot because we can do it all 8231 // at once after scanning all existing packages. 8232 // 8233 // We also do this *before* we perform dexopt on this package, so that 8234 // we can avoid redundant dexopts, and also to make sure we've got the 8235 // code and package path correct. 8236 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8237 pkg, true /* boot complete */); 8238 } 8239 8240 if (mFactoryTest && pkg.requestedPermissions.contains( 8241 android.Manifest.permission.FACTORY_TEST)) { 8242 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8243 } 8244 8245 ArrayList<PackageParser.Package> clientLibPkgs = null; 8246 8247 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8248 if (nonMutatedPs != null) { 8249 synchronized (mPackages) { 8250 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8251 } 8252 } 8253 return pkg; 8254 } 8255 8256 // Only privileged apps and updated privileged apps can add child packages. 8257 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8258 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8259 throw new PackageManagerException("Only privileged apps and updated " 8260 + "privileged apps can add child packages. Ignoring package " 8261 + pkg.packageName); 8262 } 8263 final int childCount = pkg.childPackages.size(); 8264 for (int i = 0; i < childCount; i++) { 8265 PackageParser.Package childPkg = pkg.childPackages.get(i); 8266 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8267 childPkg.packageName)) { 8268 throw new PackageManagerException("Cannot override a child package of " 8269 + "another disabled system app. Ignoring package " + pkg.packageName); 8270 } 8271 } 8272 } 8273 8274 // writer 8275 synchronized (mPackages) { 8276 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8277 // Only system apps can add new shared libraries. 8278 if (pkg.libraryNames != null) { 8279 for (int i=0; i<pkg.libraryNames.size(); i++) { 8280 String name = pkg.libraryNames.get(i); 8281 boolean allowed = false; 8282 if (pkg.isUpdatedSystemApp()) { 8283 // New library entries can only be added through the 8284 // system image. This is important to get rid of a lot 8285 // of nasty edge cases: for example if we allowed a non- 8286 // system update of the app to add a library, then uninstalling 8287 // the update would make the library go away, and assumptions 8288 // we made such as through app install filtering would now 8289 // have allowed apps on the device which aren't compatible 8290 // with it. Better to just have the restriction here, be 8291 // conservative, and create many fewer cases that can negatively 8292 // impact the user experience. 8293 final PackageSetting sysPs = mSettings 8294 .getDisabledSystemPkgLPr(pkg.packageName); 8295 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8296 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8297 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8298 allowed = true; 8299 break; 8300 } 8301 } 8302 } 8303 } else { 8304 allowed = true; 8305 } 8306 if (allowed) { 8307 if (!mSharedLibraries.containsKey(name)) { 8308 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8309 } else if (!name.equals(pkg.packageName)) { 8310 Slog.w(TAG, "Package " + pkg.packageName + " library " 8311 + name + " already exists; skipping"); 8312 } 8313 } else { 8314 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8315 + name + " that is not declared on system image; skipping"); 8316 } 8317 } 8318 if ((scanFlags & SCAN_BOOTING) == 0) { 8319 // If we are not booting, we need to update any applications 8320 // that are clients of our shared library. If we are booting, 8321 // this will all be done once the scan is complete. 8322 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8323 } 8324 } 8325 } 8326 } 8327 8328 if ((scanFlags & SCAN_BOOTING) != 0) { 8329 // No apps can run during boot scan, so they don't need to be frozen 8330 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8331 // Caller asked to not kill app, so it's probably not frozen 8332 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8333 // Caller asked us to ignore frozen check for some reason; they 8334 // probably didn't know the package name 8335 } else { 8336 // We're doing major surgery on this package, so it better be frozen 8337 // right now to keep it from launching 8338 checkPackageFrozen(pkgName); 8339 } 8340 8341 // Also need to kill any apps that are dependent on the library. 8342 if (clientLibPkgs != null) { 8343 for (int i=0; i<clientLibPkgs.size(); i++) { 8344 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8345 killApplication(clientPkg.applicationInfo.packageName, 8346 clientPkg.applicationInfo.uid, "update lib"); 8347 } 8348 } 8349 8350 // Make sure we're not adding any bogus keyset info 8351 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8352 ksms.assertScannedPackageValid(pkg); 8353 8354 // writer 8355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8356 8357 boolean createIdmapFailed = false; 8358 synchronized (mPackages) { 8359 // We don't expect installation to fail beyond this point 8360 8361 // Add the new setting to mSettings 8362 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8363 // Add the new setting to mPackages 8364 mPackages.put(pkg.applicationInfo.packageName, pkg); 8365 // Make sure we don't accidentally delete its data. 8366 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8367 while (iter.hasNext()) { 8368 PackageCleanItem item = iter.next(); 8369 if (pkgName.equals(item.packageName)) { 8370 iter.remove(); 8371 } 8372 } 8373 8374 // Take care of first install / last update times. 8375 if (currentTime != 0) { 8376 if (pkgSetting.firstInstallTime == 0) { 8377 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8378 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8379 pkgSetting.lastUpdateTime = currentTime; 8380 } 8381 } else if (pkgSetting.firstInstallTime == 0) { 8382 // We need *something*. Take time time stamp of the file. 8383 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8384 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8385 if (scanFileTime != pkgSetting.timeStamp) { 8386 // A package on the system image has changed; consider this 8387 // to be an update. 8388 pkgSetting.lastUpdateTime = scanFileTime; 8389 } 8390 } 8391 8392 // Add the package's KeySets to the global KeySetManagerService 8393 ksms.addScannedPackageLPw(pkg); 8394 8395 int N = pkg.providers.size(); 8396 StringBuilder r = null; 8397 int i; 8398 for (i=0; i<N; i++) { 8399 PackageParser.Provider p = pkg.providers.get(i); 8400 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8401 p.info.processName, pkg.applicationInfo.uid); 8402 mProviders.addProvider(p); 8403 p.syncable = p.info.isSyncable; 8404 if (p.info.authority != null) { 8405 String names[] = p.info.authority.split(";"); 8406 p.info.authority = null; 8407 for (int j = 0; j < names.length; j++) { 8408 if (j == 1 && p.syncable) { 8409 // We only want the first authority for a provider to possibly be 8410 // syncable, so if we already added this provider using a different 8411 // authority clear the syncable flag. We copy the provider before 8412 // changing it because the mProviders object contains a reference 8413 // to a provider that we don't want to change. 8414 // Only do this for the second authority since the resulting provider 8415 // object can be the same for all future authorities for this provider. 8416 p = new PackageParser.Provider(p); 8417 p.syncable = false; 8418 } 8419 if (!mProvidersByAuthority.containsKey(names[j])) { 8420 mProvidersByAuthority.put(names[j], p); 8421 if (p.info.authority == null) { 8422 p.info.authority = names[j]; 8423 } else { 8424 p.info.authority = p.info.authority + ";" + names[j]; 8425 } 8426 if (DEBUG_PACKAGE_SCANNING) { 8427 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8428 Log.d(TAG, "Registered content provider: " + names[j] 8429 + ", className = " + p.info.name + ", isSyncable = " 8430 + p.info.isSyncable); 8431 } 8432 } else { 8433 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8434 Slog.w(TAG, "Skipping provider name " + names[j] + 8435 " (in package " + pkg.applicationInfo.packageName + 8436 "): name already used by " 8437 + ((other != null && other.getComponentName() != null) 8438 ? other.getComponentName().getPackageName() : "?")); 8439 } 8440 } 8441 } 8442 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8443 if (r == null) { 8444 r = new StringBuilder(256); 8445 } else { 8446 r.append(' '); 8447 } 8448 r.append(p.info.name); 8449 } 8450 } 8451 if (r != null) { 8452 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8453 } 8454 8455 N = pkg.services.size(); 8456 r = null; 8457 for (i=0; i<N; i++) { 8458 PackageParser.Service s = pkg.services.get(i); 8459 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8460 s.info.processName, pkg.applicationInfo.uid); 8461 mServices.addService(s); 8462 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8463 if (r == null) { 8464 r = new StringBuilder(256); 8465 } else { 8466 r.append(' '); 8467 } 8468 r.append(s.info.name); 8469 } 8470 } 8471 if (r != null) { 8472 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8473 } 8474 8475 N = pkg.receivers.size(); 8476 r = null; 8477 for (i=0; i<N; i++) { 8478 PackageParser.Activity a = pkg.receivers.get(i); 8479 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8480 a.info.processName, pkg.applicationInfo.uid); 8481 mReceivers.addActivity(a, "receiver"); 8482 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8483 if (r == null) { 8484 r = new StringBuilder(256); 8485 } else { 8486 r.append(' '); 8487 } 8488 r.append(a.info.name); 8489 } 8490 } 8491 if (r != null) { 8492 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8493 } 8494 8495 N = pkg.activities.size(); 8496 r = null; 8497 for (i=0; i<N; i++) { 8498 PackageParser.Activity a = pkg.activities.get(i); 8499 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8500 a.info.processName, pkg.applicationInfo.uid); 8501 mActivities.addActivity(a, "activity"); 8502 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8503 if (r == null) { 8504 r = new StringBuilder(256); 8505 } else { 8506 r.append(' '); 8507 } 8508 r.append(a.info.name); 8509 } 8510 } 8511 if (r != null) { 8512 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8513 } 8514 8515 N = pkg.permissionGroups.size(); 8516 r = null; 8517 for (i=0; i<N; i++) { 8518 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8519 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8520 if (cur == null) { 8521 mPermissionGroups.put(pg.info.name, pg); 8522 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8523 if (r == null) { 8524 r = new StringBuilder(256); 8525 } else { 8526 r.append(' '); 8527 } 8528 r.append(pg.info.name); 8529 } 8530 } else { 8531 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8532 + pg.info.packageName + " ignored: original from " 8533 + cur.info.packageName); 8534 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8535 if (r == null) { 8536 r = new StringBuilder(256); 8537 } else { 8538 r.append(' '); 8539 } 8540 r.append("DUP:"); 8541 r.append(pg.info.name); 8542 } 8543 } 8544 } 8545 if (r != null) { 8546 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8547 } 8548 8549 N = pkg.permissions.size(); 8550 r = null; 8551 for (i=0; i<N; i++) { 8552 PackageParser.Permission p = pkg.permissions.get(i); 8553 8554 // Assume by default that we did not install this permission into the system. 8555 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8556 8557 // Now that permission groups have a special meaning, we ignore permission 8558 // groups for legacy apps to prevent unexpected behavior. In particular, 8559 // permissions for one app being granted to someone just becase they happen 8560 // to be in a group defined by another app (before this had no implications). 8561 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8562 p.group = mPermissionGroups.get(p.info.group); 8563 // Warn for a permission in an unknown group. 8564 if (p.info.group != null && p.group == null) { 8565 Slog.w(TAG, "Permission " + p.info.name + " from package " 8566 + p.info.packageName + " in an unknown group " + p.info.group); 8567 } 8568 } 8569 8570 ArrayMap<String, BasePermission> permissionMap = 8571 p.tree ? mSettings.mPermissionTrees 8572 : mSettings.mPermissions; 8573 BasePermission bp = permissionMap.get(p.info.name); 8574 8575 // Allow system apps to redefine non-system permissions 8576 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8577 final boolean currentOwnerIsSystem = (bp.perm != null 8578 && isSystemApp(bp.perm.owner)); 8579 if (isSystemApp(p.owner)) { 8580 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8581 // It's a built-in permission and no owner, take ownership now 8582 bp.packageSetting = pkgSetting; 8583 bp.perm = p; 8584 bp.uid = pkg.applicationInfo.uid; 8585 bp.sourcePackage = p.info.packageName; 8586 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8587 } else if (!currentOwnerIsSystem) { 8588 String msg = "New decl " + p.owner + " of permission " 8589 + p.info.name + " is system; overriding " + bp.sourcePackage; 8590 reportSettingsProblem(Log.WARN, msg); 8591 bp = null; 8592 } 8593 } 8594 } 8595 8596 if (bp == null) { 8597 bp = new BasePermission(p.info.name, p.info.packageName, 8598 BasePermission.TYPE_NORMAL); 8599 permissionMap.put(p.info.name, bp); 8600 } 8601 8602 if (bp.perm == null) { 8603 if (bp.sourcePackage == null 8604 || bp.sourcePackage.equals(p.info.packageName)) { 8605 BasePermission tree = findPermissionTreeLP(p.info.name); 8606 if (tree == null 8607 || tree.sourcePackage.equals(p.info.packageName)) { 8608 bp.packageSetting = pkgSetting; 8609 bp.perm = p; 8610 bp.uid = pkg.applicationInfo.uid; 8611 bp.sourcePackage = p.info.packageName; 8612 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8613 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8614 if (r == null) { 8615 r = new StringBuilder(256); 8616 } else { 8617 r.append(' '); 8618 } 8619 r.append(p.info.name); 8620 } 8621 } else { 8622 Slog.w(TAG, "Permission " + p.info.name + " from package " 8623 + p.info.packageName + " ignored: base tree " 8624 + tree.name + " is from package " 8625 + tree.sourcePackage); 8626 } 8627 } else { 8628 Slog.w(TAG, "Permission " + p.info.name + " from package " 8629 + p.info.packageName + " ignored: original from " 8630 + bp.sourcePackage); 8631 } 8632 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8633 if (r == null) { 8634 r = new StringBuilder(256); 8635 } else { 8636 r.append(' '); 8637 } 8638 r.append("DUP:"); 8639 r.append(p.info.name); 8640 } 8641 if (bp.perm == p) { 8642 bp.protectionLevel = p.info.protectionLevel; 8643 } 8644 } 8645 8646 if (r != null) { 8647 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8648 } 8649 8650 N = pkg.instrumentation.size(); 8651 r = null; 8652 for (i=0; i<N; i++) { 8653 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8654 a.info.packageName = pkg.applicationInfo.packageName; 8655 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8656 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8657 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8658 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8659 a.info.dataDir = pkg.applicationInfo.dataDir; 8660 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8661 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8662 8663 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8664 // need other information about the application, like the ABI and what not ? 8665 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8666 mInstrumentation.put(a.getComponentName(), a); 8667 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8668 if (r == null) { 8669 r = new StringBuilder(256); 8670 } else { 8671 r.append(' '); 8672 } 8673 r.append(a.info.name); 8674 } 8675 } 8676 if (r != null) { 8677 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8678 } 8679 8680 if (pkg.protectedBroadcasts != null) { 8681 N = pkg.protectedBroadcasts.size(); 8682 for (i=0; i<N; i++) { 8683 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8684 } 8685 } 8686 8687 pkgSetting.setTimeStamp(scanFileTime); 8688 8689 // Create idmap files for pairs of (packages, overlay packages). 8690 // Note: "android", ie framework-res.apk, is handled by native layers. 8691 if (pkg.mOverlayTarget != null) { 8692 // This is an overlay package. 8693 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8694 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8695 mOverlays.put(pkg.mOverlayTarget, 8696 new ArrayMap<String, PackageParser.Package>()); 8697 } 8698 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8699 map.put(pkg.packageName, pkg); 8700 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8701 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8702 createIdmapFailed = true; 8703 } 8704 } 8705 } else if (mOverlays.containsKey(pkg.packageName) && 8706 !pkg.packageName.equals("android")) { 8707 // This is a regular package, with one or more known overlay packages. 8708 createIdmapsForPackageLI(pkg); 8709 } 8710 } 8711 8712 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8713 8714 if (createIdmapFailed) { 8715 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8716 "scanPackageLI failed to createIdmap"); 8717 } 8718 return pkg; 8719 } 8720 8721 /** 8722 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8723 * is derived purely on the basis of the contents of {@code scanFile} and 8724 * {@code cpuAbiOverride}. 8725 * 8726 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8727 */ 8728 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8729 String cpuAbiOverride, boolean extractLibs) 8730 throws PackageManagerException { 8731 // TODO: We can probably be smarter about this stuff. For installed apps, 8732 // we can calculate this information at install time once and for all. For 8733 // system apps, we can probably assume that this information doesn't change 8734 // after the first boot scan. As things stand, we do lots of unnecessary work. 8735 8736 // Give ourselves some initial paths; we'll come back for another 8737 // pass once we've determined ABI below. 8738 setNativeLibraryPaths(pkg); 8739 8740 // We would never need to extract libs for forward-locked and external packages, 8741 // since the container service will do it for us. We shouldn't attempt to 8742 // extract libs from system app when it was not updated. 8743 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8744 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8745 extractLibs = false; 8746 } 8747 8748 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8749 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8750 8751 NativeLibraryHelper.Handle handle = null; 8752 try { 8753 handle = NativeLibraryHelper.Handle.create(pkg); 8754 // TODO(multiArch): This can be null for apps that didn't go through the 8755 // usual installation process. We can calculate it again, like we 8756 // do during install time. 8757 // 8758 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8759 // unnecessary. 8760 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8761 8762 // Null out the abis so that they can be recalculated. 8763 pkg.applicationInfo.primaryCpuAbi = null; 8764 pkg.applicationInfo.secondaryCpuAbi = null; 8765 if (isMultiArch(pkg.applicationInfo)) { 8766 // Warn if we've set an abiOverride for multi-lib packages.. 8767 // By definition, we need to copy both 32 and 64 bit libraries for 8768 // such packages. 8769 if (pkg.cpuAbiOverride != null 8770 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8771 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8772 } 8773 8774 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8775 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8776 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8777 if (extractLibs) { 8778 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8779 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8780 useIsaSpecificSubdirs); 8781 } else { 8782 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8783 } 8784 } 8785 8786 maybeThrowExceptionForMultiArchCopy( 8787 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8788 8789 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8790 if (extractLibs) { 8791 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8792 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8793 useIsaSpecificSubdirs); 8794 } else { 8795 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8796 } 8797 } 8798 8799 maybeThrowExceptionForMultiArchCopy( 8800 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8801 8802 if (abi64 >= 0) { 8803 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8804 } 8805 8806 if (abi32 >= 0) { 8807 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8808 if (abi64 >= 0) { 8809 if (pkg.use32bitAbi) { 8810 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8811 pkg.applicationInfo.primaryCpuAbi = abi; 8812 } else { 8813 pkg.applicationInfo.secondaryCpuAbi = abi; 8814 } 8815 } else { 8816 pkg.applicationInfo.primaryCpuAbi = abi; 8817 } 8818 } 8819 8820 } else { 8821 String[] abiList = (cpuAbiOverride != null) ? 8822 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8823 8824 // Enable gross and lame hacks for apps that are built with old 8825 // SDK tools. We must scan their APKs for renderscript bitcode and 8826 // not launch them if it's present. Don't bother checking on devices 8827 // that don't have 64 bit support. 8828 boolean needsRenderScriptOverride = false; 8829 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8830 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8831 abiList = Build.SUPPORTED_32_BIT_ABIS; 8832 needsRenderScriptOverride = true; 8833 } 8834 8835 final int copyRet; 8836 if (extractLibs) { 8837 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8838 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8839 } else { 8840 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8841 } 8842 8843 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8844 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8845 "Error unpackaging native libs for app, errorCode=" + copyRet); 8846 } 8847 8848 if (copyRet >= 0) { 8849 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8850 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8851 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8852 } else if (needsRenderScriptOverride) { 8853 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8854 } 8855 } 8856 } catch (IOException ioe) { 8857 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8858 } finally { 8859 IoUtils.closeQuietly(handle); 8860 } 8861 8862 // Now that we've calculated the ABIs and determined if it's an internal app, 8863 // we will go ahead and populate the nativeLibraryPath. 8864 setNativeLibraryPaths(pkg); 8865 } 8866 8867 /** 8868 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8869 * i.e, so that all packages can be run inside a single process if required. 8870 * 8871 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8872 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8873 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8874 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8875 * updating a package that belongs to a shared user. 8876 * 8877 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8878 * adds unnecessary complexity. 8879 */ 8880 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8881 PackageParser.Package scannedPackage, boolean bootComplete) { 8882 String requiredInstructionSet = null; 8883 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8884 requiredInstructionSet = VMRuntime.getInstructionSet( 8885 scannedPackage.applicationInfo.primaryCpuAbi); 8886 } 8887 8888 PackageSetting requirer = null; 8889 for (PackageSetting ps : packagesForUser) { 8890 // If packagesForUser contains scannedPackage, we skip it. This will happen 8891 // when scannedPackage is an update of an existing package. Without this check, 8892 // we will never be able to change the ABI of any package belonging to a shared 8893 // user, even if it's compatible with other packages. 8894 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8895 if (ps.primaryCpuAbiString == null) { 8896 continue; 8897 } 8898 8899 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8900 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8901 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8902 // this but there's not much we can do. 8903 String errorMessage = "Instruction set mismatch, " 8904 + ((requirer == null) ? "[caller]" : requirer) 8905 + " requires " + requiredInstructionSet + " whereas " + ps 8906 + " requires " + instructionSet; 8907 Slog.w(TAG, errorMessage); 8908 } 8909 8910 if (requiredInstructionSet == null) { 8911 requiredInstructionSet = instructionSet; 8912 requirer = ps; 8913 } 8914 } 8915 } 8916 8917 if (requiredInstructionSet != null) { 8918 String adjustedAbi; 8919 if (requirer != null) { 8920 // requirer != null implies that either scannedPackage was null or that scannedPackage 8921 // did not require an ABI, in which case we have to adjust scannedPackage to match 8922 // the ABI of the set (which is the same as requirer's ABI) 8923 adjustedAbi = requirer.primaryCpuAbiString; 8924 if (scannedPackage != null) { 8925 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8926 } 8927 } else { 8928 // requirer == null implies that we're updating all ABIs in the set to 8929 // match scannedPackage. 8930 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8931 } 8932 8933 for (PackageSetting ps : packagesForUser) { 8934 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8935 if (ps.primaryCpuAbiString != null) { 8936 continue; 8937 } 8938 8939 ps.primaryCpuAbiString = adjustedAbi; 8940 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8941 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8942 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8943 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8944 + " (requirer=" 8945 + (requirer == null ? "null" : requirer.pkg.packageName) 8946 + ", scannedPackage=" 8947 + (scannedPackage != null ? scannedPackage.packageName : "null") 8948 + ")"); 8949 try { 8950 mInstaller.rmdex(ps.codePathString, 8951 getDexCodeInstructionSet(getPreferredInstructionSet())); 8952 } catch (InstallerException ignored) { 8953 } 8954 } 8955 } 8956 } 8957 } 8958 } 8959 8960 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8961 synchronized (mPackages) { 8962 mResolverReplaced = true; 8963 // Set up information for custom user intent resolution activity. 8964 mResolveActivity.applicationInfo = pkg.applicationInfo; 8965 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8966 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8967 mResolveActivity.processName = pkg.applicationInfo.packageName; 8968 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8969 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8970 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8971 mResolveActivity.theme = 0; 8972 mResolveActivity.exported = true; 8973 mResolveActivity.enabled = true; 8974 mResolveInfo.activityInfo = mResolveActivity; 8975 mResolveInfo.priority = 0; 8976 mResolveInfo.preferredOrder = 0; 8977 mResolveInfo.match = 0; 8978 mResolveComponentName = mCustomResolverComponentName; 8979 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8980 mResolveComponentName); 8981 } 8982 } 8983 8984 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8985 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8986 8987 // Set up information for ephemeral installer activity 8988 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8989 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8990 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8991 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8992 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8993 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8994 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8995 mEphemeralInstallerActivity.theme = 0; 8996 mEphemeralInstallerActivity.exported = true; 8997 mEphemeralInstallerActivity.enabled = true; 8998 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8999 mEphemeralInstallerInfo.priority = 0; 9000 mEphemeralInstallerInfo.preferredOrder = 0; 9001 mEphemeralInstallerInfo.match = 0; 9002 9003 if (DEBUG_EPHEMERAL) { 9004 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9005 } 9006 } 9007 9008 private static String calculateBundledApkRoot(final String codePathString) { 9009 final File codePath = new File(codePathString); 9010 final File codeRoot; 9011 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9012 codeRoot = Environment.getRootDirectory(); 9013 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9014 codeRoot = Environment.getOemDirectory(); 9015 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9016 codeRoot = Environment.getVendorDirectory(); 9017 } else { 9018 // Unrecognized code path; take its top real segment as the apk root: 9019 // e.g. /something/app/blah.apk => /something 9020 try { 9021 File f = codePath.getCanonicalFile(); 9022 File parent = f.getParentFile(); // non-null because codePath is a file 9023 File tmp; 9024 while ((tmp = parent.getParentFile()) != null) { 9025 f = parent; 9026 parent = tmp; 9027 } 9028 codeRoot = f; 9029 Slog.w(TAG, "Unrecognized code path " 9030 + codePath + " - using " + codeRoot); 9031 } catch (IOException e) { 9032 // Can't canonicalize the code path -- shenanigans? 9033 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9034 return Environment.getRootDirectory().getPath(); 9035 } 9036 } 9037 return codeRoot.getPath(); 9038 } 9039 9040 /** 9041 * Derive and set the location of native libraries for the given package, 9042 * which varies depending on where and how the package was installed. 9043 */ 9044 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9045 final ApplicationInfo info = pkg.applicationInfo; 9046 final String codePath = pkg.codePath; 9047 final File codeFile = new File(codePath); 9048 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9049 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9050 9051 info.nativeLibraryRootDir = null; 9052 info.nativeLibraryRootRequiresIsa = false; 9053 info.nativeLibraryDir = null; 9054 info.secondaryNativeLibraryDir = null; 9055 9056 if (isApkFile(codeFile)) { 9057 // Monolithic install 9058 if (bundledApp) { 9059 // If "/system/lib64/apkname" exists, assume that is the per-package 9060 // native library directory to use; otherwise use "/system/lib/apkname". 9061 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9062 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9063 getPrimaryInstructionSet(info)); 9064 9065 // This is a bundled system app so choose the path based on the ABI. 9066 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9067 // is just the default path. 9068 final String apkName = deriveCodePathName(codePath); 9069 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9070 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9071 apkName).getAbsolutePath(); 9072 9073 if (info.secondaryCpuAbi != null) { 9074 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9075 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9076 secondaryLibDir, apkName).getAbsolutePath(); 9077 } 9078 } else if (asecApp) { 9079 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9080 .getAbsolutePath(); 9081 } else { 9082 final String apkName = deriveCodePathName(codePath); 9083 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9084 .getAbsolutePath(); 9085 } 9086 9087 info.nativeLibraryRootRequiresIsa = false; 9088 info.nativeLibraryDir = info.nativeLibraryRootDir; 9089 } else { 9090 // Cluster install 9091 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9092 info.nativeLibraryRootRequiresIsa = true; 9093 9094 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9095 getPrimaryInstructionSet(info)).getAbsolutePath(); 9096 9097 if (info.secondaryCpuAbi != null) { 9098 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9099 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9100 } 9101 } 9102 } 9103 9104 /** 9105 * Calculate the abis and roots for a bundled app. These can uniquely 9106 * be determined from the contents of the system partition, i.e whether 9107 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9108 * of this information, and instead assume that the system was built 9109 * sensibly. 9110 */ 9111 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9112 PackageSetting pkgSetting) { 9113 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9114 9115 // If "/system/lib64/apkname" exists, assume that is the per-package 9116 // native library directory to use; otherwise use "/system/lib/apkname". 9117 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9118 setBundledAppAbi(pkg, apkRoot, apkName); 9119 // pkgSetting might be null during rescan following uninstall of updates 9120 // to a bundled app, so accommodate that possibility. The settings in 9121 // that case will be established later from the parsed package. 9122 // 9123 // If the settings aren't null, sync them up with what we've just derived. 9124 // note that apkRoot isn't stored in the package settings. 9125 if (pkgSetting != null) { 9126 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9127 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9128 } 9129 } 9130 9131 /** 9132 * Deduces the ABI of a bundled app and sets the relevant fields on the 9133 * parsed pkg object. 9134 * 9135 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9136 * under which system libraries are installed. 9137 * @param apkName the name of the installed package. 9138 */ 9139 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9140 final File codeFile = new File(pkg.codePath); 9141 9142 final boolean has64BitLibs; 9143 final boolean has32BitLibs; 9144 if (isApkFile(codeFile)) { 9145 // Monolithic install 9146 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9147 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9148 } else { 9149 // Cluster install 9150 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9151 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9152 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9153 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9154 has64BitLibs = (new File(rootDir, isa)).exists(); 9155 } else { 9156 has64BitLibs = false; 9157 } 9158 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9159 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9160 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9161 has32BitLibs = (new File(rootDir, isa)).exists(); 9162 } else { 9163 has32BitLibs = false; 9164 } 9165 } 9166 9167 if (has64BitLibs && !has32BitLibs) { 9168 // The package has 64 bit libs, but not 32 bit libs. Its primary 9169 // ABI should be 64 bit. We can safely assume here that the bundled 9170 // native libraries correspond to the most preferred ABI in the list. 9171 9172 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9173 pkg.applicationInfo.secondaryCpuAbi = null; 9174 } else if (has32BitLibs && !has64BitLibs) { 9175 // The package has 32 bit libs but not 64 bit libs. Its primary 9176 // ABI should be 32 bit. 9177 9178 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9179 pkg.applicationInfo.secondaryCpuAbi = null; 9180 } else if (has32BitLibs && has64BitLibs) { 9181 // The application has both 64 and 32 bit bundled libraries. We check 9182 // here that the app declares multiArch support, and warn if it doesn't. 9183 // 9184 // We will be lenient here and record both ABIs. The primary will be the 9185 // ABI that's higher on the list, i.e, a device that's configured to prefer 9186 // 64 bit apps will see a 64 bit primary ABI, 9187 9188 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9189 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9190 } 9191 9192 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9193 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9194 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9195 } else { 9196 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9197 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9198 } 9199 } else { 9200 pkg.applicationInfo.primaryCpuAbi = null; 9201 pkg.applicationInfo.secondaryCpuAbi = null; 9202 } 9203 } 9204 9205 private void killApplication(String pkgName, int appId, String reason) { 9206 // Request the ActivityManager to kill the process(only for existing packages) 9207 // so that we do not end up in a confused state while the user is still using the older 9208 // version of the application while the new one gets installed. 9209 final long token = Binder.clearCallingIdentity(); 9210 try { 9211 IActivityManager am = ActivityManagerNative.getDefault(); 9212 if (am != null) { 9213 try { 9214 am.killApplicationWithAppId(pkgName, appId, reason); 9215 } catch (RemoteException e) { 9216 } 9217 } 9218 } finally { 9219 Binder.restoreCallingIdentity(token); 9220 } 9221 } 9222 9223 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9224 // Remove the parent package setting 9225 PackageSetting ps = (PackageSetting) pkg.mExtras; 9226 if (ps != null) { 9227 removePackageLI(ps, chatty); 9228 } 9229 // Remove the child package setting 9230 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9231 for (int i = 0; i < childCount; i++) { 9232 PackageParser.Package childPkg = pkg.childPackages.get(i); 9233 ps = (PackageSetting) childPkg.mExtras; 9234 if (ps != null) { 9235 removePackageLI(ps, chatty); 9236 } 9237 } 9238 } 9239 9240 void removePackageLI(PackageSetting ps, boolean chatty) { 9241 if (DEBUG_INSTALL) { 9242 if (chatty) 9243 Log.d(TAG, "Removing package " + ps.name); 9244 } 9245 9246 // writer 9247 synchronized (mPackages) { 9248 mPackages.remove(ps.name); 9249 final PackageParser.Package pkg = ps.pkg; 9250 if (pkg != null) { 9251 cleanPackageDataStructuresLILPw(pkg, chatty); 9252 } 9253 } 9254 } 9255 9256 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9257 if (DEBUG_INSTALL) { 9258 if (chatty) 9259 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9260 } 9261 9262 // writer 9263 synchronized (mPackages) { 9264 // Remove the parent package 9265 mPackages.remove(pkg.applicationInfo.packageName); 9266 cleanPackageDataStructuresLILPw(pkg, chatty); 9267 9268 // Remove the child packages 9269 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9270 for (int i = 0; i < childCount; i++) { 9271 PackageParser.Package childPkg = pkg.childPackages.get(i); 9272 mPackages.remove(childPkg.applicationInfo.packageName); 9273 cleanPackageDataStructuresLILPw(childPkg, chatty); 9274 } 9275 } 9276 } 9277 9278 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9279 int N = pkg.providers.size(); 9280 StringBuilder r = null; 9281 int i; 9282 for (i=0; i<N; i++) { 9283 PackageParser.Provider p = pkg.providers.get(i); 9284 mProviders.removeProvider(p); 9285 if (p.info.authority == null) { 9286 9287 /* There was another ContentProvider with this authority when 9288 * this app was installed so this authority is null, 9289 * Ignore it as we don't have to unregister the provider. 9290 */ 9291 continue; 9292 } 9293 String names[] = p.info.authority.split(";"); 9294 for (int j = 0; j < names.length; j++) { 9295 if (mProvidersByAuthority.get(names[j]) == p) { 9296 mProvidersByAuthority.remove(names[j]); 9297 if (DEBUG_REMOVE) { 9298 if (chatty) 9299 Log.d(TAG, "Unregistered content provider: " + names[j] 9300 + ", className = " + p.info.name + ", isSyncable = " 9301 + p.info.isSyncable); 9302 } 9303 } 9304 } 9305 if (DEBUG_REMOVE && chatty) { 9306 if (r == null) { 9307 r = new StringBuilder(256); 9308 } else { 9309 r.append(' '); 9310 } 9311 r.append(p.info.name); 9312 } 9313 } 9314 if (r != null) { 9315 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9316 } 9317 9318 N = pkg.services.size(); 9319 r = null; 9320 for (i=0; i<N; i++) { 9321 PackageParser.Service s = pkg.services.get(i); 9322 mServices.removeService(s); 9323 if (chatty) { 9324 if (r == null) { 9325 r = new StringBuilder(256); 9326 } else { 9327 r.append(' '); 9328 } 9329 r.append(s.info.name); 9330 } 9331 } 9332 if (r != null) { 9333 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9334 } 9335 9336 N = pkg.receivers.size(); 9337 r = null; 9338 for (i=0; i<N; i++) { 9339 PackageParser.Activity a = pkg.receivers.get(i); 9340 mReceivers.removeActivity(a, "receiver"); 9341 if (DEBUG_REMOVE && chatty) { 9342 if (r == null) { 9343 r = new StringBuilder(256); 9344 } else { 9345 r.append(' '); 9346 } 9347 r.append(a.info.name); 9348 } 9349 } 9350 if (r != null) { 9351 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9352 } 9353 9354 N = pkg.activities.size(); 9355 r = null; 9356 for (i=0; i<N; i++) { 9357 PackageParser.Activity a = pkg.activities.get(i); 9358 mActivities.removeActivity(a, "activity"); 9359 if (DEBUG_REMOVE && chatty) { 9360 if (r == null) { 9361 r = new StringBuilder(256); 9362 } else { 9363 r.append(' '); 9364 } 9365 r.append(a.info.name); 9366 } 9367 } 9368 if (r != null) { 9369 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9370 } 9371 9372 N = pkg.permissions.size(); 9373 r = null; 9374 for (i=0; i<N; i++) { 9375 PackageParser.Permission p = pkg.permissions.get(i); 9376 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9377 if (bp == null) { 9378 bp = mSettings.mPermissionTrees.get(p.info.name); 9379 } 9380 if (bp != null && bp.perm == p) { 9381 bp.perm = null; 9382 if (DEBUG_REMOVE && chatty) { 9383 if (r == null) { 9384 r = new StringBuilder(256); 9385 } else { 9386 r.append(' '); 9387 } 9388 r.append(p.info.name); 9389 } 9390 } 9391 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9392 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9393 if (appOpPkgs != null) { 9394 appOpPkgs.remove(pkg.packageName); 9395 } 9396 } 9397 } 9398 if (r != null) { 9399 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9400 } 9401 9402 N = pkg.requestedPermissions.size(); 9403 r = null; 9404 for (i=0; i<N; i++) { 9405 String perm = pkg.requestedPermissions.get(i); 9406 BasePermission bp = mSettings.mPermissions.get(perm); 9407 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9408 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9409 if (appOpPkgs != null) { 9410 appOpPkgs.remove(pkg.packageName); 9411 if (appOpPkgs.isEmpty()) { 9412 mAppOpPermissionPackages.remove(perm); 9413 } 9414 } 9415 } 9416 } 9417 if (r != null) { 9418 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9419 } 9420 9421 N = pkg.instrumentation.size(); 9422 r = null; 9423 for (i=0; i<N; i++) { 9424 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9425 mInstrumentation.remove(a.getComponentName()); 9426 if (DEBUG_REMOVE && chatty) { 9427 if (r == null) { 9428 r = new StringBuilder(256); 9429 } else { 9430 r.append(' '); 9431 } 9432 r.append(a.info.name); 9433 } 9434 } 9435 if (r != null) { 9436 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9437 } 9438 9439 r = null; 9440 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9441 // Only system apps can hold shared libraries. 9442 if (pkg.libraryNames != null) { 9443 for (i=0; i<pkg.libraryNames.size(); i++) { 9444 String name = pkg.libraryNames.get(i); 9445 SharedLibraryEntry cur = mSharedLibraries.get(name); 9446 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9447 mSharedLibraries.remove(name); 9448 if (DEBUG_REMOVE && chatty) { 9449 if (r == null) { 9450 r = new StringBuilder(256); 9451 } else { 9452 r.append(' '); 9453 } 9454 r.append(name); 9455 } 9456 } 9457 } 9458 } 9459 } 9460 if (r != null) { 9461 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9462 } 9463 } 9464 9465 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9466 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9467 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9468 return true; 9469 } 9470 } 9471 return false; 9472 } 9473 9474 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9475 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9476 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9477 9478 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9479 // Update the parent permissions 9480 updatePermissionsLPw(pkg.packageName, pkg, flags); 9481 // Update the child permissions 9482 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9483 for (int i = 0; i < childCount; i++) { 9484 PackageParser.Package childPkg = pkg.childPackages.get(i); 9485 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9486 } 9487 } 9488 9489 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9490 int flags) { 9491 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9492 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9493 } 9494 9495 private void updatePermissionsLPw(String changingPkg, 9496 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9497 // Make sure there are no dangling permission trees. 9498 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9499 while (it.hasNext()) { 9500 final BasePermission bp = it.next(); 9501 if (bp.packageSetting == null) { 9502 // We may not yet have parsed the package, so just see if 9503 // we still know about its settings. 9504 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9505 } 9506 if (bp.packageSetting == null) { 9507 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9508 + " from package " + bp.sourcePackage); 9509 it.remove(); 9510 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9511 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9512 Slog.i(TAG, "Removing old permission tree: " + bp.name 9513 + " from package " + bp.sourcePackage); 9514 flags |= UPDATE_PERMISSIONS_ALL; 9515 it.remove(); 9516 } 9517 } 9518 } 9519 9520 // Make sure all dynamic permissions have been assigned to a package, 9521 // and make sure there are no dangling permissions. 9522 it = mSettings.mPermissions.values().iterator(); 9523 while (it.hasNext()) { 9524 final BasePermission bp = it.next(); 9525 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9526 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9527 + bp.name + " pkg=" + bp.sourcePackage 9528 + " info=" + bp.pendingInfo); 9529 if (bp.packageSetting == null && bp.pendingInfo != null) { 9530 final BasePermission tree = findPermissionTreeLP(bp.name); 9531 if (tree != null && tree.perm != null) { 9532 bp.packageSetting = tree.packageSetting; 9533 bp.perm = new PackageParser.Permission(tree.perm.owner, 9534 new PermissionInfo(bp.pendingInfo)); 9535 bp.perm.info.packageName = tree.perm.info.packageName; 9536 bp.perm.info.name = bp.name; 9537 bp.uid = tree.uid; 9538 } 9539 } 9540 } 9541 if (bp.packageSetting == null) { 9542 // We may not yet have parsed the package, so just see if 9543 // we still know about its settings. 9544 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9545 } 9546 if (bp.packageSetting == null) { 9547 Slog.w(TAG, "Removing dangling permission: " + bp.name 9548 + " from package " + bp.sourcePackage); 9549 it.remove(); 9550 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9551 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9552 Slog.i(TAG, "Removing old permission: " + bp.name 9553 + " from package " + bp.sourcePackage); 9554 flags |= UPDATE_PERMISSIONS_ALL; 9555 it.remove(); 9556 } 9557 } 9558 } 9559 9560 // Now update the permissions for all packages, in particular 9561 // replace the granted permissions of the system packages. 9562 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9563 for (PackageParser.Package pkg : mPackages.values()) { 9564 if (pkg != pkgInfo) { 9565 // Only replace for packages on requested volume 9566 final String volumeUuid = getVolumeUuidForPackage(pkg); 9567 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9568 && Objects.equals(replaceVolumeUuid, volumeUuid); 9569 grantPermissionsLPw(pkg, replace, changingPkg); 9570 } 9571 } 9572 } 9573 9574 if (pkgInfo != null) { 9575 // Only replace for packages on requested volume 9576 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9577 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9578 && Objects.equals(replaceVolumeUuid, volumeUuid); 9579 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9580 } 9581 } 9582 9583 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9584 String packageOfInterest) { 9585 // IMPORTANT: There are two types of permissions: install and runtime. 9586 // Install time permissions are granted when the app is installed to 9587 // all device users and users added in the future. Runtime permissions 9588 // are granted at runtime explicitly to specific users. Normal and signature 9589 // protected permissions are install time permissions. Dangerous permissions 9590 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9591 // otherwise they are runtime permissions. This function does not manage 9592 // runtime permissions except for the case an app targeting Lollipop MR1 9593 // being upgraded to target a newer SDK, in which case dangerous permissions 9594 // are transformed from install time to runtime ones. 9595 9596 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9597 if (ps == null) { 9598 return; 9599 } 9600 9601 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9602 9603 PermissionsState permissionsState = ps.getPermissionsState(); 9604 PermissionsState origPermissions = permissionsState; 9605 9606 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9607 9608 boolean runtimePermissionsRevoked = false; 9609 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9610 9611 boolean changedInstallPermission = false; 9612 9613 if (replace) { 9614 ps.installPermissionsFixed = false; 9615 if (!ps.isSharedUser()) { 9616 origPermissions = new PermissionsState(permissionsState); 9617 permissionsState.reset(); 9618 } else { 9619 // We need to know only about runtime permission changes since the 9620 // calling code always writes the install permissions state but 9621 // the runtime ones are written only if changed. The only cases of 9622 // changed runtime permissions here are promotion of an install to 9623 // runtime and revocation of a runtime from a shared user. 9624 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9625 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9626 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9627 runtimePermissionsRevoked = true; 9628 } 9629 } 9630 } 9631 9632 permissionsState.setGlobalGids(mGlobalGids); 9633 9634 final int N = pkg.requestedPermissions.size(); 9635 for (int i=0; i<N; i++) { 9636 final String name = pkg.requestedPermissions.get(i); 9637 final BasePermission bp = mSettings.mPermissions.get(name); 9638 9639 if (DEBUG_INSTALL) { 9640 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9641 } 9642 9643 if (bp == null || bp.packageSetting == null) { 9644 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9645 Slog.w(TAG, "Unknown permission " + name 9646 + " in package " + pkg.packageName); 9647 } 9648 continue; 9649 } 9650 9651 final String perm = bp.name; 9652 boolean allowedSig = false; 9653 int grant = GRANT_DENIED; 9654 9655 // Keep track of app op permissions. 9656 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9657 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9658 if (pkgs == null) { 9659 pkgs = new ArraySet<>(); 9660 mAppOpPermissionPackages.put(bp.name, pkgs); 9661 } 9662 pkgs.add(pkg.packageName); 9663 } 9664 9665 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9666 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9667 >= Build.VERSION_CODES.M; 9668 switch (level) { 9669 case PermissionInfo.PROTECTION_NORMAL: { 9670 // For all apps normal permissions are install time ones. 9671 grant = GRANT_INSTALL; 9672 } break; 9673 9674 case PermissionInfo.PROTECTION_DANGEROUS: { 9675 // If a permission review is required for legacy apps we represent 9676 // their permissions as always granted runtime ones since we need 9677 // to keep the review required permission flag per user while an 9678 // install permission's state is shared across all users. 9679 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9680 // For legacy apps dangerous permissions are install time ones. 9681 grant = GRANT_INSTALL; 9682 } else if (origPermissions.hasInstallPermission(bp.name)) { 9683 // For legacy apps that became modern, install becomes runtime. 9684 grant = GRANT_UPGRADE; 9685 } else if (mPromoteSystemApps 9686 && isSystemApp(ps) 9687 && mExistingSystemPackages.contains(ps.name)) { 9688 // For legacy system apps, install becomes runtime. 9689 // We cannot check hasInstallPermission() for system apps since those 9690 // permissions were granted implicitly and not persisted pre-M. 9691 grant = GRANT_UPGRADE; 9692 } else { 9693 // For modern apps keep runtime permissions unchanged. 9694 grant = GRANT_RUNTIME; 9695 } 9696 } break; 9697 9698 case PermissionInfo.PROTECTION_SIGNATURE: { 9699 // For all apps signature permissions are install time ones. 9700 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9701 if (allowedSig) { 9702 grant = GRANT_INSTALL; 9703 } 9704 } break; 9705 } 9706 9707 if (DEBUG_INSTALL) { 9708 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9709 } 9710 9711 if (grant != GRANT_DENIED) { 9712 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9713 // If this is an existing, non-system package, then 9714 // we can't add any new permissions to it. 9715 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9716 // Except... if this is a permission that was added 9717 // to the platform (note: need to only do this when 9718 // updating the platform). 9719 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9720 grant = GRANT_DENIED; 9721 } 9722 } 9723 } 9724 9725 switch (grant) { 9726 case GRANT_INSTALL: { 9727 // Revoke this as runtime permission to handle the case of 9728 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9729 for (int userId : UserManagerService.getInstance().getUserIds()) { 9730 if (origPermissions.getRuntimePermissionState( 9731 bp.name, userId) != null) { 9732 // Revoke the runtime permission and clear the flags. 9733 origPermissions.revokeRuntimePermission(bp, userId); 9734 origPermissions.updatePermissionFlags(bp, userId, 9735 PackageManager.MASK_PERMISSION_FLAGS, 0); 9736 // If we revoked a permission permission, we have to write. 9737 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9738 changedRuntimePermissionUserIds, userId); 9739 } 9740 } 9741 // Grant an install permission. 9742 if (permissionsState.grantInstallPermission(bp) != 9743 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9744 changedInstallPermission = true; 9745 } 9746 } break; 9747 9748 case GRANT_RUNTIME: { 9749 // Grant previously granted runtime permissions. 9750 for (int userId : UserManagerService.getInstance().getUserIds()) { 9751 PermissionState permissionState = origPermissions 9752 .getRuntimePermissionState(bp.name, userId); 9753 int flags = permissionState != null 9754 ? permissionState.getFlags() : 0; 9755 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9756 if (permissionsState.grantRuntimePermission(bp, userId) == 9757 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9758 // If we cannot put the permission as it was, we have to write. 9759 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9760 changedRuntimePermissionUserIds, userId); 9761 } 9762 // If the app supports runtime permissions no need for a review. 9763 if (Build.PERMISSIONS_REVIEW_REQUIRED 9764 && appSupportsRuntimePermissions 9765 && (flags & PackageManager 9766 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9767 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9768 // Since we changed the flags, we have to write. 9769 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9770 changedRuntimePermissionUserIds, userId); 9771 } 9772 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9773 && !appSupportsRuntimePermissions) { 9774 // For legacy apps that need a permission review, every new 9775 // runtime permission is granted but it is pending a review. 9776 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9777 permissionsState.grantRuntimePermission(bp, userId); 9778 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9779 // We changed the permission and flags, hence have to write. 9780 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9781 changedRuntimePermissionUserIds, userId); 9782 } 9783 } 9784 // Propagate the permission flags. 9785 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9786 } 9787 } break; 9788 9789 case GRANT_UPGRADE: { 9790 // Grant runtime permissions for a previously held install permission. 9791 PermissionState permissionState = origPermissions 9792 .getInstallPermissionState(bp.name); 9793 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9794 9795 if (origPermissions.revokeInstallPermission(bp) 9796 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9797 // We will be transferring the permission flags, so clear them. 9798 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9799 PackageManager.MASK_PERMISSION_FLAGS, 0); 9800 changedInstallPermission = true; 9801 } 9802 9803 // If the permission is not to be promoted to runtime we ignore it and 9804 // also its other flags as they are not applicable to install permissions. 9805 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9806 for (int userId : currentUserIds) { 9807 if (permissionsState.grantRuntimePermission(bp, userId) != 9808 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9809 // Transfer the permission flags. 9810 permissionsState.updatePermissionFlags(bp, userId, 9811 flags, flags); 9812 // If we granted the permission, we have to write. 9813 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9814 changedRuntimePermissionUserIds, userId); 9815 } 9816 } 9817 } 9818 } break; 9819 9820 default: { 9821 if (packageOfInterest == null 9822 || packageOfInterest.equals(pkg.packageName)) { 9823 Slog.w(TAG, "Not granting permission " + perm 9824 + " to package " + pkg.packageName 9825 + " because it was previously installed without"); 9826 } 9827 } break; 9828 } 9829 } else { 9830 if (permissionsState.revokeInstallPermission(bp) != 9831 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9832 // Also drop the permission flags. 9833 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9834 PackageManager.MASK_PERMISSION_FLAGS, 0); 9835 changedInstallPermission = true; 9836 Slog.i(TAG, "Un-granting permission " + perm 9837 + " from package " + pkg.packageName 9838 + " (protectionLevel=" + bp.protectionLevel 9839 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9840 + ")"); 9841 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9842 // Don't print warning for app op permissions, since it is fine for them 9843 // not to be granted, there is a UI for the user to decide. 9844 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9845 Slog.w(TAG, "Not granting permission " + perm 9846 + " to package " + pkg.packageName 9847 + " (protectionLevel=" + bp.protectionLevel 9848 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9849 + ")"); 9850 } 9851 } 9852 } 9853 } 9854 9855 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9856 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9857 // This is the first that we have heard about this package, so the 9858 // permissions we have now selected are fixed until explicitly 9859 // changed. 9860 ps.installPermissionsFixed = true; 9861 } 9862 9863 // Persist the runtime permissions state for users with changes. If permissions 9864 // were revoked because no app in the shared user declares them we have to 9865 // write synchronously to avoid losing runtime permissions state. 9866 for (int userId : changedRuntimePermissionUserIds) { 9867 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9868 } 9869 9870 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9871 } 9872 9873 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9874 boolean allowed = false; 9875 final int NP = PackageParser.NEW_PERMISSIONS.length; 9876 for (int ip=0; ip<NP; ip++) { 9877 final PackageParser.NewPermissionInfo npi 9878 = PackageParser.NEW_PERMISSIONS[ip]; 9879 if (npi.name.equals(perm) 9880 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9881 allowed = true; 9882 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9883 + pkg.packageName); 9884 break; 9885 } 9886 } 9887 return allowed; 9888 } 9889 9890 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9891 BasePermission bp, PermissionsState origPermissions) { 9892 boolean allowed; 9893 allowed = (compareSignatures( 9894 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9895 == PackageManager.SIGNATURE_MATCH) 9896 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9897 == PackageManager.SIGNATURE_MATCH); 9898 if (!allowed && (bp.protectionLevel 9899 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9900 if (isSystemApp(pkg)) { 9901 // For updated system applications, a system permission 9902 // is granted only if it had been defined by the original application. 9903 if (pkg.isUpdatedSystemApp()) { 9904 final PackageSetting sysPs = mSettings 9905 .getDisabledSystemPkgLPr(pkg.packageName); 9906 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9907 // If the original was granted this permission, we take 9908 // that grant decision as read and propagate it to the 9909 // update. 9910 if (sysPs.isPrivileged()) { 9911 allowed = true; 9912 } 9913 } else { 9914 // The system apk may have been updated with an older 9915 // version of the one on the data partition, but which 9916 // granted a new system permission that it didn't have 9917 // before. In this case we do want to allow the app to 9918 // now get the new permission if the ancestral apk is 9919 // privileged to get it. 9920 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9921 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9922 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9923 allowed = true; 9924 break; 9925 } 9926 } 9927 } 9928 // Also if a privileged parent package on the system image or any of 9929 // its children requested a privileged permission, the updated child 9930 // packages can also get the permission. 9931 if (pkg.parentPackage != null) { 9932 final PackageSetting disabledSysParentPs = mSettings 9933 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9934 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9935 && disabledSysParentPs.isPrivileged()) { 9936 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9937 allowed = true; 9938 } else if (disabledSysParentPs.pkg.childPackages != null) { 9939 final int count = disabledSysParentPs.pkg.childPackages.size(); 9940 for (int i = 0; i < count; i++) { 9941 PackageParser.Package disabledSysChildPkg = 9942 disabledSysParentPs.pkg.childPackages.get(i); 9943 if (isPackageRequestingPermission(disabledSysChildPkg, 9944 perm)) { 9945 allowed = true; 9946 break; 9947 } 9948 } 9949 } 9950 } 9951 } 9952 } 9953 } else { 9954 allowed = isPrivilegedApp(pkg); 9955 } 9956 } 9957 } 9958 if (!allowed) { 9959 if (!allowed && (bp.protectionLevel 9960 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9961 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9962 // If this was a previously normal/dangerous permission that got moved 9963 // to a system permission as part of the runtime permission redesign, then 9964 // we still want to blindly grant it to old apps. 9965 allowed = true; 9966 } 9967 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9968 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9969 // If this permission is to be granted to the system installer and 9970 // this app is an installer, then it gets the permission. 9971 allowed = true; 9972 } 9973 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9974 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9975 // If this permission is to be granted to the system verifier and 9976 // this app is a verifier, then it gets the permission. 9977 allowed = true; 9978 } 9979 if (!allowed && (bp.protectionLevel 9980 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9981 && isSystemApp(pkg)) { 9982 // Any pre-installed system app is allowed to get this permission. 9983 allowed = true; 9984 } 9985 if (!allowed && (bp.protectionLevel 9986 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9987 // For development permissions, a development permission 9988 // is granted only if it was already granted. 9989 allowed = origPermissions.hasInstallPermission(perm); 9990 } 9991 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9992 && pkg.packageName.equals(mSetupWizardPackage)) { 9993 // If this permission is to be granted to the system setup wizard and 9994 // this app is a setup wizard, then it gets the permission. 9995 allowed = true; 9996 } 9997 } 9998 return allowed; 9999 } 10000 10001 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10002 final int permCount = pkg.requestedPermissions.size(); 10003 for (int j = 0; j < permCount; j++) { 10004 String requestedPermission = pkg.requestedPermissions.get(j); 10005 if (permission.equals(requestedPermission)) { 10006 return true; 10007 } 10008 } 10009 return false; 10010 } 10011 10012 final class ActivityIntentResolver 10013 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10014 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10015 boolean defaultOnly, int userId) { 10016 if (!sUserManager.exists(userId)) return null; 10017 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10018 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10019 } 10020 10021 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10022 int userId) { 10023 if (!sUserManager.exists(userId)) return null; 10024 mFlags = flags; 10025 return super.queryIntent(intent, resolvedType, 10026 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10027 } 10028 10029 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10030 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10031 if (!sUserManager.exists(userId)) return null; 10032 if (packageActivities == null) { 10033 return null; 10034 } 10035 mFlags = flags; 10036 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10037 final int N = packageActivities.size(); 10038 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10039 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10040 10041 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10042 for (int i = 0; i < N; ++i) { 10043 intentFilters = packageActivities.get(i).intents; 10044 if (intentFilters != null && intentFilters.size() > 0) { 10045 PackageParser.ActivityIntentInfo[] array = 10046 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10047 intentFilters.toArray(array); 10048 listCut.add(array); 10049 } 10050 } 10051 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10052 } 10053 10054 /** 10055 * Finds a privileged activity that matches the specified activity names. 10056 */ 10057 private PackageParser.Activity findMatchingActivity( 10058 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10059 for (PackageParser.Activity sysActivity : activityList) { 10060 if (sysActivity.info.name.equals(activityInfo.name)) { 10061 return sysActivity; 10062 } 10063 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10064 return sysActivity; 10065 } 10066 if (sysActivity.info.targetActivity != null) { 10067 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10068 return sysActivity; 10069 } 10070 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10071 return sysActivity; 10072 } 10073 } 10074 } 10075 return null; 10076 } 10077 10078 public class IterGenerator<E> { 10079 public Iterator<E> generate(ActivityIntentInfo info) { 10080 return null; 10081 } 10082 } 10083 10084 public class ActionIterGenerator extends IterGenerator<String> { 10085 @Override 10086 public Iterator<String> generate(ActivityIntentInfo info) { 10087 return info.actionsIterator(); 10088 } 10089 } 10090 10091 public class CategoriesIterGenerator extends IterGenerator<String> { 10092 @Override 10093 public Iterator<String> generate(ActivityIntentInfo info) { 10094 return info.categoriesIterator(); 10095 } 10096 } 10097 10098 public class SchemesIterGenerator extends IterGenerator<String> { 10099 @Override 10100 public Iterator<String> generate(ActivityIntentInfo info) { 10101 return info.schemesIterator(); 10102 } 10103 } 10104 10105 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10106 @Override 10107 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10108 return info.authoritiesIterator(); 10109 } 10110 } 10111 10112 /** 10113 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10114 * MODIFIED. Do not pass in a list that should not be changed. 10115 */ 10116 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10117 IterGenerator<T> generator, Iterator<T> searchIterator) { 10118 // loop through the set of actions; every one must be found in the intent filter 10119 while (searchIterator.hasNext()) { 10120 // we must have at least one filter in the list to consider a match 10121 if (intentList.size() == 0) { 10122 break; 10123 } 10124 10125 final T searchAction = searchIterator.next(); 10126 10127 // loop through the set of intent filters 10128 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10129 while (intentIter.hasNext()) { 10130 final ActivityIntentInfo intentInfo = intentIter.next(); 10131 boolean selectionFound = false; 10132 10133 // loop through the intent filter's selection criteria; at least one 10134 // of them must match the searched criteria 10135 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10136 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10137 final T intentSelection = intentSelectionIter.next(); 10138 if (intentSelection != null && intentSelection.equals(searchAction)) { 10139 selectionFound = true; 10140 break; 10141 } 10142 } 10143 10144 // the selection criteria wasn't found in this filter's set; this filter 10145 // is not a potential match 10146 if (!selectionFound) { 10147 intentIter.remove(); 10148 } 10149 } 10150 } 10151 } 10152 10153 private boolean isProtectedAction(ActivityIntentInfo filter) { 10154 final Iterator<String> actionsIter = filter.actionsIterator(); 10155 while (actionsIter != null && actionsIter.hasNext()) { 10156 final String filterAction = actionsIter.next(); 10157 if (PROTECTED_ACTIONS.contains(filterAction)) { 10158 return true; 10159 } 10160 } 10161 return false; 10162 } 10163 10164 /** 10165 * Adjusts the priority of the given intent filter according to policy. 10166 * <p> 10167 * <ul> 10168 * <li>The priority for non privileged applications is capped to '0'</li> 10169 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10170 * <li>The priority for unbundled updates to privileged applications is capped to the 10171 * priority defined on the system partition</li> 10172 * </ul> 10173 * <p> 10174 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10175 * allowed to obtain any priority on any action. 10176 */ 10177 private void adjustPriority( 10178 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10179 // nothing to do; priority is fine as-is 10180 if (intent.getPriority() <= 0) { 10181 return; 10182 } 10183 10184 final ActivityInfo activityInfo = intent.activity.info; 10185 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10186 10187 final boolean privilegedApp = 10188 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10189 if (!privilegedApp) { 10190 // non-privileged applications can never define a priority >0 10191 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10192 + " package: " + applicationInfo.packageName 10193 + " activity: " + intent.activity.className 10194 + " origPrio: " + intent.getPriority()); 10195 intent.setPriority(0); 10196 return; 10197 } 10198 10199 if (systemActivities == null) { 10200 // the system package is not disabled; we're parsing the system partition 10201 if (isProtectedAction(intent)) { 10202 if (mDeferProtectedFilters) { 10203 // We can't deal with these just yet. No component should ever obtain a 10204 // >0 priority for a protected actions, with ONE exception -- the setup 10205 // wizard. The setup wizard, however, cannot be known until we're able to 10206 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10207 // until all intent filters have been processed. Chicken, meet egg. 10208 // Let the filter temporarily have a high priority and rectify the 10209 // priorities after all system packages have been scanned. 10210 mProtectedFilters.add(intent); 10211 if (DEBUG_FILTERS) { 10212 Slog.i(TAG, "Protected action; save for later;" 10213 + " package: " + applicationInfo.packageName 10214 + " activity: " + intent.activity.className 10215 + " origPrio: " + intent.getPriority()); 10216 } 10217 return; 10218 } else { 10219 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10220 Slog.i(TAG, "No setup wizard;" 10221 + " All protected intents capped to priority 0"); 10222 } 10223 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10224 if (DEBUG_FILTERS) { 10225 Slog.i(TAG, "Found setup wizard;" 10226 + " allow priority " + intent.getPriority() + ";" 10227 + " package: " + intent.activity.info.packageName 10228 + " activity: " + intent.activity.className 10229 + " priority: " + intent.getPriority()); 10230 } 10231 // setup wizard gets whatever it wants 10232 return; 10233 } 10234 Slog.w(TAG, "Protected action; cap priority to 0;" 10235 + " package: " + intent.activity.info.packageName 10236 + " activity: " + intent.activity.className 10237 + " origPrio: " + intent.getPriority()); 10238 intent.setPriority(0); 10239 return; 10240 } 10241 } 10242 // privileged apps on the system image get whatever priority they request 10243 return; 10244 } 10245 10246 // privileged app unbundled update ... try to find the same activity 10247 final PackageParser.Activity foundActivity = 10248 findMatchingActivity(systemActivities, activityInfo); 10249 if (foundActivity == null) { 10250 // this is a new activity; it cannot obtain >0 priority 10251 if (DEBUG_FILTERS) { 10252 Slog.i(TAG, "New activity; cap priority to 0;" 10253 + " package: " + applicationInfo.packageName 10254 + " activity: " + intent.activity.className 10255 + " origPrio: " + intent.getPriority()); 10256 } 10257 intent.setPriority(0); 10258 return; 10259 } 10260 10261 // found activity, now check for filter equivalence 10262 10263 // a shallow copy is enough; we modify the list, not its contents 10264 final List<ActivityIntentInfo> intentListCopy = 10265 new ArrayList<>(foundActivity.intents); 10266 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10267 10268 // find matching action subsets 10269 final Iterator<String> actionsIterator = intent.actionsIterator(); 10270 if (actionsIterator != null) { 10271 getIntentListSubset( 10272 intentListCopy, new ActionIterGenerator(), actionsIterator); 10273 if (intentListCopy.size() == 0) { 10274 // no more intents to match; we're not equivalent 10275 if (DEBUG_FILTERS) { 10276 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10277 + " package: " + applicationInfo.packageName 10278 + " activity: " + intent.activity.className 10279 + " origPrio: " + intent.getPriority()); 10280 } 10281 intent.setPriority(0); 10282 return; 10283 } 10284 } 10285 10286 // find matching category subsets 10287 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10288 if (categoriesIterator != null) { 10289 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10290 categoriesIterator); 10291 if (intentListCopy.size() == 0) { 10292 // no more intents to match; we're not equivalent 10293 if (DEBUG_FILTERS) { 10294 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10295 + " package: " + applicationInfo.packageName 10296 + " activity: " + intent.activity.className 10297 + " origPrio: " + intent.getPriority()); 10298 } 10299 intent.setPriority(0); 10300 return; 10301 } 10302 } 10303 10304 // find matching schemes subsets 10305 final Iterator<String> schemesIterator = intent.schemesIterator(); 10306 if (schemesIterator != null) { 10307 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10308 schemesIterator); 10309 if (intentListCopy.size() == 0) { 10310 // no more intents to match; we're not equivalent 10311 if (DEBUG_FILTERS) { 10312 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10313 + " package: " + applicationInfo.packageName 10314 + " activity: " + intent.activity.className 10315 + " origPrio: " + intent.getPriority()); 10316 } 10317 intent.setPriority(0); 10318 return; 10319 } 10320 } 10321 10322 // find matching authorities subsets 10323 final Iterator<IntentFilter.AuthorityEntry> 10324 authoritiesIterator = intent.authoritiesIterator(); 10325 if (authoritiesIterator != null) { 10326 getIntentListSubset(intentListCopy, 10327 new AuthoritiesIterGenerator(), 10328 authoritiesIterator); 10329 if (intentListCopy.size() == 0) { 10330 // no more intents to match; we're not equivalent 10331 if (DEBUG_FILTERS) { 10332 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10333 + " package: " + applicationInfo.packageName 10334 + " activity: " + intent.activity.className 10335 + " origPrio: " + intent.getPriority()); 10336 } 10337 intent.setPriority(0); 10338 return; 10339 } 10340 } 10341 10342 // we found matching filter(s); app gets the max priority of all intents 10343 int cappedPriority = 0; 10344 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10345 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10346 } 10347 if (intent.getPriority() > cappedPriority) { 10348 if (DEBUG_FILTERS) { 10349 Slog.i(TAG, "Found matching filter(s);" 10350 + " cap priority to " + cappedPriority + ";" 10351 + " package: " + applicationInfo.packageName 10352 + " activity: " + intent.activity.className 10353 + " origPrio: " + intent.getPriority()); 10354 } 10355 intent.setPriority(cappedPriority); 10356 return; 10357 } 10358 // all this for nothing; the requested priority was <= what was on the system 10359 } 10360 10361 public final void addActivity(PackageParser.Activity a, String type) { 10362 mActivities.put(a.getComponentName(), a); 10363 if (DEBUG_SHOW_INFO) 10364 Log.v( 10365 TAG, " " + type + " " + 10366 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10367 if (DEBUG_SHOW_INFO) 10368 Log.v(TAG, " Class=" + a.info.name); 10369 final int NI = a.intents.size(); 10370 for (int j=0; j<NI; j++) { 10371 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10372 if ("activity".equals(type)) { 10373 final PackageSetting ps = 10374 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10375 final List<PackageParser.Activity> systemActivities = 10376 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10377 adjustPriority(systemActivities, intent); 10378 } 10379 if (DEBUG_SHOW_INFO) { 10380 Log.v(TAG, " IntentFilter:"); 10381 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10382 } 10383 if (!intent.debugCheck()) { 10384 Log.w(TAG, "==> For Activity " + a.info.name); 10385 } 10386 addFilter(intent); 10387 } 10388 } 10389 10390 public final void removeActivity(PackageParser.Activity a, String type) { 10391 mActivities.remove(a.getComponentName()); 10392 if (DEBUG_SHOW_INFO) { 10393 Log.v(TAG, " " + type + " " 10394 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10395 : a.info.name) + ":"); 10396 Log.v(TAG, " Class=" + a.info.name); 10397 } 10398 final int NI = a.intents.size(); 10399 for (int j=0; j<NI; j++) { 10400 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10401 if (DEBUG_SHOW_INFO) { 10402 Log.v(TAG, " IntentFilter:"); 10403 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10404 } 10405 removeFilter(intent); 10406 } 10407 } 10408 10409 @Override 10410 protected boolean allowFilterResult( 10411 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10412 ActivityInfo filterAi = filter.activity.info; 10413 for (int i=dest.size()-1; i>=0; i--) { 10414 ActivityInfo destAi = dest.get(i).activityInfo; 10415 if (destAi.name == filterAi.name 10416 && destAi.packageName == filterAi.packageName) { 10417 return false; 10418 } 10419 } 10420 return true; 10421 } 10422 10423 @Override 10424 protected ActivityIntentInfo[] newArray(int size) { 10425 return new ActivityIntentInfo[size]; 10426 } 10427 10428 @Override 10429 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10430 if (!sUserManager.exists(userId)) return true; 10431 PackageParser.Package p = filter.activity.owner; 10432 if (p != null) { 10433 PackageSetting ps = (PackageSetting)p.mExtras; 10434 if (ps != null) { 10435 // System apps are never considered stopped for purposes of 10436 // filtering, because there may be no way for the user to 10437 // actually re-launch them. 10438 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10439 && ps.getStopped(userId); 10440 } 10441 } 10442 return false; 10443 } 10444 10445 @Override 10446 protected boolean isPackageForFilter(String packageName, 10447 PackageParser.ActivityIntentInfo info) { 10448 return packageName.equals(info.activity.owner.packageName); 10449 } 10450 10451 @Override 10452 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10453 int match, int userId) { 10454 if (!sUserManager.exists(userId)) return null; 10455 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10456 return null; 10457 } 10458 final PackageParser.Activity activity = info.activity; 10459 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10460 if (ps == null) { 10461 return null; 10462 } 10463 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10464 ps.readUserState(userId), userId); 10465 if (ai == null) { 10466 return null; 10467 } 10468 final ResolveInfo res = new ResolveInfo(); 10469 res.activityInfo = ai; 10470 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10471 res.filter = info; 10472 } 10473 if (info != null) { 10474 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10475 } 10476 res.priority = info.getPriority(); 10477 res.preferredOrder = activity.owner.mPreferredOrder; 10478 //System.out.println("Result: " + res.activityInfo.className + 10479 // " = " + res.priority); 10480 res.match = match; 10481 res.isDefault = info.hasDefault; 10482 res.labelRes = info.labelRes; 10483 res.nonLocalizedLabel = info.nonLocalizedLabel; 10484 if (userNeedsBadging(userId)) { 10485 res.noResourceId = true; 10486 } else { 10487 res.icon = info.icon; 10488 } 10489 res.iconResourceId = info.icon; 10490 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10491 return res; 10492 } 10493 10494 @Override 10495 protected void sortResults(List<ResolveInfo> results) { 10496 Collections.sort(results, mResolvePrioritySorter); 10497 } 10498 10499 @Override 10500 protected void dumpFilter(PrintWriter out, String prefix, 10501 PackageParser.ActivityIntentInfo filter) { 10502 out.print(prefix); out.print( 10503 Integer.toHexString(System.identityHashCode(filter.activity))); 10504 out.print(' '); 10505 filter.activity.printComponentShortName(out); 10506 out.print(" filter "); 10507 out.println(Integer.toHexString(System.identityHashCode(filter))); 10508 } 10509 10510 @Override 10511 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10512 return filter.activity; 10513 } 10514 10515 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10516 PackageParser.Activity activity = (PackageParser.Activity)label; 10517 out.print(prefix); out.print( 10518 Integer.toHexString(System.identityHashCode(activity))); 10519 out.print(' '); 10520 activity.printComponentShortName(out); 10521 if (count > 1) { 10522 out.print(" ("); out.print(count); out.print(" filters)"); 10523 } 10524 out.println(); 10525 } 10526 10527 // Keys are String (activity class name), values are Activity. 10528 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10529 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10530 private int mFlags; 10531 } 10532 10533 private final class ServiceIntentResolver 10534 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10535 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10536 boolean defaultOnly, int userId) { 10537 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10538 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10539 } 10540 10541 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10542 int userId) { 10543 if (!sUserManager.exists(userId)) return null; 10544 mFlags = flags; 10545 return super.queryIntent(intent, resolvedType, 10546 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10547 } 10548 10549 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10550 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10551 if (!sUserManager.exists(userId)) return null; 10552 if (packageServices == null) { 10553 return null; 10554 } 10555 mFlags = flags; 10556 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10557 final int N = packageServices.size(); 10558 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10559 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10560 10561 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10562 for (int i = 0; i < N; ++i) { 10563 intentFilters = packageServices.get(i).intents; 10564 if (intentFilters != null && intentFilters.size() > 0) { 10565 PackageParser.ServiceIntentInfo[] array = 10566 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10567 intentFilters.toArray(array); 10568 listCut.add(array); 10569 } 10570 } 10571 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10572 } 10573 10574 public final void addService(PackageParser.Service s) { 10575 mServices.put(s.getComponentName(), s); 10576 if (DEBUG_SHOW_INFO) { 10577 Log.v(TAG, " " 10578 + (s.info.nonLocalizedLabel != null 10579 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10580 Log.v(TAG, " Class=" + s.info.name); 10581 } 10582 final int NI = s.intents.size(); 10583 int j; 10584 for (j=0; j<NI; j++) { 10585 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10586 if (DEBUG_SHOW_INFO) { 10587 Log.v(TAG, " IntentFilter:"); 10588 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10589 } 10590 if (!intent.debugCheck()) { 10591 Log.w(TAG, "==> For Service " + s.info.name); 10592 } 10593 addFilter(intent); 10594 } 10595 } 10596 10597 public final void removeService(PackageParser.Service s) { 10598 mServices.remove(s.getComponentName()); 10599 if (DEBUG_SHOW_INFO) { 10600 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10601 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10602 Log.v(TAG, " Class=" + s.info.name); 10603 } 10604 final int NI = s.intents.size(); 10605 int j; 10606 for (j=0; j<NI; j++) { 10607 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10608 if (DEBUG_SHOW_INFO) { 10609 Log.v(TAG, " IntentFilter:"); 10610 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10611 } 10612 removeFilter(intent); 10613 } 10614 } 10615 10616 @Override 10617 protected boolean allowFilterResult( 10618 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10619 ServiceInfo filterSi = filter.service.info; 10620 for (int i=dest.size()-1; i>=0; i--) { 10621 ServiceInfo destAi = dest.get(i).serviceInfo; 10622 if (destAi.name == filterSi.name 10623 && destAi.packageName == filterSi.packageName) { 10624 return false; 10625 } 10626 } 10627 return true; 10628 } 10629 10630 @Override 10631 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10632 return new PackageParser.ServiceIntentInfo[size]; 10633 } 10634 10635 @Override 10636 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10637 if (!sUserManager.exists(userId)) return true; 10638 PackageParser.Package p = filter.service.owner; 10639 if (p != null) { 10640 PackageSetting ps = (PackageSetting)p.mExtras; 10641 if (ps != null) { 10642 // System apps are never considered stopped for purposes of 10643 // filtering, because there may be no way for the user to 10644 // actually re-launch them. 10645 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10646 && ps.getStopped(userId); 10647 } 10648 } 10649 return false; 10650 } 10651 10652 @Override 10653 protected boolean isPackageForFilter(String packageName, 10654 PackageParser.ServiceIntentInfo info) { 10655 return packageName.equals(info.service.owner.packageName); 10656 } 10657 10658 @Override 10659 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10660 int match, int userId) { 10661 if (!sUserManager.exists(userId)) return null; 10662 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10663 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10664 return null; 10665 } 10666 final PackageParser.Service service = info.service; 10667 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10668 if (ps == null) { 10669 return null; 10670 } 10671 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10672 ps.readUserState(userId), userId); 10673 if (si == null) { 10674 return null; 10675 } 10676 final ResolveInfo res = new ResolveInfo(); 10677 res.serviceInfo = si; 10678 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10679 res.filter = filter; 10680 } 10681 res.priority = info.getPriority(); 10682 res.preferredOrder = service.owner.mPreferredOrder; 10683 res.match = match; 10684 res.isDefault = info.hasDefault; 10685 res.labelRes = info.labelRes; 10686 res.nonLocalizedLabel = info.nonLocalizedLabel; 10687 res.icon = info.icon; 10688 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10689 return res; 10690 } 10691 10692 @Override 10693 protected void sortResults(List<ResolveInfo> results) { 10694 Collections.sort(results, mResolvePrioritySorter); 10695 } 10696 10697 @Override 10698 protected void dumpFilter(PrintWriter out, String prefix, 10699 PackageParser.ServiceIntentInfo filter) { 10700 out.print(prefix); out.print( 10701 Integer.toHexString(System.identityHashCode(filter.service))); 10702 out.print(' '); 10703 filter.service.printComponentShortName(out); 10704 out.print(" filter "); 10705 out.println(Integer.toHexString(System.identityHashCode(filter))); 10706 } 10707 10708 @Override 10709 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10710 return filter.service; 10711 } 10712 10713 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10714 PackageParser.Service service = (PackageParser.Service)label; 10715 out.print(prefix); out.print( 10716 Integer.toHexString(System.identityHashCode(service))); 10717 out.print(' '); 10718 service.printComponentShortName(out); 10719 if (count > 1) { 10720 out.print(" ("); out.print(count); out.print(" filters)"); 10721 } 10722 out.println(); 10723 } 10724 10725// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10726// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10727// final List<ResolveInfo> retList = Lists.newArrayList(); 10728// while (i.hasNext()) { 10729// final ResolveInfo resolveInfo = (ResolveInfo) i; 10730// if (isEnabledLP(resolveInfo.serviceInfo)) { 10731// retList.add(resolveInfo); 10732// } 10733// } 10734// return retList; 10735// } 10736 10737 // Keys are String (activity class name), values are Activity. 10738 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10739 = new ArrayMap<ComponentName, PackageParser.Service>(); 10740 private int mFlags; 10741 }; 10742 10743 private final class ProviderIntentResolver 10744 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10745 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10746 boolean defaultOnly, int userId) { 10747 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10748 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10749 } 10750 10751 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10752 int userId) { 10753 if (!sUserManager.exists(userId)) 10754 return null; 10755 mFlags = flags; 10756 return super.queryIntent(intent, resolvedType, 10757 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10758 } 10759 10760 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10761 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10762 if (!sUserManager.exists(userId)) 10763 return null; 10764 if (packageProviders == null) { 10765 return null; 10766 } 10767 mFlags = flags; 10768 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10769 final int N = packageProviders.size(); 10770 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10771 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10772 10773 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10774 for (int i = 0; i < N; ++i) { 10775 intentFilters = packageProviders.get(i).intents; 10776 if (intentFilters != null && intentFilters.size() > 0) { 10777 PackageParser.ProviderIntentInfo[] array = 10778 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10779 intentFilters.toArray(array); 10780 listCut.add(array); 10781 } 10782 } 10783 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10784 } 10785 10786 public final void addProvider(PackageParser.Provider p) { 10787 if (mProviders.containsKey(p.getComponentName())) { 10788 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10789 return; 10790 } 10791 10792 mProviders.put(p.getComponentName(), p); 10793 if (DEBUG_SHOW_INFO) { 10794 Log.v(TAG, " " 10795 + (p.info.nonLocalizedLabel != null 10796 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10797 Log.v(TAG, " Class=" + p.info.name); 10798 } 10799 final int NI = p.intents.size(); 10800 int j; 10801 for (j = 0; j < NI; j++) { 10802 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10803 if (DEBUG_SHOW_INFO) { 10804 Log.v(TAG, " IntentFilter:"); 10805 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10806 } 10807 if (!intent.debugCheck()) { 10808 Log.w(TAG, "==> For Provider " + p.info.name); 10809 } 10810 addFilter(intent); 10811 } 10812 } 10813 10814 public final void removeProvider(PackageParser.Provider p) { 10815 mProviders.remove(p.getComponentName()); 10816 if (DEBUG_SHOW_INFO) { 10817 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10818 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10819 Log.v(TAG, " Class=" + p.info.name); 10820 } 10821 final int NI = p.intents.size(); 10822 int j; 10823 for (j = 0; j < NI; j++) { 10824 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10825 if (DEBUG_SHOW_INFO) { 10826 Log.v(TAG, " IntentFilter:"); 10827 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10828 } 10829 removeFilter(intent); 10830 } 10831 } 10832 10833 @Override 10834 protected boolean allowFilterResult( 10835 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10836 ProviderInfo filterPi = filter.provider.info; 10837 for (int i = dest.size() - 1; i >= 0; i--) { 10838 ProviderInfo destPi = dest.get(i).providerInfo; 10839 if (destPi.name == filterPi.name 10840 && destPi.packageName == filterPi.packageName) { 10841 return false; 10842 } 10843 } 10844 return true; 10845 } 10846 10847 @Override 10848 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10849 return new PackageParser.ProviderIntentInfo[size]; 10850 } 10851 10852 @Override 10853 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10854 if (!sUserManager.exists(userId)) 10855 return true; 10856 PackageParser.Package p = filter.provider.owner; 10857 if (p != null) { 10858 PackageSetting ps = (PackageSetting) p.mExtras; 10859 if (ps != null) { 10860 // System apps are never considered stopped for purposes of 10861 // filtering, because there may be no way for the user to 10862 // actually re-launch them. 10863 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10864 && ps.getStopped(userId); 10865 } 10866 } 10867 return false; 10868 } 10869 10870 @Override 10871 protected boolean isPackageForFilter(String packageName, 10872 PackageParser.ProviderIntentInfo info) { 10873 return packageName.equals(info.provider.owner.packageName); 10874 } 10875 10876 @Override 10877 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10878 int match, int userId) { 10879 if (!sUserManager.exists(userId)) 10880 return null; 10881 final PackageParser.ProviderIntentInfo info = filter; 10882 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10883 return null; 10884 } 10885 final PackageParser.Provider provider = info.provider; 10886 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10887 if (ps == null) { 10888 return null; 10889 } 10890 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10891 ps.readUserState(userId), userId); 10892 if (pi == null) { 10893 return null; 10894 } 10895 final ResolveInfo res = new ResolveInfo(); 10896 res.providerInfo = pi; 10897 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10898 res.filter = filter; 10899 } 10900 res.priority = info.getPriority(); 10901 res.preferredOrder = provider.owner.mPreferredOrder; 10902 res.match = match; 10903 res.isDefault = info.hasDefault; 10904 res.labelRes = info.labelRes; 10905 res.nonLocalizedLabel = info.nonLocalizedLabel; 10906 res.icon = info.icon; 10907 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10908 return res; 10909 } 10910 10911 @Override 10912 protected void sortResults(List<ResolveInfo> results) { 10913 Collections.sort(results, mResolvePrioritySorter); 10914 } 10915 10916 @Override 10917 protected void dumpFilter(PrintWriter out, String prefix, 10918 PackageParser.ProviderIntentInfo filter) { 10919 out.print(prefix); 10920 out.print( 10921 Integer.toHexString(System.identityHashCode(filter.provider))); 10922 out.print(' '); 10923 filter.provider.printComponentShortName(out); 10924 out.print(" filter "); 10925 out.println(Integer.toHexString(System.identityHashCode(filter))); 10926 } 10927 10928 @Override 10929 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10930 return filter.provider; 10931 } 10932 10933 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10934 PackageParser.Provider provider = (PackageParser.Provider)label; 10935 out.print(prefix); out.print( 10936 Integer.toHexString(System.identityHashCode(provider))); 10937 out.print(' '); 10938 provider.printComponentShortName(out); 10939 if (count > 1) { 10940 out.print(" ("); out.print(count); out.print(" filters)"); 10941 } 10942 out.println(); 10943 } 10944 10945 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10946 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10947 private int mFlags; 10948 } 10949 10950 private static final class EphemeralIntentResolver 10951 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10952 @Override 10953 protected EphemeralResolveIntentInfo[] newArray(int size) { 10954 return new EphemeralResolveIntentInfo[size]; 10955 } 10956 10957 @Override 10958 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10959 return true; 10960 } 10961 10962 @Override 10963 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10964 int userId) { 10965 if (!sUserManager.exists(userId)) { 10966 return null; 10967 } 10968 return info.getEphemeralResolveInfo(); 10969 } 10970 } 10971 10972 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10973 new Comparator<ResolveInfo>() { 10974 public int compare(ResolveInfo r1, ResolveInfo r2) { 10975 int v1 = r1.priority; 10976 int v2 = r2.priority; 10977 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10978 if (v1 != v2) { 10979 return (v1 > v2) ? -1 : 1; 10980 } 10981 v1 = r1.preferredOrder; 10982 v2 = r2.preferredOrder; 10983 if (v1 != v2) { 10984 return (v1 > v2) ? -1 : 1; 10985 } 10986 if (r1.isDefault != r2.isDefault) { 10987 return r1.isDefault ? -1 : 1; 10988 } 10989 v1 = r1.match; 10990 v2 = r2.match; 10991 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10992 if (v1 != v2) { 10993 return (v1 > v2) ? -1 : 1; 10994 } 10995 if (r1.system != r2.system) { 10996 return r1.system ? -1 : 1; 10997 } 10998 if (r1.activityInfo != null) { 10999 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11000 } 11001 if (r1.serviceInfo != null) { 11002 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11003 } 11004 if (r1.providerInfo != null) { 11005 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11006 } 11007 return 0; 11008 } 11009 }; 11010 11011 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11012 new Comparator<ProviderInfo>() { 11013 public int compare(ProviderInfo p1, ProviderInfo p2) { 11014 final int v1 = p1.initOrder; 11015 final int v2 = p2.initOrder; 11016 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11017 } 11018 }; 11019 11020 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11021 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11022 final int[] userIds) { 11023 mHandler.post(new Runnable() { 11024 @Override 11025 public void run() { 11026 try { 11027 final IActivityManager am = ActivityManagerNative.getDefault(); 11028 if (am == null) return; 11029 final int[] resolvedUserIds; 11030 if (userIds == null) { 11031 resolvedUserIds = am.getRunningUserIds(); 11032 } else { 11033 resolvedUserIds = userIds; 11034 } 11035 for (int id : resolvedUserIds) { 11036 final Intent intent = new Intent(action, 11037 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11038 if (extras != null) { 11039 intent.putExtras(extras); 11040 } 11041 if (targetPkg != null) { 11042 intent.setPackage(targetPkg); 11043 } 11044 // Modify the UID when posting to other users 11045 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11046 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11047 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11048 intent.putExtra(Intent.EXTRA_UID, uid); 11049 } 11050 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11051 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11052 if (DEBUG_BROADCASTS) { 11053 RuntimeException here = new RuntimeException("here"); 11054 here.fillInStackTrace(); 11055 Slog.d(TAG, "Sending to user " + id + ": " 11056 + intent.toShortString(false, true, false, false) 11057 + " " + intent.getExtras(), here); 11058 } 11059 am.broadcastIntent(null, intent, null, finishedReceiver, 11060 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11061 null, finishedReceiver != null, false, id); 11062 } 11063 } catch (RemoteException ex) { 11064 } 11065 } 11066 }); 11067 } 11068 11069 /** 11070 * Check if the external storage media is available. This is true if there 11071 * is a mounted external storage medium or if the external storage is 11072 * emulated. 11073 */ 11074 private boolean isExternalMediaAvailable() { 11075 return mMediaMounted || Environment.isExternalStorageEmulated(); 11076 } 11077 11078 @Override 11079 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11080 // writer 11081 synchronized (mPackages) { 11082 if (!isExternalMediaAvailable()) { 11083 // If the external storage is no longer mounted at this point, 11084 // the caller may not have been able to delete all of this 11085 // packages files and can not delete any more. Bail. 11086 return null; 11087 } 11088 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11089 if (lastPackage != null) { 11090 pkgs.remove(lastPackage); 11091 } 11092 if (pkgs.size() > 0) { 11093 return pkgs.get(0); 11094 } 11095 } 11096 return null; 11097 } 11098 11099 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11100 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11101 userId, andCode ? 1 : 0, packageName); 11102 if (mSystemReady) { 11103 msg.sendToTarget(); 11104 } else { 11105 if (mPostSystemReadyMessages == null) { 11106 mPostSystemReadyMessages = new ArrayList<>(); 11107 } 11108 mPostSystemReadyMessages.add(msg); 11109 } 11110 } 11111 11112 void startCleaningPackages() { 11113 // reader 11114 if (!isExternalMediaAvailable()) { 11115 return; 11116 } 11117 synchronized (mPackages) { 11118 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11119 return; 11120 } 11121 } 11122 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11123 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11124 IActivityManager am = ActivityManagerNative.getDefault(); 11125 if (am != null) { 11126 try { 11127 am.startService(null, intent, null, mContext.getOpPackageName(), 11128 UserHandle.USER_SYSTEM); 11129 } catch (RemoteException e) { 11130 } 11131 } 11132 } 11133 11134 @Override 11135 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11136 int installFlags, String installerPackageName, int userId) { 11137 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11138 11139 final int callingUid = Binder.getCallingUid(); 11140 enforceCrossUserPermission(callingUid, userId, 11141 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11142 11143 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11144 try { 11145 if (observer != null) { 11146 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11147 } 11148 } catch (RemoteException re) { 11149 } 11150 return; 11151 } 11152 11153 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11154 installFlags |= PackageManager.INSTALL_FROM_ADB; 11155 11156 } else { 11157 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11158 // about installerPackageName. 11159 11160 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11161 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11162 } 11163 11164 UserHandle user; 11165 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11166 user = UserHandle.ALL; 11167 } else { 11168 user = new UserHandle(userId); 11169 } 11170 11171 // Only system components can circumvent runtime permissions when installing. 11172 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11173 && mContext.checkCallingOrSelfPermission(Manifest.permission 11174 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11175 throw new SecurityException("You need the " 11176 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11177 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11178 } 11179 11180 final File originFile = new File(originPath); 11181 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11182 11183 final Message msg = mHandler.obtainMessage(INIT_COPY); 11184 final VerificationInfo verificationInfo = new VerificationInfo( 11185 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11186 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11187 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11188 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11189 null /*certificates*/); 11190 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11191 msg.obj = params; 11192 11193 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11194 System.identityHashCode(msg.obj)); 11195 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11196 System.identityHashCode(msg.obj)); 11197 11198 mHandler.sendMessage(msg); 11199 } 11200 11201 void installStage(String packageName, File stagedDir, String stagedCid, 11202 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11203 String installerPackageName, int installerUid, UserHandle user, 11204 Certificate[][] certificates) { 11205 if (DEBUG_EPHEMERAL) { 11206 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11207 Slog.d(TAG, "Ephemeral install of " + packageName); 11208 } 11209 } 11210 final VerificationInfo verificationInfo = new VerificationInfo( 11211 sessionParams.originatingUri, sessionParams.referrerUri, 11212 sessionParams.originatingUid, installerUid); 11213 11214 final OriginInfo origin; 11215 if (stagedDir != null) { 11216 origin = OriginInfo.fromStagedFile(stagedDir); 11217 } else { 11218 origin = OriginInfo.fromStagedContainer(stagedCid); 11219 } 11220 11221 final Message msg = mHandler.obtainMessage(INIT_COPY); 11222 final InstallParams params = new InstallParams(origin, null, observer, 11223 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11224 verificationInfo, user, sessionParams.abiOverride, 11225 sessionParams.grantedRuntimePermissions, certificates); 11226 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11227 msg.obj = params; 11228 11229 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11230 System.identityHashCode(msg.obj)); 11231 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11232 System.identityHashCode(msg.obj)); 11233 11234 mHandler.sendMessage(msg); 11235 } 11236 11237 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11238 int userId) { 11239 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11240 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11241 } 11242 11243 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11244 int appId, int userId) { 11245 Bundle extras = new Bundle(1); 11246 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11247 11248 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11249 packageName, extras, 0, null, null, new int[] {userId}); 11250 try { 11251 IActivityManager am = ActivityManagerNative.getDefault(); 11252 if (isSystem && am.isUserRunning(userId, 0)) { 11253 // The just-installed/enabled app is bundled on the system, so presumed 11254 // to be able to run automatically without needing an explicit launch. 11255 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11256 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11257 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11258 .setPackage(packageName); 11259 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11260 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11261 } 11262 } catch (RemoteException e) { 11263 // shouldn't happen 11264 Slog.w(TAG, "Unable to bootstrap installed package", e); 11265 } 11266 } 11267 11268 @Override 11269 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11270 int userId) { 11271 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11272 PackageSetting pkgSetting; 11273 final int uid = Binder.getCallingUid(); 11274 enforceCrossUserPermission(uid, userId, 11275 true /* requireFullPermission */, true /* checkShell */, 11276 "setApplicationHiddenSetting for user " + userId); 11277 11278 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11279 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11280 return false; 11281 } 11282 11283 long callingId = Binder.clearCallingIdentity(); 11284 try { 11285 boolean sendAdded = false; 11286 boolean sendRemoved = false; 11287 // writer 11288 synchronized (mPackages) { 11289 pkgSetting = mSettings.mPackages.get(packageName); 11290 if (pkgSetting == null) { 11291 return false; 11292 } 11293 if (pkgSetting.getHidden(userId) != hidden) { 11294 pkgSetting.setHidden(hidden, userId); 11295 mSettings.writePackageRestrictionsLPr(userId); 11296 if (hidden) { 11297 sendRemoved = true; 11298 } else { 11299 sendAdded = true; 11300 } 11301 } 11302 } 11303 if (sendAdded) { 11304 sendPackageAddedForUser(packageName, pkgSetting, userId); 11305 return true; 11306 } 11307 if (sendRemoved) { 11308 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11309 "hiding pkg"); 11310 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11311 return true; 11312 } 11313 } finally { 11314 Binder.restoreCallingIdentity(callingId); 11315 } 11316 return false; 11317 } 11318 11319 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11320 int userId) { 11321 final PackageRemovedInfo info = new PackageRemovedInfo(); 11322 info.removedPackage = packageName; 11323 info.removedUsers = new int[] {userId}; 11324 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11325 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11326 } 11327 11328 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11329 if (pkgList.length > 0) { 11330 Bundle extras = new Bundle(1); 11331 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11332 11333 sendPackageBroadcast( 11334 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11335 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11336 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11337 new int[] {userId}); 11338 } 11339 } 11340 11341 /** 11342 * Returns true if application is not found or there was an error. Otherwise it returns 11343 * the hidden state of the package for the given user. 11344 */ 11345 @Override 11346 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11347 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11348 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11349 true /* requireFullPermission */, false /* checkShell */, 11350 "getApplicationHidden for user " + userId); 11351 PackageSetting pkgSetting; 11352 long callingId = Binder.clearCallingIdentity(); 11353 try { 11354 // writer 11355 synchronized (mPackages) { 11356 pkgSetting = mSettings.mPackages.get(packageName); 11357 if (pkgSetting == null) { 11358 return true; 11359 } 11360 return pkgSetting.getHidden(userId); 11361 } 11362 } finally { 11363 Binder.restoreCallingIdentity(callingId); 11364 } 11365 } 11366 11367 /** 11368 * @hide 11369 */ 11370 @Override 11371 public int installExistingPackageAsUser(String packageName, int userId) { 11372 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11373 null); 11374 PackageSetting pkgSetting; 11375 final int uid = Binder.getCallingUid(); 11376 enforceCrossUserPermission(uid, userId, 11377 true /* requireFullPermission */, true /* checkShell */, 11378 "installExistingPackage for user " + userId); 11379 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11380 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11381 } 11382 11383 long callingId = Binder.clearCallingIdentity(); 11384 try { 11385 boolean installed = false; 11386 11387 // writer 11388 synchronized (mPackages) { 11389 pkgSetting = mSettings.mPackages.get(packageName); 11390 if (pkgSetting == null) { 11391 return PackageManager.INSTALL_FAILED_INVALID_URI; 11392 } 11393 if (!pkgSetting.getInstalled(userId)) { 11394 pkgSetting.setInstalled(true, userId); 11395 pkgSetting.setHidden(false, userId); 11396 mSettings.writePackageRestrictionsLPr(userId); 11397 installed = true; 11398 } 11399 } 11400 11401 if (installed) { 11402 if (pkgSetting.pkg != null) { 11403 synchronized (mInstallLock) { 11404 // We don't need to freeze for a brand new install 11405 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11406 } 11407 } 11408 sendPackageAddedForUser(packageName, pkgSetting, userId); 11409 } 11410 } finally { 11411 Binder.restoreCallingIdentity(callingId); 11412 } 11413 11414 return PackageManager.INSTALL_SUCCEEDED; 11415 } 11416 11417 boolean isUserRestricted(int userId, String restrictionKey) { 11418 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11419 if (restrictions.getBoolean(restrictionKey, false)) { 11420 Log.w(TAG, "User is restricted: " + restrictionKey); 11421 return true; 11422 } 11423 return false; 11424 } 11425 11426 @Override 11427 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11428 int userId) { 11429 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11430 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11431 true /* requireFullPermission */, true /* checkShell */, 11432 "setPackagesSuspended for user " + userId); 11433 11434 if (ArrayUtils.isEmpty(packageNames)) { 11435 return packageNames; 11436 } 11437 11438 // List of package names for whom the suspended state has changed. 11439 List<String> changedPackages = new ArrayList<>(packageNames.length); 11440 // List of package names for whom the suspended state is not set as requested in this 11441 // method. 11442 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11443 long callingId = Binder.clearCallingIdentity(); 11444 try { 11445 for (int i = 0; i < packageNames.length; i++) { 11446 String packageName = packageNames[i]; 11447 boolean changed = false; 11448 final int appId; 11449 synchronized (mPackages) { 11450 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11451 if (pkgSetting == null) { 11452 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11453 + "\". Skipping suspending/un-suspending."); 11454 unactionedPackages.add(packageName); 11455 continue; 11456 } 11457 appId = pkgSetting.appId; 11458 if (pkgSetting.getSuspended(userId) != suspended) { 11459 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11460 unactionedPackages.add(packageName); 11461 continue; 11462 } 11463 pkgSetting.setSuspended(suspended, userId); 11464 mSettings.writePackageRestrictionsLPr(userId); 11465 changed = true; 11466 changedPackages.add(packageName); 11467 } 11468 } 11469 11470 if (changed && suspended) { 11471 killApplication(packageName, UserHandle.getUid(userId, appId), 11472 "suspending package"); 11473 } 11474 } 11475 } finally { 11476 Binder.restoreCallingIdentity(callingId); 11477 } 11478 11479 if (!changedPackages.isEmpty()) { 11480 sendPackagesSuspendedForUser(changedPackages.toArray( 11481 new String[changedPackages.size()]), userId, suspended); 11482 } 11483 11484 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11485 } 11486 11487 @Override 11488 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11489 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11490 true /* requireFullPermission */, false /* checkShell */, 11491 "isPackageSuspendedForUser for user " + userId); 11492 synchronized (mPackages) { 11493 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11494 if (pkgSetting == null) { 11495 throw new IllegalArgumentException("Unknown target package: " + packageName); 11496 } 11497 return pkgSetting.getSuspended(userId); 11498 } 11499 } 11500 11501 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11502 if (isPackageDeviceAdmin(packageName, userId)) { 11503 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11504 + "\": has an active device admin"); 11505 return false; 11506 } 11507 11508 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11509 if (packageName.equals(activeLauncherPackageName)) { 11510 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11511 + "\": contains the active launcher"); 11512 return false; 11513 } 11514 11515 if (packageName.equals(mRequiredInstallerPackage)) { 11516 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11517 + "\": required for package installation"); 11518 return false; 11519 } 11520 11521 if (packageName.equals(mRequiredVerifierPackage)) { 11522 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11523 + "\": required for package verification"); 11524 return false; 11525 } 11526 11527 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11528 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11529 + "\": is the default dialer"); 11530 return false; 11531 } 11532 11533 return true; 11534 } 11535 11536 private String getActiveLauncherPackageName(int userId) { 11537 Intent intent = new Intent(Intent.ACTION_MAIN); 11538 intent.addCategory(Intent.CATEGORY_HOME); 11539 ResolveInfo resolveInfo = resolveIntent( 11540 intent, 11541 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11542 PackageManager.MATCH_DEFAULT_ONLY, 11543 userId); 11544 11545 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11546 } 11547 11548 private String getDefaultDialerPackageName(int userId) { 11549 synchronized (mPackages) { 11550 return mSettings.getDefaultDialerPackageNameLPw(userId); 11551 } 11552 } 11553 11554 @Override 11555 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11556 mContext.enforceCallingOrSelfPermission( 11557 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11558 "Only package verification agents can verify applications"); 11559 11560 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11561 final PackageVerificationResponse response = new PackageVerificationResponse( 11562 verificationCode, Binder.getCallingUid()); 11563 msg.arg1 = id; 11564 msg.obj = response; 11565 mHandler.sendMessage(msg); 11566 } 11567 11568 @Override 11569 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11570 long millisecondsToDelay) { 11571 mContext.enforceCallingOrSelfPermission( 11572 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11573 "Only package verification agents can extend verification timeouts"); 11574 11575 final PackageVerificationState state = mPendingVerification.get(id); 11576 final PackageVerificationResponse response = new PackageVerificationResponse( 11577 verificationCodeAtTimeout, Binder.getCallingUid()); 11578 11579 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11580 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11581 } 11582 if (millisecondsToDelay < 0) { 11583 millisecondsToDelay = 0; 11584 } 11585 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11586 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11587 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11588 } 11589 11590 if ((state != null) && !state.timeoutExtended()) { 11591 state.extendTimeout(); 11592 11593 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11594 msg.arg1 = id; 11595 msg.obj = response; 11596 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11597 } 11598 } 11599 11600 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11601 int verificationCode, UserHandle user) { 11602 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11603 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11604 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11605 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11606 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11607 11608 mContext.sendBroadcastAsUser(intent, user, 11609 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11610 } 11611 11612 private ComponentName matchComponentForVerifier(String packageName, 11613 List<ResolveInfo> receivers) { 11614 ActivityInfo targetReceiver = null; 11615 11616 final int NR = receivers.size(); 11617 for (int i = 0; i < NR; i++) { 11618 final ResolveInfo info = receivers.get(i); 11619 if (info.activityInfo == null) { 11620 continue; 11621 } 11622 11623 if (packageName.equals(info.activityInfo.packageName)) { 11624 targetReceiver = info.activityInfo; 11625 break; 11626 } 11627 } 11628 11629 if (targetReceiver == null) { 11630 return null; 11631 } 11632 11633 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11634 } 11635 11636 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11637 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11638 if (pkgInfo.verifiers.length == 0) { 11639 return null; 11640 } 11641 11642 final int N = pkgInfo.verifiers.length; 11643 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11644 for (int i = 0; i < N; i++) { 11645 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11646 11647 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11648 receivers); 11649 if (comp == null) { 11650 continue; 11651 } 11652 11653 final int verifierUid = getUidForVerifier(verifierInfo); 11654 if (verifierUid == -1) { 11655 continue; 11656 } 11657 11658 if (DEBUG_VERIFY) { 11659 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11660 + " with the correct signature"); 11661 } 11662 sufficientVerifiers.add(comp); 11663 verificationState.addSufficientVerifier(verifierUid); 11664 } 11665 11666 return sufficientVerifiers; 11667 } 11668 11669 private int getUidForVerifier(VerifierInfo verifierInfo) { 11670 synchronized (mPackages) { 11671 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11672 if (pkg == null) { 11673 return -1; 11674 } else if (pkg.mSignatures.length != 1) { 11675 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11676 + " has more than one signature; ignoring"); 11677 return -1; 11678 } 11679 11680 /* 11681 * If the public key of the package's signature does not match 11682 * our expected public key, then this is a different package and 11683 * we should skip. 11684 */ 11685 11686 final byte[] expectedPublicKey; 11687 try { 11688 final Signature verifierSig = pkg.mSignatures[0]; 11689 final PublicKey publicKey = verifierSig.getPublicKey(); 11690 expectedPublicKey = publicKey.getEncoded(); 11691 } catch (CertificateException e) { 11692 return -1; 11693 } 11694 11695 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11696 11697 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11698 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11699 + " does not have the expected public key; ignoring"); 11700 return -1; 11701 } 11702 11703 return pkg.applicationInfo.uid; 11704 } 11705 } 11706 11707 @Override 11708 public void finishPackageInstall(int token, boolean didLaunch) { 11709 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11710 11711 if (DEBUG_INSTALL) { 11712 Slog.v(TAG, "BM finishing package install for " + token); 11713 } 11714 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11715 11716 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11717 mHandler.sendMessage(msg); 11718 } 11719 11720 /** 11721 * Get the verification agent timeout. 11722 * 11723 * @return verification timeout in milliseconds 11724 */ 11725 private long getVerificationTimeout() { 11726 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11727 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11728 DEFAULT_VERIFICATION_TIMEOUT); 11729 } 11730 11731 /** 11732 * Get the default verification agent response code. 11733 * 11734 * @return default verification response code 11735 */ 11736 private int getDefaultVerificationResponse() { 11737 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11738 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11739 DEFAULT_VERIFICATION_RESPONSE); 11740 } 11741 11742 /** 11743 * Check whether or not package verification has been enabled. 11744 * 11745 * @return true if verification should be performed 11746 */ 11747 private boolean isVerificationEnabled(int userId, int installFlags) { 11748 if (!DEFAULT_VERIFY_ENABLE) { 11749 return false; 11750 } 11751 // Ephemeral apps don't get the full verification treatment 11752 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11753 if (DEBUG_EPHEMERAL) { 11754 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11755 } 11756 return false; 11757 } 11758 11759 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11760 11761 // Check if installing from ADB 11762 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11763 // Do not run verification in a test harness environment 11764 if (ActivityManager.isRunningInTestHarness()) { 11765 return false; 11766 } 11767 if (ensureVerifyAppsEnabled) { 11768 return true; 11769 } 11770 // Check if the developer does not want package verification for ADB installs 11771 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11772 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11773 return false; 11774 } 11775 } 11776 11777 if (ensureVerifyAppsEnabled) { 11778 return true; 11779 } 11780 11781 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11782 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11783 } 11784 11785 @Override 11786 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11787 throws RemoteException { 11788 mContext.enforceCallingOrSelfPermission( 11789 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11790 "Only intentfilter verification agents can verify applications"); 11791 11792 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11793 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11794 Binder.getCallingUid(), verificationCode, failedDomains); 11795 msg.arg1 = id; 11796 msg.obj = response; 11797 mHandler.sendMessage(msg); 11798 } 11799 11800 @Override 11801 public int getIntentVerificationStatus(String packageName, int userId) { 11802 synchronized (mPackages) { 11803 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11804 } 11805 } 11806 11807 @Override 11808 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11809 mContext.enforceCallingOrSelfPermission( 11810 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11811 11812 boolean result = false; 11813 synchronized (mPackages) { 11814 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11815 } 11816 if (result) { 11817 scheduleWritePackageRestrictionsLocked(userId); 11818 } 11819 return result; 11820 } 11821 11822 @Override 11823 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11824 String packageName) { 11825 synchronized (mPackages) { 11826 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11827 } 11828 } 11829 11830 @Override 11831 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11832 if (TextUtils.isEmpty(packageName)) { 11833 return ParceledListSlice.emptyList(); 11834 } 11835 synchronized (mPackages) { 11836 PackageParser.Package pkg = mPackages.get(packageName); 11837 if (pkg == null || pkg.activities == null) { 11838 return ParceledListSlice.emptyList(); 11839 } 11840 final int count = pkg.activities.size(); 11841 ArrayList<IntentFilter> result = new ArrayList<>(); 11842 for (int n=0; n<count; n++) { 11843 PackageParser.Activity activity = pkg.activities.get(n); 11844 if (activity.intents != null && activity.intents.size() > 0) { 11845 result.addAll(activity.intents); 11846 } 11847 } 11848 return new ParceledListSlice<>(result); 11849 } 11850 } 11851 11852 @Override 11853 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11854 mContext.enforceCallingOrSelfPermission( 11855 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11856 11857 synchronized (mPackages) { 11858 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11859 if (packageName != null) { 11860 result |= updateIntentVerificationStatus(packageName, 11861 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11862 userId); 11863 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11864 packageName, userId); 11865 } 11866 return result; 11867 } 11868 } 11869 11870 @Override 11871 public String getDefaultBrowserPackageName(int userId) { 11872 synchronized (mPackages) { 11873 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11874 } 11875 } 11876 11877 /** 11878 * Get the "allow unknown sources" setting. 11879 * 11880 * @return the current "allow unknown sources" setting 11881 */ 11882 private int getUnknownSourcesSettings() { 11883 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11884 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11885 -1); 11886 } 11887 11888 @Override 11889 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11890 final int uid = Binder.getCallingUid(); 11891 // writer 11892 synchronized (mPackages) { 11893 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11894 if (targetPackageSetting == null) { 11895 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11896 } 11897 11898 PackageSetting installerPackageSetting; 11899 if (installerPackageName != null) { 11900 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11901 if (installerPackageSetting == null) { 11902 throw new IllegalArgumentException("Unknown installer package: " 11903 + installerPackageName); 11904 } 11905 } else { 11906 installerPackageSetting = null; 11907 } 11908 11909 Signature[] callerSignature; 11910 Object obj = mSettings.getUserIdLPr(uid); 11911 if (obj != null) { 11912 if (obj instanceof SharedUserSetting) { 11913 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11914 } else if (obj instanceof PackageSetting) { 11915 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11916 } else { 11917 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11918 } 11919 } else { 11920 throw new SecurityException("Unknown calling UID: " + uid); 11921 } 11922 11923 // Verify: can't set installerPackageName to a package that is 11924 // not signed with the same cert as the caller. 11925 if (installerPackageSetting != null) { 11926 if (compareSignatures(callerSignature, 11927 installerPackageSetting.signatures.mSignatures) 11928 != PackageManager.SIGNATURE_MATCH) { 11929 throw new SecurityException( 11930 "Caller does not have same cert as new installer package " 11931 + installerPackageName); 11932 } 11933 } 11934 11935 // Verify: if target already has an installer package, it must 11936 // be signed with the same cert as the caller. 11937 if (targetPackageSetting.installerPackageName != null) { 11938 PackageSetting setting = mSettings.mPackages.get( 11939 targetPackageSetting.installerPackageName); 11940 // If the currently set package isn't valid, then it's always 11941 // okay to change it. 11942 if (setting != null) { 11943 if (compareSignatures(callerSignature, 11944 setting.signatures.mSignatures) 11945 != PackageManager.SIGNATURE_MATCH) { 11946 throw new SecurityException( 11947 "Caller does not have same cert as old installer package " 11948 + targetPackageSetting.installerPackageName); 11949 } 11950 } 11951 } 11952 11953 // Okay! 11954 targetPackageSetting.installerPackageName = installerPackageName; 11955 if (installerPackageName != null) { 11956 mSettings.mInstallerPackages.add(installerPackageName); 11957 } 11958 scheduleWriteSettingsLocked(); 11959 } 11960 } 11961 11962 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11963 // Queue up an async operation since the package installation may take a little while. 11964 mHandler.post(new Runnable() { 11965 public void run() { 11966 mHandler.removeCallbacks(this); 11967 // Result object to be returned 11968 PackageInstalledInfo res = new PackageInstalledInfo(); 11969 res.setReturnCode(currentStatus); 11970 res.uid = -1; 11971 res.pkg = null; 11972 res.removedInfo = null; 11973 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11974 args.doPreInstall(res.returnCode); 11975 synchronized (mInstallLock) { 11976 installPackageTracedLI(args, res); 11977 } 11978 args.doPostInstall(res.returnCode, res.uid); 11979 } 11980 11981 // A restore should be performed at this point if (a) the install 11982 // succeeded, (b) the operation is not an update, and (c) the new 11983 // package has not opted out of backup participation. 11984 final boolean update = res.removedInfo != null 11985 && res.removedInfo.removedPackage != null; 11986 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11987 boolean doRestore = !update 11988 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11989 11990 // Set up the post-install work request bookkeeping. This will be used 11991 // and cleaned up by the post-install event handling regardless of whether 11992 // there's a restore pass performed. Token values are >= 1. 11993 int token; 11994 if (mNextInstallToken < 0) mNextInstallToken = 1; 11995 token = mNextInstallToken++; 11996 11997 PostInstallData data = new PostInstallData(args, res); 11998 mRunningInstalls.put(token, data); 11999 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12000 12001 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12002 // Pass responsibility to the Backup Manager. It will perform a 12003 // restore if appropriate, then pass responsibility back to the 12004 // Package Manager to run the post-install observer callbacks 12005 // and broadcasts. 12006 IBackupManager bm = IBackupManager.Stub.asInterface( 12007 ServiceManager.getService(Context.BACKUP_SERVICE)); 12008 if (bm != null) { 12009 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12010 + " to BM for possible restore"); 12011 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12012 try { 12013 // TODO: http://b/22388012 12014 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12015 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12016 } else { 12017 doRestore = false; 12018 } 12019 } catch (RemoteException e) { 12020 // can't happen; the backup manager is local 12021 } catch (Exception e) { 12022 Slog.e(TAG, "Exception trying to enqueue restore", e); 12023 doRestore = false; 12024 } 12025 } else { 12026 Slog.e(TAG, "Backup Manager not found!"); 12027 doRestore = false; 12028 } 12029 } 12030 12031 if (!doRestore) { 12032 // No restore possible, or the Backup Manager was mysteriously not 12033 // available -- just fire the post-install work request directly. 12034 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12035 12036 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12037 12038 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12039 mHandler.sendMessage(msg); 12040 } 12041 } 12042 }); 12043 } 12044 12045 /** 12046 * Callback from PackageSettings whenever an app is first transitioned out of the 12047 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12048 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12049 * here whether the app is the target of an ongoing install, and only send the 12050 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12051 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12052 * handling. 12053 */ 12054 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12055 // Serialize this with the rest of the install-process message chain. In the 12056 // restore-at-install case, this Runnable will necessarily run before the 12057 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12058 // are coherent. In the non-restore case, the app has already completed install 12059 // and been launched through some other means, so it is not in a problematic 12060 // state for observers to see the FIRST_LAUNCH signal. 12061 mHandler.post(new Runnable() { 12062 @Override 12063 public void run() { 12064 for (int i = 0; i < mRunningInstalls.size(); i++) { 12065 final PostInstallData data = mRunningInstalls.valueAt(i); 12066 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12067 // right package; but is it for the right user? 12068 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12069 if (userId == data.res.newUsers[uIndex]) { 12070 if (DEBUG_BACKUP) { 12071 Slog.i(TAG, "Package " + pkgName 12072 + " being restored so deferring FIRST_LAUNCH"); 12073 } 12074 return; 12075 } 12076 } 12077 } 12078 } 12079 // didn't find it, so not being restored 12080 if (DEBUG_BACKUP) { 12081 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12082 } 12083 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12084 } 12085 }); 12086 } 12087 12088 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12089 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12090 installerPkg, null, userIds); 12091 } 12092 12093 private abstract class HandlerParams { 12094 private static final int MAX_RETRIES = 4; 12095 12096 /** 12097 * Number of times startCopy() has been attempted and had a non-fatal 12098 * error. 12099 */ 12100 private int mRetries = 0; 12101 12102 /** User handle for the user requesting the information or installation. */ 12103 private final UserHandle mUser; 12104 String traceMethod; 12105 int traceCookie; 12106 12107 HandlerParams(UserHandle user) { 12108 mUser = user; 12109 } 12110 12111 UserHandle getUser() { 12112 return mUser; 12113 } 12114 12115 HandlerParams setTraceMethod(String traceMethod) { 12116 this.traceMethod = traceMethod; 12117 return this; 12118 } 12119 12120 HandlerParams setTraceCookie(int traceCookie) { 12121 this.traceCookie = traceCookie; 12122 return this; 12123 } 12124 12125 final boolean startCopy() { 12126 boolean res; 12127 try { 12128 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12129 12130 if (++mRetries > MAX_RETRIES) { 12131 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12132 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12133 handleServiceError(); 12134 return false; 12135 } else { 12136 handleStartCopy(); 12137 res = true; 12138 } 12139 } catch (RemoteException e) { 12140 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12141 mHandler.sendEmptyMessage(MCS_RECONNECT); 12142 res = false; 12143 } 12144 handleReturnCode(); 12145 return res; 12146 } 12147 12148 final void serviceError() { 12149 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12150 handleServiceError(); 12151 handleReturnCode(); 12152 } 12153 12154 abstract void handleStartCopy() throws RemoteException; 12155 abstract void handleServiceError(); 12156 abstract void handleReturnCode(); 12157 } 12158 12159 class MeasureParams extends HandlerParams { 12160 private final PackageStats mStats; 12161 private boolean mSuccess; 12162 12163 private final IPackageStatsObserver mObserver; 12164 12165 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12166 super(new UserHandle(stats.userHandle)); 12167 mObserver = observer; 12168 mStats = stats; 12169 } 12170 12171 @Override 12172 public String toString() { 12173 return "MeasureParams{" 12174 + Integer.toHexString(System.identityHashCode(this)) 12175 + " " + mStats.packageName + "}"; 12176 } 12177 12178 @Override 12179 void handleStartCopy() throws RemoteException { 12180 synchronized (mInstallLock) { 12181 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12182 } 12183 12184 if (mSuccess) { 12185 final boolean mounted; 12186 if (Environment.isExternalStorageEmulated()) { 12187 mounted = true; 12188 } else { 12189 final String status = Environment.getExternalStorageState(); 12190 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12191 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12192 } 12193 12194 if (mounted) { 12195 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12196 12197 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12198 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12199 12200 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12201 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12202 12203 // Always subtract cache size, since it's a subdirectory 12204 mStats.externalDataSize -= mStats.externalCacheSize; 12205 12206 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12207 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12208 12209 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12210 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12211 } 12212 } 12213 } 12214 12215 @Override 12216 void handleReturnCode() { 12217 if (mObserver != null) { 12218 try { 12219 mObserver.onGetStatsCompleted(mStats, mSuccess); 12220 } catch (RemoteException e) { 12221 Slog.i(TAG, "Observer no longer exists."); 12222 } 12223 } 12224 } 12225 12226 @Override 12227 void handleServiceError() { 12228 Slog.e(TAG, "Could not measure application " + mStats.packageName 12229 + " external storage"); 12230 } 12231 } 12232 12233 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12234 throws RemoteException { 12235 long result = 0; 12236 for (File path : paths) { 12237 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12238 } 12239 return result; 12240 } 12241 12242 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12243 for (File path : paths) { 12244 try { 12245 mcs.clearDirectory(path.getAbsolutePath()); 12246 } catch (RemoteException e) { 12247 } 12248 } 12249 } 12250 12251 static class OriginInfo { 12252 /** 12253 * Location where install is coming from, before it has been 12254 * copied/renamed into place. This could be a single monolithic APK 12255 * file, or a cluster directory. This location may be untrusted. 12256 */ 12257 final File file; 12258 final String cid; 12259 12260 /** 12261 * Flag indicating that {@link #file} or {@link #cid} has already been 12262 * staged, meaning downstream users don't need to defensively copy the 12263 * contents. 12264 */ 12265 final boolean staged; 12266 12267 /** 12268 * Flag indicating that {@link #file} or {@link #cid} is an already 12269 * installed app that is being moved. 12270 */ 12271 final boolean existing; 12272 12273 final String resolvedPath; 12274 final File resolvedFile; 12275 12276 static OriginInfo fromNothing() { 12277 return new OriginInfo(null, null, false, false); 12278 } 12279 12280 static OriginInfo fromUntrustedFile(File file) { 12281 return new OriginInfo(file, null, false, false); 12282 } 12283 12284 static OriginInfo fromExistingFile(File file) { 12285 return new OriginInfo(file, null, false, true); 12286 } 12287 12288 static OriginInfo fromStagedFile(File file) { 12289 return new OriginInfo(file, null, true, false); 12290 } 12291 12292 static OriginInfo fromStagedContainer(String cid) { 12293 return new OriginInfo(null, cid, true, false); 12294 } 12295 12296 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12297 this.file = file; 12298 this.cid = cid; 12299 this.staged = staged; 12300 this.existing = existing; 12301 12302 if (cid != null) { 12303 resolvedPath = PackageHelper.getSdDir(cid); 12304 resolvedFile = new File(resolvedPath); 12305 } else if (file != null) { 12306 resolvedPath = file.getAbsolutePath(); 12307 resolvedFile = file; 12308 } else { 12309 resolvedPath = null; 12310 resolvedFile = null; 12311 } 12312 } 12313 } 12314 12315 static class MoveInfo { 12316 final int moveId; 12317 final String fromUuid; 12318 final String toUuid; 12319 final String packageName; 12320 final String dataAppName; 12321 final int appId; 12322 final String seinfo; 12323 final int targetSdkVersion; 12324 12325 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12326 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12327 this.moveId = moveId; 12328 this.fromUuid = fromUuid; 12329 this.toUuid = toUuid; 12330 this.packageName = packageName; 12331 this.dataAppName = dataAppName; 12332 this.appId = appId; 12333 this.seinfo = seinfo; 12334 this.targetSdkVersion = targetSdkVersion; 12335 } 12336 } 12337 12338 static class VerificationInfo { 12339 /** A constant used to indicate that a uid value is not present. */ 12340 public static final int NO_UID = -1; 12341 12342 /** URI referencing where the package was downloaded from. */ 12343 final Uri originatingUri; 12344 12345 /** HTTP referrer URI associated with the originatingURI. */ 12346 final Uri referrer; 12347 12348 /** UID of the application that the install request originated from. */ 12349 final int originatingUid; 12350 12351 /** UID of application requesting the install */ 12352 final int installerUid; 12353 12354 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12355 this.originatingUri = originatingUri; 12356 this.referrer = referrer; 12357 this.originatingUid = originatingUid; 12358 this.installerUid = installerUid; 12359 } 12360 } 12361 12362 class InstallParams extends HandlerParams { 12363 final OriginInfo origin; 12364 final MoveInfo move; 12365 final IPackageInstallObserver2 observer; 12366 int installFlags; 12367 final String installerPackageName; 12368 final String volumeUuid; 12369 private InstallArgs mArgs; 12370 private int mRet; 12371 final String packageAbiOverride; 12372 final String[] grantedRuntimePermissions; 12373 final VerificationInfo verificationInfo; 12374 final Certificate[][] certificates; 12375 12376 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12377 int installFlags, String installerPackageName, String volumeUuid, 12378 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12379 String[] grantedPermissions, Certificate[][] certificates) { 12380 super(user); 12381 this.origin = origin; 12382 this.move = move; 12383 this.observer = observer; 12384 this.installFlags = installFlags; 12385 this.installerPackageName = installerPackageName; 12386 this.volumeUuid = volumeUuid; 12387 this.verificationInfo = verificationInfo; 12388 this.packageAbiOverride = packageAbiOverride; 12389 this.grantedRuntimePermissions = grantedPermissions; 12390 this.certificates = certificates; 12391 } 12392 12393 @Override 12394 public String toString() { 12395 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12396 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12397 } 12398 12399 private int installLocationPolicy(PackageInfoLite pkgLite) { 12400 String packageName = pkgLite.packageName; 12401 int installLocation = pkgLite.installLocation; 12402 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12403 // reader 12404 synchronized (mPackages) { 12405 // Currently installed package which the new package is attempting to replace or 12406 // null if no such package is installed. 12407 PackageParser.Package installedPkg = mPackages.get(packageName); 12408 // Package which currently owns the data which the new package will own if installed. 12409 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12410 // will be null whereas dataOwnerPkg will contain information about the package 12411 // which was uninstalled while keeping its data. 12412 PackageParser.Package dataOwnerPkg = installedPkg; 12413 if (dataOwnerPkg == null) { 12414 PackageSetting ps = mSettings.mPackages.get(packageName); 12415 if (ps != null) { 12416 dataOwnerPkg = ps.pkg; 12417 } 12418 } 12419 12420 if (dataOwnerPkg != null) { 12421 // If installed, the package will get access to data left on the device by its 12422 // predecessor. As a security measure, this is permited only if this is not a 12423 // version downgrade or if the predecessor package is marked as debuggable and 12424 // a downgrade is explicitly requested. 12425 // 12426 // On debuggable platform builds, downgrades are permitted even for 12427 // non-debuggable packages to make testing easier. Debuggable platform builds do 12428 // not offer security guarantees and thus it's OK to disable some security 12429 // mechanisms to make debugging/testing easier on those builds. However, even on 12430 // debuggable builds downgrades of packages are permitted only if requested via 12431 // installFlags. This is because we aim to keep the behavior of debuggable 12432 // platform builds as close as possible to the behavior of non-debuggable 12433 // platform builds. 12434 final boolean downgradeRequested = 12435 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12436 final boolean packageDebuggable = 12437 (dataOwnerPkg.applicationInfo.flags 12438 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12439 final boolean downgradePermitted = 12440 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12441 if (!downgradePermitted) { 12442 try { 12443 checkDowngrade(dataOwnerPkg, pkgLite); 12444 } catch (PackageManagerException e) { 12445 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12446 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12447 } 12448 } 12449 } 12450 12451 if (installedPkg != null) { 12452 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12453 // Check for updated system application. 12454 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12455 if (onSd) { 12456 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12457 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12458 } 12459 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12460 } else { 12461 if (onSd) { 12462 // Install flag overrides everything. 12463 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12464 } 12465 // If current upgrade specifies particular preference 12466 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12467 // Application explicitly specified internal. 12468 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12469 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12470 // App explictly prefers external. Let policy decide 12471 } else { 12472 // Prefer previous location 12473 if (isExternal(installedPkg)) { 12474 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12475 } 12476 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12477 } 12478 } 12479 } else { 12480 // Invalid install. Return error code 12481 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12482 } 12483 } 12484 } 12485 // All the special cases have been taken care of. 12486 // Return result based on recommended install location. 12487 if (onSd) { 12488 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12489 } 12490 return pkgLite.recommendedInstallLocation; 12491 } 12492 12493 /* 12494 * Invoke remote method to get package information and install 12495 * location values. Override install location based on default 12496 * policy if needed and then create install arguments based 12497 * on the install location. 12498 */ 12499 public void handleStartCopy() throws RemoteException { 12500 int ret = PackageManager.INSTALL_SUCCEEDED; 12501 12502 // If we're already staged, we've firmly committed to an install location 12503 if (origin.staged) { 12504 if (origin.file != null) { 12505 installFlags |= PackageManager.INSTALL_INTERNAL; 12506 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12507 } else if (origin.cid != null) { 12508 installFlags |= PackageManager.INSTALL_EXTERNAL; 12509 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12510 } else { 12511 throw new IllegalStateException("Invalid stage location"); 12512 } 12513 } 12514 12515 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12516 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12517 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12518 PackageInfoLite pkgLite = null; 12519 12520 if (onInt && onSd) { 12521 // Check if both bits are set. 12522 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12523 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12524 } else if (onSd && ephemeral) { 12525 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12526 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12527 } else { 12528 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12529 packageAbiOverride); 12530 12531 if (DEBUG_EPHEMERAL && ephemeral) { 12532 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12533 } 12534 12535 /* 12536 * If we have too little free space, try to free cache 12537 * before giving up. 12538 */ 12539 if (!origin.staged && pkgLite.recommendedInstallLocation 12540 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12541 // TODO: focus freeing disk space on the target device 12542 final StorageManager storage = StorageManager.from(mContext); 12543 final long lowThreshold = storage.getStorageLowBytes( 12544 Environment.getDataDirectory()); 12545 12546 final long sizeBytes = mContainerService.calculateInstalledSize( 12547 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12548 12549 try { 12550 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12551 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12552 installFlags, packageAbiOverride); 12553 } catch (InstallerException e) { 12554 Slog.w(TAG, "Failed to free cache", e); 12555 } 12556 12557 /* 12558 * The cache free must have deleted the file we 12559 * downloaded to install. 12560 * 12561 * TODO: fix the "freeCache" call to not delete 12562 * the file we care about. 12563 */ 12564 if (pkgLite.recommendedInstallLocation 12565 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12566 pkgLite.recommendedInstallLocation 12567 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12568 } 12569 } 12570 } 12571 12572 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12573 int loc = pkgLite.recommendedInstallLocation; 12574 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12575 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12576 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12577 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12578 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12579 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12580 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12581 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12582 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12583 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12584 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12585 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12586 } else { 12587 // Override with defaults if needed. 12588 loc = installLocationPolicy(pkgLite); 12589 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12590 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12591 } else if (!onSd && !onInt) { 12592 // Override install location with flags 12593 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12594 // Set the flag to install on external media. 12595 installFlags |= PackageManager.INSTALL_EXTERNAL; 12596 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12597 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12598 if (DEBUG_EPHEMERAL) { 12599 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12600 } 12601 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12602 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12603 |PackageManager.INSTALL_INTERNAL); 12604 } else { 12605 // Make sure the flag for installing on external 12606 // media is unset 12607 installFlags |= PackageManager.INSTALL_INTERNAL; 12608 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12609 } 12610 } 12611 } 12612 } 12613 12614 final InstallArgs args = createInstallArgs(this); 12615 mArgs = args; 12616 12617 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12618 // TODO: http://b/22976637 12619 // Apps installed for "all" users use the device owner to verify the app 12620 UserHandle verifierUser = getUser(); 12621 if (verifierUser == UserHandle.ALL) { 12622 verifierUser = UserHandle.SYSTEM; 12623 } 12624 12625 /* 12626 * Determine if we have any installed package verifiers. If we 12627 * do, then we'll defer to them to verify the packages. 12628 */ 12629 final int requiredUid = mRequiredVerifierPackage == null ? -1 12630 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12631 verifierUser.getIdentifier()); 12632 if (!origin.existing && requiredUid != -1 12633 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12634 final Intent verification = new Intent( 12635 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12636 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12637 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12638 PACKAGE_MIME_TYPE); 12639 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12640 12641 // Query all live verifiers based on current user state 12642 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12643 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12644 12645 if (DEBUG_VERIFY) { 12646 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12647 + verification.toString() + " with " + pkgLite.verifiers.length 12648 + " optional verifiers"); 12649 } 12650 12651 final int verificationId = mPendingVerificationToken++; 12652 12653 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12654 12655 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12656 installerPackageName); 12657 12658 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12659 installFlags); 12660 12661 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12662 pkgLite.packageName); 12663 12664 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12665 pkgLite.versionCode); 12666 12667 if (verificationInfo != null) { 12668 if (verificationInfo.originatingUri != null) { 12669 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12670 verificationInfo.originatingUri); 12671 } 12672 if (verificationInfo.referrer != null) { 12673 verification.putExtra(Intent.EXTRA_REFERRER, 12674 verificationInfo.referrer); 12675 } 12676 if (verificationInfo.originatingUid >= 0) { 12677 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12678 verificationInfo.originatingUid); 12679 } 12680 if (verificationInfo.installerUid >= 0) { 12681 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12682 verificationInfo.installerUid); 12683 } 12684 } 12685 12686 final PackageVerificationState verificationState = new PackageVerificationState( 12687 requiredUid, args); 12688 12689 mPendingVerification.append(verificationId, verificationState); 12690 12691 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12692 receivers, verificationState); 12693 12694 /* 12695 * If any sufficient verifiers were listed in the package 12696 * manifest, attempt to ask them. 12697 */ 12698 if (sufficientVerifiers != null) { 12699 final int N = sufficientVerifiers.size(); 12700 if (N == 0) { 12701 Slog.i(TAG, "Additional verifiers required, but none installed."); 12702 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12703 } else { 12704 for (int i = 0; i < N; i++) { 12705 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12706 12707 final Intent sufficientIntent = new Intent(verification); 12708 sufficientIntent.setComponent(verifierComponent); 12709 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12710 } 12711 } 12712 } 12713 12714 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12715 mRequiredVerifierPackage, receivers); 12716 if (ret == PackageManager.INSTALL_SUCCEEDED 12717 && mRequiredVerifierPackage != null) { 12718 Trace.asyncTraceBegin( 12719 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12720 /* 12721 * Send the intent to the required verification agent, 12722 * but only start the verification timeout after the 12723 * target BroadcastReceivers have run. 12724 */ 12725 verification.setComponent(requiredVerifierComponent); 12726 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12727 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12728 new BroadcastReceiver() { 12729 @Override 12730 public void onReceive(Context context, Intent intent) { 12731 final Message msg = mHandler 12732 .obtainMessage(CHECK_PENDING_VERIFICATION); 12733 msg.arg1 = verificationId; 12734 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12735 } 12736 }, null, 0, null, null); 12737 12738 /* 12739 * We don't want the copy to proceed until verification 12740 * succeeds, so null out this field. 12741 */ 12742 mArgs = null; 12743 } 12744 } else { 12745 /* 12746 * No package verification is enabled, so immediately start 12747 * the remote call to initiate copy using temporary file. 12748 */ 12749 ret = args.copyApk(mContainerService, true); 12750 } 12751 } 12752 12753 mRet = ret; 12754 } 12755 12756 @Override 12757 void handleReturnCode() { 12758 // If mArgs is null, then MCS couldn't be reached. When it 12759 // reconnects, it will try again to install. At that point, this 12760 // will succeed. 12761 if (mArgs != null) { 12762 processPendingInstall(mArgs, mRet); 12763 } 12764 } 12765 12766 @Override 12767 void handleServiceError() { 12768 mArgs = createInstallArgs(this); 12769 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12770 } 12771 12772 public boolean isForwardLocked() { 12773 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12774 } 12775 } 12776 12777 /** 12778 * Used during creation of InstallArgs 12779 * 12780 * @param installFlags package installation flags 12781 * @return true if should be installed on external storage 12782 */ 12783 private static boolean installOnExternalAsec(int installFlags) { 12784 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12785 return false; 12786 } 12787 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12788 return true; 12789 } 12790 return false; 12791 } 12792 12793 /** 12794 * Used during creation of InstallArgs 12795 * 12796 * @param installFlags package installation flags 12797 * @return true if should be installed as forward locked 12798 */ 12799 private static boolean installForwardLocked(int installFlags) { 12800 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12801 } 12802 12803 private InstallArgs createInstallArgs(InstallParams params) { 12804 if (params.move != null) { 12805 return new MoveInstallArgs(params); 12806 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12807 return new AsecInstallArgs(params); 12808 } else { 12809 return new FileInstallArgs(params); 12810 } 12811 } 12812 12813 /** 12814 * Create args that describe an existing installed package. Typically used 12815 * when cleaning up old installs, or used as a move source. 12816 */ 12817 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12818 String resourcePath, String[] instructionSets) { 12819 final boolean isInAsec; 12820 if (installOnExternalAsec(installFlags)) { 12821 /* Apps on SD card are always in ASEC containers. */ 12822 isInAsec = true; 12823 } else if (installForwardLocked(installFlags) 12824 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12825 /* 12826 * Forward-locked apps are only in ASEC containers if they're the 12827 * new style 12828 */ 12829 isInAsec = true; 12830 } else { 12831 isInAsec = false; 12832 } 12833 12834 if (isInAsec) { 12835 return new AsecInstallArgs(codePath, instructionSets, 12836 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12837 } else { 12838 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12839 } 12840 } 12841 12842 static abstract class InstallArgs { 12843 /** @see InstallParams#origin */ 12844 final OriginInfo origin; 12845 /** @see InstallParams#move */ 12846 final MoveInfo move; 12847 12848 final IPackageInstallObserver2 observer; 12849 // Always refers to PackageManager flags only 12850 final int installFlags; 12851 final String installerPackageName; 12852 final String volumeUuid; 12853 final UserHandle user; 12854 final String abiOverride; 12855 final String[] installGrantPermissions; 12856 /** If non-null, drop an async trace when the install completes */ 12857 final String traceMethod; 12858 final int traceCookie; 12859 final Certificate[][] certificates; 12860 12861 // The list of instruction sets supported by this app. This is currently 12862 // only used during the rmdex() phase to clean up resources. We can get rid of this 12863 // if we move dex files under the common app path. 12864 /* nullable */ String[] instructionSets; 12865 12866 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12867 int installFlags, String installerPackageName, String volumeUuid, 12868 UserHandle user, String[] instructionSets, 12869 String abiOverride, String[] installGrantPermissions, 12870 String traceMethod, int traceCookie, Certificate[][] certificates) { 12871 this.origin = origin; 12872 this.move = move; 12873 this.installFlags = installFlags; 12874 this.observer = observer; 12875 this.installerPackageName = installerPackageName; 12876 this.volumeUuid = volumeUuid; 12877 this.user = user; 12878 this.instructionSets = instructionSets; 12879 this.abiOverride = abiOverride; 12880 this.installGrantPermissions = installGrantPermissions; 12881 this.traceMethod = traceMethod; 12882 this.traceCookie = traceCookie; 12883 this.certificates = certificates; 12884 } 12885 12886 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12887 abstract int doPreInstall(int status); 12888 12889 /** 12890 * Rename package into final resting place. All paths on the given 12891 * scanned package should be updated to reflect the rename. 12892 */ 12893 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12894 abstract int doPostInstall(int status, int uid); 12895 12896 /** @see PackageSettingBase#codePathString */ 12897 abstract String getCodePath(); 12898 /** @see PackageSettingBase#resourcePathString */ 12899 abstract String getResourcePath(); 12900 12901 // Need installer lock especially for dex file removal. 12902 abstract void cleanUpResourcesLI(); 12903 abstract boolean doPostDeleteLI(boolean delete); 12904 12905 /** 12906 * Called before the source arguments are copied. This is used mostly 12907 * for MoveParams when it needs to read the source file to put it in the 12908 * destination. 12909 */ 12910 int doPreCopy() { 12911 return PackageManager.INSTALL_SUCCEEDED; 12912 } 12913 12914 /** 12915 * Called after the source arguments are copied. This is used mostly for 12916 * MoveParams when it needs to read the source file to put it in the 12917 * destination. 12918 */ 12919 int doPostCopy(int uid) { 12920 return PackageManager.INSTALL_SUCCEEDED; 12921 } 12922 12923 protected boolean isFwdLocked() { 12924 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12925 } 12926 12927 protected boolean isExternalAsec() { 12928 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12929 } 12930 12931 protected boolean isEphemeral() { 12932 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12933 } 12934 12935 UserHandle getUser() { 12936 return user; 12937 } 12938 } 12939 12940 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12941 if (!allCodePaths.isEmpty()) { 12942 if (instructionSets == null) { 12943 throw new IllegalStateException("instructionSet == null"); 12944 } 12945 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12946 for (String codePath : allCodePaths) { 12947 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12948 try { 12949 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12950 } catch (InstallerException ignored) { 12951 } 12952 } 12953 } 12954 } 12955 } 12956 12957 /** 12958 * Logic to handle installation of non-ASEC applications, including copying 12959 * and renaming logic. 12960 */ 12961 class FileInstallArgs extends InstallArgs { 12962 private File codeFile; 12963 private File resourceFile; 12964 12965 // Example topology: 12966 // /data/app/com.example/base.apk 12967 // /data/app/com.example/split_foo.apk 12968 // /data/app/com.example/lib/arm/libfoo.so 12969 // /data/app/com.example/lib/arm64/libfoo.so 12970 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12971 12972 /** New install */ 12973 FileInstallArgs(InstallParams params) { 12974 super(params.origin, params.move, params.observer, params.installFlags, 12975 params.installerPackageName, params.volumeUuid, 12976 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12977 params.grantedRuntimePermissions, 12978 params.traceMethod, params.traceCookie, params.certificates); 12979 if (isFwdLocked()) { 12980 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12981 } 12982 } 12983 12984 /** Existing install */ 12985 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12986 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12987 null, null, null, 0, null /*certificates*/); 12988 this.codeFile = (codePath != null) ? new File(codePath) : null; 12989 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12990 } 12991 12992 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12993 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12994 try { 12995 return doCopyApk(imcs, temp); 12996 } finally { 12997 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12998 } 12999 } 13000 13001 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13002 if (origin.staged) { 13003 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13004 codeFile = origin.file; 13005 resourceFile = origin.file; 13006 return PackageManager.INSTALL_SUCCEEDED; 13007 } 13008 13009 try { 13010 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13011 final File tempDir = 13012 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13013 codeFile = tempDir; 13014 resourceFile = tempDir; 13015 } catch (IOException e) { 13016 Slog.w(TAG, "Failed to create copy file: " + e); 13017 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13018 } 13019 13020 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13021 @Override 13022 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13023 if (!FileUtils.isValidExtFilename(name)) { 13024 throw new IllegalArgumentException("Invalid filename: " + name); 13025 } 13026 try { 13027 final File file = new File(codeFile, name); 13028 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13029 O_RDWR | O_CREAT, 0644); 13030 Os.chmod(file.getAbsolutePath(), 0644); 13031 return new ParcelFileDescriptor(fd); 13032 } catch (ErrnoException e) { 13033 throw new RemoteException("Failed to open: " + e.getMessage()); 13034 } 13035 } 13036 }; 13037 13038 int ret = PackageManager.INSTALL_SUCCEEDED; 13039 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13040 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13041 Slog.e(TAG, "Failed to copy package"); 13042 return ret; 13043 } 13044 13045 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13046 NativeLibraryHelper.Handle handle = null; 13047 try { 13048 handle = NativeLibraryHelper.Handle.create(codeFile); 13049 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13050 abiOverride); 13051 } catch (IOException e) { 13052 Slog.e(TAG, "Copying native libraries failed", e); 13053 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13054 } finally { 13055 IoUtils.closeQuietly(handle); 13056 } 13057 13058 return ret; 13059 } 13060 13061 int doPreInstall(int status) { 13062 if (status != PackageManager.INSTALL_SUCCEEDED) { 13063 cleanUp(); 13064 } 13065 return status; 13066 } 13067 13068 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13069 if (status != PackageManager.INSTALL_SUCCEEDED) { 13070 cleanUp(); 13071 return false; 13072 } 13073 13074 final File targetDir = codeFile.getParentFile(); 13075 final File beforeCodeFile = codeFile; 13076 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13077 13078 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13079 try { 13080 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13081 } catch (ErrnoException e) { 13082 Slog.w(TAG, "Failed to rename", e); 13083 return false; 13084 } 13085 13086 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13087 Slog.w(TAG, "Failed to restorecon"); 13088 return false; 13089 } 13090 13091 // Reflect the rename internally 13092 codeFile = afterCodeFile; 13093 resourceFile = afterCodeFile; 13094 13095 // Reflect the rename in scanned details 13096 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13097 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13098 afterCodeFile, pkg.baseCodePath)); 13099 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13100 afterCodeFile, pkg.splitCodePaths)); 13101 13102 // Reflect the rename in app info 13103 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13104 pkg.setApplicationInfoCodePath(pkg.codePath); 13105 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13106 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13107 pkg.setApplicationInfoResourcePath(pkg.codePath); 13108 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13109 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13110 13111 return true; 13112 } 13113 13114 int doPostInstall(int status, int uid) { 13115 if (status != PackageManager.INSTALL_SUCCEEDED) { 13116 cleanUp(); 13117 } 13118 return status; 13119 } 13120 13121 @Override 13122 String getCodePath() { 13123 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13124 } 13125 13126 @Override 13127 String getResourcePath() { 13128 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13129 } 13130 13131 private boolean cleanUp() { 13132 if (codeFile == null || !codeFile.exists()) { 13133 return false; 13134 } 13135 13136 removeCodePathLI(codeFile); 13137 13138 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13139 resourceFile.delete(); 13140 } 13141 13142 return true; 13143 } 13144 13145 void cleanUpResourcesLI() { 13146 // Try enumerating all code paths before deleting 13147 List<String> allCodePaths = Collections.EMPTY_LIST; 13148 if (codeFile != null && codeFile.exists()) { 13149 try { 13150 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13151 allCodePaths = pkg.getAllCodePaths(); 13152 } catch (PackageParserException e) { 13153 // Ignored; we tried our best 13154 } 13155 } 13156 13157 cleanUp(); 13158 removeDexFiles(allCodePaths, instructionSets); 13159 } 13160 13161 boolean doPostDeleteLI(boolean delete) { 13162 // XXX err, shouldn't we respect the delete flag? 13163 cleanUpResourcesLI(); 13164 return true; 13165 } 13166 } 13167 13168 private boolean isAsecExternal(String cid) { 13169 final String asecPath = PackageHelper.getSdFilesystem(cid); 13170 return !asecPath.startsWith(mAsecInternalPath); 13171 } 13172 13173 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13174 PackageManagerException { 13175 if (copyRet < 0) { 13176 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13177 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13178 throw new PackageManagerException(copyRet, message); 13179 } 13180 } 13181 } 13182 13183 /** 13184 * Extract the MountService "container ID" from the full code path of an 13185 * .apk. 13186 */ 13187 static String cidFromCodePath(String fullCodePath) { 13188 int eidx = fullCodePath.lastIndexOf("/"); 13189 String subStr1 = fullCodePath.substring(0, eidx); 13190 int sidx = subStr1.lastIndexOf("/"); 13191 return subStr1.substring(sidx+1, eidx); 13192 } 13193 13194 /** 13195 * Logic to handle installation of ASEC applications, including copying and 13196 * renaming logic. 13197 */ 13198 class AsecInstallArgs extends InstallArgs { 13199 static final String RES_FILE_NAME = "pkg.apk"; 13200 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13201 13202 String cid; 13203 String packagePath; 13204 String resourcePath; 13205 13206 /** New install */ 13207 AsecInstallArgs(InstallParams params) { 13208 super(params.origin, params.move, params.observer, params.installFlags, 13209 params.installerPackageName, params.volumeUuid, 13210 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13211 params.grantedRuntimePermissions, 13212 params.traceMethod, params.traceCookie, params.certificates); 13213 } 13214 13215 /** Existing install */ 13216 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13217 boolean isExternal, boolean isForwardLocked) { 13218 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13219 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13220 instructionSets, null, null, null, 0, null /*certificates*/); 13221 // Hackily pretend we're still looking at a full code path 13222 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13223 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13224 } 13225 13226 // Extract cid from fullCodePath 13227 int eidx = fullCodePath.lastIndexOf("/"); 13228 String subStr1 = fullCodePath.substring(0, eidx); 13229 int sidx = subStr1.lastIndexOf("/"); 13230 cid = subStr1.substring(sidx+1, eidx); 13231 setMountPath(subStr1); 13232 } 13233 13234 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13235 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13236 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13237 instructionSets, null, null, null, 0, null /*certificates*/); 13238 this.cid = cid; 13239 setMountPath(PackageHelper.getSdDir(cid)); 13240 } 13241 13242 void createCopyFile() { 13243 cid = mInstallerService.allocateExternalStageCidLegacy(); 13244 } 13245 13246 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13247 if (origin.staged && origin.cid != null) { 13248 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13249 cid = origin.cid; 13250 setMountPath(PackageHelper.getSdDir(cid)); 13251 return PackageManager.INSTALL_SUCCEEDED; 13252 } 13253 13254 if (temp) { 13255 createCopyFile(); 13256 } else { 13257 /* 13258 * Pre-emptively destroy the container since it's destroyed if 13259 * copying fails due to it existing anyway. 13260 */ 13261 PackageHelper.destroySdDir(cid); 13262 } 13263 13264 final String newMountPath = imcs.copyPackageToContainer( 13265 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13266 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13267 13268 if (newMountPath != null) { 13269 setMountPath(newMountPath); 13270 return PackageManager.INSTALL_SUCCEEDED; 13271 } else { 13272 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13273 } 13274 } 13275 13276 @Override 13277 String getCodePath() { 13278 return packagePath; 13279 } 13280 13281 @Override 13282 String getResourcePath() { 13283 return resourcePath; 13284 } 13285 13286 int doPreInstall(int status) { 13287 if (status != PackageManager.INSTALL_SUCCEEDED) { 13288 // Destroy container 13289 PackageHelper.destroySdDir(cid); 13290 } else { 13291 boolean mounted = PackageHelper.isContainerMounted(cid); 13292 if (!mounted) { 13293 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13294 Process.SYSTEM_UID); 13295 if (newMountPath != null) { 13296 setMountPath(newMountPath); 13297 } else { 13298 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13299 } 13300 } 13301 } 13302 return status; 13303 } 13304 13305 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13306 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13307 String newMountPath = null; 13308 if (PackageHelper.isContainerMounted(cid)) { 13309 // Unmount the container 13310 if (!PackageHelper.unMountSdDir(cid)) { 13311 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13312 return false; 13313 } 13314 } 13315 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13316 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13317 " which might be stale. Will try to clean up."); 13318 // Clean up the stale container and proceed to recreate. 13319 if (!PackageHelper.destroySdDir(newCacheId)) { 13320 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13321 return false; 13322 } 13323 // Successfully cleaned up stale container. Try to rename again. 13324 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13325 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13326 + " inspite of cleaning it up."); 13327 return false; 13328 } 13329 } 13330 if (!PackageHelper.isContainerMounted(newCacheId)) { 13331 Slog.w(TAG, "Mounting container " + newCacheId); 13332 newMountPath = PackageHelper.mountSdDir(newCacheId, 13333 getEncryptKey(), Process.SYSTEM_UID); 13334 } else { 13335 newMountPath = PackageHelper.getSdDir(newCacheId); 13336 } 13337 if (newMountPath == null) { 13338 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13339 return false; 13340 } 13341 Log.i(TAG, "Succesfully renamed " + cid + 13342 " to " + newCacheId + 13343 " at new path: " + newMountPath); 13344 cid = newCacheId; 13345 13346 final File beforeCodeFile = new File(packagePath); 13347 setMountPath(newMountPath); 13348 final File afterCodeFile = new File(packagePath); 13349 13350 // Reflect the rename in scanned details 13351 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13352 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13353 afterCodeFile, pkg.baseCodePath)); 13354 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13355 afterCodeFile, pkg.splitCodePaths)); 13356 13357 // Reflect the rename in app info 13358 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13359 pkg.setApplicationInfoCodePath(pkg.codePath); 13360 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13361 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13362 pkg.setApplicationInfoResourcePath(pkg.codePath); 13363 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13364 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13365 13366 return true; 13367 } 13368 13369 private void setMountPath(String mountPath) { 13370 final File mountFile = new File(mountPath); 13371 13372 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13373 if (monolithicFile.exists()) { 13374 packagePath = monolithicFile.getAbsolutePath(); 13375 if (isFwdLocked()) { 13376 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13377 } else { 13378 resourcePath = packagePath; 13379 } 13380 } else { 13381 packagePath = mountFile.getAbsolutePath(); 13382 resourcePath = packagePath; 13383 } 13384 } 13385 13386 int doPostInstall(int status, int uid) { 13387 if (status != PackageManager.INSTALL_SUCCEEDED) { 13388 cleanUp(); 13389 } else { 13390 final int groupOwner; 13391 final String protectedFile; 13392 if (isFwdLocked()) { 13393 groupOwner = UserHandle.getSharedAppGid(uid); 13394 protectedFile = RES_FILE_NAME; 13395 } else { 13396 groupOwner = -1; 13397 protectedFile = null; 13398 } 13399 13400 if (uid < Process.FIRST_APPLICATION_UID 13401 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13402 Slog.e(TAG, "Failed to finalize " + cid); 13403 PackageHelper.destroySdDir(cid); 13404 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13405 } 13406 13407 boolean mounted = PackageHelper.isContainerMounted(cid); 13408 if (!mounted) { 13409 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13410 } 13411 } 13412 return status; 13413 } 13414 13415 private void cleanUp() { 13416 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13417 13418 // Destroy secure container 13419 PackageHelper.destroySdDir(cid); 13420 } 13421 13422 private List<String> getAllCodePaths() { 13423 final File codeFile = new File(getCodePath()); 13424 if (codeFile != null && codeFile.exists()) { 13425 try { 13426 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13427 return pkg.getAllCodePaths(); 13428 } catch (PackageParserException e) { 13429 // Ignored; we tried our best 13430 } 13431 } 13432 return Collections.EMPTY_LIST; 13433 } 13434 13435 void cleanUpResourcesLI() { 13436 // Enumerate all code paths before deleting 13437 cleanUpResourcesLI(getAllCodePaths()); 13438 } 13439 13440 private void cleanUpResourcesLI(List<String> allCodePaths) { 13441 cleanUp(); 13442 removeDexFiles(allCodePaths, instructionSets); 13443 } 13444 13445 String getPackageName() { 13446 return getAsecPackageName(cid); 13447 } 13448 13449 boolean doPostDeleteLI(boolean delete) { 13450 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13451 final List<String> allCodePaths = getAllCodePaths(); 13452 boolean mounted = PackageHelper.isContainerMounted(cid); 13453 if (mounted) { 13454 // Unmount first 13455 if (PackageHelper.unMountSdDir(cid)) { 13456 mounted = false; 13457 } 13458 } 13459 if (!mounted && delete) { 13460 cleanUpResourcesLI(allCodePaths); 13461 } 13462 return !mounted; 13463 } 13464 13465 @Override 13466 int doPreCopy() { 13467 if (isFwdLocked()) { 13468 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13469 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13470 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13471 } 13472 } 13473 13474 return PackageManager.INSTALL_SUCCEEDED; 13475 } 13476 13477 @Override 13478 int doPostCopy(int uid) { 13479 if (isFwdLocked()) { 13480 if (uid < Process.FIRST_APPLICATION_UID 13481 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13482 RES_FILE_NAME)) { 13483 Slog.e(TAG, "Failed to finalize " + cid); 13484 PackageHelper.destroySdDir(cid); 13485 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13486 } 13487 } 13488 13489 return PackageManager.INSTALL_SUCCEEDED; 13490 } 13491 } 13492 13493 /** 13494 * Logic to handle movement of existing installed applications. 13495 */ 13496 class MoveInstallArgs extends InstallArgs { 13497 private File codeFile; 13498 private File resourceFile; 13499 13500 /** New install */ 13501 MoveInstallArgs(InstallParams params) { 13502 super(params.origin, params.move, params.observer, params.installFlags, 13503 params.installerPackageName, params.volumeUuid, 13504 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13505 params.grantedRuntimePermissions, 13506 params.traceMethod, params.traceCookie, params.certificates); 13507 } 13508 13509 int copyApk(IMediaContainerService imcs, boolean temp) { 13510 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13511 + move.fromUuid + " to " + move.toUuid); 13512 synchronized (mInstaller) { 13513 try { 13514 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13515 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13516 } catch (InstallerException e) { 13517 Slog.w(TAG, "Failed to move app", e); 13518 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13519 } 13520 } 13521 13522 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13523 resourceFile = codeFile; 13524 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13525 13526 return PackageManager.INSTALL_SUCCEEDED; 13527 } 13528 13529 int doPreInstall(int status) { 13530 if (status != PackageManager.INSTALL_SUCCEEDED) { 13531 cleanUp(move.toUuid); 13532 } 13533 return status; 13534 } 13535 13536 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13537 if (status != PackageManager.INSTALL_SUCCEEDED) { 13538 cleanUp(move.toUuid); 13539 return false; 13540 } 13541 13542 // Reflect the move in app info 13543 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13544 pkg.setApplicationInfoCodePath(pkg.codePath); 13545 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13546 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13547 pkg.setApplicationInfoResourcePath(pkg.codePath); 13548 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13549 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13550 13551 return true; 13552 } 13553 13554 int doPostInstall(int status, int uid) { 13555 if (status == PackageManager.INSTALL_SUCCEEDED) { 13556 cleanUp(move.fromUuid); 13557 } else { 13558 cleanUp(move.toUuid); 13559 } 13560 return status; 13561 } 13562 13563 @Override 13564 String getCodePath() { 13565 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13566 } 13567 13568 @Override 13569 String getResourcePath() { 13570 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13571 } 13572 13573 private boolean cleanUp(String volumeUuid) { 13574 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13575 move.dataAppName); 13576 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13577 final int[] userIds = sUserManager.getUserIds(); 13578 synchronized (mInstallLock) { 13579 // Clean up both app data and code 13580 // All package moves are frozen until finished 13581 for (int userId : userIds) { 13582 try { 13583 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13584 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13585 } catch (InstallerException e) { 13586 Slog.w(TAG, String.valueOf(e)); 13587 } 13588 } 13589 removeCodePathLI(codeFile); 13590 } 13591 return true; 13592 } 13593 13594 void cleanUpResourcesLI() { 13595 throw new UnsupportedOperationException(); 13596 } 13597 13598 boolean doPostDeleteLI(boolean delete) { 13599 throw new UnsupportedOperationException(); 13600 } 13601 } 13602 13603 static String getAsecPackageName(String packageCid) { 13604 int idx = packageCid.lastIndexOf("-"); 13605 if (idx == -1) { 13606 return packageCid; 13607 } 13608 return packageCid.substring(0, idx); 13609 } 13610 13611 // Utility method used to create code paths based on package name and available index. 13612 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13613 String idxStr = ""; 13614 int idx = 1; 13615 // Fall back to default value of idx=1 if prefix is not 13616 // part of oldCodePath 13617 if (oldCodePath != null) { 13618 String subStr = oldCodePath; 13619 // Drop the suffix right away 13620 if (suffix != null && subStr.endsWith(suffix)) { 13621 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13622 } 13623 // If oldCodePath already contains prefix find out the 13624 // ending index to either increment or decrement. 13625 int sidx = subStr.lastIndexOf(prefix); 13626 if (sidx != -1) { 13627 subStr = subStr.substring(sidx + prefix.length()); 13628 if (subStr != null) { 13629 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13630 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13631 } 13632 try { 13633 idx = Integer.parseInt(subStr); 13634 if (idx <= 1) { 13635 idx++; 13636 } else { 13637 idx--; 13638 } 13639 } catch(NumberFormatException e) { 13640 } 13641 } 13642 } 13643 } 13644 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13645 return prefix + idxStr; 13646 } 13647 13648 private File getNextCodePath(File targetDir, String packageName) { 13649 int suffix = 1; 13650 File result; 13651 do { 13652 result = new File(targetDir, packageName + "-" + suffix); 13653 suffix++; 13654 } while (result.exists()); 13655 return result; 13656 } 13657 13658 // Utility method that returns the relative package path with respect 13659 // to the installation directory. Like say for /data/data/com.test-1.apk 13660 // string com.test-1 is returned. 13661 static String deriveCodePathName(String codePath) { 13662 if (codePath == null) { 13663 return null; 13664 } 13665 final File codeFile = new File(codePath); 13666 final String name = codeFile.getName(); 13667 if (codeFile.isDirectory()) { 13668 return name; 13669 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13670 final int lastDot = name.lastIndexOf('.'); 13671 return name.substring(0, lastDot); 13672 } else { 13673 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13674 return null; 13675 } 13676 } 13677 13678 static class PackageInstalledInfo { 13679 String name; 13680 int uid; 13681 // The set of users that originally had this package installed. 13682 int[] origUsers; 13683 // The set of users that now have this package installed. 13684 int[] newUsers; 13685 PackageParser.Package pkg; 13686 int returnCode; 13687 String returnMsg; 13688 PackageRemovedInfo removedInfo; 13689 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13690 13691 public void setError(int code, String msg) { 13692 setReturnCode(code); 13693 setReturnMessage(msg); 13694 Slog.w(TAG, msg); 13695 } 13696 13697 public void setError(String msg, PackageParserException e) { 13698 setReturnCode(e.error); 13699 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13700 Slog.w(TAG, msg, e); 13701 } 13702 13703 public void setError(String msg, PackageManagerException e) { 13704 returnCode = e.error; 13705 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13706 Slog.w(TAG, msg, e); 13707 } 13708 13709 public void setReturnCode(int returnCode) { 13710 this.returnCode = returnCode; 13711 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13712 for (int i = 0; i < childCount; i++) { 13713 addedChildPackages.valueAt(i).returnCode = returnCode; 13714 } 13715 } 13716 13717 private void setReturnMessage(String returnMsg) { 13718 this.returnMsg = returnMsg; 13719 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13720 for (int i = 0; i < childCount; i++) { 13721 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13722 } 13723 } 13724 13725 // In some error cases we want to convey more info back to the observer 13726 String origPackage; 13727 String origPermission; 13728 } 13729 13730 /* 13731 * Install a non-existing package. 13732 */ 13733 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13734 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13735 PackageInstalledInfo res) { 13736 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13737 13738 // Remember this for later, in case we need to rollback this install 13739 String pkgName = pkg.packageName; 13740 13741 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13742 13743 synchronized(mPackages) { 13744 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13745 // A package with the same name is already installed, though 13746 // it has been renamed to an older name. The package we 13747 // are trying to install should be installed as an update to 13748 // the existing one, but that has not been requested, so bail. 13749 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13750 + " without first uninstalling package running as " 13751 + mSettings.mRenamedPackages.get(pkgName)); 13752 return; 13753 } 13754 if (mPackages.containsKey(pkgName)) { 13755 // Don't allow installation over an existing package with the same name. 13756 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13757 + " without first uninstalling."); 13758 return; 13759 } 13760 } 13761 13762 try { 13763 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13764 System.currentTimeMillis(), user); 13765 13766 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13767 13768 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13769 prepareAppDataAfterInstallLIF(newPackage); 13770 13771 } else { 13772 // Remove package from internal structures, but keep around any 13773 // data that might have already existed 13774 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13775 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13776 } 13777 } catch (PackageManagerException e) { 13778 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13779 } 13780 13781 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13782 } 13783 13784 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13785 // Can't rotate keys during boot or if sharedUser. 13786 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13787 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13788 return false; 13789 } 13790 // app is using upgradeKeySets; make sure all are valid 13791 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13792 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13793 for (int i = 0; i < upgradeKeySets.length; i++) { 13794 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13795 Slog.wtf(TAG, "Package " 13796 + (oldPs.name != null ? oldPs.name : "<null>") 13797 + " contains upgrade-key-set reference to unknown key-set: " 13798 + upgradeKeySets[i] 13799 + " reverting to signatures check."); 13800 return false; 13801 } 13802 } 13803 return true; 13804 } 13805 13806 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13807 // Upgrade keysets are being used. Determine if new package has a superset of the 13808 // required keys. 13809 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13810 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13811 for (int i = 0; i < upgradeKeySets.length; i++) { 13812 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13813 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13814 return true; 13815 } 13816 } 13817 return false; 13818 } 13819 13820 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13821 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13822 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13823 13824 final PackageParser.Package oldPackage; 13825 final String pkgName = pkg.packageName; 13826 final int[] allUsers; 13827 final int[] installedUsers; 13828 13829 synchronized(mPackages) { 13830 oldPackage = mPackages.get(pkgName); 13831 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13832 13833 // don't allow upgrade to target a release SDK from a pre-release SDK 13834 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13835 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13836 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13837 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13838 if (oldTargetsPreRelease 13839 && !newTargetsPreRelease 13840 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13841 Slog.w(TAG, "Can't install package targeting released sdk"); 13842 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13843 return; 13844 } 13845 13846 // don't allow an upgrade from full to ephemeral 13847 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13848 if (isEphemeral && !oldIsEphemeral) { 13849 // can't downgrade from full to ephemeral 13850 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13851 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13852 return; 13853 } 13854 13855 // verify signatures are valid 13856 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13857 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13858 if (!checkUpgradeKeySetLP(ps, pkg)) { 13859 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13860 "New package not signed by keys specified by upgrade-keysets: " 13861 + pkgName); 13862 return; 13863 } 13864 } else { 13865 // default to original signature matching 13866 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13867 != PackageManager.SIGNATURE_MATCH) { 13868 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13869 "New package has a different signature: " + pkgName); 13870 return; 13871 } 13872 } 13873 13874 // Check for shared user id changes 13875 String invalidPackageName = 13876 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13877 if (invalidPackageName != null) { 13878 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13879 "Package " + invalidPackageName + " tried to change user " 13880 + oldPackage.mSharedUserId); 13881 return; 13882 } 13883 13884 // In case of rollback, remember per-user/profile install state 13885 allUsers = sUserManager.getUserIds(); 13886 installedUsers = ps.queryInstalledUsers(allUsers, true); 13887 } 13888 13889 // Update what is removed 13890 res.removedInfo = new PackageRemovedInfo(); 13891 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13892 res.removedInfo.removedPackage = oldPackage.packageName; 13893 res.removedInfo.isUpdate = true; 13894 res.removedInfo.origUsers = installedUsers; 13895 final int childCount = (oldPackage.childPackages != null) 13896 ? oldPackage.childPackages.size() : 0; 13897 for (int i = 0; i < childCount; i++) { 13898 boolean childPackageUpdated = false; 13899 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13900 if (res.addedChildPackages != null) { 13901 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13902 if (childRes != null) { 13903 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13904 childRes.removedInfo.removedPackage = childPkg.packageName; 13905 childRes.removedInfo.isUpdate = true; 13906 childPackageUpdated = true; 13907 } 13908 } 13909 if (!childPackageUpdated) { 13910 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13911 childRemovedRes.removedPackage = childPkg.packageName; 13912 childRemovedRes.isUpdate = false; 13913 childRemovedRes.dataRemoved = true; 13914 synchronized (mPackages) { 13915 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13916 if (childPs != null) { 13917 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13918 } 13919 } 13920 if (res.removedInfo.removedChildPackages == null) { 13921 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13922 } 13923 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13924 } 13925 } 13926 13927 boolean sysPkg = (isSystemApp(oldPackage)); 13928 if (sysPkg) { 13929 // Set the system/privileged flags as needed 13930 final boolean privileged = 13931 (oldPackage.applicationInfo.privateFlags 13932 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13933 final int systemPolicyFlags = policyFlags 13934 | PackageParser.PARSE_IS_SYSTEM 13935 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13936 13937 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13938 user, allUsers, installerPackageName, res); 13939 } else { 13940 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13941 user, allUsers, installerPackageName, res); 13942 } 13943 } 13944 13945 public List<String> getPreviousCodePaths(String packageName) { 13946 final PackageSetting ps = mSettings.mPackages.get(packageName); 13947 final List<String> result = new ArrayList<String>(); 13948 if (ps != null && ps.oldCodePaths != null) { 13949 result.addAll(ps.oldCodePaths); 13950 } 13951 return result; 13952 } 13953 13954 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13955 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13956 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13957 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13958 + deletedPackage); 13959 13960 String pkgName = deletedPackage.packageName; 13961 boolean deletedPkg = true; 13962 boolean addedPkg = false; 13963 boolean updatedSettings = false; 13964 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13965 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13966 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13967 13968 final long origUpdateTime = (pkg.mExtras != null) 13969 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13970 13971 // First delete the existing package while retaining the data directory 13972 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13973 res.removedInfo, true, pkg)) { 13974 // If the existing package wasn't successfully deleted 13975 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13976 deletedPkg = false; 13977 } else { 13978 // Successfully deleted the old package; proceed with replace. 13979 13980 // If deleted package lived in a container, give users a chance to 13981 // relinquish resources before killing. 13982 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13983 if (DEBUG_INSTALL) { 13984 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13985 } 13986 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13987 final ArrayList<String> pkgList = new ArrayList<String>(1); 13988 pkgList.add(deletedPackage.applicationInfo.packageName); 13989 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13990 } 13991 13992 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13993 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13994 clearAppProfilesLIF(pkg); 13995 13996 try { 13997 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13998 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13999 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14000 14001 // Update the in-memory copy of the previous code paths. 14002 PackageSetting ps = mSettings.mPackages.get(pkgName); 14003 if (!killApp) { 14004 if (ps.oldCodePaths == null) { 14005 ps.oldCodePaths = new ArraySet<>(); 14006 } 14007 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14008 if (deletedPackage.splitCodePaths != null) { 14009 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14010 } 14011 } else { 14012 ps.oldCodePaths = null; 14013 } 14014 if (ps.childPackageNames != null) { 14015 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14016 final String childPkgName = ps.childPackageNames.get(i); 14017 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14018 childPs.oldCodePaths = ps.oldCodePaths; 14019 } 14020 } 14021 prepareAppDataAfterInstallLIF(newPackage); 14022 addedPkg = true; 14023 } catch (PackageManagerException e) { 14024 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14025 } 14026 } 14027 14028 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14029 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14030 14031 // Revert all internal state mutations and added folders for the failed install 14032 if (addedPkg) { 14033 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14034 res.removedInfo, true, null); 14035 } 14036 14037 // Restore the old package 14038 if (deletedPkg) { 14039 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14040 File restoreFile = new File(deletedPackage.codePath); 14041 // Parse old package 14042 boolean oldExternal = isExternal(deletedPackage); 14043 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14044 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14045 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14046 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14047 try { 14048 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14049 null); 14050 } catch (PackageManagerException e) { 14051 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14052 + e.getMessage()); 14053 return; 14054 } 14055 14056 synchronized (mPackages) { 14057 // Ensure the installer package name up to date 14058 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14059 14060 // Update permissions for restored package 14061 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14062 14063 mSettings.writeLPr(); 14064 } 14065 14066 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14067 } 14068 } else { 14069 synchronized (mPackages) { 14070 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14071 if (ps != null) { 14072 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14073 if (res.removedInfo.removedChildPackages != null) { 14074 final int childCount = res.removedInfo.removedChildPackages.size(); 14075 // Iterate in reverse as we may modify the collection 14076 for (int i = childCount - 1; i >= 0; i--) { 14077 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14078 if (res.addedChildPackages.containsKey(childPackageName)) { 14079 res.removedInfo.removedChildPackages.removeAt(i); 14080 } else { 14081 PackageRemovedInfo childInfo = res.removedInfo 14082 .removedChildPackages.valueAt(i); 14083 childInfo.removedForAllUsers = mPackages.get( 14084 childInfo.removedPackage) == null; 14085 } 14086 } 14087 } 14088 } 14089 } 14090 } 14091 } 14092 14093 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14094 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14095 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14096 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14097 + ", old=" + deletedPackage); 14098 14099 final boolean disabledSystem; 14100 14101 // Remove existing system package 14102 removePackageLI(deletedPackage, true); 14103 14104 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14105 if (!disabledSystem) { 14106 // We didn't need to disable the .apk as a current system package, 14107 // which means we are replacing another update that is already 14108 // installed. We need to make sure to delete the older one's .apk. 14109 res.removedInfo.args = createInstallArgsForExisting(0, 14110 deletedPackage.applicationInfo.getCodePath(), 14111 deletedPackage.applicationInfo.getResourcePath(), 14112 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14113 } else { 14114 res.removedInfo.args = null; 14115 } 14116 14117 // Successfully disabled the old package. Now proceed with re-installation 14118 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14119 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14120 clearAppProfilesLIF(pkg); 14121 14122 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14123 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14124 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14125 14126 PackageParser.Package newPackage = null; 14127 try { 14128 // Add the package to the internal data structures 14129 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14130 14131 // Set the update and install times 14132 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14133 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14134 System.currentTimeMillis()); 14135 14136 // Update the package dynamic state if succeeded 14137 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14138 // Now that the install succeeded make sure we remove data 14139 // directories for any child package the update removed. 14140 final int deletedChildCount = (deletedPackage.childPackages != null) 14141 ? deletedPackage.childPackages.size() : 0; 14142 final int newChildCount = (newPackage.childPackages != null) 14143 ? newPackage.childPackages.size() : 0; 14144 for (int i = 0; i < deletedChildCount; i++) { 14145 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14146 boolean childPackageDeleted = true; 14147 for (int j = 0; j < newChildCount; j++) { 14148 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14149 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14150 childPackageDeleted = false; 14151 break; 14152 } 14153 } 14154 if (childPackageDeleted) { 14155 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14156 deletedChildPkg.packageName); 14157 if (ps != null && res.removedInfo.removedChildPackages != null) { 14158 PackageRemovedInfo removedChildRes = res.removedInfo 14159 .removedChildPackages.get(deletedChildPkg.packageName); 14160 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14161 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14162 } 14163 } 14164 } 14165 14166 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14167 prepareAppDataAfterInstallLIF(newPackage); 14168 } 14169 } catch (PackageManagerException e) { 14170 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14171 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14172 } 14173 14174 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14175 // Re installation failed. Restore old information 14176 // Remove new pkg information 14177 if (newPackage != null) { 14178 removeInstalledPackageLI(newPackage, true); 14179 } 14180 // Add back the old system package 14181 try { 14182 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14183 } catch (PackageManagerException e) { 14184 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14185 } 14186 14187 synchronized (mPackages) { 14188 if (disabledSystem) { 14189 enableSystemPackageLPw(deletedPackage); 14190 } 14191 14192 // Ensure the installer package name up to date 14193 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14194 14195 // Update permissions for restored package 14196 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14197 14198 mSettings.writeLPr(); 14199 } 14200 14201 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14202 + " after failed upgrade"); 14203 } 14204 } 14205 14206 /** 14207 * Checks whether the parent or any of the child packages have a change shared 14208 * user. For a package to be a valid update the shred users of the parent and 14209 * the children should match. We may later support changing child shared users. 14210 * @param oldPkg The updated package. 14211 * @param newPkg The update package. 14212 * @return The shared user that change between the versions. 14213 */ 14214 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14215 PackageParser.Package newPkg) { 14216 // Check parent shared user 14217 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14218 return newPkg.packageName; 14219 } 14220 // Check child shared users 14221 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14222 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14223 for (int i = 0; i < newChildCount; i++) { 14224 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14225 // If this child was present, did it have the same shared user? 14226 for (int j = 0; j < oldChildCount; j++) { 14227 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14228 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14229 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14230 return newChildPkg.packageName; 14231 } 14232 } 14233 } 14234 return null; 14235 } 14236 14237 private void removeNativeBinariesLI(PackageSetting ps) { 14238 // Remove the lib path for the parent package 14239 if (ps != null) { 14240 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14241 // Remove the lib path for the child packages 14242 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14243 for (int i = 0; i < childCount; i++) { 14244 PackageSetting childPs = null; 14245 synchronized (mPackages) { 14246 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14247 } 14248 if (childPs != null) { 14249 NativeLibraryHelper.removeNativeBinariesLI(childPs 14250 .legacyNativeLibraryPathString); 14251 } 14252 } 14253 } 14254 } 14255 14256 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14257 // Enable the parent package 14258 mSettings.enableSystemPackageLPw(pkg.packageName); 14259 // Enable the child packages 14260 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14261 for (int i = 0; i < childCount; i++) { 14262 PackageParser.Package childPkg = pkg.childPackages.get(i); 14263 mSettings.enableSystemPackageLPw(childPkg.packageName); 14264 } 14265 } 14266 14267 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14268 PackageParser.Package newPkg) { 14269 // Disable the parent package (parent always replaced) 14270 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14271 // Disable the child packages 14272 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14273 for (int i = 0; i < childCount; i++) { 14274 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14275 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14276 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14277 } 14278 return disabled; 14279 } 14280 14281 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14282 String installerPackageName) { 14283 // Enable the parent package 14284 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14285 // Enable the child packages 14286 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14287 for (int i = 0; i < childCount; i++) { 14288 PackageParser.Package childPkg = pkg.childPackages.get(i); 14289 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14290 } 14291 } 14292 14293 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14294 // Collect all used permissions in the UID 14295 ArraySet<String> usedPermissions = new ArraySet<>(); 14296 final int packageCount = su.packages.size(); 14297 for (int i = 0; i < packageCount; i++) { 14298 PackageSetting ps = su.packages.valueAt(i); 14299 if (ps.pkg == null) { 14300 continue; 14301 } 14302 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14303 for (int j = 0; j < requestedPermCount; j++) { 14304 String permission = ps.pkg.requestedPermissions.get(j); 14305 BasePermission bp = mSettings.mPermissions.get(permission); 14306 if (bp != null) { 14307 usedPermissions.add(permission); 14308 } 14309 } 14310 } 14311 14312 PermissionsState permissionsState = su.getPermissionsState(); 14313 // Prune install permissions 14314 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14315 final int installPermCount = installPermStates.size(); 14316 for (int i = installPermCount - 1; i >= 0; i--) { 14317 PermissionState permissionState = installPermStates.get(i); 14318 if (!usedPermissions.contains(permissionState.getName())) { 14319 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14320 if (bp != null) { 14321 permissionsState.revokeInstallPermission(bp); 14322 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14323 PackageManager.MASK_PERMISSION_FLAGS, 0); 14324 } 14325 } 14326 } 14327 14328 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14329 14330 // Prune runtime permissions 14331 for (int userId : allUserIds) { 14332 List<PermissionState> runtimePermStates = permissionsState 14333 .getRuntimePermissionStates(userId); 14334 final int runtimePermCount = runtimePermStates.size(); 14335 for (int i = runtimePermCount - 1; i >= 0; i--) { 14336 PermissionState permissionState = runtimePermStates.get(i); 14337 if (!usedPermissions.contains(permissionState.getName())) { 14338 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14339 if (bp != null) { 14340 permissionsState.revokeRuntimePermission(bp, userId); 14341 permissionsState.updatePermissionFlags(bp, userId, 14342 PackageManager.MASK_PERMISSION_FLAGS, 0); 14343 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14344 runtimePermissionChangedUserIds, userId); 14345 } 14346 } 14347 } 14348 } 14349 14350 return runtimePermissionChangedUserIds; 14351 } 14352 14353 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14354 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14355 // Update the parent package setting 14356 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14357 res, user); 14358 // Update the child packages setting 14359 final int childCount = (newPackage.childPackages != null) 14360 ? newPackage.childPackages.size() : 0; 14361 for (int i = 0; i < childCount; i++) { 14362 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14363 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14364 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14365 childRes.origUsers, childRes, user); 14366 } 14367 } 14368 14369 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14370 String installerPackageName, int[] allUsers, int[] installedForUsers, 14371 PackageInstalledInfo res, UserHandle user) { 14372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14373 14374 String pkgName = newPackage.packageName; 14375 synchronized (mPackages) { 14376 //write settings. the installStatus will be incomplete at this stage. 14377 //note that the new package setting would have already been 14378 //added to mPackages. It hasn't been persisted yet. 14379 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14381 mSettings.writeLPr(); 14382 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14383 } 14384 14385 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14386 synchronized (mPackages) { 14387 updatePermissionsLPw(newPackage.packageName, newPackage, 14388 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14389 ? UPDATE_PERMISSIONS_ALL : 0)); 14390 // For system-bundled packages, we assume that installing an upgraded version 14391 // of the package implies that the user actually wants to run that new code, 14392 // so we enable the package. 14393 PackageSetting ps = mSettings.mPackages.get(pkgName); 14394 final int userId = user.getIdentifier(); 14395 if (ps != null) { 14396 if (isSystemApp(newPackage)) { 14397 if (DEBUG_INSTALL) { 14398 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14399 } 14400 // Enable system package for requested users 14401 if (res.origUsers != null) { 14402 for (int origUserId : res.origUsers) { 14403 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14404 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14405 origUserId, installerPackageName); 14406 } 14407 } 14408 } 14409 // Also convey the prior install/uninstall state 14410 if (allUsers != null && installedForUsers != null) { 14411 for (int currentUserId : allUsers) { 14412 final boolean installed = ArrayUtils.contains( 14413 installedForUsers, currentUserId); 14414 if (DEBUG_INSTALL) { 14415 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14416 } 14417 ps.setInstalled(installed, currentUserId); 14418 } 14419 // these install state changes will be persisted in the 14420 // upcoming call to mSettings.writeLPr(). 14421 } 14422 } 14423 // It's implied that when a user requests installation, they want the app to be 14424 // installed and enabled. 14425 if (userId != UserHandle.USER_ALL) { 14426 ps.setInstalled(true, userId); 14427 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14428 } 14429 } 14430 res.name = pkgName; 14431 res.uid = newPackage.applicationInfo.uid; 14432 res.pkg = newPackage; 14433 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14434 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14435 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14436 //to update install status 14437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14438 mSettings.writeLPr(); 14439 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14440 } 14441 14442 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14443 } 14444 14445 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14446 try { 14447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14448 installPackageLI(args, res); 14449 } finally { 14450 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14451 } 14452 } 14453 14454 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14455 final int installFlags = args.installFlags; 14456 final String installerPackageName = args.installerPackageName; 14457 final String volumeUuid = args.volumeUuid; 14458 final File tmpPackageFile = new File(args.getCodePath()); 14459 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14460 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14461 || (args.volumeUuid != null)); 14462 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14463 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14464 boolean replace = false; 14465 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14466 if (args.move != null) { 14467 // moving a complete application; perform an initial scan on the new install location 14468 scanFlags |= SCAN_INITIAL; 14469 } 14470 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14471 scanFlags |= SCAN_DONT_KILL_APP; 14472 } 14473 14474 // Result object to be returned 14475 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14476 14477 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14478 14479 // Sanity check 14480 if (ephemeral && (forwardLocked || onExternal)) { 14481 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14482 + " external=" + onExternal); 14483 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14484 return; 14485 } 14486 14487 // Retrieve PackageSettings and parse package 14488 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14489 | PackageParser.PARSE_ENFORCE_CODE 14490 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14491 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14492 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14493 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14494 PackageParser pp = new PackageParser(); 14495 pp.setSeparateProcesses(mSeparateProcesses); 14496 pp.setDisplayMetrics(mMetrics); 14497 14498 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14499 final PackageParser.Package pkg; 14500 try { 14501 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14502 } catch (PackageParserException e) { 14503 res.setError("Failed parse during installPackageLI", e); 14504 return; 14505 } finally { 14506 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14507 } 14508 14509 // If we are installing a clustered package add results for the children 14510 if (pkg.childPackages != null) { 14511 synchronized (mPackages) { 14512 final int childCount = pkg.childPackages.size(); 14513 for (int i = 0; i < childCount; i++) { 14514 PackageParser.Package childPkg = pkg.childPackages.get(i); 14515 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14516 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14517 childRes.pkg = childPkg; 14518 childRes.name = childPkg.packageName; 14519 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14520 if (childPs != null) { 14521 childRes.origUsers = childPs.queryInstalledUsers( 14522 sUserManager.getUserIds(), true); 14523 } 14524 if ((mPackages.containsKey(childPkg.packageName))) { 14525 childRes.removedInfo = new PackageRemovedInfo(); 14526 childRes.removedInfo.removedPackage = childPkg.packageName; 14527 } 14528 if (res.addedChildPackages == null) { 14529 res.addedChildPackages = new ArrayMap<>(); 14530 } 14531 res.addedChildPackages.put(childPkg.packageName, childRes); 14532 } 14533 } 14534 } 14535 14536 // If package doesn't declare API override, mark that we have an install 14537 // time CPU ABI override. 14538 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14539 pkg.cpuAbiOverride = args.abiOverride; 14540 } 14541 14542 String pkgName = res.name = pkg.packageName; 14543 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14544 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14545 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14546 return; 14547 } 14548 } 14549 14550 try { 14551 // either use what we've been given or parse directly from the APK 14552 if (args.certificates != null) { 14553 try { 14554 PackageParser.populateCertificates(pkg, args.certificates); 14555 } catch (PackageParserException e) { 14556 // there was something wrong with the certificates we were given; 14557 // try to pull them from the APK 14558 PackageParser.collectCertificates(pkg, parseFlags); 14559 } 14560 } else { 14561 PackageParser.collectCertificates(pkg, parseFlags); 14562 } 14563 } catch (PackageParserException e) { 14564 res.setError("Failed collect during installPackageLI", e); 14565 return; 14566 } 14567 14568 // Get rid of all references to package scan path via parser. 14569 pp = null; 14570 String oldCodePath = null; 14571 boolean systemApp = false; 14572 synchronized (mPackages) { 14573 // Check if installing already existing package 14574 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14575 String oldName = mSettings.mRenamedPackages.get(pkgName); 14576 if (pkg.mOriginalPackages != null 14577 && pkg.mOriginalPackages.contains(oldName) 14578 && mPackages.containsKey(oldName)) { 14579 // This package is derived from an original package, 14580 // and this device has been updating from that original 14581 // name. We must continue using the original name, so 14582 // rename the new package here. 14583 pkg.setPackageName(oldName); 14584 pkgName = pkg.packageName; 14585 replace = true; 14586 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14587 + oldName + " pkgName=" + pkgName); 14588 } else if (mPackages.containsKey(pkgName)) { 14589 // This package, under its official name, already exists 14590 // on the device; we should replace it. 14591 replace = true; 14592 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14593 } 14594 14595 // Child packages are installed through the parent package 14596 if (pkg.parentPackage != null) { 14597 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14598 "Package " + pkg.packageName + " is child of package " 14599 + pkg.parentPackage.parentPackage + ". Child packages " 14600 + "can be updated only through the parent package."); 14601 return; 14602 } 14603 14604 if (replace) { 14605 // Prevent apps opting out from runtime permissions 14606 PackageParser.Package oldPackage = mPackages.get(pkgName); 14607 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14608 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14609 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14610 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14611 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14612 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14613 + " doesn't support runtime permissions but the old" 14614 + " target SDK " + oldTargetSdk + " does."); 14615 return; 14616 } 14617 14618 // Prevent installing of child packages 14619 if (oldPackage.parentPackage != null) { 14620 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14621 "Package " + pkg.packageName + " is child of package " 14622 + oldPackage.parentPackage + ". Child packages " 14623 + "can be updated only through the parent package."); 14624 return; 14625 } 14626 } 14627 } 14628 14629 PackageSetting ps = mSettings.mPackages.get(pkgName); 14630 if (ps != null) { 14631 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14632 14633 // Quick sanity check that we're signed correctly if updating; 14634 // we'll check this again later when scanning, but we want to 14635 // bail early here before tripping over redefined permissions. 14636 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14637 if (!checkUpgradeKeySetLP(ps, pkg)) { 14638 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14639 + pkg.packageName + " upgrade keys do not match the " 14640 + "previously installed version"); 14641 return; 14642 } 14643 } else { 14644 try { 14645 verifySignaturesLP(ps, pkg); 14646 } catch (PackageManagerException e) { 14647 res.setError(e.error, e.getMessage()); 14648 return; 14649 } 14650 } 14651 14652 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14653 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14654 systemApp = (ps.pkg.applicationInfo.flags & 14655 ApplicationInfo.FLAG_SYSTEM) != 0; 14656 } 14657 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14658 } 14659 14660 // Check whether the newly-scanned package wants to define an already-defined perm 14661 int N = pkg.permissions.size(); 14662 for (int i = N-1; i >= 0; i--) { 14663 PackageParser.Permission perm = pkg.permissions.get(i); 14664 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14665 if (bp != null) { 14666 // If the defining package is signed with our cert, it's okay. This 14667 // also includes the "updating the same package" case, of course. 14668 // "updating same package" could also involve key-rotation. 14669 final boolean sigsOk; 14670 if (bp.sourcePackage.equals(pkg.packageName) 14671 && (bp.packageSetting instanceof PackageSetting) 14672 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14673 scanFlags))) { 14674 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14675 } else { 14676 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14677 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14678 } 14679 if (!sigsOk) { 14680 // If the owning package is the system itself, we log but allow 14681 // install to proceed; we fail the install on all other permission 14682 // redefinitions. 14683 if (!bp.sourcePackage.equals("android")) { 14684 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14685 + pkg.packageName + " attempting to redeclare permission " 14686 + perm.info.name + " already owned by " + bp.sourcePackage); 14687 res.origPermission = perm.info.name; 14688 res.origPackage = bp.sourcePackage; 14689 return; 14690 } else { 14691 Slog.w(TAG, "Package " + pkg.packageName 14692 + " attempting to redeclare system permission " 14693 + perm.info.name + "; ignoring new declaration"); 14694 pkg.permissions.remove(i); 14695 } 14696 } 14697 } 14698 } 14699 } 14700 14701 if (systemApp) { 14702 if (onExternal) { 14703 // Abort update; system app can't be replaced with app on sdcard 14704 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14705 "Cannot install updates to system apps on sdcard"); 14706 return; 14707 } else if (ephemeral) { 14708 // Abort update; system app can't be replaced with an ephemeral app 14709 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14710 "Cannot update a system app with an ephemeral app"); 14711 return; 14712 } 14713 } 14714 14715 if (args.move != null) { 14716 // We did an in-place move, so dex is ready to roll 14717 scanFlags |= SCAN_NO_DEX; 14718 scanFlags |= SCAN_MOVE; 14719 14720 synchronized (mPackages) { 14721 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14722 if (ps == null) { 14723 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14724 "Missing settings for moved package " + pkgName); 14725 } 14726 14727 // We moved the entire application as-is, so bring over the 14728 // previously derived ABI information. 14729 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14730 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14731 } 14732 14733 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14734 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14735 scanFlags |= SCAN_NO_DEX; 14736 14737 try { 14738 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14739 args.abiOverride : pkg.cpuAbiOverride); 14740 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14741 true /* extract libs */); 14742 } catch (PackageManagerException pme) { 14743 Slog.e(TAG, "Error deriving application ABI", pme); 14744 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14745 return; 14746 } 14747 14748 // Shared libraries for the package need to be updated. 14749 synchronized (mPackages) { 14750 try { 14751 updateSharedLibrariesLPw(pkg, null); 14752 } catch (PackageManagerException e) { 14753 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14754 } 14755 } 14756 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14757 // Do not run PackageDexOptimizer through the local performDexOpt 14758 // method because `pkg` is not in `mPackages` yet. 14759 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14760 null /* instructionSets */, false /* checkProfiles */, 14761 getCompilerFilterForReason(REASON_INSTALL)); 14762 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14763 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14764 String msg = "Extracting package failed for " + pkgName; 14765 res.setError(INSTALL_FAILED_DEXOPT, msg); 14766 return; 14767 } 14768 14769 // Notify BackgroundDexOptService that the package has been changed. 14770 // If this is an update of a package which used to fail to compile, 14771 // BDOS will remove it from its blacklist. 14772 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14773 } 14774 14775 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14776 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14777 return; 14778 } 14779 14780 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14781 14782 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14783 "installPackageLI")) { 14784 if (replace) { 14785 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14786 installerPackageName, res); 14787 } else { 14788 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14789 args.user, installerPackageName, volumeUuid, res); 14790 } 14791 } 14792 synchronized (mPackages) { 14793 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14794 if (ps != null) { 14795 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14796 } 14797 14798 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14799 for (int i = 0; i < childCount; i++) { 14800 PackageParser.Package childPkg = pkg.childPackages.get(i); 14801 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14802 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14803 if (childPs != null) { 14804 childRes.newUsers = childPs.queryInstalledUsers( 14805 sUserManager.getUserIds(), true); 14806 } 14807 } 14808 } 14809 } 14810 14811 private void startIntentFilterVerifications(int userId, boolean replacing, 14812 PackageParser.Package pkg) { 14813 if (mIntentFilterVerifierComponent == null) { 14814 Slog.w(TAG, "No IntentFilter verification will not be done as " 14815 + "there is no IntentFilterVerifier available!"); 14816 return; 14817 } 14818 14819 final int verifierUid = getPackageUid( 14820 mIntentFilterVerifierComponent.getPackageName(), 14821 MATCH_DEBUG_TRIAGED_MISSING, 14822 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14823 14824 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14825 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14826 mHandler.sendMessage(msg); 14827 14828 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14829 for (int i = 0; i < childCount; i++) { 14830 PackageParser.Package childPkg = pkg.childPackages.get(i); 14831 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14832 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14833 mHandler.sendMessage(msg); 14834 } 14835 } 14836 14837 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14838 PackageParser.Package pkg) { 14839 int size = pkg.activities.size(); 14840 if (size == 0) { 14841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14842 "No activity, so no need to verify any IntentFilter!"); 14843 return; 14844 } 14845 14846 final boolean hasDomainURLs = hasDomainURLs(pkg); 14847 if (!hasDomainURLs) { 14848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14849 "No domain URLs, so no need to verify any IntentFilter!"); 14850 return; 14851 } 14852 14853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14854 + " if any IntentFilter from the " + size 14855 + " Activities needs verification ..."); 14856 14857 int count = 0; 14858 final String packageName = pkg.packageName; 14859 14860 synchronized (mPackages) { 14861 // If this is a new install and we see that we've already run verification for this 14862 // package, we have nothing to do: it means the state was restored from backup. 14863 if (!replacing) { 14864 IntentFilterVerificationInfo ivi = 14865 mSettings.getIntentFilterVerificationLPr(packageName); 14866 if (ivi != null) { 14867 if (DEBUG_DOMAIN_VERIFICATION) { 14868 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14869 + ivi.getStatusString()); 14870 } 14871 return; 14872 } 14873 } 14874 14875 // If any filters need to be verified, then all need to be. 14876 boolean needToVerify = false; 14877 for (PackageParser.Activity a : pkg.activities) { 14878 for (ActivityIntentInfo filter : a.intents) { 14879 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14880 if (DEBUG_DOMAIN_VERIFICATION) { 14881 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14882 } 14883 needToVerify = true; 14884 break; 14885 } 14886 } 14887 } 14888 14889 if (needToVerify) { 14890 final int verificationId = mIntentFilterVerificationToken++; 14891 for (PackageParser.Activity a : pkg.activities) { 14892 for (ActivityIntentInfo filter : a.intents) { 14893 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14894 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14895 "Verification needed for IntentFilter:" + filter.toString()); 14896 mIntentFilterVerifier.addOneIntentFilterVerification( 14897 verifierUid, userId, verificationId, filter, packageName); 14898 count++; 14899 } 14900 } 14901 } 14902 } 14903 } 14904 14905 if (count > 0) { 14906 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14907 + " IntentFilter verification" + (count > 1 ? "s" : "") 14908 + " for userId:" + userId); 14909 mIntentFilterVerifier.startVerifications(userId); 14910 } else { 14911 if (DEBUG_DOMAIN_VERIFICATION) { 14912 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14913 } 14914 } 14915 } 14916 14917 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14918 final ComponentName cn = filter.activity.getComponentName(); 14919 final String packageName = cn.getPackageName(); 14920 14921 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14922 packageName); 14923 if (ivi == null) { 14924 return true; 14925 } 14926 int status = ivi.getStatus(); 14927 switch (status) { 14928 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14929 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14930 return true; 14931 14932 default: 14933 // Nothing to do 14934 return false; 14935 } 14936 } 14937 14938 private static boolean isMultiArch(ApplicationInfo info) { 14939 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14940 } 14941 14942 private static boolean isExternal(PackageParser.Package pkg) { 14943 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14944 } 14945 14946 private static boolean isExternal(PackageSetting ps) { 14947 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14948 } 14949 14950 private static boolean isEphemeral(PackageParser.Package pkg) { 14951 return pkg.applicationInfo.isEphemeralApp(); 14952 } 14953 14954 private static boolean isEphemeral(PackageSetting ps) { 14955 return ps.pkg != null && isEphemeral(ps.pkg); 14956 } 14957 14958 private static boolean isSystemApp(PackageParser.Package pkg) { 14959 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14960 } 14961 14962 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14963 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14964 } 14965 14966 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14967 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14968 } 14969 14970 private static boolean isSystemApp(PackageSetting ps) { 14971 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14972 } 14973 14974 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14975 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14976 } 14977 14978 private int packageFlagsToInstallFlags(PackageSetting ps) { 14979 int installFlags = 0; 14980 if (isEphemeral(ps)) { 14981 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14982 } 14983 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14984 // This existing package was an external ASEC install when we have 14985 // the external flag without a UUID 14986 installFlags |= PackageManager.INSTALL_EXTERNAL; 14987 } 14988 if (ps.isForwardLocked()) { 14989 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14990 } 14991 return installFlags; 14992 } 14993 14994 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14995 if (isExternal(pkg)) { 14996 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14997 return StorageManager.UUID_PRIMARY_PHYSICAL; 14998 } else { 14999 return pkg.volumeUuid; 15000 } 15001 } else { 15002 return StorageManager.UUID_PRIVATE_INTERNAL; 15003 } 15004 } 15005 15006 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15007 if (isExternal(pkg)) { 15008 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15009 return mSettings.getExternalVersion(); 15010 } else { 15011 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15012 } 15013 } else { 15014 return mSettings.getInternalVersion(); 15015 } 15016 } 15017 15018 private void deleteTempPackageFiles() { 15019 final FilenameFilter filter = new FilenameFilter() { 15020 public boolean accept(File dir, String name) { 15021 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15022 } 15023 }; 15024 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15025 file.delete(); 15026 } 15027 } 15028 15029 @Override 15030 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15031 int flags) { 15032 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15033 flags); 15034 } 15035 15036 @Override 15037 public void deletePackage(final String packageName, 15038 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15039 mContext.enforceCallingOrSelfPermission( 15040 android.Manifest.permission.DELETE_PACKAGES, null); 15041 Preconditions.checkNotNull(packageName); 15042 Preconditions.checkNotNull(observer); 15043 final int uid = Binder.getCallingUid(); 15044 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15045 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15046 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15047 mContext.enforceCallingOrSelfPermission( 15048 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15049 "deletePackage for user " + userId); 15050 } 15051 15052 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15053 try { 15054 observer.onPackageDeleted(packageName, 15055 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15056 } catch (RemoteException re) { 15057 } 15058 return; 15059 } 15060 15061 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15062 try { 15063 observer.onPackageDeleted(packageName, 15064 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15065 } catch (RemoteException re) { 15066 } 15067 return; 15068 } 15069 15070 if (DEBUG_REMOVE) { 15071 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15072 + " deleteAllUsers: " + deleteAllUsers ); 15073 } 15074 // Queue up an async operation since the package deletion may take a little while. 15075 mHandler.post(new Runnable() { 15076 public void run() { 15077 mHandler.removeCallbacks(this); 15078 int returnCode; 15079 if (!deleteAllUsers) { 15080 returnCode = deletePackageX(packageName, userId, deleteFlags); 15081 } else { 15082 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15083 // If nobody is blocking uninstall, proceed with delete for all users 15084 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15085 returnCode = deletePackageX(packageName, userId, deleteFlags); 15086 } else { 15087 // Otherwise uninstall individually for users with blockUninstalls=false 15088 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15089 for (int userId : users) { 15090 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15091 returnCode = deletePackageX(packageName, userId, userFlags); 15092 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15093 Slog.w(TAG, "Package delete failed for user " + userId 15094 + ", returnCode " + returnCode); 15095 } 15096 } 15097 } 15098 // The app has only been marked uninstalled for certain users. 15099 // We still need to report that delete was blocked 15100 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15101 } 15102 } 15103 try { 15104 observer.onPackageDeleted(packageName, returnCode, null); 15105 } catch (RemoteException e) { 15106 Log.i(TAG, "Observer no longer exists."); 15107 } //end catch 15108 } //end run 15109 }); 15110 } 15111 15112 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15113 int[] result = EMPTY_INT_ARRAY; 15114 for (int userId : userIds) { 15115 if (getBlockUninstallForUser(packageName, userId)) { 15116 result = ArrayUtils.appendInt(result, userId); 15117 } 15118 } 15119 return result; 15120 } 15121 15122 @Override 15123 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15124 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15125 } 15126 15127 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15128 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15129 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15130 try { 15131 if (dpm != null) { 15132 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15133 /* callingUserOnly =*/ false); 15134 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15135 : deviceOwnerComponentName.getPackageName(); 15136 // Does the package contains the device owner? 15137 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15138 // this check is probably not needed, since DO should be registered as a device 15139 // admin on some user too. (Original bug for this: b/17657954) 15140 if (packageName.equals(deviceOwnerPackageName)) { 15141 return true; 15142 } 15143 // Does it contain a device admin for any user? 15144 int[] users; 15145 if (userId == UserHandle.USER_ALL) { 15146 users = sUserManager.getUserIds(); 15147 } else { 15148 users = new int[]{userId}; 15149 } 15150 for (int i = 0; i < users.length; ++i) { 15151 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15152 return true; 15153 } 15154 } 15155 } 15156 } catch (RemoteException e) { 15157 } 15158 return false; 15159 } 15160 15161 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15162 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15163 } 15164 15165 /** 15166 * This method is an internal method that could be get invoked either 15167 * to delete an installed package or to clean up a failed installation. 15168 * After deleting an installed package, a broadcast is sent to notify any 15169 * listeners that the package has been removed. For cleaning up a failed 15170 * installation, the broadcast is not necessary since the package's 15171 * installation wouldn't have sent the initial broadcast either 15172 * The key steps in deleting a package are 15173 * deleting the package information in internal structures like mPackages, 15174 * deleting the packages base directories through installd 15175 * updating mSettings to reflect current status 15176 * persisting settings for later use 15177 * sending a broadcast if necessary 15178 */ 15179 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15180 final PackageRemovedInfo info = new PackageRemovedInfo(); 15181 final boolean res; 15182 15183 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15184 ? UserHandle.ALL : new UserHandle(userId); 15185 15186 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15187 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15188 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15189 } 15190 15191 PackageSetting uninstalledPs = null; 15192 15193 // for the uninstall-updates case and restricted profiles, remember the per- 15194 // user handle installed state 15195 int[] allUsers; 15196 synchronized (mPackages) { 15197 uninstalledPs = mSettings.mPackages.get(packageName); 15198 if (uninstalledPs == null) { 15199 Slog.w(TAG, "Not removing non-existent package " + packageName); 15200 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15201 } 15202 allUsers = sUserManager.getUserIds(); 15203 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15204 } 15205 15206 synchronized (mInstallLock) { 15207 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15208 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15209 "deletePackageX")) { 15210 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15211 deleteFlags | REMOVE_CHATTY, info, true, null); 15212 } 15213 synchronized (mPackages) { 15214 if (res) { 15215 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15216 } 15217 } 15218 } 15219 15220 if (res) { 15221 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15222 info.sendPackageRemovedBroadcasts(killApp); 15223 info.sendSystemPackageUpdatedBroadcasts(); 15224 info.sendSystemPackageAppearedBroadcasts(); 15225 } 15226 // Force a gc here. 15227 Runtime.getRuntime().gc(); 15228 // Delete the resources here after sending the broadcast to let 15229 // other processes clean up before deleting resources. 15230 if (info.args != null) { 15231 synchronized (mInstallLock) { 15232 info.args.doPostDeleteLI(true); 15233 } 15234 } 15235 15236 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15237 } 15238 15239 class PackageRemovedInfo { 15240 String removedPackage; 15241 int uid = -1; 15242 int removedAppId = -1; 15243 int[] origUsers; 15244 int[] removedUsers = null; 15245 boolean isRemovedPackageSystemUpdate = false; 15246 boolean isUpdate; 15247 boolean dataRemoved; 15248 boolean removedForAllUsers; 15249 // Clean up resources deleted packages. 15250 InstallArgs args = null; 15251 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15252 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15253 15254 void sendPackageRemovedBroadcasts(boolean killApp) { 15255 sendPackageRemovedBroadcastInternal(killApp); 15256 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15257 for (int i = 0; i < childCount; i++) { 15258 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15259 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15260 } 15261 } 15262 15263 void sendSystemPackageUpdatedBroadcasts() { 15264 if (isRemovedPackageSystemUpdate) { 15265 sendSystemPackageUpdatedBroadcastsInternal(); 15266 final int childCount = (removedChildPackages != null) 15267 ? removedChildPackages.size() : 0; 15268 for (int i = 0; i < childCount; i++) { 15269 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15270 if (childInfo.isRemovedPackageSystemUpdate) { 15271 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15272 } 15273 } 15274 } 15275 } 15276 15277 void sendSystemPackageAppearedBroadcasts() { 15278 final int packageCount = (appearedChildPackages != null) 15279 ? appearedChildPackages.size() : 0; 15280 for (int i = 0; i < packageCount; i++) { 15281 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15282 for (int userId : installedInfo.newUsers) { 15283 sendPackageAddedForUser(installedInfo.name, true, 15284 UserHandle.getAppId(installedInfo.uid), userId); 15285 } 15286 } 15287 } 15288 15289 private void sendSystemPackageUpdatedBroadcastsInternal() { 15290 Bundle extras = new Bundle(2); 15291 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15292 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15293 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15294 extras, 0, null, null, null); 15295 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15296 extras, 0, null, null, null); 15297 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15298 null, 0, removedPackage, null, null); 15299 } 15300 15301 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15302 Bundle extras = new Bundle(2); 15303 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15304 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15305 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15306 if (isUpdate || isRemovedPackageSystemUpdate) { 15307 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15308 } 15309 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15310 if (removedPackage != null) { 15311 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15312 extras, 0, null, null, removedUsers); 15313 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15314 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15315 removedPackage, extras, 0, null, null, removedUsers); 15316 } 15317 } 15318 if (removedAppId >= 0) { 15319 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15320 removedUsers); 15321 } 15322 } 15323 } 15324 15325 /* 15326 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15327 * flag is not set, the data directory is removed as well. 15328 * make sure this flag is set for partially installed apps. If not its meaningless to 15329 * delete a partially installed application. 15330 */ 15331 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15332 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15333 String packageName = ps.name; 15334 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15335 // Retrieve object to delete permissions for shared user later on 15336 final PackageParser.Package deletedPkg; 15337 final PackageSetting deletedPs; 15338 // reader 15339 synchronized (mPackages) { 15340 deletedPkg = mPackages.get(packageName); 15341 deletedPs = mSettings.mPackages.get(packageName); 15342 if (outInfo != null) { 15343 outInfo.removedPackage = packageName; 15344 outInfo.removedUsers = deletedPs != null 15345 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15346 : null; 15347 } 15348 } 15349 15350 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15351 15352 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15353 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15354 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15355 destroyAppProfilesLIF(deletedPkg); 15356 if (outInfo != null) { 15357 outInfo.dataRemoved = true; 15358 } 15359 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15360 } 15361 15362 // writer 15363 synchronized (mPackages) { 15364 if (deletedPs != null) { 15365 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15366 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15367 clearDefaultBrowserIfNeeded(packageName); 15368 if (outInfo != null) { 15369 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15370 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15371 } 15372 updatePermissionsLPw(deletedPs.name, null, 0); 15373 if (deletedPs.sharedUser != null) { 15374 // Remove permissions associated with package. Since runtime 15375 // permissions are per user we have to kill the removed package 15376 // or packages running under the shared user of the removed 15377 // package if revoking the permissions requested only by the removed 15378 // package is successful and this causes a change in gids. 15379 for (int userId : UserManagerService.getInstance().getUserIds()) { 15380 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15381 userId); 15382 if (userIdToKill == UserHandle.USER_ALL 15383 || userIdToKill >= UserHandle.USER_SYSTEM) { 15384 // If gids changed for this user, kill all affected packages. 15385 mHandler.post(new Runnable() { 15386 @Override 15387 public void run() { 15388 // This has to happen with no lock held. 15389 killApplication(deletedPs.name, deletedPs.appId, 15390 KILL_APP_REASON_GIDS_CHANGED); 15391 } 15392 }); 15393 break; 15394 } 15395 } 15396 } 15397 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15398 } 15399 // make sure to preserve per-user disabled state if this removal was just 15400 // a downgrade of a system app to the factory package 15401 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15402 if (DEBUG_REMOVE) { 15403 Slog.d(TAG, "Propagating install state across downgrade"); 15404 } 15405 for (int userId : allUserHandles) { 15406 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15407 if (DEBUG_REMOVE) { 15408 Slog.d(TAG, " user " + userId + " => " + installed); 15409 } 15410 ps.setInstalled(installed, userId); 15411 } 15412 } 15413 } 15414 // can downgrade to reader 15415 if (writeSettings) { 15416 // Save settings now 15417 mSettings.writeLPr(); 15418 } 15419 } 15420 if (outInfo != null) { 15421 // A user ID was deleted here. Go through all users and remove it 15422 // from KeyStore. 15423 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15424 } 15425 } 15426 15427 static boolean locationIsPrivileged(File path) { 15428 try { 15429 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15430 .getCanonicalPath(); 15431 return path.getCanonicalPath().startsWith(privilegedAppDir); 15432 } catch (IOException e) { 15433 Slog.e(TAG, "Unable to access code path " + path); 15434 } 15435 return false; 15436 } 15437 15438 /* 15439 * Tries to delete system package. 15440 */ 15441 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15442 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15443 boolean writeSettings) { 15444 if (deletedPs.parentPackageName != null) { 15445 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15446 return false; 15447 } 15448 15449 final boolean applyUserRestrictions 15450 = (allUserHandles != null) && (outInfo.origUsers != null); 15451 final PackageSetting disabledPs; 15452 // Confirm if the system package has been updated 15453 // An updated system app can be deleted. This will also have to restore 15454 // the system pkg from system partition 15455 // reader 15456 synchronized (mPackages) { 15457 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15458 } 15459 15460 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15461 + " disabledPs=" + disabledPs); 15462 15463 if (disabledPs == null) { 15464 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15465 return false; 15466 } else if (DEBUG_REMOVE) { 15467 Slog.d(TAG, "Deleting system pkg from data partition"); 15468 } 15469 15470 if (DEBUG_REMOVE) { 15471 if (applyUserRestrictions) { 15472 Slog.d(TAG, "Remembering install states:"); 15473 for (int userId : allUserHandles) { 15474 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15475 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15476 } 15477 } 15478 } 15479 15480 // Delete the updated package 15481 outInfo.isRemovedPackageSystemUpdate = true; 15482 if (outInfo.removedChildPackages != null) { 15483 final int childCount = (deletedPs.childPackageNames != null) 15484 ? deletedPs.childPackageNames.size() : 0; 15485 for (int i = 0; i < childCount; i++) { 15486 String childPackageName = deletedPs.childPackageNames.get(i); 15487 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15488 .contains(childPackageName)) { 15489 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15490 childPackageName); 15491 if (childInfo != null) { 15492 childInfo.isRemovedPackageSystemUpdate = true; 15493 } 15494 } 15495 } 15496 } 15497 15498 if (disabledPs.versionCode < deletedPs.versionCode) { 15499 // Delete data for downgrades 15500 flags &= ~PackageManager.DELETE_KEEP_DATA; 15501 } else { 15502 // Preserve data by setting flag 15503 flags |= PackageManager.DELETE_KEEP_DATA; 15504 } 15505 15506 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15507 outInfo, writeSettings, disabledPs.pkg); 15508 if (!ret) { 15509 return false; 15510 } 15511 15512 // writer 15513 synchronized (mPackages) { 15514 // Reinstate the old system package 15515 enableSystemPackageLPw(disabledPs.pkg); 15516 // Remove any native libraries from the upgraded package. 15517 removeNativeBinariesLI(deletedPs); 15518 } 15519 15520 // Install the system package 15521 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15522 int parseFlags = mDefParseFlags 15523 | PackageParser.PARSE_MUST_BE_APK 15524 | PackageParser.PARSE_IS_SYSTEM 15525 | PackageParser.PARSE_IS_SYSTEM_DIR; 15526 if (locationIsPrivileged(disabledPs.codePath)) { 15527 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15528 } 15529 15530 final PackageParser.Package newPkg; 15531 try { 15532 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15533 } catch (PackageManagerException e) { 15534 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15535 + e.getMessage()); 15536 return false; 15537 } 15538 15539 prepareAppDataAfterInstallLIF(newPkg); 15540 15541 // writer 15542 synchronized (mPackages) { 15543 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15544 15545 // Propagate the permissions state as we do not want to drop on the floor 15546 // runtime permissions. The update permissions method below will take 15547 // care of removing obsolete permissions and grant install permissions. 15548 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15549 updatePermissionsLPw(newPkg.packageName, newPkg, 15550 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15551 15552 if (applyUserRestrictions) { 15553 if (DEBUG_REMOVE) { 15554 Slog.d(TAG, "Propagating install state across reinstall"); 15555 } 15556 for (int userId : allUserHandles) { 15557 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15558 if (DEBUG_REMOVE) { 15559 Slog.d(TAG, " user " + userId + " => " + installed); 15560 } 15561 ps.setInstalled(installed, userId); 15562 15563 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15564 } 15565 // Regardless of writeSettings we need to ensure that this restriction 15566 // state propagation is persisted 15567 mSettings.writeAllUsersPackageRestrictionsLPr(); 15568 } 15569 // can downgrade to reader here 15570 if (writeSettings) { 15571 mSettings.writeLPr(); 15572 } 15573 } 15574 return true; 15575 } 15576 15577 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15578 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15579 PackageRemovedInfo outInfo, boolean writeSettings, 15580 PackageParser.Package replacingPackage) { 15581 synchronized (mPackages) { 15582 if (outInfo != null) { 15583 outInfo.uid = ps.appId; 15584 } 15585 15586 if (outInfo != null && outInfo.removedChildPackages != null) { 15587 final int childCount = (ps.childPackageNames != null) 15588 ? ps.childPackageNames.size() : 0; 15589 for (int i = 0; i < childCount; i++) { 15590 String childPackageName = ps.childPackageNames.get(i); 15591 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15592 if (childPs == null) { 15593 return false; 15594 } 15595 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15596 childPackageName); 15597 if (childInfo != null) { 15598 childInfo.uid = childPs.appId; 15599 } 15600 } 15601 } 15602 } 15603 15604 // Delete package data from internal structures and also remove data if flag is set 15605 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15606 15607 // Delete the child packages data 15608 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15609 for (int i = 0; i < childCount; i++) { 15610 PackageSetting childPs; 15611 synchronized (mPackages) { 15612 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15613 } 15614 if (childPs != null) { 15615 PackageRemovedInfo childOutInfo = (outInfo != null 15616 && outInfo.removedChildPackages != null) 15617 ? outInfo.removedChildPackages.get(childPs.name) : null; 15618 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15619 && (replacingPackage != null 15620 && !replacingPackage.hasChildPackage(childPs.name)) 15621 ? flags & ~DELETE_KEEP_DATA : flags; 15622 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15623 deleteFlags, writeSettings); 15624 } 15625 } 15626 15627 // Delete application code and resources only for parent packages 15628 if (ps.parentPackageName == null) { 15629 if (deleteCodeAndResources && (outInfo != null)) { 15630 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15631 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15632 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15633 } 15634 } 15635 15636 return true; 15637 } 15638 15639 @Override 15640 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15641 int userId) { 15642 mContext.enforceCallingOrSelfPermission( 15643 android.Manifest.permission.DELETE_PACKAGES, null); 15644 synchronized (mPackages) { 15645 PackageSetting ps = mSettings.mPackages.get(packageName); 15646 if (ps == null) { 15647 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15648 return false; 15649 } 15650 if (!ps.getInstalled(userId)) { 15651 // Can't block uninstall for an app that is not installed or enabled. 15652 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15653 return false; 15654 } 15655 ps.setBlockUninstall(blockUninstall, userId); 15656 mSettings.writePackageRestrictionsLPr(userId); 15657 } 15658 return true; 15659 } 15660 15661 @Override 15662 public boolean getBlockUninstallForUser(String packageName, int userId) { 15663 synchronized (mPackages) { 15664 PackageSetting ps = mSettings.mPackages.get(packageName); 15665 if (ps == null) { 15666 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15667 return false; 15668 } 15669 return ps.getBlockUninstall(userId); 15670 } 15671 } 15672 15673 @Override 15674 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15675 int callingUid = Binder.getCallingUid(); 15676 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15677 throw new SecurityException( 15678 "setRequiredForSystemUser can only be run by the system or root"); 15679 } 15680 synchronized (mPackages) { 15681 PackageSetting ps = mSettings.mPackages.get(packageName); 15682 if (ps == null) { 15683 Log.w(TAG, "Package doesn't exist: " + packageName); 15684 return false; 15685 } 15686 if (systemUserApp) { 15687 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15688 } else { 15689 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15690 } 15691 mSettings.writeLPr(); 15692 } 15693 return true; 15694 } 15695 15696 /* 15697 * This method handles package deletion in general 15698 */ 15699 private boolean deletePackageLIF(String packageName, UserHandle user, 15700 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15701 PackageRemovedInfo outInfo, boolean writeSettings, 15702 PackageParser.Package replacingPackage) { 15703 if (packageName == null) { 15704 Slog.w(TAG, "Attempt to delete null packageName."); 15705 return false; 15706 } 15707 15708 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15709 15710 PackageSetting ps; 15711 15712 synchronized (mPackages) { 15713 ps = mSettings.mPackages.get(packageName); 15714 if (ps == null) { 15715 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15716 return false; 15717 } 15718 15719 if (ps.parentPackageName != null && (!isSystemApp(ps) 15720 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15721 if (DEBUG_REMOVE) { 15722 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15723 + ((user == null) ? UserHandle.USER_ALL : user)); 15724 } 15725 final int removedUserId = (user != null) ? user.getIdentifier() 15726 : UserHandle.USER_ALL; 15727 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15728 return false; 15729 } 15730 markPackageUninstalledForUserLPw(ps, user); 15731 scheduleWritePackageRestrictionsLocked(user); 15732 return true; 15733 } 15734 } 15735 15736 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15737 && user.getIdentifier() != UserHandle.USER_ALL)) { 15738 // The caller is asking that the package only be deleted for a single 15739 // user. To do this, we just mark its uninstalled state and delete 15740 // its data. If this is a system app, we only allow this to happen if 15741 // they have set the special DELETE_SYSTEM_APP which requests different 15742 // semantics than normal for uninstalling system apps. 15743 markPackageUninstalledForUserLPw(ps, user); 15744 15745 if (!isSystemApp(ps)) { 15746 // Do not uninstall the APK if an app should be cached 15747 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15748 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15749 // Other user still have this package installed, so all 15750 // we need to do is clear this user's data and save that 15751 // it is uninstalled. 15752 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15753 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15754 return false; 15755 } 15756 scheduleWritePackageRestrictionsLocked(user); 15757 return true; 15758 } else { 15759 // We need to set it back to 'installed' so the uninstall 15760 // broadcasts will be sent correctly. 15761 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15762 ps.setInstalled(true, user.getIdentifier()); 15763 } 15764 } else { 15765 // This is a system app, so we assume that the 15766 // other users still have this package installed, so all 15767 // we need to do is clear this user's data and save that 15768 // it is uninstalled. 15769 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15770 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15771 return false; 15772 } 15773 scheduleWritePackageRestrictionsLocked(user); 15774 return true; 15775 } 15776 } 15777 15778 // If we are deleting a composite package for all users, keep track 15779 // of result for each child. 15780 if (ps.childPackageNames != null && outInfo != null) { 15781 synchronized (mPackages) { 15782 final int childCount = ps.childPackageNames.size(); 15783 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15784 for (int i = 0; i < childCount; i++) { 15785 String childPackageName = ps.childPackageNames.get(i); 15786 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15787 childInfo.removedPackage = childPackageName; 15788 outInfo.removedChildPackages.put(childPackageName, childInfo); 15789 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15790 if (childPs != null) { 15791 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15792 } 15793 } 15794 } 15795 } 15796 15797 boolean ret = false; 15798 if (isSystemApp(ps)) { 15799 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15800 // When an updated system application is deleted we delete the existing resources 15801 // as well and fall back to existing code in system partition 15802 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15803 } else { 15804 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15805 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15806 outInfo, writeSettings, replacingPackage); 15807 } 15808 15809 // Take a note whether we deleted the package for all users 15810 if (outInfo != null) { 15811 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15812 if (outInfo.removedChildPackages != null) { 15813 synchronized (mPackages) { 15814 final int childCount = outInfo.removedChildPackages.size(); 15815 for (int i = 0; i < childCount; i++) { 15816 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15817 if (childInfo != null) { 15818 childInfo.removedForAllUsers = mPackages.get( 15819 childInfo.removedPackage) == null; 15820 } 15821 } 15822 } 15823 } 15824 // If we uninstalled an update to a system app there may be some 15825 // child packages that appeared as they are declared in the system 15826 // app but were not declared in the update. 15827 if (isSystemApp(ps)) { 15828 synchronized (mPackages) { 15829 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15830 final int childCount = (updatedPs.childPackageNames != null) 15831 ? updatedPs.childPackageNames.size() : 0; 15832 for (int i = 0; i < childCount; i++) { 15833 String childPackageName = updatedPs.childPackageNames.get(i); 15834 if (outInfo.removedChildPackages == null 15835 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15836 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15837 if (childPs == null) { 15838 continue; 15839 } 15840 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15841 installRes.name = childPackageName; 15842 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15843 installRes.pkg = mPackages.get(childPackageName); 15844 installRes.uid = childPs.pkg.applicationInfo.uid; 15845 if (outInfo.appearedChildPackages == null) { 15846 outInfo.appearedChildPackages = new ArrayMap<>(); 15847 } 15848 outInfo.appearedChildPackages.put(childPackageName, installRes); 15849 } 15850 } 15851 } 15852 } 15853 } 15854 15855 return ret; 15856 } 15857 15858 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15859 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15860 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15861 for (int nextUserId : userIds) { 15862 if (DEBUG_REMOVE) { 15863 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15864 } 15865 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15866 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15867 false /*hidden*/, false /*suspended*/, null, null, null, 15868 false /*blockUninstall*/, 15869 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15870 } 15871 } 15872 15873 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15874 PackageRemovedInfo outInfo) { 15875 final PackageParser.Package pkg; 15876 synchronized (mPackages) { 15877 pkg = mPackages.get(ps.name); 15878 } 15879 15880 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15881 : new int[] {userId}; 15882 for (int nextUserId : userIds) { 15883 if (DEBUG_REMOVE) { 15884 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15885 + nextUserId); 15886 } 15887 15888 destroyAppDataLIF(pkg, userId, 15889 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15890 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15891 schedulePackageCleaning(ps.name, nextUserId, false); 15892 synchronized (mPackages) { 15893 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15894 scheduleWritePackageRestrictionsLocked(nextUserId); 15895 } 15896 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15897 } 15898 } 15899 15900 if (outInfo != null) { 15901 outInfo.removedPackage = ps.name; 15902 outInfo.removedAppId = ps.appId; 15903 outInfo.removedUsers = userIds; 15904 } 15905 15906 return true; 15907 } 15908 15909 private final class ClearStorageConnection implements ServiceConnection { 15910 IMediaContainerService mContainerService; 15911 15912 @Override 15913 public void onServiceConnected(ComponentName name, IBinder service) { 15914 synchronized (this) { 15915 mContainerService = IMediaContainerService.Stub.asInterface(service); 15916 notifyAll(); 15917 } 15918 } 15919 15920 @Override 15921 public void onServiceDisconnected(ComponentName name) { 15922 } 15923 } 15924 15925 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15926 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15927 15928 final boolean mounted; 15929 if (Environment.isExternalStorageEmulated()) { 15930 mounted = true; 15931 } else { 15932 final String status = Environment.getExternalStorageState(); 15933 15934 mounted = status.equals(Environment.MEDIA_MOUNTED) 15935 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15936 } 15937 15938 if (!mounted) { 15939 return; 15940 } 15941 15942 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15943 int[] users; 15944 if (userId == UserHandle.USER_ALL) { 15945 users = sUserManager.getUserIds(); 15946 } else { 15947 users = new int[] { userId }; 15948 } 15949 final ClearStorageConnection conn = new ClearStorageConnection(); 15950 if (mContext.bindServiceAsUser( 15951 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15952 try { 15953 for (int curUser : users) { 15954 long timeout = SystemClock.uptimeMillis() + 5000; 15955 synchronized (conn) { 15956 long now = SystemClock.uptimeMillis(); 15957 while (conn.mContainerService == null && now < timeout) { 15958 try { 15959 conn.wait(timeout - now); 15960 } catch (InterruptedException e) { 15961 } 15962 } 15963 } 15964 if (conn.mContainerService == null) { 15965 return; 15966 } 15967 15968 final UserEnvironment userEnv = new UserEnvironment(curUser); 15969 clearDirectory(conn.mContainerService, 15970 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15971 if (allData) { 15972 clearDirectory(conn.mContainerService, 15973 userEnv.buildExternalStorageAppDataDirs(packageName)); 15974 clearDirectory(conn.mContainerService, 15975 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15976 } 15977 } 15978 } finally { 15979 mContext.unbindService(conn); 15980 } 15981 } 15982 } 15983 15984 @Override 15985 public void clearApplicationProfileData(String packageName) { 15986 enforceSystemOrRoot("Only the system can clear all profile data"); 15987 15988 final PackageParser.Package pkg; 15989 synchronized (mPackages) { 15990 pkg = mPackages.get(packageName); 15991 } 15992 15993 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15994 synchronized (mInstallLock) { 15995 clearAppProfilesLIF(pkg); 15996 } 15997 } 15998 } 15999 16000 @Override 16001 public void clearApplicationUserData(final String packageName, 16002 final IPackageDataObserver observer, final int userId) { 16003 mContext.enforceCallingOrSelfPermission( 16004 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16005 16006 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16007 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16008 16009 final DevicePolicyManagerInternal dpmi = LocalServices 16010 .getService(DevicePolicyManagerInternal.class); 16011 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16012 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16013 } 16014 // Queue up an async operation since the package deletion may take a little while. 16015 mHandler.post(new Runnable() { 16016 public void run() { 16017 mHandler.removeCallbacks(this); 16018 final boolean succeeded; 16019 try (PackageFreezer freezer = freezePackage(packageName, 16020 "clearApplicationUserData")) { 16021 synchronized (mInstallLock) { 16022 succeeded = clearApplicationUserDataLIF(packageName, userId); 16023 } 16024 clearExternalStorageDataSync(packageName, userId, true); 16025 } 16026 if (succeeded) { 16027 // invoke DeviceStorageMonitor's update method to clear any notifications 16028 DeviceStorageMonitorInternal dsm = LocalServices 16029 .getService(DeviceStorageMonitorInternal.class); 16030 if (dsm != null) { 16031 dsm.checkMemory(); 16032 } 16033 } 16034 if(observer != null) { 16035 try { 16036 observer.onRemoveCompleted(packageName, succeeded); 16037 } catch (RemoteException e) { 16038 Log.i(TAG, "Observer no longer exists."); 16039 } 16040 } //end if observer 16041 } //end run 16042 }); 16043 } 16044 16045 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16046 if (packageName == null) { 16047 Slog.w(TAG, "Attempt to delete null packageName."); 16048 return false; 16049 } 16050 16051 // Try finding details about the requested package 16052 PackageParser.Package pkg; 16053 synchronized (mPackages) { 16054 pkg = mPackages.get(packageName); 16055 if (pkg == null) { 16056 final PackageSetting ps = mSettings.mPackages.get(packageName); 16057 if (ps != null) { 16058 pkg = ps.pkg; 16059 } 16060 } 16061 16062 if (pkg == null) { 16063 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16064 return false; 16065 } 16066 16067 PackageSetting ps = (PackageSetting) pkg.mExtras; 16068 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16069 } 16070 16071 clearAppDataLIF(pkg, userId, 16072 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16073 16074 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16075 removeKeystoreDataIfNeeded(userId, appId); 16076 16077 final UserManager um = mContext.getSystemService(UserManager.class); 16078 final int flags; 16079 if (um.isUserUnlockingOrUnlocked(userId)) { 16080 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16081 } else if (um.isUserRunning(userId)) { 16082 flags = StorageManager.FLAG_STORAGE_DE; 16083 } else { 16084 flags = 0; 16085 } 16086 prepareAppDataContentsLIF(pkg, userId, flags); 16087 16088 return true; 16089 } 16090 16091 /** 16092 * Reverts user permission state changes (permissions and flags) in 16093 * all packages for a given user. 16094 * 16095 * @param userId The device user for which to do a reset. 16096 */ 16097 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16098 final int packageCount = mPackages.size(); 16099 for (int i = 0; i < packageCount; i++) { 16100 PackageParser.Package pkg = mPackages.valueAt(i); 16101 PackageSetting ps = (PackageSetting) pkg.mExtras; 16102 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16103 } 16104 } 16105 16106 /** 16107 * Reverts user permission state changes (permissions and flags). 16108 * 16109 * @param ps The package for which to reset. 16110 * @param userId The device user for which to do a reset. 16111 */ 16112 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16113 final PackageSetting ps, final int userId) { 16114 if (ps.pkg == null) { 16115 return; 16116 } 16117 16118 // These are flags that can change base on user actions. 16119 final int userSettableMask = FLAG_PERMISSION_USER_SET 16120 | FLAG_PERMISSION_USER_FIXED 16121 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16122 | FLAG_PERMISSION_REVIEW_REQUIRED; 16123 16124 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16125 | FLAG_PERMISSION_POLICY_FIXED; 16126 16127 boolean writeInstallPermissions = false; 16128 boolean writeRuntimePermissions = false; 16129 16130 final int permissionCount = ps.pkg.requestedPermissions.size(); 16131 for (int i = 0; i < permissionCount; i++) { 16132 String permission = ps.pkg.requestedPermissions.get(i); 16133 16134 BasePermission bp = mSettings.mPermissions.get(permission); 16135 if (bp == null) { 16136 continue; 16137 } 16138 16139 // If shared user we just reset the state to which only this app contributed. 16140 if (ps.sharedUser != null) { 16141 boolean used = false; 16142 final int packageCount = ps.sharedUser.packages.size(); 16143 for (int j = 0; j < packageCount; j++) { 16144 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16145 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16146 && pkg.pkg.requestedPermissions.contains(permission)) { 16147 used = true; 16148 break; 16149 } 16150 } 16151 if (used) { 16152 continue; 16153 } 16154 } 16155 16156 PermissionsState permissionsState = ps.getPermissionsState(); 16157 16158 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16159 16160 // Always clear the user settable flags. 16161 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16162 bp.name) != null; 16163 // If permission review is enabled and this is a legacy app, mark the 16164 // permission as requiring a review as this is the initial state. 16165 int flags = 0; 16166 if (Build.PERMISSIONS_REVIEW_REQUIRED 16167 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16168 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16169 } 16170 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16171 if (hasInstallState) { 16172 writeInstallPermissions = true; 16173 } else { 16174 writeRuntimePermissions = true; 16175 } 16176 } 16177 16178 // Below is only runtime permission handling. 16179 if (!bp.isRuntime()) { 16180 continue; 16181 } 16182 16183 // Never clobber system or policy. 16184 if ((oldFlags & policyOrSystemFlags) != 0) { 16185 continue; 16186 } 16187 16188 // If this permission was granted by default, make sure it is. 16189 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16190 if (permissionsState.grantRuntimePermission(bp, userId) 16191 != PERMISSION_OPERATION_FAILURE) { 16192 writeRuntimePermissions = true; 16193 } 16194 // If permission review is enabled the permissions for a legacy apps 16195 // are represented as constantly granted runtime ones, so don't revoke. 16196 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16197 // Otherwise, reset the permission. 16198 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16199 switch (revokeResult) { 16200 case PERMISSION_OPERATION_SUCCESS: 16201 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16202 writeRuntimePermissions = true; 16203 final int appId = ps.appId; 16204 mHandler.post(new Runnable() { 16205 @Override 16206 public void run() { 16207 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16208 } 16209 }); 16210 } break; 16211 } 16212 } 16213 } 16214 16215 // Synchronously write as we are taking permissions away. 16216 if (writeRuntimePermissions) { 16217 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16218 } 16219 16220 // Synchronously write as we are taking permissions away. 16221 if (writeInstallPermissions) { 16222 mSettings.writeLPr(); 16223 } 16224 } 16225 16226 /** 16227 * Remove entries from the keystore daemon. Will only remove it if the 16228 * {@code appId} is valid. 16229 */ 16230 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16231 if (appId < 0) { 16232 return; 16233 } 16234 16235 final KeyStore keyStore = KeyStore.getInstance(); 16236 if (keyStore != null) { 16237 if (userId == UserHandle.USER_ALL) { 16238 for (final int individual : sUserManager.getUserIds()) { 16239 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16240 } 16241 } else { 16242 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16243 } 16244 } else { 16245 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16246 } 16247 } 16248 16249 @Override 16250 public void deleteApplicationCacheFiles(final String packageName, 16251 final IPackageDataObserver observer) { 16252 final int userId = UserHandle.getCallingUserId(); 16253 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16254 } 16255 16256 @Override 16257 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16258 final IPackageDataObserver observer) { 16259 mContext.enforceCallingOrSelfPermission( 16260 android.Manifest.permission.DELETE_CACHE_FILES, null); 16261 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16262 /* requireFullPermission= */ true, /* checkShell= */ false, 16263 "delete application cache files"); 16264 16265 final PackageParser.Package pkg; 16266 synchronized (mPackages) { 16267 pkg = mPackages.get(packageName); 16268 } 16269 16270 // Queue up an async operation since the package deletion may take a little while. 16271 mHandler.post(new Runnable() { 16272 public void run() { 16273 synchronized (mInstallLock) { 16274 final int flags = StorageManager.FLAG_STORAGE_DE 16275 | StorageManager.FLAG_STORAGE_CE; 16276 // We're only clearing cache files, so we don't care if the 16277 // app is unfrozen and still able to run 16278 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16279 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16280 } 16281 clearExternalStorageDataSync(packageName, userId, false); 16282 if (observer != null) { 16283 try { 16284 observer.onRemoveCompleted(packageName, true); 16285 } catch (RemoteException e) { 16286 Log.i(TAG, "Observer no longer exists."); 16287 } 16288 } 16289 } 16290 }); 16291 } 16292 16293 @Override 16294 public void getPackageSizeInfo(final String packageName, int userHandle, 16295 final IPackageStatsObserver observer) { 16296 mContext.enforceCallingOrSelfPermission( 16297 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16298 if (packageName == null) { 16299 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16300 } 16301 16302 PackageStats stats = new PackageStats(packageName, userHandle); 16303 16304 /* 16305 * Queue up an async operation since the package measurement may take a 16306 * little while. 16307 */ 16308 Message msg = mHandler.obtainMessage(INIT_COPY); 16309 msg.obj = new MeasureParams(stats, observer); 16310 mHandler.sendMessage(msg); 16311 } 16312 16313 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16314 final PackageSetting ps; 16315 synchronized (mPackages) { 16316 ps = mSettings.mPackages.get(packageName); 16317 if (ps == null) { 16318 Slog.w(TAG, "Failed to find settings for " + packageName); 16319 return false; 16320 } 16321 } 16322 try { 16323 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16324 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16325 ps.getCeDataInode(userId), ps.codePathString, stats); 16326 } catch (InstallerException e) { 16327 Slog.w(TAG, String.valueOf(e)); 16328 return false; 16329 } 16330 16331 // For now, ignore code size of packages on system partition 16332 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16333 stats.codeSize = 0; 16334 } 16335 16336 return true; 16337 } 16338 16339 private int getUidTargetSdkVersionLockedLPr(int uid) { 16340 Object obj = mSettings.getUserIdLPr(uid); 16341 if (obj instanceof SharedUserSetting) { 16342 final SharedUserSetting sus = (SharedUserSetting) obj; 16343 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16344 final Iterator<PackageSetting> it = sus.packages.iterator(); 16345 while (it.hasNext()) { 16346 final PackageSetting ps = it.next(); 16347 if (ps.pkg != null) { 16348 int v = ps.pkg.applicationInfo.targetSdkVersion; 16349 if (v < vers) vers = v; 16350 } 16351 } 16352 return vers; 16353 } else if (obj instanceof PackageSetting) { 16354 final PackageSetting ps = (PackageSetting) obj; 16355 if (ps.pkg != null) { 16356 return ps.pkg.applicationInfo.targetSdkVersion; 16357 } 16358 } 16359 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16360 } 16361 16362 @Override 16363 public void addPreferredActivity(IntentFilter filter, int match, 16364 ComponentName[] set, ComponentName activity, int userId) { 16365 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16366 "Adding preferred"); 16367 } 16368 16369 private void addPreferredActivityInternal(IntentFilter filter, int match, 16370 ComponentName[] set, ComponentName activity, boolean always, int userId, 16371 String opname) { 16372 // writer 16373 int callingUid = Binder.getCallingUid(); 16374 enforceCrossUserPermission(callingUid, userId, 16375 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16376 if (filter.countActions() == 0) { 16377 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16378 return; 16379 } 16380 synchronized (mPackages) { 16381 if (mContext.checkCallingOrSelfPermission( 16382 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16383 != PackageManager.PERMISSION_GRANTED) { 16384 if (getUidTargetSdkVersionLockedLPr(callingUid) 16385 < Build.VERSION_CODES.FROYO) { 16386 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16387 + callingUid); 16388 return; 16389 } 16390 mContext.enforceCallingOrSelfPermission( 16391 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16392 } 16393 16394 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16395 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16396 + userId + ":"); 16397 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16398 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16399 scheduleWritePackageRestrictionsLocked(userId); 16400 } 16401 } 16402 16403 @Override 16404 public void replacePreferredActivity(IntentFilter filter, int match, 16405 ComponentName[] set, ComponentName activity, int userId) { 16406 if (filter.countActions() != 1) { 16407 throw new IllegalArgumentException( 16408 "replacePreferredActivity expects filter to have only 1 action."); 16409 } 16410 if (filter.countDataAuthorities() != 0 16411 || filter.countDataPaths() != 0 16412 || filter.countDataSchemes() > 1 16413 || filter.countDataTypes() != 0) { 16414 throw new IllegalArgumentException( 16415 "replacePreferredActivity expects filter to have no data authorities, " + 16416 "paths, or types; and at most one scheme."); 16417 } 16418 16419 final int callingUid = Binder.getCallingUid(); 16420 enforceCrossUserPermission(callingUid, userId, 16421 true /* requireFullPermission */, false /* checkShell */, 16422 "replace preferred activity"); 16423 synchronized (mPackages) { 16424 if (mContext.checkCallingOrSelfPermission( 16425 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16426 != PackageManager.PERMISSION_GRANTED) { 16427 if (getUidTargetSdkVersionLockedLPr(callingUid) 16428 < Build.VERSION_CODES.FROYO) { 16429 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16430 + Binder.getCallingUid()); 16431 return; 16432 } 16433 mContext.enforceCallingOrSelfPermission( 16434 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16435 } 16436 16437 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16438 if (pir != null) { 16439 // Get all of the existing entries that exactly match this filter. 16440 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16441 if (existing != null && existing.size() == 1) { 16442 PreferredActivity cur = existing.get(0); 16443 if (DEBUG_PREFERRED) { 16444 Slog.i(TAG, "Checking replace of preferred:"); 16445 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16446 if (!cur.mPref.mAlways) { 16447 Slog.i(TAG, " -- CUR; not mAlways!"); 16448 } else { 16449 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16450 Slog.i(TAG, " -- CUR: mSet=" 16451 + Arrays.toString(cur.mPref.mSetComponents)); 16452 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16453 Slog.i(TAG, " -- NEW: mMatch=" 16454 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16455 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16456 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16457 } 16458 } 16459 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16460 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16461 && cur.mPref.sameSet(set)) { 16462 // Setting the preferred activity to what it happens to be already 16463 if (DEBUG_PREFERRED) { 16464 Slog.i(TAG, "Replacing with same preferred activity " 16465 + cur.mPref.mShortComponent + " for user " 16466 + userId + ":"); 16467 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16468 } 16469 return; 16470 } 16471 } 16472 16473 if (existing != null) { 16474 if (DEBUG_PREFERRED) { 16475 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16476 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16477 } 16478 for (int i = 0; i < existing.size(); i++) { 16479 PreferredActivity pa = existing.get(i); 16480 if (DEBUG_PREFERRED) { 16481 Slog.i(TAG, "Removing existing preferred activity " 16482 + pa.mPref.mComponent + ":"); 16483 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16484 } 16485 pir.removeFilter(pa); 16486 } 16487 } 16488 } 16489 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16490 "Replacing preferred"); 16491 } 16492 } 16493 16494 @Override 16495 public void clearPackagePreferredActivities(String packageName) { 16496 final int uid = Binder.getCallingUid(); 16497 // writer 16498 synchronized (mPackages) { 16499 PackageParser.Package pkg = mPackages.get(packageName); 16500 if (pkg == null || pkg.applicationInfo.uid != uid) { 16501 if (mContext.checkCallingOrSelfPermission( 16502 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16503 != PackageManager.PERMISSION_GRANTED) { 16504 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16505 < Build.VERSION_CODES.FROYO) { 16506 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16507 + Binder.getCallingUid()); 16508 return; 16509 } 16510 mContext.enforceCallingOrSelfPermission( 16511 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16512 } 16513 } 16514 16515 int user = UserHandle.getCallingUserId(); 16516 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16517 scheduleWritePackageRestrictionsLocked(user); 16518 } 16519 } 16520 } 16521 16522 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16523 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16524 ArrayList<PreferredActivity> removed = null; 16525 boolean changed = false; 16526 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16527 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16528 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16529 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16530 continue; 16531 } 16532 Iterator<PreferredActivity> it = pir.filterIterator(); 16533 while (it.hasNext()) { 16534 PreferredActivity pa = it.next(); 16535 // Mark entry for removal only if it matches the package name 16536 // and the entry is of type "always". 16537 if (packageName == null || 16538 (pa.mPref.mComponent.getPackageName().equals(packageName) 16539 && pa.mPref.mAlways)) { 16540 if (removed == null) { 16541 removed = new ArrayList<PreferredActivity>(); 16542 } 16543 removed.add(pa); 16544 } 16545 } 16546 if (removed != null) { 16547 for (int j=0; j<removed.size(); j++) { 16548 PreferredActivity pa = removed.get(j); 16549 pir.removeFilter(pa); 16550 } 16551 changed = true; 16552 } 16553 } 16554 return changed; 16555 } 16556 16557 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16558 private void clearIntentFilterVerificationsLPw(int userId) { 16559 final int packageCount = mPackages.size(); 16560 for (int i = 0; i < packageCount; i++) { 16561 PackageParser.Package pkg = mPackages.valueAt(i); 16562 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16563 } 16564 } 16565 16566 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16567 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16568 if (userId == UserHandle.USER_ALL) { 16569 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16570 sUserManager.getUserIds())) { 16571 for (int oneUserId : sUserManager.getUserIds()) { 16572 scheduleWritePackageRestrictionsLocked(oneUserId); 16573 } 16574 } 16575 } else { 16576 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16577 scheduleWritePackageRestrictionsLocked(userId); 16578 } 16579 } 16580 } 16581 16582 void clearDefaultBrowserIfNeeded(String packageName) { 16583 for (int oneUserId : sUserManager.getUserIds()) { 16584 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16585 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16586 if (packageName.equals(defaultBrowserPackageName)) { 16587 setDefaultBrowserPackageName(null, oneUserId); 16588 } 16589 } 16590 } 16591 16592 @Override 16593 public void resetApplicationPreferences(int userId) { 16594 mContext.enforceCallingOrSelfPermission( 16595 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16596 // writer 16597 synchronized (mPackages) { 16598 final long identity = Binder.clearCallingIdentity(); 16599 try { 16600 clearPackagePreferredActivitiesLPw(null, userId); 16601 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16602 // TODO: We have to reset the default SMS and Phone. This requires 16603 // significant refactoring to keep all default apps in the package 16604 // manager (cleaner but more work) or have the services provide 16605 // callbacks to the package manager to request a default app reset. 16606 applyFactoryDefaultBrowserLPw(userId); 16607 clearIntentFilterVerificationsLPw(userId); 16608 primeDomainVerificationsLPw(userId); 16609 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16610 scheduleWritePackageRestrictionsLocked(userId); 16611 } finally { 16612 Binder.restoreCallingIdentity(identity); 16613 } 16614 } 16615 } 16616 16617 @Override 16618 public int getPreferredActivities(List<IntentFilter> outFilters, 16619 List<ComponentName> outActivities, String packageName) { 16620 16621 int num = 0; 16622 final int userId = UserHandle.getCallingUserId(); 16623 // reader 16624 synchronized (mPackages) { 16625 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16626 if (pir != null) { 16627 final Iterator<PreferredActivity> it = pir.filterIterator(); 16628 while (it.hasNext()) { 16629 final PreferredActivity pa = it.next(); 16630 if (packageName == null 16631 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16632 && pa.mPref.mAlways)) { 16633 if (outFilters != null) { 16634 outFilters.add(new IntentFilter(pa)); 16635 } 16636 if (outActivities != null) { 16637 outActivities.add(pa.mPref.mComponent); 16638 } 16639 } 16640 } 16641 } 16642 } 16643 16644 return num; 16645 } 16646 16647 @Override 16648 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16649 int userId) { 16650 int callingUid = Binder.getCallingUid(); 16651 if (callingUid != Process.SYSTEM_UID) { 16652 throw new SecurityException( 16653 "addPersistentPreferredActivity can only be run by the system"); 16654 } 16655 if (filter.countActions() == 0) { 16656 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16657 return; 16658 } 16659 synchronized (mPackages) { 16660 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16661 ":"); 16662 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16663 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16664 new PersistentPreferredActivity(filter, activity)); 16665 scheduleWritePackageRestrictionsLocked(userId); 16666 } 16667 } 16668 16669 @Override 16670 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16671 int callingUid = Binder.getCallingUid(); 16672 if (callingUid != Process.SYSTEM_UID) { 16673 throw new SecurityException( 16674 "clearPackagePersistentPreferredActivities can only be run by the system"); 16675 } 16676 ArrayList<PersistentPreferredActivity> removed = null; 16677 boolean changed = false; 16678 synchronized (mPackages) { 16679 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16680 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16681 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16682 .valueAt(i); 16683 if (userId != thisUserId) { 16684 continue; 16685 } 16686 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16687 while (it.hasNext()) { 16688 PersistentPreferredActivity ppa = it.next(); 16689 // Mark entry for removal only if it matches the package name. 16690 if (ppa.mComponent.getPackageName().equals(packageName)) { 16691 if (removed == null) { 16692 removed = new ArrayList<PersistentPreferredActivity>(); 16693 } 16694 removed.add(ppa); 16695 } 16696 } 16697 if (removed != null) { 16698 for (int j=0; j<removed.size(); j++) { 16699 PersistentPreferredActivity ppa = removed.get(j); 16700 ppir.removeFilter(ppa); 16701 } 16702 changed = true; 16703 } 16704 } 16705 16706 if (changed) { 16707 scheduleWritePackageRestrictionsLocked(userId); 16708 } 16709 } 16710 } 16711 16712 /** 16713 * Common machinery for picking apart a restored XML blob and passing 16714 * it to a caller-supplied functor to be applied to the running system. 16715 */ 16716 private void restoreFromXml(XmlPullParser parser, int userId, 16717 String expectedStartTag, BlobXmlRestorer functor) 16718 throws IOException, XmlPullParserException { 16719 int type; 16720 while ((type = parser.next()) != XmlPullParser.START_TAG 16721 && type != XmlPullParser.END_DOCUMENT) { 16722 } 16723 if (type != XmlPullParser.START_TAG) { 16724 // oops didn't find a start tag?! 16725 if (DEBUG_BACKUP) { 16726 Slog.e(TAG, "Didn't find start tag during restore"); 16727 } 16728 return; 16729 } 16730Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16731 // this is supposed to be TAG_PREFERRED_BACKUP 16732 if (!expectedStartTag.equals(parser.getName())) { 16733 if (DEBUG_BACKUP) { 16734 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16735 } 16736 return; 16737 } 16738 16739 // skip interfering stuff, then we're aligned with the backing implementation 16740 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16741Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16742 functor.apply(parser, userId); 16743 } 16744 16745 private interface BlobXmlRestorer { 16746 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16747 } 16748 16749 /** 16750 * Non-Binder method, support for the backup/restore mechanism: write the 16751 * full set of preferred activities in its canonical XML format. Returns the 16752 * XML output as a byte array, or null if there is none. 16753 */ 16754 @Override 16755 public byte[] getPreferredActivityBackup(int userId) { 16756 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16757 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16758 } 16759 16760 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16761 try { 16762 final XmlSerializer serializer = new FastXmlSerializer(); 16763 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16764 serializer.startDocument(null, true); 16765 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16766 16767 synchronized (mPackages) { 16768 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16769 } 16770 16771 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16772 serializer.endDocument(); 16773 serializer.flush(); 16774 } catch (Exception e) { 16775 if (DEBUG_BACKUP) { 16776 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16777 } 16778 return null; 16779 } 16780 16781 return dataStream.toByteArray(); 16782 } 16783 16784 @Override 16785 public void restorePreferredActivities(byte[] backup, int userId) { 16786 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16787 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16788 } 16789 16790 try { 16791 final XmlPullParser parser = Xml.newPullParser(); 16792 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16793 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16794 new BlobXmlRestorer() { 16795 @Override 16796 public void apply(XmlPullParser parser, int userId) 16797 throws XmlPullParserException, IOException { 16798 synchronized (mPackages) { 16799 mSettings.readPreferredActivitiesLPw(parser, userId); 16800 } 16801 } 16802 } ); 16803 } catch (Exception e) { 16804 if (DEBUG_BACKUP) { 16805 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16806 } 16807 } 16808 } 16809 16810 /** 16811 * Non-Binder method, support for the backup/restore mechanism: write the 16812 * default browser (etc) settings in its canonical XML format. Returns the default 16813 * browser XML representation as a byte array, or null if there is none. 16814 */ 16815 @Override 16816 public byte[] getDefaultAppsBackup(int userId) { 16817 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16818 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16819 } 16820 16821 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16822 try { 16823 final XmlSerializer serializer = new FastXmlSerializer(); 16824 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16825 serializer.startDocument(null, true); 16826 serializer.startTag(null, TAG_DEFAULT_APPS); 16827 16828 synchronized (mPackages) { 16829 mSettings.writeDefaultAppsLPr(serializer, userId); 16830 } 16831 16832 serializer.endTag(null, TAG_DEFAULT_APPS); 16833 serializer.endDocument(); 16834 serializer.flush(); 16835 } catch (Exception e) { 16836 if (DEBUG_BACKUP) { 16837 Slog.e(TAG, "Unable to write default apps for backup", e); 16838 } 16839 return null; 16840 } 16841 16842 return dataStream.toByteArray(); 16843 } 16844 16845 @Override 16846 public void restoreDefaultApps(byte[] backup, int userId) { 16847 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16848 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16849 } 16850 16851 try { 16852 final XmlPullParser parser = Xml.newPullParser(); 16853 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16854 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16855 new BlobXmlRestorer() { 16856 @Override 16857 public void apply(XmlPullParser parser, int userId) 16858 throws XmlPullParserException, IOException { 16859 synchronized (mPackages) { 16860 mSettings.readDefaultAppsLPw(parser, userId); 16861 } 16862 } 16863 } ); 16864 } catch (Exception e) { 16865 if (DEBUG_BACKUP) { 16866 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16867 } 16868 } 16869 } 16870 16871 @Override 16872 public byte[] getIntentFilterVerificationBackup(int userId) { 16873 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16874 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16875 } 16876 16877 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16878 try { 16879 final XmlSerializer serializer = new FastXmlSerializer(); 16880 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16881 serializer.startDocument(null, true); 16882 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16883 16884 synchronized (mPackages) { 16885 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16886 } 16887 16888 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16889 serializer.endDocument(); 16890 serializer.flush(); 16891 } catch (Exception e) { 16892 if (DEBUG_BACKUP) { 16893 Slog.e(TAG, "Unable to write default apps for backup", e); 16894 } 16895 return null; 16896 } 16897 16898 return dataStream.toByteArray(); 16899 } 16900 16901 @Override 16902 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16904 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16905 } 16906 16907 try { 16908 final XmlPullParser parser = Xml.newPullParser(); 16909 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16910 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16911 new BlobXmlRestorer() { 16912 @Override 16913 public void apply(XmlPullParser parser, int userId) 16914 throws XmlPullParserException, IOException { 16915 synchronized (mPackages) { 16916 mSettings.readAllDomainVerificationsLPr(parser, userId); 16917 mSettings.writeLPr(); 16918 } 16919 } 16920 } ); 16921 } catch (Exception e) { 16922 if (DEBUG_BACKUP) { 16923 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16924 } 16925 } 16926 } 16927 16928 @Override 16929 public byte[] getPermissionGrantBackup(int userId) { 16930 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16931 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16932 } 16933 16934 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16935 try { 16936 final XmlSerializer serializer = new FastXmlSerializer(); 16937 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16938 serializer.startDocument(null, true); 16939 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16940 16941 synchronized (mPackages) { 16942 serializeRuntimePermissionGrantsLPr(serializer, userId); 16943 } 16944 16945 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16946 serializer.endDocument(); 16947 serializer.flush(); 16948 } catch (Exception e) { 16949 if (DEBUG_BACKUP) { 16950 Slog.e(TAG, "Unable to write default apps for backup", e); 16951 } 16952 return null; 16953 } 16954 16955 return dataStream.toByteArray(); 16956 } 16957 16958 @Override 16959 public void restorePermissionGrants(byte[] backup, int userId) { 16960 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16961 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16962 } 16963 16964 try { 16965 final XmlPullParser parser = Xml.newPullParser(); 16966 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16967 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16968 new BlobXmlRestorer() { 16969 @Override 16970 public void apply(XmlPullParser parser, int userId) 16971 throws XmlPullParserException, IOException { 16972 synchronized (mPackages) { 16973 processRestoredPermissionGrantsLPr(parser, userId); 16974 } 16975 } 16976 } ); 16977 } catch (Exception e) { 16978 if (DEBUG_BACKUP) { 16979 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16980 } 16981 } 16982 } 16983 16984 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16985 throws IOException { 16986 serializer.startTag(null, TAG_ALL_GRANTS); 16987 16988 final int N = mSettings.mPackages.size(); 16989 for (int i = 0; i < N; i++) { 16990 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16991 boolean pkgGrantsKnown = false; 16992 16993 PermissionsState packagePerms = ps.getPermissionsState(); 16994 16995 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16996 final int grantFlags = state.getFlags(); 16997 // only look at grants that are not system/policy fixed 16998 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16999 final boolean isGranted = state.isGranted(); 17000 // And only back up the user-twiddled state bits 17001 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17002 final String packageName = mSettings.mPackages.keyAt(i); 17003 if (!pkgGrantsKnown) { 17004 serializer.startTag(null, TAG_GRANT); 17005 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17006 pkgGrantsKnown = true; 17007 } 17008 17009 final boolean userSet = 17010 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17011 final boolean userFixed = 17012 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17013 final boolean revoke = 17014 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17015 17016 serializer.startTag(null, TAG_PERMISSION); 17017 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17018 if (isGranted) { 17019 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17020 } 17021 if (userSet) { 17022 serializer.attribute(null, ATTR_USER_SET, "true"); 17023 } 17024 if (userFixed) { 17025 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17026 } 17027 if (revoke) { 17028 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17029 } 17030 serializer.endTag(null, TAG_PERMISSION); 17031 } 17032 } 17033 } 17034 17035 if (pkgGrantsKnown) { 17036 serializer.endTag(null, TAG_GRANT); 17037 } 17038 } 17039 17040 serializer.endTag(null, TAG_ALL_GRANTS); 17041 } 17042 17043 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17044 throws XmlPullParserException, IOException { 17045 String pkgName = null; 17046 int outerDepth = parser.getDepth(); 17047 int type; 17048 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17049 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17050 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17051 continue; 17052 } 17053 17054 final String tagName = parser.getName(); 17055 if (tagName.equals(TAG_GRANT)) { 17056 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17057 if (DEBUG_BACKUP) { 17058 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17059 } 17060 } else if (tagName.equals(TAG_PERMISSION)) { 17061 17062 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17063 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17064 17065 int newFlagSet = 0; 17066 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17067 newFlagSet |= FLAG_PERMISSION_USER_SET; 17068 } 17069 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17070 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17071 } 17072 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17073 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17074 } 17075 if (DEBUG_BACKUP) { 17076 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17077 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17078 } 17079 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17080 if (ps != null) { 17081 // Already installed so we apply the grant immediately 17082 if (DEBUG_BACKUP) { 17083 Slog.v(TAG, " + already installed; applying"); 17084 } 17085 PermissionsState perms = ps.getPermissionsState(); 17086 BasePermission bp = mSettings.mPermissions.get(permName); 17087 if (bp != null) { 17088 if (isGranted) { 17089 perms.grantRuntimePermission(bp, userId); 17090 } 17091 if (newFlagSet != 0) { 17092 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17093 } 17094 } 17095 } else { 17096 // Need to wait for post-restore install to apply the grant 17097 if (DEBUG_BACKUP) { 17098 Slog.v(TAG, " - not yet installed; saving for later"); 17099 } 17100 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17101 isGranted, newFlagSet, userId); 17102 } 17103 } else { 17104 PackageManagerService.reportSettingsProblem(Log.WARN, 17105 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17106 XmlUtils.skipCurrentTag(parser); 17107 } 17108 } 17109 17110 scheduleWriteSettingsLocked(); 17111 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17112 } 17113 17114 @Override 17115 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17116 int sourceUserId, int targetUserId, int flags) { 17117 mContext.enforceCallingOrSelfPermission( 17118 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17119 int callingUid = Binder.getCallingUid(); 17120 enforceOwnerRights(ownerPackage, callingUid); 17121 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17122 if (intentFilter.countActions() == 0) { 17123 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17124 return; 17125 } 17126 synchronized (mPackages) { 17127 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17128 ownerPackage, targetUserId, flags); 17129 CrossProfileIntentResolver resolver = 17130 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17131 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17132 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17133 if (existing != null) { 17134 int size = existing.size(); 17135 for (int i = 0; i < size; i++) { 17136 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17137 return; 17138 } 17139 } 17140 } 17141 resolver.addFilter(newFilter); 17142 scheduleWritePackageRestrictionsLocked(sourceUserId); 17143 } 17144 } 17145 17146 @Override 17147 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17148 mContext.enforceCallingOrSelfPermission( 17149 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17150 int callingUid = Binder.getCallingUid(); 17151 enforceOwnerRights(ownerPackage, callingUid); 17152 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17153 synchronized (mPackages) { 17154 CrossProfileIntentResolver resolver = 17155 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17156 ArraySet<CrossProfileIntentFilter> set = 17157 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17158 for (CrossProfileIntentFilter filter : set) { 17159 if (filter.getOwnerPackage().equals(ownerPackage)) { 17160 resolver.removeFilter(filter); 17161 } 17162 } 17163 scheduleWritePackageRestrictionsLocked(sourceUserId); 17164 } 17165 } 17166 17167 // Enforcing that callingUid is owning pkg on userId 17168 private void enforceOwnerRights(String pkg, int callingUid) { 17169 // The system owns everything. 17170 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17171 return; 17172 } 17173 int callingUserId = UserHandle.getUserId(callingUid); 17174 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17175 if (pi == null) { 17176 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17177 + callingUserId); 17178 } 17179 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17180 throw new SecurityException("Calling uid " + callingUid 17181 + " does not own package " + pkg); 17182 } 17183 } 17184 17185 @Override 17186 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17187 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17188 } 17189 17190 private Intent getHomeIntent() { 17191 Intent intent = new Intent(Intent.ACTION_MAIN); 17192 intent.addCategory(Intent.CATEGORY_HOME); 17193 return intent; 17194 } 17195 17196 private IntentFilter getHomeFilter() { 17197 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17198 filter.addCategory(Intent.CATEGORY_HOME); 17199 filter.addCategory(Intent.CATEGORY_DEFAULT); 17200 return filter; 17201 } 17202 17203 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17204 int userId) { 17205 Intent intent = getHomeIntent(); 17206 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17207 PackageManager.GET_META_DATA, userId); 17208 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17209 true, false, false, userId); 17210 17211 allHomeCandidates.clear(); 17212 if (list != null) { 17213 for (ResolveInfo ri : list) { 17214 allHomeCandidates.add(ri); 17215 } 17216 } 17217 return (preferred == null || preferred.activityInfo == null) 17218 ? null 17219 : new ComponentName(preferred.activityInfo.packageName, 17220 preferred.activityInfo.name); 17221 } 17222 17223 @Override 17224 public void setHomeActivity(ComponentName comp, int userId) { 17225 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17226 getHomeActivitiesAsUser(homeActivities, userId); 17227 17228 boolean found = false; 17229 17230 final int size = homeActivities.size(); 17231 final ComponentName[] set = new ComponentName[size]; 17232 for (int i = 0; i < size; i++) { 17233 final ResolveInfo candidate = homeActivities.get(i); 17234 final ActivityInfo info = candidate.activityInfo; 17235 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17236 set[i] = activityName; 17237 if (!found && activityName.equals(comp)) { 17238 found = true; 17239 } 17240 } 17241 if (!found) { 17242 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17243 + userId); 17244 } 17245 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17246 set, comp, userId); 17247 } 17248 17249 private @Nullable String getSetupWizardPackageName() { 17250 final Intent intent = new Intent(Intent.ACTION_MAIN); 17251 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17252 17253 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17254 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17255 | MATCH_DISABLED_COMPONENTS, 17256 UserHandle.myUserId()); 17257 if (matches.size() == 1) { 17258 return matches.get(0).getComponentInfo().packageName; 17259 } else { 17260 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17261 + ": matches=" + matches); 17262 return null; 17263 } 17264 } 17265 17266 @Override 17267 public void setApplicationEnabledSetting(String appPackageName, 17268 int newState, int flags, int userId, String callingPackage) { 17269 if (!sUserManager.exists(userId)) return; 17270 if (callingPackage == null) { 17271 callingPackage = Integer.toString(Binder.getCallingUid()); 17272 } 17273 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17274 } 17275 17276 @Override 17277 public void setComponentEnabledSetting(ComponentName componentName, 17278 int newState, int flags, int userId) { 17279 if (!sUserManager.exists(userId)) return; 17280 setEnabledSetting(componentName.getPackageName(), 17281 componentName.getClassName(), newState, flags, userId, null); 17282 } 17283 17284 private void setEnabledSetting(final String packageName, String className, int newState, 17285 final int flags, int userId, String callingPackage) { 17286 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17287 || newState == COMPONENT_ENABLED_STATE_ENABLED 17288 || newState == COMPONENT_ENABLED_STATE_DISABLED 17289 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17290 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17291 throw new IllegalArgumentException("Invalid new component state: " 17292 + newState); 17293 } 17294 PackageSetting pkgSetting; 17295 final int uid = Binder.getCallingUid(); 17296 final int permission; 17297 if (uid == Process.SYSTEM_UID) { 17298 permission = PackageManager.PERMISSION_GRANTED; 17299 } else { 17300 permission = mContext.checkCallingOrSelfPermission( 17301 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17302 } 17303 enforceCrossUserPermission(uid, userId, 17304 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17305 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17306 boolean sendNow = false; 17307 boolean isApp = (className == null); 17308 String componentName = isApp ? packageName : className; 17309 int packageUid = -1; 17310 ArrayList<String> components; 17311 17312 // writer 17313 synchronized (mPackages) { 17314 pkgSetting = mSettings.mPackages.get(packageName); 17315 if (pkgSetting == null) { 17316 if (className == null) { 17317 throw new IllegalArgumentException("Unknown package: " + packageName); 17318 } 17319 throw new IllegalArgumentException( 17320 "Unknown component: " + packageName + "/" + className); 17321 } 17322 // Allow root and verify that userId is not being specified by a different user 17323 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17324 throw new SecurityException( 17325 "Permission Denial: attempt to change component state from pid=" 17326 + Binder.getCallingPid() 17327 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17328 } 17329 if (className == null) { 17330 // We're dealing with an application/package level state change 17331 if (pkgSetting.getEnabled(userId) == newState) { 17332 // Nothing to do 17333 return; 17334 } 17335 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17336 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17337 // Don't care about who enables an app. 17338 callingPackage = null; 17339 } 17340 pkgSetting.setEnabled(newState, userId, callingPackage); 17341 // pkgSetting.pkg.mSetEnabled = newState; 17342 } else { 17343 // We're dealing with a component level state change 17344 // First, verify that this is a valid class name. 17345 PackageParser.Package pkg = pkgSetting.pkg; 17346 if (pkg == null || !pkg.hasComponentClassName(className)) { 17347 if (pkg != null && 17348 pkg.applicationInfo.targetSdkVersion >= 17349 Build.VERSION_CODES.JELLY_BEAN) { 17350 throw new IllegalArgumentException("Component class " + className 17351 + " does not exist in " + packageName); 17352 } else { 17353 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17354 + className + " does not exist in " + packageName); 17355 } 17356 } 17357 switch (newState) { 17358 case COMPONENT_ENABLED_STATE_ENABLED: 17359 if (!pkgSetting.enableComponentLPw(className, userId)) { 17360 return; 17361 } 17362 break; 17363 case COMPONENT_ENABLED_STATE_DISABLED: 17364 if (!pkgSetting.disableComponentLPw(className, userId)) { 17365 return; 17366 } 17367 break; 17368 case COMPONENT_ENABLED_STATE_DEFAULT: 17369 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17370 return; 17371 } 17372 break; 17373 default: 17374 Slog.e(TAG, "Invalid new component state: " + newState); 17375 return; 17376 } 17377 } 17378 scheduleWritePackageRestrictionsLocked(userId); 17379 components = mPendingBroadcasts.get(userId, packageName); 17380 final boolean newPackage = components == null; 17381 if (newPackage) { 17382 components = new ArrayList<String>(); 17383 } 17384 if (!components.contains(componentName)) { 17385 components.add(componentName); 17386 } 17387 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17388 sendNow = true; 17389 // Purge entry from pending broadcast list if another one exists already 17390 // since we are sending one right away. 17391 mPendingBroadcasts.remove(userId, packageName); 17392 } else { 17393 if (newPackage) { 17394 mPendingBroadcasts.put(userId, packageName, components); 17395 } 17396 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17397 // Schedule a message 17398 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17399 } 17400 } 17401 } 17402 17403 long callingId = Binder.clearCallingIdentity(); 17404 try { 17405 if (sendNow) { 17406 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17407 sendPackageChangedBroadcast(packageName, 17408 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17409 } 17410 } finally { 17411 Binder.restoreCallingIdentity(callingId); 17412 } 17413 } 17414 17415 @Override 17416 public void flushPackageRestrictionsAsUser(int userId) { 17417 if (!sUserManager.exists(userId)) { 17418 return; 17419 } 17420 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17421 false /* checkShell */, "flushPackageRestrictions"); 17422 synchronized (mPackages) { 17423 mSettings.writePackageRestrictionsLPr(userId); 17424 mDirtyUsers.remove(userId); 17425 if (mDirtyUsers.isEmpty()) { 17426 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17427 } 17428 } 17429 } 17430 17431 private void sendPackageChangedBroadcast(String packageName, 17432 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17433 if (DEBUG_INSTALL) 17434 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17435 + componentNames); 17436 Bundle extras = new Bundle(4); 17437 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17438 String nameList[] = new String[componentNames.size()]; 17439 componentNames.toArray(nameList); 17440 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17441 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17442 extras.putInt(Intent.EXTRA_UID, packageUid); 17443 // If this is not reporting a change of the overall package, then only send it 17444 // to registered receivers. We don't want to launch a swath of apps for every 17445 // little component state change. 17446 final int flags = !componentNames.contains(packageName) 17447 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17448 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17449 new int[] {UserHandle.getUserId(packageUid)}); 17450 } 17451 17452 @Override 17453 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17454 if (!sUserManager.exists(userId)) return; 17455 final int uid = Binder.getCallingUid(); 17456 final int permission = mContext.checkCallingOrSelfPermission( 17457 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17458 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17459 enforceCrossUserPermission(uid, userId, 17460 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17461 // writer 17462 synchronized (mPackages) { 17463 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17464 allowedByPermission, uid, userId)) { 17465 scheduleWritePackageRestrictionsLocked(userId); 17466 } 17467 } 17468 } 17469 17470 @Override 17471 public String getInstallerPackageName(String packageName) { 17472 // reader 17473 synchronized (mPackages) { 17474 return mSettings.getInstallerPackageNameLPr(packageName); 17475 } 17476 } 17477 17478 @Override 17479 public int getApplicationEnabledSetting(String packageName, int userId) { 17480 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17481 int uid = Binder.getCallingUid(); 17482 enforceCrossUserPermission(uid, userId, 17483 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17484 // reader 17485 synchronized (mPackages) { 17486 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17487 } 17488 } 17489 17490 @Override 17491 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17492 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17493 int uid = Binder.getCallingUid(); 17494 enforceCrossUserPermission(uid, userId, 17495 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17496 // reader 17497 synchronized (mPackages) { 17498 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17499 } 17500 } 17501 17502 @Override 17503 public void enterSafeMode() { 17504 enforceSystemOrRoot("Only the system can request entering safe mode"); 17505 17506 if (!mSystemReady) { 17507 mSafeMode = true; 17508 } 17509 } 17510 17511 @Override 17512 public void systemReady() { 17513 mSystemReady = true; 17514 17515 // Read the compatibilty setting when the system is ready. 17516 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17517 mContext.getContentResolver(), 17518 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17519 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17520 if (DEBUG_SETTINGS) { 17521 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17522 } 17523 17524 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17525 17526 synchronized (mPackages) { 17527 // Verify that all of the preferred activity components actually 17528 // exist. It is possible for applications to be updated and at 17529 // that point remove a previously declared activity component that 17530 // had been set as a preferred activity. We try to clean this up 17531 // the next time we encounter that preferred activity, but it is 17532 // possible for the user flow to never be able to return to that 17533 // situation so here we do a sanity check to make sure we haven't 17534 // left any junk around. 17535 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17536 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17537 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17538 removed.clear(); 17539 for (PreferredActivity pa : pir.filterSet()) { 17540 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17541 removed.add(pa); 17542 } 17543 } 17544 if (removed.size() > 0) { 17545 for (int r=0; r<removed.size(); r++) { 17546 PreferredActivity pa = removed.get(r); 17547 Slog.w(TAG, "Removing dangling preferred activity: " 17548 + pa.mPref.mComponent); 17549 pir.removeFilter(pa); 17550 } 17551 mSettings.writePackageRestrictionsLPr( 17552 mSettings.mPreferredActivities.keyAt(i)); 17553 } 17554 } 17555 17556 for (int userId : UserManagerService.getInstance().getUserIds()) { 17557 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17558 grantPermissionsUserIds = ArrayUtils.appendInt( 17559 grantPermissionsUserIds, userId); 17560 } 17561 } 17562 } 17563 sUserManager.systemReady(); 17564 17565 // If we upgraded grant all default permissions before kicking off. 17566 for (int userId : grantPermissionsUserIds) { 17567 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17568 } 17569 17570 // Kick off any messages waiting for system ready 17571 if (mPostSystemReadyMessages != null) { 17572 for (Message msg : mPostSystemReadyMessages) { 17573 msg.sendToTarget(); 17574 } 17575 mPostSystemReadyMessages = null; 17576 } 17577 17578 // Watch for external volumes that come and go over time 17579 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17580 storage.registerListener(mStorageListener); 17581 17582 mInstallerService.systemReady(); 17583 mPackageDexOptimizer.systemReady(); 17584 17585 MountServiceInternal mountServiceInternal = LocalServices.getService( 17586 MountServiceInternal.class); 17587 mountServiceInternal.addExternalStoragePolicy( 17588 new MountServiceInternal.ExternalStorageMountPolicy() { 17589 @Override 17590 public int getMountMode(int uid, String packageName) { 17591 if (Process.isIsolated(uid)) { 17592 return Zygote.MOUNT_EXTERNAL_NONE; 17593 } 17594 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17595 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17596 } 17597 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17598 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17599 } 17600 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17601 return Zygote.MOUNT_EXTERNAL_READ; 17602 } 17603 return Zygote.MOUNT_EXTERNAL_WRITE; 17604 } 17605 17606 @Override 17607 public boolean hasExternalStorage(int uid, String packageName) { 17608 return true; 17609 } 17610 }); 17611 17612 // Now that we're mostly running, clean up stale users and apps 17613 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17614 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17615 } 17616 17617 @Override 17618 public boolean isSafeMode() { 17619 return mSafeMode; 17620 } 17621 17622 @Override 17623 public boolean hasSystemUidErrors() { 17624 return mHasSystemUidErrors; 17625 } 17626 17627 static String arrayToString(int[] array) { 17628 StringBuffer buf = new StringBuffer(128); 17629 buf.append('['); 17630 if (array != null) { 17631 for (int i=0; i<array.length; i++) { 17632 if (i > 0) buf.append(", "); 17633 buf.append(array[i]); 17634 } 17635 } 17636 buf.append(']'); 17637 return buf.toString(); 17638 } 17639 17640 static class DumpState { 17641 public static final int DUMP_LIBS = 1 << 0; 17642 public static final int DUMP_FEATURES = 1 << 1; 17643 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17644 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17645 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17646 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17647 public static final int DUMP_PERMISSIONS = 1 << 6; 17648 public static final int DUMP_PACKAGES = 1 << 7; 17649 public static final int DUMP_SHARED_USERS = 1 << 8; 17650 public static final int DUMP_MESSAGES = 1 << 9; 17651 public static final int DUMP_PROVIDERS = 1 << 10; 17652 public static final int DUMP_VERIFIERS = 1 << 11; 17653 public static final int DUMP_PREFERRED = 1 << 12; 17654 public static final int DUMP_PREFERRED_XML = 1 << 13; 17655 public static final int DUMP_KEYSETS = 1 << 14; 17656 public static final int DUMP_VERSION = 1 << 15; 17657 public static final int DUMP_INSTALLS = 1 << 16; 17658 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17659 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17660 public static final int DUMP_FROZEN = 1 << 19; 17661 17662 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17663 17664 private int mTypes; 17665 17666 private int mOptions; 17667 17668 private boolean mTitlePrinted; 17669 17670 private SharedUserSetting mSharedUser; 17671 17672 public boolean isDumping(int type) { 17673 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17674 return true; 17675 } 17676 17677 return (mTypes & type) != 0; 17678 } 17679 17680 public void setDump(int type) { 17681 mTypes |= type; 17682 } 17683 17684 public boolean isOptionEnabled(int option) { 17685 return (mOptions & option) != 0; 17686 } 17687 17688 public void setOptionEnabled(int option) { 17689 mOptions |= option; 17690 } 17691 17692 public boolean onTitlePrinted() { 17693 final boolean printed = mTitlePrinted; 17694 mTitlePrinted = true; 17695 return printed; 17696 } 17697 17698 public boolean getTitlePrinted() { 17699 return mTitlePrinted; 17700 } 17701 17702 public void setTitlePrinted(boolean enabled) { 17703 mTitlePrinted = enabled; 17704 } 17705 17706 public SharedUserSetting getSharedUser() { 17707 return mSharedUser; 17708 } 17709 17710 public void setSharedUser(SharedUserSetting user) { 17711 mSharedUser = user; 17712 } 17713 } 17714 17715 @Override 17716 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17717 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17718 (new PackageManagerShellCommand(this)).exec( 17719 this, in, out, err, args, resultReceiver); 17720 } 17721 17722 @Override 17723 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17724 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17725 != PackageManager.PERMISSION_GRANTED) { 17726 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17727 + Binder.getCallingPid() 17728 + ", uid=" + Binder.getCallingUid() 17729 + " without permission " 17730 + android.Manifest.permission.DUMP); 17731 return; 17732 } 17733 17734 DumpState dumpState = new DumpState(); 17735 boolean fullPreferred = false; 17736 boolean checkin = false; 17737 17738 String packageName = null; 17739 ArraySet<String> permissionNames = null; 17740 17741 int opti = 0; 17742 while (opti < args.length) { 17743 String opt = args[opti]; 17744 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17745 break; 17746 } 17747 opti++; 17748 17749 if ("-a".equals(opt)) { 17750 // Right now we only know how to print all. 17751 } else if ("-h".equals(opt)) { 17752 pw.println("Package manager dump options:"); 17753 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17754 pw.println(" --checkin: dump for a checkin"); 17755 pw.println(" -f: print details of intent filters"); 17756 pw.println(" -h: print this help"); 17757 pw.println(" cmd may be one of:"); 17758 pw.println(" l[ibraries]: list known shared libraries"); 17759 pw.println(" f[eatures]: list device features"); 17760 pw.println(" k[eysets]: print known keysets"); 17761 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17762 pw.println(" perm[issions]: dump permissions"); 17763 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17764 pw.println(" pref[erred]: print preferred package settings"); 17765 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17766 pw.println(" prov[iders]: dump content providers"); 17767 pw.println(" p[ackages]: dump installed packages"); 17768 pw.println(" s[hared-users]: dump shared user IDs"); 17769 pw.println(" m[essages]: print collected runtime messages"); 17770 pw.println(" v[erifiers]: print package verifier info"); 17771 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17772 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17773 pw.println(" version: print database version info"); 17774 pw.println(" write: write current settings now"); 17775 pw.println(" installs: details about install sessions"); 17776 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17777 pw.println(" <package.name>: info about given package"); 17778 return; 17779 } else if ("--checkin".equals(opt)) { 17780 checkin = true; 17781 } else if ("-f".equals(opt)) { 17782 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17783 } else { 17784 pw.println("Unknown argument: " + opt + "; use -h for help"); 17785 } 17786 } 17787 17788 // Is the caller requesting to dump a particular piece of data? 17789 if (opti < args.length) { 17790 String cmd = args[opti]; 17791 opti++; 17792 // Is this a package name? 17793 if ("android".equals(cmd) || cmd.contains(".")) { 17794 packageName = cmd; 17795 // When dumping a single package, we always dump all of its 17796 // filter information since the amount of data will be reasonable. 17797 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17798 } else if ("check-permission".equals(cmd)) { 17799 if (opti >= args.length) { 17800 pw.println("Error: check-permission missing permission argument"); 17801 return; 17802 } 17803 String perm = args[opti]; 17804 opti++; 17805 if (opti >= args.length) { 17806 pw.println("Error: check-permission missing package argument"); 17807 return; 17808 } 17809 String pkg = args[opti]; 17810 opti++; 17811 int user = UserHandle.getUserId(Binder.getCallingUid()); 17812 if (opti < args.length) { 17813 try { 17814 user = Integer.parseInt(args[opti]); 17815 } catch (NumberFormatException e) { 17816 pw.println("Error: check-permission user argument is not a number: " 17817 + args[opti]); 17818 return; 17819 } 17820 } 17821 pw.println(checkPermission(perm, pkg, user)); 17822 return; 17823 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17824 dumpState.setDump(DumpState.DUMP_LIBS); 17825 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17826 dumpState.setDump(DumpState.DUMP_FEATURES); 17827 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17828 if (opti >= args.length) { 17829 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17830 | DumpState.DUMP_SERVICE_RESOLVERS 17831 | DumpState.DUMP_RECEIVER_RESOLVERS 17832 | DumpState.DUMP_CONTENT_RESOLVERS); 17833 } else { 17834 while (opti < args.length) { 17835 String name = args[opti]; 17836 if ("a".equals(name) || "activity".equals(name)) { 17837 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17838 } else if ("s".equals(name) || "service".equals(name)) { 17839 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17840 } else if ("r".equals(name) || "receiver".equals(name)) { 17841 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17842 } else if ("c".equals(name) || "content".equals(name)) { 17843 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17844 } else { 17845 pw.println("Error: unknown resolver table type: " + name); 17846 return; 17847 } 17848 opti++; 17849 } 17850 } 17851 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17852 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17853 } else if ("permission".equals(cmd)) { 17854 if (opti >= args.length) { 17855 pw.println("Error: permission requires permission name"); 17856 return; 17857 } 17858 permissionNames = new ArraySet<>(); 17859 while (opti < args.length) { 17860 permissionNames.add(args[opti]); 17861 opti++; 17862 } 17863 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17864 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17865 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17866 dumpState.setDump(DumpState.DUMP_PREFERRED); 17867 } else if ("preferred-xml".equals(cmd)) { 17868 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17869 if (opti < args.length && "--full".equals(args[opti])) { 17870 fullPreferred = true; 17871 opti++; 17872 } 17873 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17874 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17875 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17876 dumpState.setDump(DumpState.DUMP_PACKAGES); 17877 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17878 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17879 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17880 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17881 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17882 dumpState.setDump(DumpState.DUMP_MESSAGES); 17883 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17884 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17885 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17886 || "intent-filter-verifiers".equals(cmd)) { 17887 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17888 } else if ("version".equals(cmd)) { 17889 dumpState.setDump(DumpState.DUMP_VERSION); 17890 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17891 dumpState.setDump(DumpState.DUMP_KEYSETS); 17892 } else if ("installs".equals(cmd)) { 17893 dumpState.setDump(DumpState.DUMP_INSTALLS); 17894 } else if ("frozen".equals(cmd)) { 17895 dumpState.setDump(DumpState.DUMP_FROZEN); 17896 } else if ("write".equals(cmd)) { 17897 synchronized (mPackages) { 17898 mSettings.writeLPr(); 17899 pw.println("Settings written."); 17900 return; 17901 } 17902 } 17903 } 17904 17905 if (checkin) { 17906 pw.println("vers,1"); 17907 } 17908 17909 // reader 17910 synchronized (mPackages) { 17911 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17912 if (!checkin) { 17913 if (dumpState.onTitlePrinted()) 17914 pw.println(); 17915 pw.println("Database versions:"); 17916 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17917 } 17918 } 17919 17920 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17921 if (!checkin) { 17922 if (dumpState.onTitlePrinted()) 17923 pw.println(); 17924 pw.println("Verifiers:"); 17925 pw.print(" Required: "); 17926 pw.print(mRequiredVerifierPackage); 17927 pw.print(" (uid="); 17928 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17929 UserHandle.USER_SYSTEM)); 17930 pw.println(")"); 17931 } else if (mRequiredVerifierPackage != null) { 17932 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17933 pw.print(","); 17934 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17935 UserHandle.USER_SYSTEM)); 17936 } 17937 } 17938 17939 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17940 packageName == null) { 17941 if (mIntentFilterVerifierComponent != null) { 17942 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17943 if (!checkin) { 17944 if (dumpState.onTitlePrinted()) 17945 pw.println(); 17946 pw.println("Intent Filter Verifier:"); 17947 pw.print(" Using: "); 17948 pw.print(verifierPackageName); 17949 pw.print(" (uid="); 17950 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17951 UserHandle.USER_SYSTEM)); 17952 pw.println(")"); 17953 } else if (verifierPackageName != null) { 17954 pw.print("ifv,"); pw.print(verifierPackageName); 17955 pw.print(","); 17956 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17957 UserHandle.USER_SYSTEM)); 17958 } 17959 } else { 17960 pw.println(); 17961 pw.println("No Intent Filter Verifier available!"); 17962 } 17963 } 17964 17965 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17966 boolean printedHeader = false; 17967 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17968 while (it.hasNext()) { 17969 String name = it.next(); 17970 SharedLibraryEntry ent = mSharedLibraries.get(name); 17971 if (!checkin) { 17972 if (!printedHeader) { 17973 if (dumpState.onTitlePrinted()) 17974 pw.println(); 17975 pw.println("Libraries:"); 17976 printedHeader = true; 17977 } 17978 pw.print(" "); 17979 } else { 17980 pw.print("lib,"); 17981 } 17982 pw.print(name); 17983 if (!checkin) { 17984 pw.print(" -> "); 17985 } 17986 if (ent.path != null) { 17987 if (!checkin) { 17988 pw.print("(jar) "); 17989 pw.print(ent.path); 17990 } else { 17991 pw.print(",jar,"); 17992 pw.print(ent.path); 17993 } 17994 } else { 17995 if (!checkin) { 17996 pw.print("(apk) "); 17997 pw.print(ent.apk); 17998 } else { 17999 pw.print(",apk,"); 18000 pw.print(ent.apk); 18001 } 18002 } 18003 pw.println(); 18004 } 18005 } 18006 18007 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18008 if (dumpState.onTitlePrinted()) 18009 pw.println(); 18010 if (!checkin) { 18011 pw.println("Features:"); 18012 } 18013 18014 for (FeatureInfo feat : mAvailableFeatures.values()) { 18015 if (checkin) { 18016 pw.print("feat,"); 18017 pw.print(feat.name); 18018 pw.print(","); 18019 pw.println(feat.version); 18020 } else { 18021 pw.print(" "); 18022 pw.print(feat.name); 18023 if (feat.version > 0) { 18024 pw.print(" version="); 18025 pw.print(feat.version); 18026 } 18027 pw.println(); 18028 } 18029 } 18030 } 18031 18032 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18033 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18034 : "Activity Resolver Table:", " ", packageName, 18035 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18036 dumpState.setTitlePrinted(true); 18037 } 18038 } 18039 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18040 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18041 : "Receiver Resolver Table:", " ", packageName, 18042 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18043 dumpState.setTitlePrinted(true); 18044 } 18045 } 18046 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18047 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18048 : "Service Resolver Table:", " ", packageName, 18049 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18050 dumpState.setTitlePrinted(true); 18051 } 18052 } 18053 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18054 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18055 : "Provider Resolver Table:", " ", packageName, 18056 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18057 dumpState.setTitlePrinted(true); 18058 } 18059 } 18060 18061 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18062 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18063 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18064 int user = mSettings.mPreferredActivities.keyAt(i); 18065 if (pir.dump(pw, 18066 dumpState.getTitlePrinted() 18067 ? "\nPreferred Activities User " + user + ":" 18068 : "Preferred Activities User " + user + ":", " ", 18069 packageName, true, false)) { 18070 dumpState.setTitlePrinted(true); 18071 } 18072 } 18073 } 18074 18075 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18076 pw.flush(); 18077 FileOutputStream fout = new FileOutputStream(fd); 18078 BufferedOutputStream str = new BufferedOutputStream(fout); 18079 XmlSerializer serializer = new FastXmlSerializer(); 18080 try { 18081 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18082 serializer.startDocument(null, true); 18083 serializer.setFeature( 18084 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18085 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18086 serializer.endDocument(); 18087 serializer.flush(); 18088 } catch (IllegalArgumentException e) { 18089 pw.println("Failed writing: " + e); 18090 } catch (IllegalStateException e) { 18091 pw.println("Failed writing: " + e); 18092 } catch (IOException e) { 18093 pw.println("Failed writing: " + e); 18094 } 18095 } 18096 18097 if (!checkin 18098 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18099 && packageName == null) { 18100 pw.println(); 18101 int count = mSettings.mPackages.size(); 18102 if (count == 0) { 18103 pw.println("No applications!"); 18104 pw.println(); 18105 } else { 18106 final String prefix = " "; 18107 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18108 if (allPackageSettings.size() == 0) { 18109 pw.println("No domain preferred apps!"); 18110 pw.println(); 18111 } else { 18112 pw.println("App verification status:"); 18113 pw.println(); 18114 count = 0; 18115 for (PackageSetting ps : allPackageSettings) { 18116 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18117 if (ivi == null || ivi.getPackageName() == null) continue; 18118 pw.println(prefix + "Package: " + ivi.getPackageName()); 18119 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18120 pw.println(prefix + "Status: " + ivi.getStatusString()); 18121 pw.println(); 18122 count++; 18123 } 18124 if (count == 0) { 18125 pw.println(prefix + "No app verification established."); 18126 pw.println(); 18127 } 18128 for (int userId : sUserManager.getUserIds()) { 18129 pw.println("App linkages for user " + userId + ":"); 18130 pw.println(); 18131 count = 0; 18132 for (PackageSetting ps : allPackageSettings) { 18133 final long status = ps.getDomainVerificationStatusForUser(userId); 18134 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18135 continue; 18136 } 18137 pw.println(prefix + "Package: " + ps.name); 18138 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18139 String statusStr = IntentFilterVerificationInfo. 18140 getStatusStringFromValue(status); 18141 pw.println(prefix + "Status: " + statusStr); 18142 pw.println(); 18143 count++; 18144 } 18145 if (count == 0) { 18146 pw.println(prefix + "No configured app linkages."); 18147 pw.println(); 18148 } 18149 } 18150 } 18151 } 18152 } 18153 18154 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18155 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18156 if (packageName == null && permissionNames == null) { 18157 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18158 if (iperm == 0) { 18159 if (dumpState.onTitlePrinted()) 18160 pw.println(); 18161 pw.println("AppOp Permissions:"); 18162 } 18163 pw.print(" AppOp Permission "); 18164 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18165 pw.println(":"); 18166 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18167 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18168 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18169 } 18170 } 18171 } 18172 } 18173 18174 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18175 boolean printedSomething = false; 18176 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18177 if (packageName != null && !packageName.equals(p.info.packageName)) { 18178 continue; 18179 } 18180 if (!printedSomething) { 18181 if (dumpState.onTitlePrinted()) 18182 pw.println(); 18183 pw.println("Registered ContentProviders:"); 18184 printedSomething = true; 18185 } 18186 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18187 pw.print(" "); pw.println(p.toString()); 18188 } 18189 printedSomething = false; 18190 for (Map.Entry<String, PackageParser.Provider> entry : 18191 mProvidersByAuthority.entrySet()) { 18192 PackageParser.Provider p = entry.getValue(); 18193 if (packageName != null && !packageName.equals(p.info.packageName)) { 18194 continue; 18195 } 18196 if (!printedSomething) { 18197 if (dumpState.onTitlePrinted()) 18198 pw.println(); 18199 pw.println("ContentProvider Authorities:"); 18200 printedSomething = true; 18201 } 18202 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18203 pw.print(" "); pw.println(p.toString()); 18204 if (p.info != null && p.info.applicationInfo != null) { 18205 final String appInfo = p.info.applicationInfo.toString(); 18206 pw.print(" applicationInfo="); pw.println(appInfo); 18207 } 18208 } 18209 } 18210 18211 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18212 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18213 } 18214 18215 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18216 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18217 } 18218 18219 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18220 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18221 } 18222 18223 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18224 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18225 } 18226 18227 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18228 // XXX should handle packageName != null by dumping only install data that 18229 // the given package is involved with. 18230 if (dumpState.onTitlePrinted()) pw.println(); 18231 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18232 } 18233 18234 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18235 // XXX should handle packageName != null by dumping only install data that 18236 // the given package is involved with. 18237 if (dumpState.onTitlePrinted()) pw.println(); 18238 18239 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18240 ipw.println(); 18241 ipw.println("Frozen packages:"); 18242 ipw.increaseIndent(); 18243 if (mFrozenPackages.size() == 0) { 18244 ipw.println("(none)"); 18245 } else { 18246 for (int i = 0; i < mFrozenPackages.size(); i++) { 18247 ipw.println(mFrozenPackages.valueAt(i)); 18248 } 18249 } 18250 ipw.decreaseIndent(); 18251 } 18252 18253 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18254 if (dumpState.onTitlePrinted()) pw.println(); 18255 mSettings.dumpReadMessagesLPr(pw, dumpState); 18256 18257 pw.println(); 18258 pw.println("Package warning messages:"); 18259 BufferedReader in = null; 18260 String line = null; 18261 try { 18262 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18263 while ((line = in.readLine()) != null) { 18264 if (line.contains("ignored: updated version")) continue; 18265 pw.println(line); 18266 } 18267 } catch (IOException ignored) { 18268 } finally { 18269 IoUtils.closeQuietly(in); 18270 } 18271 } 18272 18273 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18274 BufferedReader in = null; 18275 String line = null; 18276 try { 18277 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18278 while ((line = in.readLine()) != null) { 18279 if (line.contains("ignored: updated version")) continue; 18280 pw.print("msg,"); 18281 pw.println(line); 18282 } 18283 } catch (IOException ignored) { 18284 } finally { 18285 IoUtils.closeQuietly(in); 18286 } 18287 } 18288 } 18289 } 18290 18291 private String dumpDomainString(String packageName) { 18292 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18293 .getList(); 18294 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18295 18296 ArraySet<String> result = new ArraySet<>(); 18297 if (iviList.size() > 0) { 18298 for (IntentFilterVerificationInfo ivi : iviList) { 18299 for (String host : ivi.getDomains()) { 18300 result.add(host); 18301 } 18302 } 18303 } 18304 if (filters != null && filters.size() > 0) { 18305 for (IntentFilter filter : filters) { 18306 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18307 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18308 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18309 result.addAll(filter.getHostsList()); 18310 } 18311 } 18312 } 18313 18314 StringBuilder sb = new StringBuilder(result.size() * 16); 18315 for (String domain : result) { 18316 if (sb.length() > 0) sb.append(" "); 18317 sb.append(domain); 18318 } 18319 return sb.toString(); 18320 } 18321 18322 // ------- apps on sdcard specific code ------- 18323 static final boolean DEBUG_SD_INSTALL = false; 18324 18325 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18326 18327 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18328 18329 private boolean mMediaMounted = false; 18330 18331 static String getEncryptKey() { 18332 try { 18333 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18334 SD_ENCRYPTION_KEYSTORE_NAME); 18335 if (sdEncKey == null) { 18336 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18337 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18338 if (sdEncKey == null) { 18339 Slog.e(TAG, "Failed to create encryption keys"); 18340 return null; 18341 } 18342 } 18343 return sdEncKey; 18344 } catch (NoSuchAlgorithmException nsae) { 18345 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18346 return null; 18347 } catch (IOException ioe) { 18348 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18349 return null; 18350 } 18351 } 18352 18353 /* 18354 * Update media status on PackageManager. 18355 */ 18356 @Override 18357 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18358 int callingUid = Binder.getCallingUid(); 18359 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18360 throw new SecurityException("Media status can only be updated by the system"); 18361 } 18362 // reader; this apparently protects mMediaMounted, but should probably 18363 // be a different lock in that case. 18364 synchronized (mPackages) { 18365 Log.i(TAG, "Updating external media status from " 18366 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18367 + (mediaStatus ? "mounted" : "unmounted")); 18368 if (DEBUG_SD_INSTALL) 18369 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18370 + ", mMediaMounted=" + mMediaMounted); 18371 if (mediaStatus == mMediaMounted) { 18372 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18373 : 0, -1); 18374 mHandler.sendMessage(msg); 18375 return; 18376 } 18377 mMediaMounted = mediaStatus; 18378 } 18379 // Queue up an async operation since the package installation may take a 18380 // little while. 18381 mHandler.post(new Runnable() { 18382 public void run() { 18383 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18384 } 18385 }); 18386 } 18387 18388 /** 18389 * Called by MountService when the initial ASECs to scan are available. 18390 * Should block until all the ASEC containers are finished being scanned. 18391 */ 18392 public void scanAvailableAsecs() { 18393 updateExternalMediaStatusInner(true, false, false); 18394 } 18395 18396 /* 18397 * Collect information of applications on external media, map them against 18398 * existing containers and update information based on current mount status. 18399 * Please note that we always have to report status if reportStatus has been 18400 * set to true especially when unloading packages. 18401 */ 18402 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18403 boolean externalStorage) { 18404 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18405 int[] uidArr = EmptyArray.INT; 18406 18407 final String[] list = PackageHelper.getSecureContainerList(); 18408 if (ArrayUtils.isEmpty(list)) { 18409 Log.i(TAG, "No secure containers found"); 18410 } else { 18411 // Process list of secure containers and categorize them 18412 // as active or stale based on their package internal state. 18413 18414 // reader 18415 synchronized (mPackages) { 18416 for (String cid : list) { 18417 // Leave stages untouched for now; installer service owns them 18418 if (PackageInstallerService.isStageName(cid)) continue; 18419 18420 if (DEBUG_SD_INSTALL) 18421 Log.i(TAG, "Processing container " + cid); 18422 String pkgName = getAsecPackageName(cid); 18423 if (pkgName == null) { 18424 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18425 continue; 18426 } 18427 if (DEBUG_SD_INSTALL) 18428 Log.i(TAG, "Looking for pkg : " + pkgName); 18429 18430 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18431 if (ps == null) { 18432 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18433 continue; 18434 } 18435 18436 /* 18437 * Skip packages that are not external if we're unmounting 18438 * external storage. 18439 */ 18440 if (externalStorage && !isMounted && !isExternal(ps)) { 18441 continue; 18442 } 18443 18444 final AsecInstallArgs args = new AsecInstallArgs(cid, 18445 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18446 // The package status is changed only if the code path 18447 // matches between settings and the container id. 18448 if (ps.codePathString != null 18449 && ps.codePathString.startsWith(args.getCodePath())) { 18450 if (DEBUG_SD_INSTALL) { 18451 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18452 + " at code path: " + ps.codePathString); 18453 } 18454 18455 // We do have a valid package installed on sdcard 18456 processCids.put(args, ps.codePathString); 18457 final int uid = ps.appId; 18458 if (uid != -1) { 18459 uidArr = ArrayUtils.appendInt(uidArr, uid); 18460 } 18461 } else { 18462 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18463 + ps.codePathString); 18464 } 18465 } 18466 } 18467 18468 Arrays.sort(uidArr); 18469 } 18470 18471 // Process packages with valid entries. 18472 if (isMounted) { 18473 if (DEBUG_SD_INSTALL) 18474 Log.i(TAG, "Loading packages"); 18475 loadMediaPackages(processCids, uidArr, externalStorage); 18476 startCleaningPackages(); 18477 mInstallerService.onSecureContainersAvailable(); 18478 } else { 18479 if (DEBUG_SD_INSTALL) 18480 Log.i(TAG, "Unloading packages"); 18481 unloadMediaPackages(processCids, uidArr, reportStatus); 18482 } 18483 } 18484 18485 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18486 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18487 final int size = infos.size(); 18488 final String[] packageNames = new String[size]; 18489 final int[] packageUids = new int[size]; 18490 for (int i = 0; i < size; i++) { 18491 final ApplicationInfo info = infos.get(i); 18492 packageNames[i] = info.packageName; 18493 packageUids[i] = info.uid; 18494 } 18495 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18496 finishedReceiver); 18497 } 18498 18499 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18500 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18501 sendResourcesChangedBroadcast(mediaStatus, replacing, 18502 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18503 } 18504 18505 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18506 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18507 int size = pkgList.length; 18508 if (size > 0) { 18509 // Send broadcasts here 18510 Bundle extras = new Bundle(); 18511 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18512 if (uidArr != null) { 18513 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18514 } 18515 if (replacing) { 18516 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18517 } 18518 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18519 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18520 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18521 } 18522 } 18523 18524 /* 18525 * Look at potentially valid container ids from processCids If package 18526 * information doesn't match the one on record or package scanning fails, 18527 * the cid is added to list of removeCids. We currently don't delete stale 18528 * containers. 18529 */ 18530 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18531 boolean externalStorage) { 18532 ArrayList<String> pkgList = new ArrayList<String>(); 18533 Set<AsecInstallArgs> keys = processCids.keySet(); 18534 18535 for (AsecInstallArgs args : keys) { 18536 String codePath = processCids.get(args); 18537 if (DEBUG_SD_INSTALL) 18538 Log.i(TAG, "Loading container : " + args.cid); 18539 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18540 try { 18541 // Make sure there are no container errors first. 18542 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18543 Slog.e(TAG, "Failed to mount cid : " + args.cid 18544 + " when installing from sdcard"); 18545 continue; 18546 } 18547 // Check code path here. 18548 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18549 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18550 + " does not match one in settings " + codePath); 18551 continue; 18552 } 18553 // Parse package 18554 int parseFlags = mDefParseFlags; 18555 if (args.isExternalAsec()) { 18556 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18557 } 18558 if (args.isFwdLocked()) { 18559 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18560 } 18561 18562 synchronized (mInstallLock) { 18563 PackageParser.Package pkg = null; 18564 try { 18565 // Sadly we don't know the package name yet to freeze it 18566 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18567 SCAN_IGNORE_FROZEN, 0, null); 18568 } catch (PackageManagerException e) { 18569 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18570 } 18571 // Scan the package 18572 if (pkg != null) { 18573 /* 18574 * TODO why is the lock being held? doPostInstall is 18575 * called in other places without the lock. This needs 18576 * to be straightened out. 18577 */ 18578 // writer 18579 synchronized (mPackages) { 18580 retCode = PackageManager.INSTALL_SUCCEEDED; 18581 pkgList.add(pkg.packageName); 18582 // Post process args 18583 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18584 pkg.applicationInfo.uid); 18585 } 18586 } else { 18587 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18588 } 18589 } 18590 18591 } finally { 18592 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18593 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18594 } 18595 } 18596 } 18597 // writer 18598 synchronized (mPackages) { 18599 // If the platform SDK has changed since the last time we booted, 18600 // we need to re-grant app permission to catch any new ones that 18601 // appear. This is really a hack, and means that apps can in some 18602 // cases get permissions that the user didn't initially explicitly 18603 // allow... it would be nice to have some better way to handle 18604 // this situation. 18605 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18606 : mSettings.getInternalVersion(); 18607 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18608 : StorageManager.UUID_PRIVATE_INTERNAL; 18609 18610 int updateFlags = UPDATE_PERMISSIONS_ALL; 18611 if (ver.sdkVersion != mSdkVersion) { 18612 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18613 + mSdkVersion + "; regranting permissions for external"); 18614 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18615 } 18616 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18617 18618 // Yay, everything is now upgraded 18619 ver.forceCurrent(); 18620 18621 // can downgrade to reader 18622 // Persist settings 18623 mSettings.writeLPr(); 18624 } 18625 // Send a broadcast to let everyone know we are done processing 18626 if (pkgList.size() > 0) { 18627 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18628 } 18629 } 18630 18631 /* 18632 * Utility method to unload a list of specified containers 18633 */ 18634 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18635 // Just unmount all valid containers. 18636 for (AsecInstallArgs arg : cidArgs) { 18637 synchronized (mInstallLock) { 18638 arg.doPostDeleteLI(false); 18639 } 18640 } 18641 } 18642 18643 /* 18644 * Unload packages mounted on external media. This involves deleting package 18645 * data from internal structures, sending broadcasts about disabled packages, 18646 * gc'ing to free up references, unmounting all secure containers 18647 * corresponding to packages on external media, and posting a 18648 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18649 * that we always have to post this message if status has been requested no 18650 * matter what. 18651 */ 18652 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18653 final boolean reportStatus) { 18654 if (DEBUG_SD_INSTALL) 18655 Log.i(TAG, "unloading media packages"); 18656 ArrayList<String> pkgList = new ArrayList<String>(); 18657 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18658 final Set<AsecInstallArgs> keys = processCids.keySet(); 18659 for (AsecInstallArgs args : keys) { 18660 String pkgName = args.getPackageName(); 18661 if (DEBUG_SD_INSTALL) 18662 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18663 // Delete package internally 18664 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18665 synchronized (mInstallLock) { 18666 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18667 final boolean res; 18668 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18669 "unloadMediaPackages")) { 18670 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18671 null); 18672 } 18673 if (res) { 18674 pkgList.add(pkgName); 18675 } else { 18676 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18677 failedList.add(args); 18678 } 18679 } 18680 } 18681 18682 // reader 18683 synchronized (mPackages) { 18684 // We didn't update the settings after removing each package; 18685 // write them now for all packages. 18686 mSettings.writeLPr(); 18687 } 18688 18689 // We have to absolutely send UPDATED_MEDIA_STATUS only 18690 // after confirming that all the receivers processed the ordered 18691 // broadcast when packages get disabled, force a gc to clean things up. 18692 // and unload all the containers. 18693 if (pkgList.size() > 0) { 18694 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18695 new IIntentReceiver.Stub() { 18696 public void performReceive(Intent intent, int resultCode, String data, 18697 Bundle extras, boolean ordered, boolean sticky, 18698 int sendingUser) throws RemoteException { 18699 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18700 reportStatus ? 1 : 0, 1, keys); 18701 mHandler.sendMessage(msg); 18702 } 18703 }); 18704 } else { 18705 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18706 keys); 18707 mHandler.sendMessage(msg); 18708 } 18709 } 18710 18711 private void loadPrivatePackages(final VolumeInfo vol) { 18712 mHandler.post(new Runnable() { 18713 @Override 18714 public void run() { 18715 loadPrivatePackagesInner(vol); 18716 } 18717 }); 18718 } 18719 18720 private void loadPrivatePackagesInner(VolumeInfo vol) { 18721 final String volumeUuid = vol.fsUuid; 18722 if (TextUtils.isEmpty(volumeUuid)) { 18723 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18724 return; 18725 } 18726 18727 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18728 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18729 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18730 18731 final VersionInfo ver; 18732 final List<PackageSetting> packages; 18733 synchronized (mPackages) { 18734 ver = mSettings.findOrCreateVersion(volumeUuid); 18735 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18736 } 18737 18738 for (PackageSetting ps : packages) { 18739 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18740 synchronized (mInstallLock) { 18741 final PackageParser.Package pkg; 18742 try { 18743 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18744 loaded.add(pkg.applicationInfo); 18745 18746 } catch (PackageManagerException e) { 18747 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18748 } 18749 18750 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18751 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18752 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18753 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18754 } 18755 } 18756 } 18757 18758 // Reconcile app data for all started/unlocked users 18759 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18760 final UserManager um = mContext.getSystemService(UserManager.class); 18761 for (UserInfo user : um.getUsers()) { 18762 final int flags; 18763 if (um.isUserUnlockingOrUnlocked(user.id)) { 18764 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18765 } else if (um.isUserRunning(user.id)) { 18766 flags = StorageManager.FLAG_STORAGE_DE; 18767 } else { 18768 continue; 18769 } 18770 18771 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18772 synchronized (mInstallLock) { 18773 reconcileAppsDataLI(volumeUuid, user.id, flags); 18774 } 18775 } 18776 18777 synchronized (mPackages) { 18778 int updateFlags = UPDATE_PERMISSIONS_ALL; 18779 if (ver.sdkVersion != mSdkVersion) { 18780 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18781 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18782 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18783 } 18784 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18785 18786 // Yay, everything is now upgraded 18787 ver.forceCurrent(); 18788 18789 mSettings.writeLPr(); 18790 } 18791 18792 for (PackageFreezer freezer : freezers) { 18793 freezer.close(); 18794 } 18795 18796 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18797 sendResourcesChangedBroadcast(true, false, loaded, null); 18798 } 18799 18800 private void unloadPrivatePackages(final VolumeInfo vol) { 18801 mHandler.post(new Runnable() { 18802 @Override 18803 public void run() { 18804 unloadPrivatePackagesInner(vol); 18805 } 18806 }); 18807 } 18808 18809 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18810 final String volumeUuid = vol.fsUuid; 18811 if (TextUtils.isEmpty(volumeUuid)) { 18812 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18813 return; 18814 } 18815 18816 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18817 synchronized (mInstallLock) { 18818 synchronized (mPackages) { 18819 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18820 for (PackageSetting ps : packages) { 18821 if (ps.pkg == null) continue; 18822 18823 final ApplicationInfo info = ps.pkg.applicationInfo; 18824 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18825 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18826 18827 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18828 "unloadPrivatePackagesInner")) { 18829 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18830 false, null)) { 18831 unloaded.add(info); 18832 } else { 18833 Slog.w(TAG, "Failed to unload " + ps.codePath); 18834 } 18835 } 18836 } 18837 18838 mSettings.writeLPr(); 18839 } 18840 } 18841 18842 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18843 sendResourcesChangedBroadcast(false, false, unloaded, null); 18844 } 18845 18846 /** 18847 * Prepare storage areas for given user on all mounted devices. 18848 */ 18849 void prepareUserData(int userId, int userSerial, int flags) { 18850 synchronized (mInstallLock) { 18851 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18852 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18853 final String volumeUuid = vol.getFsUuid(); 18854 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18855 } 18856 } 18857 } 18858 18859 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18860 boolean allowRecover) { 18861 // Prepare storage and verify that serial numbers are consistent; if 18862 // there's a mismatch we need to destroy to avoid leaking data 18863 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18864 try { 18865 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18866 18867 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18868 UserManagerService.enforceSerialNumber( 18869 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18870 } 18871 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18872 UserManagerService.enforceSerialNumber( 18873 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18874 } 18875 18876 synchronized (mInstallLock) { 18877 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18878 } 18879 } catch (Exception e) { 18880 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18881 + " because we failed to prepare: " + e); 18882 destroyUserDataLI(volumeUuid, userId, 18883 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18884 18885 if (allowRecover) { 18886 // Try one last time; if we fail again we're really in trouble 18887 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18888 } 18889 } 18890 } 18891 18892 /** 18893 * Destroy storage areas for given user on all mounted devices. 18894 */ 18895 void destroyUserData(int userId, int flags) { 18896 synchronized (mInstallLock) { 18897 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18898 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18899 final String volumeUuid = vol.getFsUuid(); 18900 destroyUserDataLI(volumeUuid, userId, flags); 18901 } 18902 } 18903 } 18904 18905 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18906 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18907 try { 18908 // Clean up app data, profile data, and media data 18909 mInstaller.destroyUserData(volumeUuid, userId, flags); 18910 18911 // Clean up system data 18912 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18913 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18914 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18915 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18916 } 18917 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18918 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18919 } 18920 } 18921 18922 // Data with special labels is now gone, so finish the job 18923 storage.destroyUserStorage(volumeUuid, userId, flags); 18924 18925 } catch (Exception e) { 18926 logCriticalInfo(Log.WARN, 18927 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18928 } 18929 } 18930 18931 /** 18932 * Examine all users present on given mounted volume, and destroy data 18933 * belonging to users that are no longer valid, or whose user ID has been 18934 * recycled. 18935 */ 18936 private void reconcileUsers(String volumeUuid) { 18937 final List<File> files = new ArrayList<>(); 18938 Collections.addAll(files, FileUtils 18939 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18940 Collections.addAll(files, FileUtils 18941 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18942 for (File file : files) { 18943 if (!file.isDirectory()) continue; 18944 18945 final int userId; 18946 final UserInfo info; 18947 try { 18948 userId = Integer.parseInt(file.getName()); 18949 info = sUserManager.getUserInfo(userId); 18950 } catch (NumberFormatException e) { 18951 Slog.w(TAG, "Invalid user directory " + file); 18952 continue; 18953 } 18954 18955 boolean destroyUser = false; 18956 if (info == null) { 18957 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18958 + " because no matching user was found"); 18959 destroyUser = true; 18960 } else if (!mOnlyCore) { 18961 try { 18962 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18963 } catch (IOException e) { 18964 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18965 + " because we failed to enforce serial number: " + e); 18966 destroyUser = true; 18967 } 18968 } 18969 18970 if (destroyUser) { 18971 synchronized (mInstallLock) { 18972 destroyUserDataLI(volumeUuid, userId, 18973 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18974 } 18975 } 18976 } 18977 } 18978 18979 private void assertPackageKnown(String volumeUuid, String packageName) 18980 throws PackageManagerException { 18981 synchronized (mPackages) { 18982 final PackageSetting ps = mSettings.mPackages.get(packageName); 18983 if (ps == null) { 18984 throw new PackageManagerException("Package " + packageName + " is unknown"); 18985 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18986 throw new PackageManagerException( 18987 "Package " + packageName + " found on unknown volume " + volumeUuid 18988 + "; expected volume " + ps.volumeUuid); 18989 } 18990 } 18991 } 18992 18993 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18994 throws PackageManagerException { 18995 synchronized (mPackages) { 18996 final PackageSetting ps = mSettings.mPackages.get(packageName); 18997 if (ps == null) { 18998 throw new PackageManagerException("Package " + packageName + " is unknown"); 18999 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19000 throw new PackageManagerException( 19001 "Package " + packageName + " found on unknown volume " + volumeUuid 19002 + "; expected volume " + ps.volumeUuid); 19003 } else if (!ps.getInstalled(userId)) { 19004 throw new PackageManagerException( 19005 "Package " + packageName + " not installed for user " + userId); 19006 } 19007 } 19008 } 19009 19010 /** 19011 * Examine all apps present on given mounted volume, and destroy apps that 19012 * aren't expected, either due to uninstallation or reinstallation on 19013 * another volume. 19014 */ 19015 private void reconcileApps(String volumeUuid) { 19016 final File[] files = FileUtils 19017 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19018 for (File file : files) { 19019 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19020 && !PackageInstallerService.isStageName(file.getName()); 19021 if (!isPackage) { 19022 // Ignore entries which are not packages 19023 continue; 19024 } 19025 19026 try { 19027 final PackageLite pkg = PackageParser.parsePackageLite(file, 19028 PackageParser.PARSE_MUST_BE_APK); 19029 assertPackageKnown(volumeUuid, pkg.packageName); 19030 19031 } catch (PackageParserException | PackageManagerException e) { 19032 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19033 synchronized (mInstallLock) { 19034 removeCodePathLI(file); 19035 } 19036 } 19037 } 19038 } 19039 19040 /** 19041 * Reconcile all app data for the given user. 19042 * <p> 19043 * Verifies that directories exist and that ownership and labeling is 19044 * correct for all installed apps on all mounted volumes. 19045 */ 19046 void reconcileAppsData(int userId, int flags) { 19047 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19048 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19049 final String volumeUuid = vol.getFsUuid(); 19050 synchronized (mInstallLock) { 19051 reconcileAppsDataLI(volumeUuid, userId, flags); 19052 } 19053 } 19054 } 19055 19056 /** 19057 * Reconcile all app data on given mounted volume. 19058 * <p> 19059 * Destroys app data that isn't expected, either due to uninstallation or 19060 * reinstallation on another volume. 19061 * <p> 19062 * Verifies that directories exist and that ownership and labeling is 19063 * correct for all installed apps. 19064 */ 19065 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19066 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19067 + Integer.toHexString(flags)); 19068 19069 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19070 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19071 19072 boolean restoreconNeeded = false; 19073 19074 // First look for stale data that doesn't belong, and check if things 19075 // have changed since we did our last restorecon 19076 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19077 if (!StorageManager.isUserKeyUnlocked(userId)) { 19078 throw new RuntimeException( 19079 "Yikes, someone asked us to reconcile CE storage while " + userId 19080 + " was still locked; this would have caused massive data loss!"); 19081 } 19082 19083 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19084 19085 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19086 for (File file : files) { 19087 final String packageName = file.getName(); 19088 try { 19089 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19090 } catch (PackageManagerException e) { 19091 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19092 try { 19093 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19094 StorageManager.FLAG_STORAGE_CE, 0); 19095 } catch (InstallerException e2) { 19096 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19097 } 19098 } 19099 } 19100 } 19101 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19102 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19103 19104 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19105 for (File file : files) { 19106 final String packageName = file.getName(); 19107 try { 19108 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19109 } catch (PackageManagerException e) { 19110 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19111 try { 19112 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19113 StorageManager.FLAG_STORAGE_DE, 0); 19114 } catch (InstallerException e2) { 19115 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19116 } 19117 } 19118 } 19119 } 19120 19121 // Ensure that data directories are ready to roll for all packages 19122 // installed for this volume and user 19123 final List<PackageSetting> packages; 19124 synchronized (mPackages) { 19125 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19126 } 19127 int preparedCount = 0; 19128 for (PackageSetting ps : packages) { 19129 final String packageName = ps.name; 19130 if (ps.pkg == null) { 19131 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19132 // TODO: might be due to legacy ASEC apps; we should circle back 19133 // and reconcile again once they're scanned 19134 continue; 19135 } 19136 19137 if (ps.getInstalled(userId)) { 19138 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19139 19140 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19141 // We may have just shuffled around app data directories, so 19142 // prepare them one more time 19143 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19144 } 19145 19146 preparedCount++; 19147 } 19148 } 19149 19150 if (restoreconNeeded) { 19151 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19152 SELinuxMMAC.setRestoreconDone(ceDir); 19153 } 19154 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19155 SELinuxMMAC.setRestoreconDone(deDir); 19156 } 19157 } 19158 19159 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19160 + " packages; restoreconNeeded was " + restoreconNeeded); 19161 } 19162 19163 /** 19164 * Prepare app data for the given app just after it was installed or 19165 * upgraded. This method carefully only touches users that it's installed 19166 * for, and it forces a restorecon to handle any seinfo changes. 19167 * <p> 19168 * Verifies that directories exist and that ownership and labeling is 19169 * correct for all installed apps. If there is an ownership mismatch, it 19170 * will try recovering system apps by wiping data; third-party app data is 19171 * left intact. 19172 * <p> 19173 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19174 */ 19175 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19176 final PackageSetting ps; 19177 synchronized (mPackages) { 19178 ps = mSettings.mPackages.get(pkg.packageName); 19179 mSettings.writeKernelMappingLPr(ps); 19180 } 19181 19182 final UserManager um = mContext.getSystemService(UserManager.class); 19183 for (UserInfo user : um.getUsers()) { 19184 final int flags; 19185 if (um.isUserUnlockingOrUnlocked(user.id)) { 19186 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19187 } else if (um.isUserRunning(user.id)) { 19188 flags = StorageManager.FLAG_STORAGE_DE; 19189 } else { 19190 continue; 19191 } 19192 19193 if (ps.getInstalled(user.id)) { 19194 // Whenever an app changes, force a restorecon of its data 19195 // TODO: when user data is locked, mark that we're still dirty 19196 prepareAppDataLIF(pkg, user.id, flags, true); 19197 } 19198 } 19199 } 19200 19201 /** 19202 * Prepare app data for the given app. 19203 * <p> 19204 * Verifies that directories exist and that ownership and labeling is 19205 * correct for all installed apps. If there is an ownership mismatch, this 19206 * will try recovering system apps by wiping data; third-party app data is 19207 * left intact. 19208 */ 19209 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19210 boolean restoreconNeeded) { 19211 if (pkg == null) { 19212 Slog.wtf(TAG, "Package was null!", new Throwable()); 19213 return; 19214 } 19215 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19216 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19217 for (int i = 0; i < childCount; i++) { 19218 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19219 } 19220 } 19221 19222 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19223 boolean restoreconNeeded) { 19224 if (DEBUG_APP_DATA) { 19225 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19226 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19227 } 19228 19229 final String volumeUuid = pkg.volumeUuid; 19230 final String packageName = pkg.packageName; 19231 final ApplicationInfo app = pkg.applicationInfo; 19232 final int appId = UserHandle.getAppId(app.uid); 19233 19234 Preconditions.checkNotNull(app.seinfo); 19235 19236 try { 19237 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19238 appId, app.seinfo, app.targetSdkVersion); 19239 } catch (InstallerException e) { 19240 if (app.isSystemApp()) { 19241 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19242 + ", but trying to recover: " + e); 19243 destroyAppDataLeafLIF(pkg, userId, flags); 19244 try { 19245 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19246 appId, app.seinfo, app.targetSdkVersion); 19247 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19248 } catch (InstallerException e2) { 19249 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19250 } 19251 } else { 19252 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19253 } 19254 } 19255 19256 if (restoreconNeeded) { 19257 try { 19258 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19259 app.seinfo); 19260 } catch (InstallerException e) { 19261 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19262 } 19263 } 19264 19265 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19266 try { 19267 // CE storage is unlocked right now, so read out the inode and 19268 // remember for use later when it's locked 19269 // TODO: mark this structure as dirty so we persist it! 19270 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19271 StorageManager.FLAG_STORAGE_CE); 19272 synchronized (mPackages) { 19273 final PackageSetting ps = mSettings.mPackages.get(packageName); 19274 if (ps != null) { 19275 ps.setCeDataInode(ceDataInode, userId); 19276 } 19277 } 19278 } catch (InstallerException e) { 19279 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19280 } 19281 } 19282 19283 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19284 } 19285 19286 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19287 if (pkg == null) { 19288 Slog.wtf(TAG, "Package was null!", new Throwable()); 19289 return; 19290 } 19291 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19292 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19293 for (int i = 0; i < childCount; i++) { 19294 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19295 } 19296 } 19297 19298 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19299 final String volumeUuid = pkg.volumeUuid; 19300 final String packageName = pkg.packageName; 19301 final ApplicationInfo app = pkg.applicationInfo; 19302 19303 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19304 // Create a native library symlink only if we have native libraries 19305 // and if the native libraries are 32 bit libraries. We do not provide 19306 // this symlink for 64 bit libraries. 19307 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19308 final String nativeLibPath = app.nativeLibraryDir; 19309 try { 19310 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19311 nativeLibPath, userId); 19312 } catch (InstallerException e) { 19313 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19314 } 19315 } 19316 } 19317 } 19318 19319 /** 19320 * For system apps on non-FBE devices, this method migrates any existing 19321 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19322 * requested by the app. 19323 */ 19324 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19325 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19326 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19327 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19328 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19329 try { 19330 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19331 storageTarget); 19332 } catch (InstallerException e) { 19333 logCriticalInfo(Log.WARN, 19334 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19335 } 19336 return true; 19337 } else { 19338 return false; 19339 } 19340 } 19341 19342 public PackageFreezer freezePackage(String packageName, String killReason) { 19343 return new PackageFreezer(packageName, killReason); 19344 } 19345 19346 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19347 String killReason) { 19348 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19349 return new PackageFreezer(); 19350 } else { 19351 return freezePackage(packageName, killReason); 19352 } 19353 } 19354 19355 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19356 String killReason) { 19357 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19358 return new PackageFreezer(); 19359 } else { 19360 return freezePackage(packageName, killReason); 19361 } 19362 } 19363 19364 /** 19365 * Class that freezes and kills the given package upon creation, and 19366 * unfreezes it upon closing. This is typically used when doing surgery on 19367 * app code/data to prevent the app from running while you're working. 19368 */ 19369 private class PackageFreezer implements AutoCloseable { 19370 private final String mPackageName; 19371 private final PackageFreezer[] mChildren; 19372 19373 private final boolean mWeFroze; 19374 19375 private final AtomicBoolean mClosed = new AtomicBoolean(); 19376 private final CloseGuard mCloseGuard = CloseGuard.get(); 19377 19378 /** 19379 * Create and return a stub freezer that doesn't actually do anything, 19380 * typically used when someone requested 19381 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19382 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19383 */ 19384 public PackageFreezer() { 19385 mPackageName = null; 19386 mChildren = null; 19387 mWeFroze = false; 19388 mCloseGuard.open("close"); 19389 } 19390 19391 public PackageFreezer(String packageName, String killReason) { 19392 synchronized (mPackages) { 19393 mPackageName = packageName; 19394 mWeFroze = mFrozenPackages.add(mPackageName); 19395 19396 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19397 if (ps != null) { 19398 killApplication(ps.name, ps.appId, killReason); 19399 } 19400 19401 final PackageParser.Package p = mPackages.get(packageName); 19402 if (p != null && p.childPackages != null) { 19403 final int N = p.childPackages.size(); 19404 mChildren = new PackageFreezer[N]; 19405 for (int i = 0; i < N; i++) { 19406 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19407 killReason); 19408 } 19409 } else { 19410 mChildren = null; 19411 } 19412 } 19413 mCloseGuard.open("close"); 19414 } 19415 19416 @Override 19417 protected void finalize() throws Throwable { 19418 try { 19419 mCloseGuard.warnIfOpen(); 19420 close(); 19421 } finally { 19422 super.finalize(); 19423 } 19424 } 19425 19426 @Override 19427 public void close() { 19428 mCloseGuard.close(); 19429 if (mClosed.compareAndSet(false, true)) { 19430 synchronized (mPackages) { 19431 if (mWeFroze) { 19432 mFrozenPackages.remove(mPackageName); 19433 } 19434 19435 if (mChildren != null) { 19436 for (PackageFreezer freezer : mChildren) { 19437 freezer.close(); 19438 } 19439 } 19440 } 19441 } 19442 } 19443 } 19444 19445 /** 19446 * Verify that given package is currently frozen. 19447 */ 19448 private void checkPackageFrozen(String packageName) { 19449 synchronized (mPackages) { 19450 if (!mFrozenPackages.contains(packageName)) { 19451 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19452 } 19453 } 19454 } 19455 19456 @Override 19457 public int movePackage(final String packageName, final String volumeUuid) { 19458 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19459 19460 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19461 final int moveId = mNextMoveId.getAndIncrement(); 19462 mHandler.post(new Runnable() { 19463 @Override 19464 public void run() { 19465 try { 19466 movePackageInternal(packageName, volumeUuid, moveId, user); 19467 } catch (PackageManagerException e) { 19468 Slog.w(TAG, "Failed to move " + packageName, e); 19469 mMoveCallbacks.notifyStatusChanged(moveId, 19470 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19471 } 19472 } 19473 }); 19474 return moveId; 19475 } 19476 19477 private void movePackageInternal(final String packageName, final String volumeUuid, 19478 final int moveId, UserHandle user) throws PackageManagerException { 19479 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19480 final PackageManager pm = mContext.getPackageManager(); 19481 19482 final boolean currentAsec; 19483 final String currentVolumeUuid; 19484 final File codeFile; 19485 final String installerPackageName; 19486 final String packageAbiOverride; 19487 final int appId; 19488 final String seinfo; 19489 final String label; 19490 final int targetSdkVersion; 19491 final PackageFreezer freezer; 19492 19493 // reader 19494 synchronized (mPackages) { 19495 final PackageParser.Package pkg = mPackages.get(packageName); 19496 final PackageSetting ps = mSettings.mPackages.get(packageName); 19497 if (pkg == null || ps == null) { 19498 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19499 } 19500 19501 if (pkg.applicationInfo.isSystemApp()) { 19502 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19503 "Cannot move system application"); 19504 } 19505 19506 if (pkg.applicationInfo.isExternalAsec()) { 19507 currentAsec = true; 19508 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19509 } else if (pkg.applicationInfo.isForwardLocked()) { 19510 currentAsec = true; 19511 currentVolumeUuid = "forward_locked"; 19512 } else { 19513 currentAsec = false; 19514 currentVolumeUuid = ps.volumeUuid; 19515 19516 final File probe = new File(pkg.codePath); 19517 final File probeOat = new File(probe, "oat"); 19518 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19519 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19520 "Move only supported for modern cluster style installs"); 19521 } 19522 } 19523 19524 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19525 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19526 "Package already moved to " + volumeUuid); 19527 } 19528 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19529 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19530 "Device admin cannot be moved"); 19531 } 19532 19533 if (mFrozenPackages.contains(packageName)) { 19534 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19535 "Failed to move already frozen package"); 19536 } 19537 19538 codeFile = new File(pkg.codePath); 19539 installerPackageName = ps.installerPackageName; 19540 packageAbiOverride = ps.cpuAbiOverrideString; 19541 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19542 seinfo = pkg.applicationInfo.seinfo; 19543 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19544 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19545 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19546 } 19547 19548 final Bundle extras = new Bundle(); 19549 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19550 extras.putString(Intent.EXTRA_TITLE, label); 19551 mMoveCallbacks.notifyCreated(moveId, extras); 19552 19553 int installFlags; 19554 final boolean moveCompleteApp; 19555 final File measurePath; 19556 19557 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19558 installFlags = INSTALL_INTERNAL; 19559 moveCompleteApp = !currentAsec; 19560 measurePath = Environment.getDataAppDirectory(volumeUuid); 19561 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19562 installFlags = INSTALL_EXTERNAL; 19563 moveCompleteApp = false; 19564 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19565 } else { 19566 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19567 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19568 || !volume.isMountedWritable()) { 19569 freezer.close(); 19570 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19571 "Move location not mounted private volume"); 19572 } 19573 19574 Preconditions.checkState(!currentAsec); 19575 19576 installFlags = INSTALL_INTERNAL; 19577 moveCompleteApp = true; 19578 measurePath = Environment.getDataAppDirectory(volumeUuid); 19579 } 19580 19581 final PackageStats stats = new PackageStats(null, -1); 19582 synchronized (mInstaller) { 19583 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19584 freezer.close(); 19585 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19586 "Failed to measure package size"); 19587 } 19588 } 19589 19590 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19591 + stats.dataSize); 19592 19593 final long startFreeBytes = measurePath.getFreeSpace(); 19594 final long sizeBytes; 19595 if (moveCompleteApp) { 19596 sizeBytes = stats.codeSize + stats.dataSize; 19597 } else { 19598 sizeBytes = stats.codeSize; 19599 } 19600 19601 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19602 freezer.close(); 19603 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19604 "Not enough free space to move"); 19605 } 19606 19607 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19608 19609 final CountDownLatch installedLatch = new CountDownLatch(1); 19610 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19611 @Override 19612 public void onUserActionRequired(Intent intent) throws RemoteException { 19613 throw new IllegalStateException(); 19614 } 19615 19616 @Override 19617 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19618 Bundle extras) throws RemoteException { 19619 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19620 + PackageManager.installStatusToString(returnCode, msg)); 19621 19622 installedLatch.countDown(); 19623 freezer.close(); 19624 19625 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19626 switch (status) { 19627 case PackageInstaller.STATUS_SUCCESS: 19628 mMoveCallbacks.notifyStatusChanged(moveId, 19629 PackageManager.MOVE_SUCCEEDED); 19630 break; 19631 case PackageInstaller.STATUS_FAILURE_STORAGE: 19632 mMoveCallbacks.notifyStatusChanged(moveId, 19633 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19634 break; 19635 default: 19636 mMoveCallbacks.notifyStatusChanged(moveId, 19637 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19638 break; 19639 } 19640 } 19641 }; 19642 19643 final MoveInfo move; 19644 if (moveCompleteApp) { 19645 // Kick off a thread to report progress estimates 19646 new Thread() { 19647 @Override 19648 public void run() { 19649 while (true) { 19650 try { 19651 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19652 break; 19653 } 19654 } catch (InterruptedException ignored) { 19655 } 19656 19657 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19658 final int progress = 10 + (int) MathUtils.constrain( 19659 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19660 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19661 } 19662 } 19663 }.start(); 19664 19665 final String dataAppName = codeFile.getName(); 19666 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19667 dataAppName, appId, seinfo, targetSdkVersion); 19668 } else { 19669 move = null; 19670 } 19671 19672 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19673 19674 final Message msg = mHandler.obtainMessage(INIT_COPY); 19675 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19676 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19677 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19678 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19679 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19680 msg.obj = params; 19681 19682 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19683 System.identityHashCode(msg.obj)); 19684 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19685 System.identityHashCode(msg.obj)); 19686 19687 mHandler.sendMessage(msg); 19688 } 19689 19690 @Override 19691 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19692 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19693 19694 final int realMoveId = mNextMoveId.getAndIncrement(); 19695 final Bundle extras = new Bundle(); 19696 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19697 mMoveCallbacks.notifyCreated(realMoveId, extras); 19698 19699 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19700 @Override 19701 public void onCreated(int moveId, Bundle extras) { 19702 // Ignored 19703 } 19704 19705 @Override 19706 public void onStatusChanged(int moveId, int status, long estMillis) { 19707 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19708 } 19709 }; 19710 19711 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19712 storage.setPrimaryStorageUuid(volumeUuid, callback); 19713 return realMoveId; 19714 } 19715 19716 @Override 19717 public int getMoveStatus(int moveId) { 19718 mContext.enforceCallingOrSelfPermission( 19719 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19720 return mMoveCallbacks.mLastStatus.get(moveId); 19721 } 19722 19723 @Override 19724 public void registerMoveCallback(IPackageMoveObserver callback) { 19725 mContext.enforceCallingOrSelfPermission( 19726 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19727 mMoveCallbacks.register(callback); 19728 } 19729 19730 @Override 19731 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19732 mContext.enforceCallingOrSelfPermission( 19733 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19734 mMoveCallbacks.unregister(callback); 19735 } 19736 19737 @Override 19738 public boolean setInstallLocation(int loc) { 19739 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19740 null); 19741 if (getInstallLocation() == loc) { 19742 return true; 19743 } 19744 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19745 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19746 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19747 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19748 return true; 19749 } 19750 return false; 19751 } 19752 19753 @Override 19754 public int getInstallLocation() { 19755 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19756 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19757 PackageHelper.APP_INSTALL_AUTO); 19758 } 19759 19760 /** Called by UserManagerService */ 19761 void cleanUpUser(UserManagerService userManager, int userHandle) { 19762 synchronized (mPackages) { 19763 mDirtyUsers.remove(userHandle); 19764 mUserNeedsBadging.delete(userHandle); 19765 mSettings.removeUserLPw(userHandle); 19766 mPendingBroadcasts.remove(userHandle); 19767 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19768 removeUnusedPackagesLPw(userManager, userHandle); 19769 } 19770 } 19771 19772 /** 19773 * We're removing userHandle and would like to remove any downloaded packages 19774 * that are no longer in use by any other user. 19775 * @param userHandle the user being removed 19776 */ 19777 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19778 final boolean DEBUG_CLEAN_APKS = false; 19779 int [] users = userManager.getUserIds(); 19780 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19781 while (psit.hasNext()) { 19782 PackageSetting ps = psit.next(); 19783 if (ps.pkg == null) { 19784 continue; 19785 } 19786 final String packageName = ps.pkg.packageName; 19787 // Skip over if system app 19788 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19789 continue; 19790 } 19791 if (DEBUG_CLEAN_APKS) { 19792 Slog.i(TAG, "Checking package " + packageName); 19793 } 19794 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19795 if (keep) { 19796 if (DEBUG_CLEAN_APKS) { 19797 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19798 } 19799 } else { 19800 for (int i = 0; i < users.length; i++) { 19801 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19802 keep = true; 19803 if (DEBUG_CLEAN_APKS) { 19804 Slog.i(TAG, " Keeping package " + packageName + " for user " 19805 + users[i]); 19806 } 19807 break; 19808 } 19809 } 19810 } 19811 if (!keep) { 19812 if (DEBUG_CLEAN_APKS) { 19813 Slog.i(TAG, " Removing package " + packageName); 19814 } 19815 mHandler.post(new Runnable() { 19816 public void run() { 19817 deletePackageX(packageName, userHandle, 0); 19818 } //end run 19819 }); 19820 } 19821 } 19822 } 19823 19824 /** Called by UserManagerService */ 19825 void createNewUser(int userHandle) { 19826 synchronized (mInstallLock) { 19827 mSettings.createNewUserLI(this, mInstaller, userHandle); 19828 } 19829 synchronized (mPackages) { 19830 applyFactoryDefaultBrowserLPw(userHandle); 19831 primeDomainVerificationsLPw(userHandle); 19832 } 19833 } 19834 19835 void newUserCreated(final int userHandle) { 19836 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19837 // If permission review for legacy apps is required, we represent 19838 // dagerous permissions for such apps as always granted runtime 19839 // permissions to keep per user flag state whether review is needed. 19840 // Hence, if a new user is added we have to propagate dangerous 19841 // permission grants for these legacy apps. 19842 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19843 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19844 | UPDATE_PERMISSIONS_REPLACE_ALL); 19845 } 19846 } 19847 19848 @Override 19849 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19850 mContext.enforceCallingOrSelfPermission( 19851 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19852 "Only package verification agents can read the verifier device identity"); 19853 19854 synchronized (mPackages) { 19855 return mSettings.getVerifierDeviceIdentityLPw(); 19856 } 19857 } 19858 19859 @Override 19860 public void setPermissionEnforced(String permission, boolean enforced) { 19861 // TODO: Now that we no longer change GID for storage, this should to away. 19862 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19863 "setPermissionEnforced"); 19864 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19865 synchronized (mPackages) { 19866 if (mSettings.mReadExternalStorageEnforced == null 19867 || mSettings.mReadExternalStorageEnforced != enforced) { 19868 mSettings.mReadExternalStorageEnforced = enforced; 19869 mSettings.writeLPr(); 19870 } 19871 } 19872 // kill any non-foreground processes so we restart them and 19873 // grant/revoke the GID. 19874 final IActivityManager am = ActivityManagerNative.getDefault(); 19875 if (am != null) { 19876 final long token = Binder.clearCallingIdentity(); 19877 try { 19878 am.killProcessesBelowForeground("setPermissionEnforcement"); 19879 } catch (RemoteException e) { 19880 } finally { 19881 Binder.restoreCallingIdentity(token); 19882 } 19883 } 19884 } else { 19885 throw new IllegalArgumentException("No selective enforcement for " + permission); 19886 } 19887 } 19888 19889 @Override 19890 @Deprecated 19891 public boolean isPermissionEnforced(String permission) { 19892 return true; 19893 } 19894 19895 @Override 19896 public boolean isStorageLow() { 19897 final long token = Binder.clearCallingIdentity(); 19898 try { 19899 final DeviceStorageMonitorInternal 19900 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19901 if (dsm != null) { 19902 return dsm.isMemoryLow(); 19903 } else { 19904 return false; 19905 } 19906 } finally { 19907 Binder.restoreCallingIdentity(token); 19908 } 19909 } 19910 19911 @Override 19912 public IPackageInstaller getPackageInstaller() { 19913 return mInstallerService; 19914 } 19915 19916 private boolean userNeedsBadging(int userId) { 19917 int index = mUserNeedsBadging.indexOfKey(userId); 19918 if (index < 0) { 19919 final UserInfo userInfo; 19920 final long token = Binder.clearCallingIdentity(); 19921 try { 19922 userInfo = sUserManager.getUserInfo(userId); 19923 } finally { 19924 Binder.restoreCallingIdentity(token); 19925 } 19926 final boolean b; 19927 if (userInfo != null && userInfo.isManagedProfile()) { 19928 b = true; 19929 } else { 19930 b = false; 19931 } 19932 mUserNeedsBadging.put(userId, b); 19933 return b; 19934 } 19935 return mUserNeedsBadging.valueAt(index); 19936 } 19937 19938 @Override 19939 public KeySet getKeySetByAlias(String packageName, String alias) { 19940 if (packageName == null || alias == null) { 19941 return null; 19942 } 19943 synchronized(mPackages) { 19944 final PackageParser.Package pkg = mPackages.get(packageName); 19945 if (pkg == null) { 19946 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19947 throw new IllegalArgumentException("Unknown package: " + packageName); 19948 } 19949 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19950 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19951 } 19952 } 19953 19954 @Override 19955 public KeySet getSigningKeySet(String packageName) { 19956 if (packageName == null) { 19957 return null; 19958 } 19959 synchronized(mPackages) { 19960 final PackageParser.Package pkg = mPackages.get(packageName); 19961 if (pkg == null) { 19962 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19963 throw new IllegalArgumentException("Unknown package: " + packageName); 19964 } 19965 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19966 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19967 throw new SecurityException("May not access signing KeySet of other apps."); 19968 } 19969 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19970 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19971 } 19972 } 19973 19974 @Override 19975 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19976 if (packageName == null || ks == null) { 19977 return false; 19978 } 19979 synchronized(mPackages) { 19980 final PackageParser.Package pkg = mPackages.get(packageName); 19981 if (pkg == null) { 19982 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19983 throw new IllegalArgumentException("Unknown package: " + packageName); 19984 } 19985 IBinder ksh = ks.getToken(); 19986 if (ksh instanceof KeySetHandle) { 19987 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19988 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19989 } 19990 return false; 19991 } 19992 } 19993 19994 @Override 19995 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19996 if (packageName == null || ks == null) { 19997 return false; 19998 } 19999 synchronized(mPackages) { 20000 final PackageParser.Package pkg = mPackages.get(packageName); 20001 if (pkg == null) { 20002 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20003 throw new IllegalArgumentException("Unknown package: " + packageName); 20004 } 20005 IBinder ksh = ks.getToken(); 20006 if (ksh instanceof KeySetHandle) { 20007 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20008 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20009 } 20010 return false; 20011 } 20012 } 20013 20014 private void deletePackageIfUnusedLPr(final String packageName) { 20015 PackageSetting ps = mSettings.mPackages.get(packageName); 20016 if (ps == null) { 20017 return; 20018 } 20019 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20020 // TODO Implement atomic delete if package is unused 20021 // It is currently possible that the package will be deleted even if it is installed 20022 // after this method returns. 20023 mHandler.post(new Runnable() { 20024 public void run() { 20025 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20026 } 20027 }); 20028 } 20029 } 20030 20031 /** 20032 * Check and throw if the given before/after packages would be considered a 20033 * downgrade. 20034 */ 20035 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20036 throws PackageManagerException { 20037 if (after.versionCode < before.mVersionCode) { 20038 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20039 "Update version code " + after.versionCode + " is older than current " 20040 + before.mVersionCode); 20041 } else if (after.versionCode == before.mVersionCode) { 20042 if (after.baseRevisionCode < before.baseRevisionCode) { 20043 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20044 "Update base revision code " + after.baseRevisionCode 20045 + " is older than current " + before.baseRevisionCode); 20046 } 20047 20048 if (!ArrayUtils.isEmpty(after.splitNames)) { 20049 for (int i = 0; i < after.splitNames.length; i++) { 20050 final String splitName = after.splitNames[i]; 20051 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20052 if (j != -1) { 20053 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20054 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20055 "Update split " + splitName + " revision code " 20056 + after.splitRevisionCodes[i] + " is older than current " 20057 + before.splitRevisionCodes[j]); 20058 } 20059 } 20060 } 20061 } 20062 } 20063 } 20064 20065 private static class MoveCallbacks extends Handler { 20066 private static final int MSG_CREATED = 1; 20067 private static final int MSG_STATUS_CHANGED = 2; 20068 20069 private final RemoteCallbackList<IPackageMoveObserver> 20070 mCallbacks = new RemoteCallbackList<>(); 20071 20072 private final SparseIntArray mLastStatus = new SparseIntArray(); 20073 20074 public MoveCallbacks(Looper looper) { 20075 super(looper); 20076 } 20077 20078 public void register(IPackageMoveObserver callback) { 20079 mCallbacks.register(callback); 20080 } 20081 20082 public void unregister(IPackageMoveObserver callback) { 20083 mCallbacks.unregister(callback); 20084 } 20085 20086 @Override 20087 public void handleMessage(Message msg) { 20088 final SomeArgs args = (SomeArgs) msg.obj; 20089 final int n = mCallbacks.beginBroadcast(); 20090 for (int i = 0; i < n; i++) { 20091 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20092 try { 20093 invokeCallback(callback, msg.what, args); 20094 } catch (RemoteException ignored) { 20095 } 20096 } 20097 mCallbacks.finishBroadcast(); 20098 args.recycle(); 20099 } 20100 20101 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20102 throws RemoteException { 20103 switch (what) { 20104 case MSG_CREATED: { 20105 callback.onCreated(args.argi1, (Bundle) args.arg2); 20106 break; 20107 } 20108 case MSG_STATUS_CHANGED: { 20109 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20110 break; 20111 } 20112 } 20113 } 20114 20115 private void notifyCreated(int moveId, Bundle extras) { 20116 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20117 20118 final SomeArgs args = SomeArgs.obtain(); 20119 args.argi1 = moveId; 20120 args.arg2 = extras; 20121 obtainMessage(MSG_CREATED, args).sendToTarget(); 20122 } 20123 20124 private void notifyStatusChanged(int moveId, int status) { 20125 notifyStatusChanged(moveId, status, -1); 20126 } 20127 20128 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20129 Slog.v(TAG, "Move " + moveId + " status " + status); 20130 20131 final SomeArgs args = SomeArgs.obtain(); 20132 args.argi1 = moveId; 20133 args.argi2 = status; 20134 args.arg3 = estMillis; 20135 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20136 20137 synchronized (mLastStatus) { 20138 mLastStatus.put(moveId, status); 20139 } 20140 } 20141 } 20142 20143 private final static class OnPermissionChangeListeners extends Handler { 20144 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20145 20146 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20147 new RemoteCallbackList<>(); 20148 20149 public OnPermissionChangeListeners(Looper looper) { 20150 super(looper); 20151 } 20152 20153 @Override 20154 public void handleMessage(Message msg) { 20155 switch (msg.what) { 20156 case MSG_ON_PERMISSIONS_CHANGED: { 20157 final int uid = msg.arg1; 20158 handleOnPermissionsChanged(uid); 20159 } break; 20160 } 20161 } 20162 20163 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20164 mPermissionListeners.register(listener); 20165 20166 } 20167 20168 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20169 mPermissionListeners.unregister(listener); 20170 } 20171 20172 public void onPermissionsChanged(int uid) { 20173 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20174 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20175 } 20176 } 20177 20178 private void handleOnPermissionsChanged(int uid) { 20179 final int count = mPermissionListeners.beginBroadcast(); 20180 try { 20181 for (int i = 0; i < count; i++) { 20182 IOnPermissionsChangeListener callback = mPermissionListeners 20183 .getBroadcastItem(i); 20184 try { 20185 callback.onPermissionsChanged(uid); 20186 } catch (RemoteException e) { 20187 Log.e(TAG, "Permission listener is dead", e); 20188 } 20189 } 20190 } finally { 20191 mPermissionListeners.finishBroadcast(); 20192 } 20193 } 20194 } 20195 20196 private class PackageManagerInternalImpl extends PackageManagerInternal { 20197 @Override 20198 public void setLocationPackagesProvider(PackagesProvider provider) { 20199 synchronized (mPackages) { 20200 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20201 } 20202 } 20203 20204 @Override 20205 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20206 synchronized (mPackages) { 20207 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20208 } 20209 } 20210 20211 @Override 20212 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20213 synchronized (mPackages) { 20214 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20215 } 20216 } 20217 20218 @Override 20219 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20220 synchronized (mPackages) { 20221 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20222 } 20223 } 20224 20225 @Override 20226 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20227 synchronized (mPackages) { 20228 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20229 } 20230 } 20231 20232 @Override 20233 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20234 synchronized (mPackages) { 20235 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20236 } 20237 } 20238 20239 @Override 20240 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20241 synchronized (mPackages) { 20242 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20243 packageName, userId); 20244 } 20245 } 20246 20247 @Override 20248 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20249 synchronized (mPackages) { 20250 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20251 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20252 packageName, userId); 20253 } 20254 } 20255 20256 @Override 20257 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20258 synchronized (mPackages) { 20259 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20260 packageName, userId); 20261 } 20262 } 20263 20264 @Override 20265 public void setKeepUninstalledPackages(final List<String> packageList) { 20266 Preconditions.checkNotNull(packageList); 20267 List<String> removedFromList = null; 20268 synchronized (mPackages) { 20269 if (mKeepUninstalledPackages != null) { 20270 final int packagesCount = mKeepUninstalledPackages.size(); 20271 for (int i = 0; i < packagesCount; i++) { 20272 String oldPackage = mKeepUninstalledPackages.get(i); 20273 if (packageList != null && packageList.contains(oldPackage)) { 20274 continue; 20275 } 20276 if (removedFromList == null) { 20277 removedFromList = new ArrayList<>(); 20278 } 20279 removedFromList.add(oldPackage); 20280 } 20281 } 20282 mKeepUninstalledPackages = new ArrayList<>(packageList); 20283 if (removedFromList != null) { 20284 final int removedCount = removedFromList.size(); 20285 for (int i = 0; i < removedCount; i++) { 20286 deletePackageIfUnusedLPr(removedFromList.get(i)); 20287 } 20288 } 20289 } 20290 } 20291 20292 @Override 20293 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20294 synchronized (mPackages) { 20295 // If we do not support permission review, done. 20296 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20297 return false; 20298 } 20299 20300 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20301 if (packageSetting == null) { 20302 return false; 20303 } 20304 20305 // Permission review applies only to apps not supporting the new permission model. 20306 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20307 return false; 20308 } 20309 20310 // Legacy apps have the permission and get user consent on launch. 20311 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20312 return permissionsState.isPermissionReviewRequired(userId); 20313 } 20314 } 20315 20316 @Override 20317 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20318 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20319 } 20320 20321 @Override 20322 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20323 int userId) { 20324 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20325 } 20326 } 20327 20328 @Override 20329 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20330 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20331 synchronized (mPackages) { 20332 final long identity = Binder.clearCallingIdentity(); 20333 try { 20334 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20335 packageNames, userId); 20336 } finally { 20337 Binder.restoreCallingIdentity(identity); 20338 } 20339 } 20340 } 20341 20342 private static void enforceSystemOrPhoneCaller(String tag) { 20343 int callingUid = Binder.getCallingUid(); 20344 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20345 throw new SecurityException( 20346 "Cannot call " + tag + " from UID " + callingUid); 20347 } 20348 } 20349 20350 boolean isHistoricalPackageUsageAvailable() { 20351 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20352 } 20353 20354 /** 20355 * Return a <b>copy</b> of the collection of packages known to the package manager. 20356 * @return A copy of the values of mPackages. 20357 */ 20358 Collection<PackageParser.Package> getPackages() { 20359 synchronized (mPackages) { 20360 return new ArrayList<>(mPackages.values()); 20361 } 20362 } 20363 20364 /** 20365 * Logs process start information (including base APK hash) to the security log. 20366 * @hide 20367 */ 20368 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20369 String apkFile, int pid) { 20370 if (!SecurityLog.isLoggingEnabled()) { 20371 return; 20372 } 20373 Bundle data = new Bundle(); 20374 data.putLong("startTimestamp", System.currentTimeMillis()); 20375 data.putString("processName", processName); 20376 data.putInt("uid", uid); 20377 data.putString("seinfo", seinfo); 20378 data.putString("apkFile", apkFile); 20379 data.putInt("pid", pid); 20380 Message msg = mProcessLoggingHandler.obtainMessage( 20381 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20382 msg.setData(data); 20383 mProcessLoggingHandler.sendMessage(msg); 20384 } 20385} 20386