PackageManagerService.java revision 46ef0579dddd6480306fa58553a6e3180aedf9c7
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.INetworkPolicyManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.os.IParcelFileDescriptorFactory; 230import com.android.internal.os.InstallerConnection.InstallerException; 231import com.android.internal.os.SomeArgs; 232import com.android.internal.os.Zygote; 233import com.android.internal.telephony.CarrierAppUtils; 234import com.android.internal.util.ArrayUtils; 235import com.android.internal.util.FastPrintWriter; 236import com.android.internal.util.FastXmlSerializer; 237import com.android.internal.util.IndentingPrintWriter; 238import com.android.internal.util.Preconditions; 239import com.android.internal.util.XmlUtils; 240import com.android.server.EventLogTags; 241import com.android.server.FgThread; 242import com.android.server.IntentResolver; 243import com.android.server.LocalServices; 244import com.android.server.ServiceThread; 245import com.android.server.SystemConfig; 246import com.android.server.Watchdog; 247import com.android.server.net.NetworkPolicyManagerInternal; 248import com.android.server.pm.PermissionsState.PermissionState; 249import com.android.server.pm.Settings.DatabaseVersion; 250import com.android.server.pm.Settings.VersionInfo; 251import com.android.server.storage.DeviceStorageMonitorInternal; 252 253import dalvik.system.CloseGuard; 254import dalvik.system.DexFile; 255import dalvik.system.VMRuntime; 256 257import libcore.io.IoUtils; 258import libcore.util.EmptyArray; 259 260import org.xmlpull.v1.XmlPullParser; 261import org.xmlpull.v1.XmlPullParserException; 262import org.xmlpull.v1.XmlSerializer; 263 264import java.io.BufferedInputStream; 265import java.io.BufferedOutputStream; 266import java.io.BufferedReader; 267import java.io.ByteArrayInputStream; 268import java.io.ByteArrayOutputStream; 269import java.io.File; 270import java.io.FileDescriptor; 271import java.io.FileInputStream; 272import java.io.FileNotFoundException; 273import java.io.FileOutputStream; 274import java.io.FileReader; 275import java.io.FilenameFilter; 276import java.io.IOException; 277import java.io.InputStream; 278import java.io.PrintWriter; 279import java.nio.charset.StandardCharsets; 280import java.security.DigestInputStream; 281import java.security.MessageDigest; 282import java.security.NoSuchAlgorithmException; 283import java.security.PublicKey; 284import java.security.cert.Certificate; 285import java.security.cert.CertificateEncodingException; 286import java.security.cert.CertificateException; 287import java.text.SimpleDateFormat; 288import java.util.ArrayList; 289import java.util.Arrays; 290import java.util.Collection; 291import java.util.Collections; 292import java.util.Comparator; 293import java.util.Date; 294import java.util.HashSet; 295import java.util.Iterator; 296import java.util.List; 297import java.util.Map; 298import java.util.Objects; 299import java.util.Set; 300import java.util.concurrent.CountDownLatch; 301import java.util.concurrent.TimeUnit; 302import java.util.concurrent.atomic.AtomicBoolean; 303import java.util.concurrent.atomic.AtomicInteger; 304import java.util.concurrent.atomic.AtomicLong; 305 306/** 307 * Keep track of all those APKs everywhere. 308 * <p> 309 * Internally there are two important locks: 310 * <ul> 311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 312 * and other related state. It is a fine-grained lock that should only be held 313 * momentarily, as it's one of the most contended locks in the system. 314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 315 * operations typically involve heavy lifting of application data on disk. Since 316 * {@code installd} is single-threaded, and it's operations can often be slow, 317 * this lock should never be acquired while already holding {@link #mPackages}. 318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 319 * holding {@link #mInstallLock}. 320 * </ul> 321 * Many internal methods rely on the caller to hold the appropriate locks, and 322 * this contract is expressed through method name suffixes: 323 * <ul> 324 * <li>fooLI(): the caller must hold {@link #mInstallLock} 325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 326 * being modified must be frozen 327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 329 * </ul> 330 * <p> 331 * Because this class is very central to the platform's security; please run all 332 * CTS and unit tests whenever making modifications: 333 * 334 * <pre> 335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 337 * </pre> 338 */ 339public class PackageManagerService extends IPackageManager.Stub { 340 static final String TAG = "PackageManager"; 341 static final boolean DEBUG_SETTINGS = false; 342 static final boolean DEBUG_PREFERRED = false; 343 static final boolean DEBUG_UPGRADE = false; 344 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 345 private static final boolean DEBUG_BACKUP = false; 346 private static final boolean DEBUG_INSTALL = false; 347 private static final boolean DEBUG_REMOVE = false; 348 private static final boolean DEBUG_BROADCASTS = false; 349 private static final boolean DEBUG_SHOW_INFO = false; 350 private static final boolean DEBUG_PACKAGE_INFO = false; 351 private static final boolean DEBUG_INTENT_MATCHING = false; 352 private static final boolean DEBUG_PACKAGE_SCANNING = false; 353 private static final boolean DEBUG_VERIFY = false; 354 private static final boolean DEBUG_FILTERS = false; 355 356 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 357 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 358 // user, but by default initialize to this. 359 static final boolean DEBUG_DEXOPT = false; 360 361 private static final boolean DEBUG_ABI_SELECTION = false; 362 private static final boolean DEBUG_EPHEMERAL = false; 363 private static final boolean DEBUG_TRIAGED_MISSING = false; 364 private static final boolean DEBUG_APP_DATA = false; 365 366 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 367 368 private static final boolean DISABLE_EPHEMERAL_APPS = true; 369 370 private static final int RADIO_UID = Process.PHONE_UID; 371 private static final int LOG_UID = Process.LOG_UID; 372 private static final int NFC_UID = Process.NFC_UID; 373 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 374 private static final int SHELL_UID = Process.SHELL_UID; 375 376 // Cap the size of permission trees that 3rd party apps can define 377 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 378 379 // Suffix used during package installation when copying/moving 380 // package apks to install directory. 381 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 382 383 static final int SCAN_NO_DEX = 1<<1; 384 static final int SCAN_FORCE_DEX = 1<<2; 385 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 386 static final int SCAN_NEW_INSTALL = 1<<4; 387 static final int SCAN_NO_PATHS = 1<<5; 388 static final int SCAN_UPDATE_TIME = 1<<6; 389 static final int SCAN_DEFER_DEX = 1<<7; 390 static final int SCAN_BOOTING = 1<<8; 391 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 392 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 393 static final int SCAN_REPLACING = 1<<11; 394 static final int SCAN_REQUIRE_KNOWN = 1<<12; 395 static final int SCAN_MOVE = 1<<13; 396 static final int SCAN_INITIAL = 1<<14; 397 static final int SCAN_CHECK_ONLY = 1<<15; 398 static final int SCAN_DONT_KILL_APP = 1<<17; 399 static final int SCAN_IGNORE_FROZEN = 1<<18; 400 401 static final int REMOVE_CHATTY = 1<<16; 402 403 private static final int[] EMPTY_INT_ARRAY = new int[0]; 404 405 /** 406 * Timeout (in milliseconds) after which the watchdog should declare that 407 * our handler thread is wedged. The usual default for such things is one 408 * minute but we sometimes do very lengthy I/O operations on this thread, 409 * such as installing multi-gigabyte applications, so ours needs to be longer. 410 */ 411 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 412 413 /** 414 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 415 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 416 * settings entry if available, otherwise we use the hardcoded default. If it's been 417 * more than this long since the last fstrim, we force one during the boot sequence. 418 * 419 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 420 * one gets run at the next available charging+idle time. This final mandatory 421 * no-fstrim check kicks in only of the other scheduling criteria is never met. 422 */ 423 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 424 425 /** 426 * Whether verification is enabled by default. 427 */ 428 private static final boolean DEFAULT_VERIFY_ENABLE = true; 429 430 /** 431 * The default maximum time to wait for the verification agent to return in 432 * milliseconds. 433 */ 434 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 435 436 /** 437 * The default response for package verification timeout. 438 * 439 * This can be either PackageManager.VERIFICATION_ALLOW or 440 * PackageManager.VERIFICATION_REJECT. 441 */ 442 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 443 444 static final String PLATFORM_PACKAGE_NAME = "android"; 445 446 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 447 448 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 449 DEFAULT_CONTAINER_PACKAGE, 450 "com.android.defcontainer.DefaultContainerService"); 451 452 private static final String KILL_APP_REASON_GIDS_CHANGED = 453 "permission grant or revoke changed gids"; 454 455 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 456 "permissions revoked"; 457 458 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 459 460 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 461 462 /** Permission grant: not grant the permission. */ 463 private static final int GRANT_DENIED = 1; 464 465 /** Permission grant: grant the permission as an install permission. */ 466 private static final int GRANT_INSTALL = 2; 467 468 /** Permission grant: grant the permission as a runtime one. */ 469 private static final int GRANT_RUNTIME = 3; 470 471 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 472 private static final int GRANT_UPGRADE = 4; 473 474 /** Canonical intent used to identify what counts as a "web browser" app */ 475 private static final Intent sBrowserIntent; 476 static { 477 sBrowserIntent = new Intent(); 478 sBrowserIntent.setAction(Intent.ACTION_VIEW); 479 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 480 sBrowserIntent.setData(Uri.parse("http:")); 481 } 482 483 /** 484 * The set of all protected actions [i.e. those actions for which a high priority 485 * intent filter is disallowed]. 486 */ 487 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 488 static { 489 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 490 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 492 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 493 } 494 495 // Compilation reasons. 496 public static final int REASON_FIRST_BOOT = 0; 497 public static final int REASON_BOOT = 1; 498 public static final int REASON_INSTALL = 2; 499 public static final int REASON_BACKGROUND_DEXOPT = 3; 500 public static final int REASON_AB_OTA = 4; 501 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 502 public static final int REASON_SHARED_APK = 6; 503 public static final int REASON_FORCED_DEXOPT = 7; 504 505 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 506 507 /** Special library name that skips shared libraries check during compilation. */ 508 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 509 510 final ServiceThread mHandlerThread; 511 512 final PackageHandler mHandler; 513 514 private final ProcessLoggingHandler mProcessLoggingHandler; 515 516 /** 517 * Messages for {@link #mHandler} that need to wait for system ready before 518 * being dispatched. 519 */ 520 private ArrayList<Message> mPostSystemReadyMessages; 521 522 final int mSdkVersion = Build.VERSION.SDK_INT; 523 524 final Context mContext; 525 final boolean mFactoryTest; 526 final boolean mOnlyCore; 527 final DisplayMetrics mMetrics; 528 final int mDefParseFlags; 529 final String[] mSeparateProcesses; 530 final boolean mIsUpgrade; 531 final boolean mIsPreNUpgrade; 532 533 /** The location for ASEC container files on internal storage. */ 534 final String mAsecInternalPath; 535 536 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 537 // LOCK HELD. Can be called with mInstallLock held. 538 @GuardedBy("mInstallLock") 539 final Installer mInstaller; 540 541 /** Directory where installed third-party apps stored */ 542 final File mAppInstallDir; 543 final File mEphemeralInstallDir; 544 545 /** 546 * Directory to which applications installed internally have their 547 * 32 bit native libraries copied. 548 */ 549 private File mAppLib32InstallDir; 550 551 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 552 // apps. 553 final File mDrmAppPrivateInstallDir; 554 555 // ---------------------------------------------------------------- 556 557 // Lock for state used when installing and doing other long running 558 // operations. Methods that must be called with this lock held have 559 // the suffix "LI". 560 final Object mInstallLock = new Object(); 561 562 // ---------------------------------------------------------------- 563 564 // Keys are String (package name), values are Package. This also serves 565 // as the lock for the global state. Methods that must be called with 566 // this lock held have the prefix "LP". 567 @GuardedBy("mPackages") 568 final ArrayMap<String, PackageParser.Package> mPackages = 569 new ArrayMap<String, PackageParser.Package>(); 570 571 final ArrayMap<String, Set<String>> mKnownCodebase = 572 new ArrayMap<String, Set<String>>(); 573 574 // Tracks available target package names -> overlay package paths. 575 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 576 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 577 578 /** 579 * Tracks new system packages [received in an OTA] that we expect to 580 * find updated user-installed versions. Keys are package name, values 581 * are package location. 582 */ 583 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 584 /** 585 * Tracks high priority intent filters for protected actions. During boot, certain 586 * filter actions are protected and should never be allowed to have a high priority 587 * intent filter for them. However, there is one, and only one exception -- the 588 * setup wizard. It must be able to define a high priority intent filter for these 589 * actions to ensure there are no escapes from the wizard. We need to delay processing 590 * of these during boot as we need to look at all of the system packages in order 591 * to know which component is the setup wizard. 592 */ 593 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 594 /** 595 * Whether or not processing protected filters should be deferred. 596 */ 597 private boolean mDeferProtectedFilters = true; 598 599 /** 600 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 601 */ 602 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 603 /** 604 * Whether or not system app permissions should be promoted from install to runtime. 605 */ 606 boolean mPromoteSystemApps; 607 608 @GuardedBy("mPackages") 609 final Settings mSettings; 610 611 /** 612 * Set of package names that are currently "frozen", which means active 613 * surgery is being done on the code/data for that package. The platform 614 * will refuse to launch frozen packages to avoid race conditions. 615 * 616 * @see PackageFreezer 617 */ 618 @GuardedBy("mPackages") 619 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 620 621 boolean mRestoredSettings; 622 623 // System configuration read by SystemConfig. 624 final int[] mGlobalGids; 625 final SparseArray<ArraySet<String>> mSystemPermissions; 626 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 627 628 // If mac_permissions.xml was found for seinfo labeling. 629 boolean mFoundPolicyFile; 630 631 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 632 633 public static final class SharedLibraryEntry { 634 public final String path; 635 public final String apk; 636 637 SharedLibraryEntry(String _path, String _apk) { 638 path = _path; 639 apk = _apk; 640 } 641 } 642 643 // Currently known shared libraries. 644 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 645 new ArrayMap<String, SharedLibraryEntry>(); 646 647 // All available activities, for your resolving pleasure. 648 final ActivityIntentResolver mActivities = 649 new ActivityIntentResolver(); 650 651 // All available receivers, for your resolving pleasure. 652 final ActivityIntentResolver mReceivers = 653 new ActivityIntentResolver(); 654 655 // All available services, for your resolving pleasure. 656 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 657 658 // All available providers, for your resolving pleasure. 659 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 660 661 // Mapping from provider base names (first directory in content URI codePath) 662 // to the provider information. 663 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 664 new ArrayMap<String, PackageParser.Provider>(); 665 666 // Mapping from instrumentation class names to info about them. 667 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 668 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 669 670 // Mapping from permission names to info about them. 671 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 672 new ArrayMap<String, PackageParser.PermissionGroup>(); 673 674 // Packages whose data we have transfered into another package, thus 675 // should no longer exist. 676 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 677 678 // Broadcast actions that are only available to the system. 679 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 680 681 /** List of packages waiting for verification. */ 682 final SparseArray<PackageVerificationState> mPendingVerification 683 = new SparseArray<PackageVerificationState>(); 684 685 /** Set of packages associated with each app op permission. */ 686 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 687 688 final PackageInstallerService mInstallerService; 689 690 private final PackageDexOptimizer mPackageDexOptimizer; 691 692 private AtomicInteger mNextMoveId = new AtomicInteger(); 693 private final MoveCallbacks mMoveCallbacks; 694 695 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 696 697 // Cache of users who need badging. 698 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 699 700 /** Token for keys in mPendingVerification. */ 701 private int mPendingVerificationToken = 0; 702 703 volatile boolean mSystemReady; 704 volatile boolean mSafeMode; 705 volatile boolean mHasSystemUidErrors; 706 707 ApplicationInfo mAndroidApplication; 708 final ActivityInfo mResolveActivity = new ActivityInfo(); 709 final ResolveInfo mResolveInfo = new ResolveInfo(); 710 ComponentName mResolveComponentName; 711 PackageParser.Package mPlatformPackage; 712 ComponentName mCustomResolverComponentName; 713 714 boolean mResolverReplaced = false; 715 716 private final @Nullable ComponentName mIntentFilterVerifierComponent; 717 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 718 719 private int mIntentFilterVerificationToken = 0; 720 721 /** Component that knows whether or not an ephemeral application exists */ 722 final ComponentName mEphemeralResolverComponent; 723 /** The service connection to the ephemeral resolver */ 724 final EphemeralResolverConnection mEphemeralResolverConnection; 725 726 /** Component used to install ephemeral applications */ 727 final ComponentName mEphemeralInstallerComponent; 728 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 729 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 730 731 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 732 = new SparseArray<IntentFilterVerificationState>(); 733 734 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 735 new DefaultPermissionGrantPolicy(this); 736 737 // List of packages names to keep cached, even if they are uninstalled for all users 738 private List<String> mKeepUninstalledPackages; 739 740 private static class IFVerificationParams { 741 PackageParser.Package pkg; 742 boolean replacing; 743 int userId; 744 int verifierUid; 745 746 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 747 int _userId, int _verifierUid) { 748 pkg = _pkg; 749 replacing = _replacing; 750 userId = _userId; 751 replacing = _replacing; 752 verifierUid = _verifierUid; 753 } 754 } 755 756 private interface IntentFilterVerifier<T extends IntentFilter> { 757 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 758 T filter, String packageName); 759 void startVerifications(int userId); 760 void receiveVerificationResponse(int verificationId); 761 } 762 763 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 764 private Context mContext; 765 private ComponentName mIntentFilterVerifierComponent; 766 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 767 768 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 769 mContext = context; 770 mIntentFilterVerifierComponent = verifierComponent; 771 } 772 773 private String getDefaultScheme() { 774 return IntentFilter.SCHEME_HTTPS; 775 } 776 777 @Override 778 public void startVerifications(int userId) { 779 // Launch verifications requests 780 int count = mCurrentIntentFilterVerifications.size(); 781 for (int n=0; n<count; n++) { 782 int verificationId = mCurrentIntentFilterVerifications.get(n); 783 final IntentFilterVerificationState ivs = 784 mIntentFilterVerificationStates.get(verificationId); 785 786 String packageName = ivs.getPackageName(); 787 788 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 789 final int filterCount = filters.size(); 790 ArraySet<String> domainsSet = new ArraySet<>(); 791 for (int m=0; m<filterCount; m++) { 792 PackageParser.ActivityIntentInfo filter = filters.get(m); 793 domainsSet.addAll(filter.getHostsList()); 794 } 795 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 796 synchronized (mPackages) { 797 if (mSettings.createIntentFilterVerificationIfNeededLPw( 798 packageName, domainsList) != null) { 799 scheduleWriteSettingsLocked(); 800 } 801 } 802 sendVerificationRequest(userId, verificationId, ivs); 803 } 804 mCurrentIntentFilterVerifications.clear(); 805 } 806 807 private void sendVerificationRequest(int userId, int verificationId, 808 IntentFilterVerificationState ivs) { 809 810 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 813 verificationId); 814 verificationIntent.putExtra( 815 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 816 getDefaultScheme()); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 819 ivs.getHostsString()); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 822 ivs.getPackageName()); 823 verificationIntent.setComponent(mIntentFilterVerifierComponent); 824 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 825 826 UserHandle user = new UserHandle(userId); 827 mContext.sendBroadcastAsUser(verificationIntent, user); 828 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 829 "Sending IntentFilter verification broadcast"); 830 } 831 832 public void receiveVerificationResponse(int verificationId) { 833 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 834 835 final boolean verified = ivs.isVerified(); 836 837 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 838 final int count = filters.size(); 839 if (DEBUG_DOMAIN_VERIFICATION) { 840 Slog.i(TAG, "Received verification response " + verificationId 841 + " for " + count + " filters, verified=" + verified); 842 } 843 for (int n=0; n<count; n++) { 844 PackageParser.ActivityIntentInfo filter = filters.get(n); 845 filter.setVerified(verified); 846 847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 848 + " verified with result:" + verified + " and hosts:" 849 + ivs.getHostsString()); 850 } 851 852 mIntentFilterVerificationStates.remove(verificationId); 853 854 final String packageName = ivs.getPackageName(); 855 IntentFilterVerificationInfo ivi = null; 856 857 synchronized (mPackages) { 858 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 859 } 860 if (ivi == null) { 861 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 862 + verificationId + " packageName:" + packageName); 863 return; 864 } 865 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 866 "Updating IntentFilterVerificationInfo for package " + packageName 867 +" verificationId:" + verificationId); 868 869 synchronized (mPackages) { 870 if (verified) { 871 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 872 } else { 873 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 874 } 875 scheduleWriteSettingsLocked(); 876 877 final int userId = ivs.getUserId(); 878 if (userId != UserHandle.USER_ALL) { 879 final int userStatus = 880 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 881 882 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 883 boolean needUpdate = false; 884 885 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 886 // already been set by the User thru the Disambiguation dialog 887 switch (userStatus) { 888 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 889 if (verified) { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 891 } else { 892 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 893 } 894 needUpdate = true; 895 break; 896 897 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 898 if (verified) { 899 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 900 needUpdate = true; 901 } 902 break; 903 904 default: 905 // Nothing to do 906 } 907 908 if (needUpdate) { 909 mSettings.updateIntentFilterVerificationStatusLPw( 910 packageName, updatedStatus, userId); 911 scheduleWritePackageRestrictionsLocked(userId); 912 } 913 } 914 } 915 } 916 917 @Override 918 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 919 ActivityIntentInfo filter, String packageName) { 920 if (!hasValidDomains(filter)) { 921 return false; 922 } 923 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 924 if (ivs == null) { 925 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 926 packageName); 927 } 928 if (DEBUG_DOMAIN_VERIFICATION) { 929 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 930 } 931 ivs.addFilter(filter); 932 return true; 933 } 934 935 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 936 int userId, int verificationId, String packageName) { 937 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 938 verifierUid, userId, packageName); 939 ivs.setPendingState(); 940 synchronized (mPackages) { 941 mIntentFilterVerificationStates.append(verificationId, ivs); 942 mCurrentIntentFilterVerifications.add(verificationId); 943 } 944 return ivs; 945 } 946 } 947 948 private static boolean hasValidDomains(ActivityIntentInfo filter) { 949 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 950 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 951 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 952 } 953 954 // Set of pending broadcasts for aggregating enable/disable of components. 955 static class PendingPackageBroadcasts { 956 // for each user id, a map of <package name -> components within that package> 957 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 958 959 public PendingPackageBroadcasts() { 960 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 961 } 962 963 public ArrayList<String> get(int userId, String packageName) { 964 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 965 return packages.get(packageName); 966 } 967 968 public void put(int userId, String packageName, ArrayList<String> components) { 969 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 970 packages.put(packageName, components); 971 } 972 973 public void remove(int userId, String packageName) { 974 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 975 if (packages != null) { 976 packages.remove(packageName); 977 } 978 } 979 980 public void remove(int userId) { 981 mUidMap.remove(userId); 982 } 983 984 public int userIdCount() { 985 return mUidMap.size(); 986 } 987 988 public int userIdAt(int n) { 989 return mUidMap.keyAt(n); 990 } 991 992 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 993 return mUidMap.get(userId); 994 } 995 996 public int size() { 997 // total number of pending broadcast entries across all userIds 998 int num = 0; 999 for (int i = 0; i< mUidMap.size(); i++) { 1000 num += mUidMap.valueAt(i).size(); 1001 } 1002 return num; 1003 } 1004 1005 public void clear() { 1006 mUidMap.clear(); 1007 } 1008 1009 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1010 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1011 if (map == null) { 1012 map = new ArrayMap<String, ArrayList<String>>(); 1013 mUidMap.put(userId, map); 1014 } 1015 return map; 1016 } 1017 } 1018 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1019 1020 // Service Connection to remote media container service to copy 1021 // package uri's from external media onto secure containers 1022 // or internal storage. 1023 private IMediaContainerService mContainerService = null; 1024 1025 static final int SEND_PENDING_BROADCAST = 1; 1026 static final int MCS_BOUND = 3; 1027 static final int END_COPY = 4; 1028 static final int INIT_COPY = 5; 1029 static final int MCS_UNBIND = 6; 1030 static final int START_CLEANING_PACKAGE = 7; 1031 static final int FIND_INSTALL_LOC = 8; 1032 static final int POST_INSTALL = 9; 1033 static final int MCS_RECONNECT = 10; 1034 static final int MCS_GIVE_UP = 11; 1035 static final int UPDATED_MEDIA_STATUS = 12; 1036 static final int WRITE_SETTINGS = 13; 1037 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1038 static final int PACKAGE_VERIFIED = 15; 1039 static final int CHECK_PENDING_VERIFICATION = 16; 1040 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1041 static final int INTENT_FILTER_VERIFIED = 18; 1042 1043 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1044 1045 // Delay time in millisecs 1046 static final int BROADCAST_DELAY = 10 * 1000; 1047 1048 static UserManagerService sUserManager; 1049 1050 // Stores a list of users whose package restrictions file needs to be updated 1051 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1052 1053 final private DefaultContainerConnection mDefContainerConn = 1054 new DefaultContainerConnection(); 1055 class DefaultContainerConnection implements ServiceConnection { 1056 public void onServiceConnected(ComponentName name, IBinder service) { 1057 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1058 IMediaContainerService imcs = 1059 IMediaContainerService.Stub.asInterface(service); 1060 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1061 } 1062 1063 public void onServiceDisconnected(ComponentName name) { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1065 } 1066 } 1067 1068 // Recordkeeping of restore-after-install operations that are currently in flight 1069 // between the Package Manager and the Backup Manager 1070 static class PostInstallData { 1071 public InstallArgs args; 1072 public PackageInstalledInfo res; 1073 1074 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1075 args = _a; 1076 res = _r; 1077 } 1078 } 1079 1080 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1081 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1082 1083 // XML tags for backup/restore of various bits of state 1084 private static final String TAG_PREFERRED_BACKUP = "pa"; 1085 private static final String TAG_DEFAULT_APPS = "da"; 1086 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1087 1088 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1089 private static final String TAG_ALL_GRANTS = "rt-grants"; 1090 private static final String TAG_GRANT = "grant"; 1091 private static final String ATTR_PACKAGE_NAME = "pkg"; 1092 1093 private static final String TAG_PERMISSION = "perm"; 1094 private static final String ATTR_PERMISSION_NAME = "name"; 1095 private static final String ATTR_IS_GRANTED = "g"; 1096 private static final String ATTR_USER_SET = "set"; 1097 private static final String ATTR_USER_FIXED = "fixed"; 1098 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1099 1100 // System/policy permission grants are not backed up 1101 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1102 FLAG_PERMISSION_POLICY_FIXED 1103 | FLAG_PERMISSION_SYSTEM_FIXED 1104 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1105 1106 // And we back up these user-adjusted states 1107 private static final int USER_RUNTIME_GRANT_MASK = 1108 FLAG_PERMISSION_USER_SET 1109 | FLAG_PERMISSION_USER_FIXED 1110 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1111 1112 final @Nullable String mRequiredVerifierPackage; 1113 final @NonNull String mRequiredInstallerPackage; 1114 final @Nullable String mSetupWizardPackage; 1115 final @NonNull String mServicesSystemSharedLibraryPackageName; 1116 final @NonNull String mSharedSystemSharedLibraryPackageName; 1117 1118 private final PackageUsage mPackageUsage = new PackageUsage(); 1119 1120 private class PackageUsage { 1121 private static final int WRITE_INTERVAL 1122 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1123 1124 private final Object mFileLock = new Object(); 1125 private final AtomicLong mLastWritten = new AtomicLong(0); 1126 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1127 1128 private boolean mIsHistoricalPackageUsageAvailable = true; 1129 1130 boolean isHistoricalPackageUsageAvailable() { 1131 return mIsHistoricalPackageUsageAvailable; 1132 } 1133 1134 void write(boolean force) { 1135 if (force) { 1136 writeInternal(); 1137 return; 1138 } 1139 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1140 && !DEBUG_DEXOPT) { 1141 return; 1142 } 1143 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1144 new Thread("PackageUsage_DiskWriter") { 1145 @Override 1146 public void run() { 1147 try { 1148 writeInternal(); 1149 } finally { 1150 mBackgroundWriteRunning.set(false); 1151 } 1152 } 1153 }.start(); 1154 } 1155 } 1156 1157 private void writeInternal() { 1158 synchronized (mPackages) { 1159 synchronized (mFileLock) { 1160 AtomicFile file = getFile(); 1161 FileOutputStream f = null; 1162 try { 1163 f = file.startWrite(); 1164 BufferedOutputStream out = new BufferedOutputStream(f); 1165 FileUtils.setPermissions(file.getBaseFile().getPath(), 1166 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1167 StringBuilder sb = new StringBuilder(); 1168 1169 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1170 sb.append('\n'); 1171 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1172 1173 for (PackageParser.Package pkg : mPackages.values()) { 1174 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1175 continue; 1176 } 1177 sb.setLength(0); 1178 sb.append(pkg.packageName); 1179 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1180 sb.append(' '); 1181 sb.append(usageTimeInMillis); 1182 } 1183 sb.append('\n'); 1184 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1185 } 1186 out.flush(); 1187 file.finishWrite(f); 1188 } catch (IOException e) { 1189 if (f != null) { 1190 file.failWrite(f); 1191 } 1192 Log.e(TAG, "Failed to write package usage times", e); 1193 } 1194 } 1195 } 1196 mLastWritten.set(SystemClock.elapsedRealtime()); 1197 } 1198 1199 void readLP() { 1200 synchronized (mFileLock) { 1201 AtomicFile file = getFile(); 1202 BufferedInputStream in = null; 1203 try { 1204 in = new BufferedInputStream(file.openRead()); 1205 StringBuffer sb = new StringBuffer(); 1206 1207 String firstLine = readLine(in, sb); 1208 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1209 readVersion1LP(in, sb); 1210 } else { 1211 readVersion0LP(in, sb, firstLine); 1212 } 1213 } catch (FileNotFoundException expected) { 1214 mIsHistoricalPackageUsageAvailable = false; 1215 } catch (IOException e) { 1216 Log.w(TAG, "Failed to read package usage times", e); 1217 } finally { 1218 IoUtils.closeQuietly(in); 1219 } 1220 } 1221 mLastWritten.set(SystemClock.elapsedRealtime()); 1222 } 1223 1224 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1225 throws IOException { 1226 // Initial version of the file had no version number and stored one 1227 // package-timestamp pair per line. 1228 // Note that the first line has already been read from the InputStream. 1229 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1230 String[] tokens = line.split(" "); 1231 if (tokens.length != 2) { 1232 throw new IOException("Failed to parse " + line + 1233 " as package-timestamp pair."); 1234 } 1235 1236 String packageName = tokens[0]; 1237 PackageParser.Package pkg = mPackages.get(packageName); 1238 if (pkg == null) { 1239 continue; 1240 } 1241 1242 long timestamp = parseAsLong(tokens[1]); 1243 for (int reason = 0; 1244 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1245 reason++) { 1246 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1247 } 1248 } 1249 } 1250 1251 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1252 // Version 1 of the file started with the corresponding version 1253 // number and then stored a package name and eight timestamps per line. 1254 String line; 1255 while ((line = readLine(in, sb)) != null) { 1256 String[] tokens = line.split(" "); 1257 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1258 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1259 } 1260 1261 String packageName = tokens[0]; 1262 PackageParser.Package pkg = mPackages.get(packageName); 1263 if (pkg == null) { 1264 continue; 1265 } 1266 1267 for (int reason = 0; 1268 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1269 reason++) { 1270 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1271 } 1272 } 1273 } 1274 1275 private long parseAsLong(String token) throws IOException { 1276 try { 1277 return Long.parseLong(token); 1278 } catch (NumberFormatException e) { 1279 throw new IOException("Failed to parse " + token + " as a long.", e); 1280 } 1281 } 1282 1283 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1284 return readToken(in, sb, '\n'); 1285 } 1286 1287 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1288 throws IOException { 1289 sb.setLength(0); 1290 while (true) { 1291 int ch = in.read(); 1292 if (ch == -1) { 1293 if (sb.length() == 0) { 1294 return null; 1295 } 1296 throw new IOException("Unexpected EOF"); 1297 } 1298 if (ch == endOfToken) { 1299 return sb.toString(); 1300 } 1301 sb.append((char)ch); 1302 } 1303 } 1304 1305 private AtomicFile getFile() { 1306 File dataDir = Environment.getDataDirectory(); 1307 File systemDir = new File(dataDir, "system"); 1308 File fname = new File(systemDir, "package-usage.list"); 1309 return new AtomicFile(fname); 1310 } 1311 1312 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1313 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1314 } 1315 1316 class PackageHandler extends Handler { 1317 private boolean mBound = false; 1318 final ArrayList<HandlerParams> mPendingInstalls = 1319 new ArrayList<HandlerParams>(); 1320 1321 private boolean connectToService() { 1322 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1323 " DefaultContainerService"); 1324 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1325 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1326 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1327 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1329 mBound = true; 1330 return true; 1331 } 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 return false; 1334 } 1335 1336 private void disconnectService() { 1337 mContainerService = null; 1338 mBound = false; 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 mContext.unbindService(mDefContainerConn); 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1342 } 1343 1344 PackageHandler(Looper looper) { 1345 super(looper); 1346 } 1347 1348 public void handleMessage(Message msg) { 1349 try { 1350 doHandleMessage(msg); 1351 } finally { 1352 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1353 } 1354 } 1355 1356 void doHandleMessage(Message msg) { 1357 switch (msg.what) { 1358 case INIT_COPY: { 1359 HandlerParams params = (HandlerParams) msg.obj; 1360 int idx = mPendingInstalls.size(); 1361 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1362 // If a bind was already initiated we dont really 1363 // need to do anything. The pending install 1364 // will be processed later on. 1365 if (!mBound) { 1366 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1367 System.identityHashCode(mHandler)); 1368 // If this is the only one pending we might 1369 // have to bind to the service again. 1370 if (!connectToService()) { 1371 Slog.e(TAG, "Failed to bind to media container service"); 1372 params.serviceError(); 1373 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1374 System.identityHashCode(mHandler)); 1375 if (params.traceMethod != null) { 1376 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1377 params.traceCookie); 1378 } 1379 return; 1380 } else { 1381 // Once we bind to the service, the first 1382 // pending request will be processed. 1383 mPendingInstalls.add(idx, params); 1384 } 1385 } else { 1386 mPendingInstalls.add(idx, params); 1387 // Already bound to the service. Just make 1388 // sure we trigger off processing the first request. 1389 if (idx == 0) { 1390 mHandler.sendEmptyMessage(MCS_BOUND); 1391 } 1392 } 1393 break; 1394 } 1395 case MCS_BOUND: { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1397 if (msg.obj != null) { 1398 mContainerService = (IMediaContainerService) msg.obj; 1399 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1400 System.identityHashCode(mHandler)); 1401 } 1402 if (mContainerService == null) { 1403 if (!mBound) { 1404 // Something seriously wrong since we are not bound and we are not 1405 // waiting for connection. Bail out. 1406 Slog.e(TAG, "Cannot bind to media container service"); 1407 for (HandlerParams params : mPendingInstalls) { 1408 // Indicate service bind error 1409 params.serviceError(); 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1411 System.identityHashCode(params)); 1412 if (params.traceMethod != null) { 1413 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1414 params.traceMethod, params.traceCookie); 1415 } 1416 return; 1417 } 1418 mPendingInstalls.clear(); 1419 } else { 1420 Slog.w(TAG, "Waiting to connect to media container service"); 1421 } 1422 } else if (mPendingInstalls.size() > 0) { 1423 HandlerParams params = mPendingInstalls.get(0); 1424 if (params != null) { 1425 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1426 System.identityHashCode(params)); 1427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1428 if (params.startCopy()) { 1429 // We are done... look for more work or to 1430 // go idle. 1431 if (DEBUG_SD_INSTALL) Log.i(TAG, 1432 "Checking for more work or unbind..."); 1433 // Delete pending install 1434 if (mPendingInstalls.size() > 0) { 1435 mPendingInstalls.remove(0); 1436 } 1437 if (mPendingInstalls.size() == 0) { 1438 if (mBound) { 1439 if (DEBUG_SD_INSTALL) Log.i(TAG, 1440 "Posting delayed MCS_UNBIND"); 1441 removeMessages(MCS_UNBIND); 1442 Message ubmsg = obtainMessage(MCS_UNBIND); 1443 // Unbind after a little delay, to avoid 1444 // continual thrashing. 1445 sendMessageDelayed(ubmsg, 10000); 1446 } 1447 } else { 1448 // There are more pending requests in queue. 1449 // Just post MCS_BOUND message to trigger processing 1450 // of next pending install. 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, 1452 "Posting MCS_BOUND for next work"); 1453 mHandler.sendEmptyMessage(MCS_BOUND); 1454 } 1455 } 1456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1457 } 1458 } else { 1459 // Should never happen ideally. 1460 Slog.w(TAG, "Empty queue"); 1461 } 1462 break; 1463 } 1464 case MCS_RECONNECT: { 1465 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1466 if (mPendingInstalls.size() > 0) { 1467 if (mBound) { 1468 disconnectService(); 1469 } 1470 if (!connectToService()) { 1471 Slog.e(TAG, "Failed to bind to media container service"); 1472 for (HandlerParams params : mPendingInstalls) { 1473 // Indicate service bind error 1474 params.serviceError(); 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1476 System.identityHashCode(params)); 1477 } 1478 mPendingInstalls.clear(); 1479 } 1480 } 1481 break; 1482 } 1483 case MCS_UNBIND: { 1484 // If there is no actual work left, then time to unbind. 1485 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1486 1487 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1488 if (mBound) { 1489 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1490 1491 disconnectService(); 1492 } 1493 } else if (mPendingInstalls.size() > 0) { 1494 // There are more pending requests in queue. 1495 // Just post MCS_BOUND message to trigger processing 1496 // of next pending install. 1497 mHandler.sendEmptyMessage(MCS_BOUND); 1498 } 1499 1500 break; 1501 } 1502 case MCS_GIVE_UP: { 1503 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1504 HandlerParams params = mPendingInstalls.remove(0); 1505 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1506 System.identityHashCode(params)); 1507 break; 1508 } 1509 case SEND_PENDING_BROADCAST: { 1510 String packages[]; 1511 ArrayList<String> components[]; 1512 int size = 0; 1513 int uids[]; 1514 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1515 synchronized (mPackages) { 1516 if (mPendingBroadcasts == null) { 1517 return; 1518 } 1519 size = mPendingBroadcasts.size(); 1520 if (size <= 0) { 1521 // Nothing to be done. Just return 1522 return; 1523 } 1524 packages = new String[size]; 1525 components = new ArrayList[size]; 1526 uids = new int[size]; 1527 int i = 0; // filling out the above arrays 1528 1529 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1530 int packageUserId = mPendingBroadcasts.userIdAt(n); 1531 Iterator<Map.Entry<String, ArrayList<String>>> it 1532 = mPendingBroadcasts.packagesForUserId(packageUserId) 1533 .entrySet().iterator(); 1534 while (it.hasNext() && i < size) { 1535 Map.Entry<String, ArrayList<String>> ent = it.next(); 1536 packages[i] = ent.getKey(); 1537 components[i] = ent.getValue(); 1538 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1539 uids[i] = (ps != null) 1540 ? UserHandle.getUid(packageUserId, ps.appId) 1541 : -1; 1542 i++; 1543 } 1544 } 1545 size = i; 1546 mPendingBroadcasts.clear(); 1547 } 1548 // Send broadcasts 1549 for (int i = 0; i < size; i++) { 1550 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1551 } 1552 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1553 break; 1554 } 1555 case START_CLEANING_PACKAGE: { 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1557 final String packageName = (String)msg.obj; 1558 final int userId = msg.arg1; 1559 final boolean andCode = msg.arg2 != 0; 1560 synchronized (mPackages) { 1561 if (userId == UserHandle.USER_ALL) { 1562 int[] users = sUserManager.getUserIds(); 1563 for (int user : users) { 1564 mSettings.addPackageToCleanLPw( 1565 new PackageCleanItem(user, packageName, andCode)); 1566 } 1567 } else { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(userId, packageName, andCode)); 1570 } 1571 } 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1573 startCleaningPackages(); 1574 } break; 1575 case POST_INSTALL: { 1576 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1577 1578 PostInstallData data = mRunningInstalls.get(msg.arg1); 1579 final boolean didRestore = (msg.arg2 != 0); 1580 mRunningInstalls.delete(msg.arg1); 1581 1582 if (data != null) { 1583 InstallArgs args = data.args; 1584 PackageInstalledInfo parentRes = data.res; 1585 1586 final boolean grantPermissions = (args.installFlags 1587 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1588 final boolean killApp = (args.installFlags 1589 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1590 final String[] grantedPermissions = args.installGrantPermissions; 1591 1592 // Handle the parent package 1593 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1594 grantedPermissions, didRestore, args.installerPackageName, 1595 args.observer); 1596 1597 // Handle the child packages 1598 final int childCount = (parentRes.addedChildPackages != null) 1599 ? parentRes.addedChildPackages.size() : 0; 1600 for (int i = 0; i < childCount; i++) { 1601 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1602 handlePackagePostInstall(childRes, grantPermissions, killApp, 1603 grantedPermissions, false, args.installerPackageName, 1604 args.observer); 1605 } 1606 1607 // Log tracing if needed 1608 if (args.traceMethod != null) { 1609 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1610 args.traceCookie); 1611 } 1612 } else { 1613 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1614 } 1615 1616 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1617 } break; 1618 case UPDATED_MEDIA_STATUS: { 1619 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1620 boolean reportStatus = msg.arg1 == 1; 1621 boolean doGc = msg.arg2 == 1; 1622 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1623 if (doGc) { 1624 // Force a gc to clear up stale containers. 1625 Runtime.getRuntime().gc(); 1626 } 1627 if (msg.obj != null) { 1628 @SuppressWarnings("unchecked") 1629 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1630 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1631 // Unload containers 1632 unloadAllContainers(args); 1633 } 1634 if (reportStatus) { 1635 try { 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1637 PackageHelper.getMountService().finishMediaUpdate(); 1638 } catch (RemoteException e) { 1639 Log.e(TAG, "MountService not running?"); 1640 } 1641 } 1642 } break; 1643 case WRITE_SETTINGS: { 1644 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1645 synchronized (mPackages) { 1646 removeMessages(WRITE_SETTINGS); 1647 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1648 mSettings.writeLPr(); 1649 mDirtyUsers.clear(); 1650 } 1651 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1652 } break; 1653 case WRITE_PACKAGE_RESTRICTIONS: { 1654 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1655 synchronized (mPackages) { 1656 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1657 for (int userId : mDirtyUsers) { 1658 mSettings.writePackageRestrictionsLPr(userId); 1659 } 1660 mDirtyUsers.clear(); 1661 } 1662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1663 } break; 1664 case CHECK_PENDING_VERIFICATION: { 1665 final int verificationId = msg.arg1; 1666 final PackageVerificationState state = mPendingVerification.get(verificationId); 1667 1668 if ((state != null) && !state.timeoutExtended()) { 1669 final InstallArgs args = state.getInstallArgs(); 1670 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1671 1672 Slog.i(TAG, "Verification timed out for " + originUri); 1673 mPendingVerification.remove(verificationId); 1674 1675 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1676 1677 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1678 Slog.i(TAG, "Continuing with installation of " + originUri); 1679 state.setVerifierResponse(Binder.getCallingUid(), 1680 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1681 broadcastPackageVerified(verificationId, originUri, 1682 PackageManager.VERIFICATION_ALLOW, 1683 state.getInstallArgs().getUser()); 1684 try { 1685 ret = args.copyApk(mContainerService, true); 1686 } catch (RemoteException e) { 1687 Slog.e(TAG, "Could not contact the ContainerService"); 1688 } 1689 } else { 1690 broadcastPackageVerified(verificationId, originUri, 1691 PackageManager.VERIFICATION_REJECT, 1692 state.getInstallArgs().getUser()); 1693 } 1694 1695 Trace.asyncTraceEnd( 1696 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1697 1698 processPendingInstall(args, ret); 1699 mHandler.sendEmptyMessage(MCS_UNBIND); 1700 } 1701 break; 1702 } 1703 case PACKAGE_VERIFIED: { 1704 final int verificationId = msg.arg1; 1705 1706 final PackageVerificationState state = mPendingVerification.get(verificationId); 1707 if (state == null) { 1708 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1709 break; 1710 } 1711 1712 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1713 1714 state.setVerifierResponse(response.callerUid, response.code); 1715 1716 if (state.isVerificationComplete()) { 1717 mPendingVerification.remove(verificationId); 1718 1719 final InstallArgs args = state.getInstallArgs(); 1720 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1721 1722 int ret; 1723 if (state.isInstallAllowed()) { 1724 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1725 broadcastPackageVerified(verificationId, originUri, 1726 response.code, state.getInstallArgs().getUser()); 1727 try { 1728 ret = args.copyApk(mContainerService, true); 1729 } catch (RemoteException e) { 1730 Slog.e(TAG, "Could not contact the ContainerService"); 1731 } 1732 } else { 1733 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1734 } 1735 1736 Trace.asyncTraceEnd( 1737 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1738 1739 processPendingInstall(args, ret); 1740 mHandler.sendEmptyMessage(MCS_UNBIND); 1741 } 1742 1743 break; 1744 } 1745 case START_INTENT_FILTER_VERIFICATIONS: { 1746 IFVerificationParams params = (IFVerificationParams) msg.obj; 1747 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1748 params.replacing, params.pkg); 1749 break; 1750 } 1751 case INTENT_FILTER_VERIFIED: { 1752 final int verificationId = msg.arg1; 1753 1754 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1755 verificationId); 1756 if (state == null) { 1757 Slog.w(TAG, "Invalid IntentFilter verification token " 1758 + verificationId + " received"); 1759 break; 1760 } 1761 1762 final int userId = state.getUserId(); 1763 1764 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1765 "Processing IntentFilter verification with token:" 1766 + verificationId + " and userId:" + userId); 1767 1768 final IntentFilterVerificationResponse response = 1769 (IntentFilterVerificationResponse) msg.obj; 1770 1771 state.setVerifierResponse(response.callerUid, response.code); 1772 1773 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1774 "IntentFilter verification with token:" + verificationId 1775 + " and userId:" + userId 1776 + " is settings verifier response with response code:" 1777 + response.code); 1778 1779 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1780 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1781 + response.getFailedDomainsString()); 1782 } 1783 1784 if (state.isVerificationComplete()) { 1785 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1786 } else { 1787 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1788 "IntentFilter verification with token:" + verificationId 1789 + " was not said to be complete"); 1790 } 1791 1792 break; 1793 } 1794 } 1795 } 1796 } 1797 1798 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1799 boolean killApp, String[] grantedPermissions, 1800 boolean launchedForRestore, String installerPackage, 1801 IPackageInstallObserver2 installObserver) { 1802 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1803 // Send the removed broadcasts 1804 if (res.removedInfo != null) { 1805 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1806 } 1807 1808 // Now that we successfully installed the package, grant runtime 1809 // permissions if requested before broadcasting the install. 1810 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1811 >= Build.VERSION_CODES.M) { 1812 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1813 } 1814 1815 final boolean update = res.removedInfo != null 1816 && res.removedInfo.removedPackage != null; 1817 1818 // If this is the first time we have child packages for a disabled privileged 1819 // app that had no children, we grant requested runtime permissions to the new 1820 // children if the parent on the system image had them already granted. 1821 if (res.pkg.parentPackage != null) { 1822 synchronized (mPackages) { 1823 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1824 } 1825 } 1826 1827 synchronized (mPackages) { 1828 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1829 } 1830 1831 final String packageName = res.pkg.applicationInfo.packageName; 1832 Bundle extras = new Bundle(1); 1833 extras.putInt(Intent.EXTRA_UID, res.uid); 1834 1835 // Determine the set of users who are adding this package for 1836 // the first time vs. those who are seeing an update. 1837 int[] firstUsers = EMPTY_INT_ARRAY; 1838 int[] updateUsers = EMPTY_INT_ARRAY; 1839 if (res.origUsers == null || res.origUsers.length == 0) { 1840 firstUsers = res.newUsers; 1841 } else { 1842 for (int newUser : res.newUsers) { 1843 boolean isNew = true; 1844 for (int origUser : res.origUsers) { 1845 if (origUser == newUser) { 1846 isNew = false; 1847 break; 1848 } 1849 } 1850 if (isNew) { 1851 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1852 } else { 1853 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1854 } 1855 } 1856 } 1857 1858 // Send installed broadcasts if the install/update is not ephemeral 1859 if (!isEphemeral(res.pkg)) { 1860 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1861 1862 // Send added for users that see the package for the first time 1863 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1864 extras, 0 /*flags*/, null /*targetPackage*/, 1865 null /*finishedReceiver*/, firstUsers); 1866 1867 // Send added for users that don't see the package for the first time 1868 if (update) { 1869 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1870 } 1871 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1872 extras, 0 /*flags*/, null /*targetPackage*/, 1873 null /*finishedReceiver*/, updateUsers); 1874 1875 // Send replaced for users that don't see the package for the first time 1876 if (update) { 1877 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1878 packageName, extras, 0 /*flags*/, 1879 null /*targetPackage*/, null /*finishedReceiver*/, 1880 updateUsers); 1881 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1882 null /*package*/, null /*extras*/, 0 /*flags*/, 1883 packageName /*targetPackage*/, 1884 null /*finishedReceiver*/, updateUsers); 1885 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1886 // First-install and we did a restore, so we're responsible for the 1887 // first-launch broadcast. 1888 if (DEBUG_BACKUP) { 1889 Slog.i(TAG, "Post-restore of " + packageName 1890 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1891 } 1892 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1893 } 1894 1895 // Send broadcast package appeared if forward locked/external for all users 1896 // treat asec-hosted packages like removable media on upgrade 1897 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1898 if (DEBUG_INSTALL) { 1899 Slog.i(TAG, "upgrading pkg " + res.pkg 1900 + " is ASEC-hosted -> AVAILABLE"); 1901 } 1902 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1903 ArrayList<String> pkgList = new ArrayList<>(1); 1904 pkgList.add(packageName); 1905 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1906 } 1907 } 1908 1909 // Work that needs to happen on first install within each user 1910 if (firstUsers != null && firstUsers.length > 0) { 1911 synchronized (mPackages) { 1912 for (int userId : firstUsers) { 1913 // If this app is a browser and it's newly-installed for some 1914 // users, clear any default-browser state in those users. The 1915 // app's nature doesn't depend on the user, so we can just check 1916 // its browser nature in any user and generalize. 1917 if (packageIsBrowser(packageName, userId)) { 1918 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1919 } 1920 1921 // We may also need to apply pending (restored) runtime 1922 // permission grants within these users. 1923 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1924 } 1925 } 1926 } 1927 1928 // Log current value of "unknown sources" setting 1929 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1930 getUnknownSourcesSettings()); 1931 1932 // Force a gc to clear up things 1933 Runtime.getRuntime().gc(); 1934 1935 // Remove the replaced package's older resources safely now 1936 // We delete after a gc for applications on sdcard. 1937 if (res.removedInfo != null && res.removedInfo.args != null) { 1938 synchronized (mInstallLock) { 1939 res.removedInfo.args.doPostDeleteLI(true); 1940 } 1941 } 1942 } 1943 1944 // If someone is watching installs - notify them 1945 if (installObserver != null) { 1946 try { 1947 Bundle extras = extrasForInstallResult(res); 1948 installObserver.onPackageInstalled(res.name, res.returnCode, 1949 res.returnMsg, extras); 1950 } catch (RemoteException e) { 1951 Slog.i(TAG, "Observer no longer exists."); 1952 } 1953 } 1954 } 1955 1956 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1957 PackageParser.Package pkg) { 1958 if (pkg.parentPackage == null) { 1959 return; 1960 } 1961 if (pkg.requestedPermissions == null) { 1962 return; 1963 } 1964 final PackageSetting disabledSysParentPs = mSettings 1965 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1966 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1967 || !disabledSysParentPs.isPrivileged() 1968 || (disabledSysParentPs.childPackageNames != null 1969 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1970 return; 1971 } 1972 final int[] allUserIds = sUserManager.getUserIds(); 1973 final int permCount = pkg.requestedPermissions.size(); 1974 for (int i = 0; i < permCount; i++) { 1975 String permission = pkg.requestedPermissions.get(i); 1976 BasePermission bp = mSettings.mPermissions.get(permission); 1977 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1978 continue; 1979 } 1980 for (int userId : allUserIds) { 1981 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1982 permission, userId)) { 1983 grantRuntimePermission(pkg.packageName, permission, userId); 1984 } 1985 } 1986 } 1987 } 1988 1989 private StorageEventListener mStorageListener = new StorageEventListener() { 1990 @Override 1991 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1992 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1993 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1994 final String volumeUuid = vol.getFsUuid(); 1995 1996 // Clean up any users or apps that were removed or recreated 1997 // while this volume was missing 1998 reconcileUsers(volumeUuid); 1999 reconcileApps(volumeUuid); 2000 2001 // Clean up any install sessions that expired or were 2002 // cancelled while this volume was missing 2003 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2004 2005 loadPrivatePackages(vol); 2006 2007 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2008 unloadPrivatePackages(vol); 2009 } 2010 } 2011 2012 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2013 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2014 updateExternalMediaStatus(true, false); 2015 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2016 updateExternalMediaStatus(false, false); 2017 } 2018 } 2019 } 2020 2021 @Override 2022 public void onVolumeForgotten(String fsUuid) { 2023 if (TextUtils.isEmpty(fsUuid)) { 2024 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2025 return; 2026 } 2027 2028 // Remove any apps installed on the forgotten volume 2029 synchronized (mPackages) { 2030 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2031 for (PackageSetting ps : packages) { 2032 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2033 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2034 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2035 } 2036 2037 mSettings.onVolumeForgotten(fsUuid); 2038 mSettings.writeLPr(); 2039 } 2040 } 2041 }; 2042 2043 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2044 String[] grantedPermissions) { 2045 for (int userId : userIds) { 2046 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2047 } 2048 2049 // We could have touched GID membership, so flush out packages.list 2050 synchronized (mPackages) { 2051 mSettings.writePackageListLPr(); 2052 } 2053 } 2054 2055 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2056 String[] grantedPermissions) { 2057 SettingBase sb = (SettingBase) pkg.mExtras; 2058 if (sb == null) { 2059 return; 2060 } 2061 2062 PermissionsState permissionsState = sb.getPermissionsState(); 2063 2064 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2065 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2066 2067 for (String permission : pkg.requestedPermissions) { 2068 final BasePermission bp; 2069 synchronized (mPackages) { 2070 bp = mSettings.mPermissions.get(permission); 2071 } 2072 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2073 && (grantedPermissions == null 2074 || ArrayUtils.contains(grantedPermissions, permission))) { 2075 final int flags = permissionsState.getPermissionFlags(permission, userId); 2076 // Installer cannot change immutable permissions. 2077 if ((flags & immutableFlags) == 0) { 2078 grantRuntimePermission(pkg.packageName, permission, userId); 2079 } 2080 } 2081 } 2082 } 2083 2084 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2085 Bundle extras = null; 2086 switch (res.returnCode) { 2087 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2088 extras = new Bundle(); 2089 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2090 res.origPermission); 2091 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2092 res.origPackage); 2093 break; 2094 } 2095 case PackageManager.INSTALL_SUCCEEDED: { 2096 extras = new Bundle(); 2097 extras.putBoolean(Intent.EXTRA_REPLACING, 2098 res.removedInfo != null && res.removedInfo.removedPackage != null); 2099 break; 2100 } 2101 } 2102 return extras; 2103 } 2104 2105 void scheduleWriteSettingsLocked() { 2106 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2107 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2108 } 2109 } 2110 2111 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2112 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2113 scheduleWritePackageRestrictionsLocked(userId); 2114 } 2115 2116 void scheduleWritePackageRestrictionsLocked(int userId) { 2117 final int[] userIds = (userId == UserHandle.USER_ALL) 2118 ? sUserManager.getUserIds() : new int[]{userId}; 2119 for (int nextUserId : userIds) { 2120 if (!sUserManager.exists(nextUserId)) return; 2121 mDirtyUsers.add(nextUserId); 2122 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2123 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2124 } 2125 } 2126 } 2127 2128 public static PackageManagerService main(Context context, Installer installer, 2129 boolean factoryTest, boolean onlyCore) { 2130 // Self-check for initial settings. 2131 PackageManagerServiceCompilerMapping.checkProperties(); 2132 2133 PackageManagerService m = new PackageManagerService(context, installer, 2134 factoryTest, onlyCore); 2135 m.enableSystemUserPackages(); 2136 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2137 // disabled after already being started. 2138 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2139 UserHandle.USER_SYSTEM); 2140 ServiceManager.addService("package", m); 2141 return m; 2142 } 2143 2144 private void enableSystemUserPackages() { 2145 if (!UserManager.isSplitSystemUser()) { 2146 return; 2147 } 2148 // For system user, enable apps based on the following conditions: 2149 // - app is whitelisted or belong to one of these groups: 2150 // -- system app which has no launcher icons 2151 // -- system app which has INTERACT_ACROSS_USERS permission 2152 // -- system IME app 2153 // - app is not in the blacklist 2154 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2155 Set<String> enableApps = new ArraySet<>(); 2156 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2157 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2158 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2159 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2160 enableApps.addAll(wlApps); 2161 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2162 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2163 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2164 enableApps.removeAll(blApps); 2165 Log.i(TAG, "Applications installed for system user: " + enableApps); 2166 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2167 UserHandle.SYSTEM); 2168 final int allAppsSize = allAps.size(); 2169 synchronized (mPackages) { 2170 for (int i = 0; i < allAppsSize; i++) { 2171 String pName = allAps.get(i); 2172 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2173 // Should not happen, but we shouldn't be failing if it does 2174 if (pkgSetting == null) { 2175 continue; 2176 } 2177 boolean install = enableApps.contains(pName); 2178 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2179 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2180 + " for system user"); 2181 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2182 } 2183 } 2184 } 2185 } 2186 2187 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2188 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2189 Context.DISPLAY_SERVICE); 2190 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2191 } 2192 2193 public PackageManagerService(Context context, Installer installer, 2194 boolean factoryTest, boolean onlyCore) { 2195 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2196 SystemClock.uptimeMillis()); 2197 2198 if (mSdkVersion <= 0) { 2199 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2200 } 2201 2202 mContext = context; 2203 mFactoryTest = factoryTest; 2204 mOnlyCore = onlyCore; 2205 mMetrics = new DisplayMetrics(); 2206 mSettings = new Settings(mPackages); 2207 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2208 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2209 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2210 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2211 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 2220 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2221 if (separateProcesses != null && separateProcesses.length() > 0) { 2222 if ("*".equals(separateProcesses)) { 2223 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2224 mSeparateProcesses = null; 2225 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2226 } else { 2227 mDefParseFlags = 0; 2228 mSeparateProcesses = separateProcesses.split(","); 2229 Slog.w(TAG, "Running with debug.separate_processes: " 2230 + separateProcesses); 2231 } 2232 } else { 2233 mDefParseFlags = 0; 2234 mSeparateProcesses = null; 2235 } 2236 2237 mInstaller = installer; 2238 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2239 "*dexopt*"); 2240 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2241 2242 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2243 FgThread.get().getLooper()); 2244 2245 getDefaultDisplayMetrics(context, mMetrics); 2246 2247 SystemConfig systemConfig = SystemConfig.getInstance(); 2248 mGlobalGids = systemConfig.getGlobalGids(); 2249 mSystemPermissions = systemConfig.getSystemPermissions(); 2250 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2251 2252 synchronized (mInstallLock) { 2253 // writer 2254 synchronized (mPackages) { 2255 mHandlerThread = new ServiceThread(TAG, 2256 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2257 mHandlerThread.start(); 2258 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2259 mProcessLoggingHandler = new ProcessLoggingHandler(); 2260 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2261 2262 File dataDir = Environment.getDataDirectory(); 2263 mAppInstallDir = new File(dataDir, "app"); 2264 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2265 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2266 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2267 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2268 2269 sUserManager = new UserManagerService(context, this, mPackages); 2270 2271 // Propagate permission configuration in to package manager. 2272 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2273 = systemConfig.getPermissions(); 2274 for (int i=0; i<permConfig.size(); i++) { 2275 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2276 BasePermission bp = mSettings.mPermissions.get(perm.name); 2277 if (bp == null) { 2278 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2279 mSettings.mPermissions.put(perm.name, bp); 2280 } 2281 if (perm.gids != null) { 2282 bp.setGids(perm.gids, perm.perUser); 2283 } 2284 } 2285 2286 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2287 for (int i=0; i<libConfig.size(); i++) { 2288 mSharedLibraries.put(libConfig.keyAt(i), 2289 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2290 } 2291 2292 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2293 2294 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2295 2296 String customResolverActivity = Resources.getSystem().getString( 2297 R.string.config_customResolverActivity); 2298 if (TextUtils.isEmpty(customResolverActivity)) { 2299 customResolverActivity = null; 2300 } else { 2301 mCustomResolverComponentName = ComponentName.unflattenFromString( 2302 customResolverActivity); 2303 } 2304 2305 long startTime = SystemClock.uptimeMillis(); 2306 2307 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2308 startTime); 2309 2310 // Set flag to monitor and not change apk file paths when 2311 // scanning install directories. 2312 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2313 2314 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2315 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2316 2317 if (bootClassPath == null) { 2318 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2319 } 2320 2321 if (systemServerClassPath == null) { 2322 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2323 } 2324 2325 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2326 final String[] dexCodeInstructionSets = 2327 getDexCodeInstructionSets( 2328 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2329 2330 /** 2331 * Ensure all external libraries have had dexopt run on them. 2332 */ 2333 if (mSharedLibraries.size() > 0) { 2334 // NOTE: For now, we're compiling these system "shared libraries" 2335 // (and framework jars) into all available architectures. It's possible 2336 // to compile them only when we come across an app that uses them (there's 2337 // already logic for that in scanPackageLI) but that adds some complexity. 2338 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2339 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2340 final String lib = libEntry.path; 2341 if (lib == null) { 2342 continue; 2343 } 2344 2345 try { 2346 // Shared libraries do not have profiles so we perform a full 2347 // AOT compilation (if needed). 2348 int dexoptNeeded = DexFile.getDexOptNeeded( 2349 lib, dexCodeInstructionSet, 2350 getCompilerFilterForReason(REASON_SHARED_APK), 2351 false /* newProfile */); 2352 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2353 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2354 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2355 getCompilerFilterForReason(REASON_SHARED_APK), 2356 StorageManager.UUID_PRIVATE_INTERNAL, 2357 SKIP_SHARED_LIBRARY_CHECK); 2358 } 2359 } catch (FileNotFoundException e) { 2360 Slog.w(TAG, "Library not found: " + lib); 2361 } catch (IOException | InstallerException e) { 2362 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2363 + e.getMessage()); 2364 } 2365 } 2366 } 2367 } 2368 2369 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2370 2371 final VersionInfo ver = mSettings.getInternalVersion(); 2372 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2373 2374 // when upgrading from pre-M, promote system app permissions from install to runtime 2375 mPromoteSystemApps = 2376 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2377 2378 // save off the names of pre-existing system packages prior to scanning; we don't 2379 // want to automatically grant runtime permissions for new system apps 2380 if (mPromoteSystemApps) { 2381 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2382 while (pkgSettingIter.hasNext()) { 2383 PackageSetting ps = pkgSettingIter.next(); 2384 if (isSystemApp(ps)) { 2385 mExistingSystemPackages.add(ps.name); 2386 } 2387 } 2388 } 2389 2390 // When upgrading from pre-N, we need to handle package extraction like first boot, 2391 // as there is no profiling data available. 2392 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2393 mSettings.setNWorkDone(); 2394 2395 // Collect vendor overlay packages. 2396 // (Do this before scanning any apps.) 2397 // For security and version matching reason, only consider 2398 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2399 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2400 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2401 | PackageParser.PARSE_IS_SYSTEM 2402 | PackageParser.PARSE_IS_SYSTEM_DIR 2403 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2404 2405 // Find base frameworks (resource packages without code). 2406 scanDirTracedLI(frameworkDir, mDefParseFlags 2407 | PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR 2409 | PackageParser.PARSE_IS_PRIVILEGED, 2410 scanFlags | SCAN_NO_DEX, 0); 2411 2412 // Collected privileged system packages. 2413 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2414 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2415 | PackageParser.PARSE_IS_SYSTEM 2416 | PackageParser.PARSE_IS_SYSTEM_DIR 2417 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2418 2419 // Collect ordinary system packages. 2420 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2421 scanDirTracedLI(systemAppDir, mDefParseFlags 2422 | PackageParser.PARSE_IS_SYSTEM 2423 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2424 2425 // Collect all vendor packages. 2426 File vendorAppDir = new File("/vendor/app"); 2427 try { 2428 vendorAppDir = vendorAppDir.getCanonicalFile(); 2429 } catch (IOException e) { 2430 // failed to look up canonical path, continue with original one 2431 } 2432 scanDirTracedLI(vendorAppDir, mDefParseFlags 2433 | PackageParser.PARSE_IS_SYSTEM 2434 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2435 2436 // Collect all OEM packages. 2437 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2438 scanDirTracedLI(oemAppDir, mDefParseFlags 2439 | PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2441 2442 // Prune any system packages that no longer exist. 2443 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2444 if (!mOnlyCore) { 2445 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2446 while (psit.hasNext()) { 2447 PackageSetting ps = psit.next(); 2448 2449 /* 2450 * If this is not a system app, it can't be a 2451 * disable system app. 2452 */ 2453 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2454 continue; 2455 } 2456 2457 /* 2458 * If the package is scanned, it's not erased. 2459 */ 2460 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2461 if (scannedPkg != null) { 2462 /* 2463 * If the system app is both scanned and in the 2464 * disabled packages list, then it must have been 2465 * added via OTA. Remove it from the currently 2466 * scanned package so the previously user-installed 2467 * application can be scanned. 2468 */ 2469 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2470 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2471 + ps.name + "; removing system app. Last known codePath=" 2472 + ps.codePathString + ", installStatus=" + ps.installStatus 2473 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2474 + scannedPkg.mVersionCode); 2475 removePackageLI(scannedPkg, true); 2476 mExpectingBetter.put(ps.name, ps.codePath); 2477 } 2478 2479 continue; 2480 } 2481 2482 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2483 psit.remove(); 2484 logCriticalInfo(Log.WARN, "System package " + ps.name 2485 + " no longer exists; it's data will be wiped"); 2486 // Actual deletion of code and data will be handled by later 2487 // reconciliation step 2488 } else { 2489 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2490 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2491 possiblyDeletedUpdatedSystemApps.add(ps.name); 2492 } 2493 } 2494 } 2495 } 2496 2497 //look for any incomplete package installations 2498 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2499 for (int i = 0; i < deletePkgsList.size(); i++) { 2500 // Actual deletion of code and data will be handled by later 2501 // reconciliation step 2502 final String packageName = deletePkgsList.get(i).name; 2503 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2504 synchronized (mPackages) { 2505 mSettings.removePackageLPw(packageName); 2506 } 2507 } 2508 2509 //delete tmp files 2510 deleteTempPackageFiles(); 2511 2512 // Remove any shared userIDs that have no associated packages 2513 mSettings.pruneSharedUsersLPw(); 2514 2515 if (!mOnlyCore) { 2516 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2517 SystemClock.uptimeMillis()); 2518 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2519 2520 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2521 | PackageParser.PARSE_FORWARD_LOCK, 2522 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2523 2524 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2525 | PackageParser.PARSE_IS_EPHEMERAL, 2526 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2527 2528 /** 2529 * Remove disable package settings for any updated system 2530 * apps that were removed via an OTA. If they're not a 2531 * previously-updated app, remove them completely. 2532 * Otherwise, just revoke their system-level permissions. 2533 */ 2534 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2535 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2536 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2537 2538 String msg; 2539 if (deletedPkg == null) { 2540 msg = "Updated system package " + deletedAppName 2541 + " no longer exists; it's data will be wiped"; 2542 // Actual deletion of code and data will be handled by later 2543 // reconciliation step 2544 } else { 2545 msg = "Updated system app + " + deletedAppName 2546 + " no longer present; removing system privileges for " 2547 + deletedAppName; 2548 2549 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2550 2551 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2552 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2553 } 2554 logCriticalInfo(Log.WARN, msg); 2555 } 2556 2557 /** 2558 * Make sure all system apps that we expected to appear on 2559 * the userdata partition actually showed up. If they never 2560 * appeared, crawl back and revive the system version. 2561 */ 2562 for (int i = 0; i < mExpectingBetter.size(); i++) { 2563 final String packageName = mExpectingBetter.keyAt(i); 2564 if (!mPackages.containsKey(packageName)) { 2565 final File scanFile = mExpectingBetter.valueAt(i); 2566 2567 logCriticalInfo(Log.WARN, "Expected better " + packageName 2568 + " but never showed up; reverting to system"); 2569 2570 int reparseFlags = mDefParseFlags; 2571 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2572 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2573 | PackageParser.PARSE_IS_SYSTEM_DIR 2574 | PackageParser.PARSE_IS_PRIVILEGED; 2575 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2576 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2577 | PackageParser.PARSE_IS_SYSTEM_DIR; 2578 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2579 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2580 | PackageParser.PARSE_IS_SYSTEM_DIR; 2581 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2582 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2583 | PackageParser.PARSE_IS_SYSTEM_DIR; 2584 } else { 2585 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2586 continue; 2587 } 2588 2589 mSettings.enableSystemPackageLPw(packageName); 2590 2591 try { 2592 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2593 } catch (PackageManagerException e) { 2594 Slog.e(TAG, "Failed to parse original system package: " 2595 + e.getMessage()); 2596 } 2597 } 2598 } 2599 } 2600 mExpectingBetter.clear(); 2601 2602 // Resolve protected action filters. Only the setup wizard is allowed to 2603 // have a high priority filter for these actions. 2604 mSetupWizardPackage = getSetupWizardPackageName(); 2605 if (mProtectedFilters.size() > 0) { 2606 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2607 Slog.i(TAG, "No setup wizard;" 2608 + " All protected intents capped to priority 0"); 2609 } 2610 for (ActivityIntentInfo filter : mProtectedFilters) { 2611 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2612 if (DEBUG_FILTERS) { 2613 Slog.i(TAG, "Found setup wizard;" 2614 + " allow priority " + filter.getPriority() + ";" 2615 + " package: " + filter.activity.info.packageName 2616 + " activity: " + filter.activity.className 2617 + " priority: " + filter.getPriority()); 2618 } 2619 // skip setup wizard; allow it to keep the high priority filter 2620 continue; 2621 } 2622 Slog.w(TAG, "Protected action; cap priority to 0;" 2623 + " package: " + filter.activity.info.packageName 2624 + " activity: " + filter.activity.className 2625 + " origPrio: " + filter.getPriority()); 2626 filter.setPriority(0); 2627 } 2628 } 2629 mDeferProtectedFilters = false; 2630 mProtectedFilters.clear(); 2631 2632 // Now that we know all of the shared libraries, update all clients to have 2633 // the correct library paths. 2634 updateAllSharedLibrariesLPw(); 2635 2636 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2637 // NOTE: We ignore potential failures here during a system scan (like 2638 // the rest of the commands above) because there's precious little we 2639 // can do about it. A settings error is reported, though. 2640 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2641 false /* boot complete */); 2642 } 2643 2644 // Now that we know all the packages we are keeping, 2645 // read and update their last usage times. 2646 mPackageUsage.readLP(); 2647 2648 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2649 SystemClock.uptimeMillis()); 2650 Slog.i(TAG, "Time to scan packages: " 2651 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2652 + " seconds"); 2653 2654 // If the platform SDK has changed since the last time we booted, 2655 // we need to re-grant app permission to catch any new ones that 2656 // appear. This is really a hack, and means that apps can in some 2657 // cases get permissions that the user didn't initially explicitly 2658 // allow... it would be nice to have some better way to handle 2659 // this situation. 2660 int updateFlags = UPDATE_PERMISSIONS_ALL; 2661 if (ver.sdkVersion != mSdkVersion) { 2662 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2663 + mSdkVersion + "; regranting permissions for internal storage"); 2664 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2665 } 2666 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2667 ver.sdkVersion = mSdkVersion; 2668 2669 // If this is the first boot or an update from pre-M, and it is a normal 2670 // boot, then we need to initialize the default preferred apps across 2671 // all defined users. 2672 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2673 for (UserInfo user : sUserManager.getUsers(true)) { 2674 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2675 applyFactoryDefaultBrowserLPw(user.id); 2676 primeDomainVerificationsLPw(user.id); 2677 } 2678 } 2679 2680 // Prepare storage for system user really early during boot, 2681 // since core system apps like SettingsProvider and SystemUI 2682 // can't wait for user to start 2683 final int storageFlags; 2684 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2685 storageFlags = StorageManager.FLAG_STORAGE_DE; 2686 } else { 2687 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2688 } 2689 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2690 storageFlags); 2691 2692 // If this is first boot after an OTA, and a normal boot, then 2693 // we need to clear code cache directories. 2694 if (mIsUpgrade && !onlyCore) { 2695 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2696 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2697 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2698 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2699 // No apps are running this early, so no need to freeze 2700 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2701 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2702 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2703 } 2704 clearAppProfilesLIF(ps.pkg); 2705 } 2706 ver.fingerprint = Build.FINGERPRINT; 2707 } 2708 2709 checkDefaultBrowser(); 2710 2711 // clear only after permissions and other defaults have been updated 2712 mExistingSystemPackages.clear(); 2713 mPromoteSystemApps = false; 2714 2715 // All the changes are done during package scanning. 2716 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2717 2718 // can downgrade to reader 2719 mSettings.writeLPr(); 2720 2721 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2722 SystemClock.uptimeMillis()); 2723 2724 if (!mOnlyCore) { 2725 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2726 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2727 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2728 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2729 mIntentFilterVerifierComponent); 2730 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2731 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2732 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2733 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2734 } else { 2735 mRequiredVerifierPackage = null; 2736 mRequiredInstallerPackage = null; 2737 mIntentFilterVerifierComponent = null; 2738 mIntentFilterVerifier = null; 2739 mServicesSystemSharedLibraryPackageName = null; 2740 mSharedSystemSharedLibraryPackageName = null; 2741 } 2742 2743 mInstallerService = new PackageInstallerService(context, this); 2744 2745 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2746 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2747 // both the installer and resolver must be present to enable ephemeral 2748 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2749 if (DEBUG_EPHEMERAL) { 2750 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2751 + " installer:" + ephemeralInstallerComponent); 2752 } 2753 mEphemeralResolverComponent = ephemeralResolverComponent; 2754 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2755 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2756 mEphemeralResolverConnection = 2757 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2758 } else { 2759 if (DEBUG_EPHEMERAL) { 2760 final String missingComponent = 2761 (ephemeralResolverComponent == null) 2762 ? (ephemeralInstallerComponent == null) 2763 ? "resolver and installer" 2764 : "resolver" 2765 : "installer"; 2766 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2767 } 2768 mEphemeralResolverComponent = null; 2769 mEphemeralInstallerComponent = null; 2770 mEphemeralResolverConnection = null; 2771 } 2772 2773 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2774 } // synchronized (mPackages) 2775 } // synchronized (mInstallLock) 2776 2777 // Now after opening every single application zip, make sure they 2778 // are all flushed. Not really needed, but keeps things nice and 2779 // tidy. 2780 Runtime.getRuntime().gc(); 2781 2782 // The initial scanning above does many calls into installd while 2783 // holding the mPackages lock, but we're mostly interested in yelling 2784 // once we have a booted system. 2785 mInstaller.setWarnIfHeld(mPackages); 2786 2787 // Expose private service for system components to use. 2788 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2789 } 2790 2791 @Override 2792 public boolean isFirstBoot() { 2793 return !mRestoredSettings; 2794 } 2795 2796 @Override 2797 public boolean isOnlyCoreApps() { 2798 return mOnlyCore; 2799 } 2800 2801 @Override 2802 public boolean isUpgrade() { 2803 return mIsUpgrade; 2804 } 2805 2806 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2807 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2808 2809 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2810 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2811 UserHandle.USER_SYSTEM); 2812 if (matches.size() == 1) { 2813 return matches.get(0).getComponentInfo().packageName; 2814 } else { 2815 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2816 return null; 2817 } 2818 } 2819 2820 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2821 synchronized (mPackages) { 2822 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2823 if (libraryEntry == null) { 2824 throw new IllegalStateException("Missing required shared library:" + libraryName); 2825 } 2826 return libraryEntry.apk; 2827 } 2828 } 2829 2830 private @NonNull String getRequiredInstallerLPr() { 2831 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2832 intent.addCategory(Intent.CATEGORY_DEFAULT); 2833 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2834 2835 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2836 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2837 UserHandle.USER_SYSTEM); 2838 if (matches.size() == 1) { 2839 ResolveInfo resolveInfo = matches.get(0); 2840 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2841 throw new RuntimeException("The installer must be a privileged app"); 2842 } 2843 return matches.get(0).getComponentInfo().packageName; 2844 } else { 2845 throw new RuntimeException("There must be exactly one installer; found " + matches); 2846 } 2847 } 2848 2849 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2850 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2851 2852 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2853 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2854 UserHandle.USER_SYSTEM); 2855 ResolveInfo best = null; 2856 final int N = matches.size(); 2857 for (int i = 0; i < N; i++) { 2858 final ResolveInfo cur = matches.get(i); 2859 final String packageName = cur.getComponentInfo().packageName; 2860 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2861 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2862 continue; 2863 } 2864 2865 if (best == null || cur.priority > best.priority) { 2866 best = cur; 2867 } 2868 } 2869 2870 if (best != null) { 2871 return best.getComponentInfo().getComponentName(); 2872 } else { 2873 throw new RuntimeException("There must be at least one intent filter verifier"); 2874 } 2875 } 2876 2877 private @Nullable ComponentName getEphemeralResolverLPr() { 2878 final String[] packageArray = 2879 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2880 if (packageArray.length == 0) { 2881 if (DEBUG_EPHEMERAL) { 2882 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2883 } 2884 return null; 2885 } 2886 2887 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2888 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2889 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2890 UserHandle.USER_SYSTEM); 2891 2892 final int N = resolvers.size(); 2893 if (N == 0) { 2894 if (DEBUG_EPHEMERAL) { 2895 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2896 } 2897 return null; 2898 } 2899 2900 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2901 for (int i = 0; i < N; i++) { 2902 final ResolveInfo info = resolvers.get(i); 2903 2904 if (info.serviceInfo == null) { 2905 continue; 2906 } 2907 2908 final String packageName = info.serviceInfo.packageName; 2909 if (!possiblePackages.contains(packageName)) { 2910 if (DEBUG_EPHEMERAL) { 2911 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2912 + " pkg: " + packageName + ", info:" + info); 2913 } 2914 continue; 2915 } 2916 2917 if (DEBUG_EPHEMERAL) { 2918 Slog.v(TAG, "Ephemeral resolver found;" 2919 + " pkg: " + packageName + ", info:" + info); 2920 } 2921 return new ComponentName(packageName, info.serviceInfo.name); 2922 } 2923 if (DEBUG_EPHEMERAL) { 2924 Slog.v(TAG, "Ephemeral resolver NOT found"); 2925 } 2926 return null; 2927 } 2928 2929 private @Nullable ComponentName getEphemeralInstallerLPr() { 2930 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2931 intent.addCategory(Intent.CATEGORY_DEFAULT); 2932 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2933 2934 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2935 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2936 UserHandle.USER_SYSTEM); 2937 if (matches.size() == 0) { 2938 return null; 2939 } else if (matches.size() == 1) { 2940 return matches.get(0).getComponentInfo().getComponentName(); 2941 } else { 2942 throw new RuntimeException( 2943 "There must be at most one ephemeral installer; found " + matches); 2944 } 2945 } 2946 2947 private void primeDomainVerificationsLPw(int userId) { 2948 if (DEBUG_DOMAIN_VERIFICATION) { 2949 Slog.d(TAG, "Priming domain verifications in user " + userId); 2950 } 2951 2952 SystemConfig systemConfig = SystemConfig.getInstance(); 2953 ArraySet<String> packages = systemConfig.getLinkedApps(); 2954 ArraySet<String> domains = new ArraySet<String>(); 2955 2956 for (String packageName : packages) { 2957 PackageParser.Package pkg = mPackages.get(packageName); 2958 if (pkg != null) { 2959 if (!pkg.isSystemApp()) { 2960 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2961 continue; 2962 } 2963 2964 domains.clear(); 2965 for (PackageParser.Activity a : pkg.activities) { 2966 for (ActivityIntentInfo filter : a.intents) { 2967 if (hasValidDomains(filter)) { 2968 domains.addAll(filter.getHostsList()); 2969 } 2970 } 2971 } 2972 2973 if (domains.size() > 0) { 2974 if (DEBUG_DOMAIN_VERIFICATION) { 2975 Slog.v(TAG, " + " + packageName); 2976 } 2977 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2978 // state w.r.t. the formal app-linkage "no verification attempted" state; 2979 // and then 'always' in the per-user state actually used for intent resolution. 2980 final IntentFilterVerificationInfo ivi; 2981 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2982 new ArrayList<String>(domains)); 2983 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2984 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2985 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2986 } else { 2987 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2988 + "' does not handle web links"); 2989 } 2990 } else { 2991 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2992 } 2993 } 2994 2995 scheduleWritePackageRestrictionsLocked(userId); 2996 scheduleWriteSettingsLocked(); 2997 } 2998 2999 private void applyFactoryDefaultBrowserLPw(int userId) { 3000 // The default browser app's package name is stored in a string resource, 3001 // with a product-specific overlay used for vendor customization. 3002 String browserPkg = mContext.getResources().getString( 3003 com.android.internal.R.string.default_browser); 3004 if (!TextUtils.isEmpty(browserPkg)) { 3005 // non-empty string => required to be a known package 3006 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3007 if (ps == null) { 3008 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3009 browserPkg = null; 3010 } else { 3011 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3012 } 3013 } 3014 3015 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3016 // default. If there's more than one, just leave everything alone. 3017 if (browserPkg == null) { 3018 calculateDefaultBrowserLPw(userId); 3019 } 3020 } 3021 3022 private void calculateDefaultBrowserLPw(int userId) { 3023 List<String> allBrowsers = resolveAllBrowserApps(userId); 3024 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3025 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3026 } 3027 3028 private List<String> resolveAllBrowserApps(int userId) { 3029 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3030 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3031 PackageManager.MATCH_ALL, userId); 3032 3033 final int count = list.size(); 3034 List<String> result = new ArrayList<String>(count); 3035 for (int i=0; i<count; i++) { 3036 ResolveInfo info = list.get(i); 3037 if (info.activityInfo == null 3038 || !info.handleAllWebDataURI 3039 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3040 || result.contains(info.activityInfo.packageName)) { 3041 continue; 3042 } 3043 result.add(info.activityInfo.packageName); 3044 } 3045 3046 return result; 3047 } 3048 3049 private boolean packageIsBrowser(String packageName, int userId) { 3050 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3051 PackageManager.MATCH_ALL, userId); 3052 final int N = list.size(); 3053 for (int i = 0; i < N; i++) { 3054 ResolveInfo info = list.get(i); 3055 if (packageName.equals(info.activityInfo.packageName)) { 3056 return true; 3057 } 3058 } 3059 return false; 3060 } 3061 3062 private void checkDefaultBrowser() { 3063 final int myUserId = UserHandle.myUserId(); 3064 final String packageName = getDefaultBrowserPackageName(myUserId); 3065 if (packageName != null) { 3066 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3067 if (info == null) { 3068 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3069 synchronized (mPackages) { 3070 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3071 } 3072 } 3073 } 3074 } 3075 3076 @Override 3077 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3078 throws RemoteException { 3079 try { 3080 return super.onTransact(code, data, reply, flags); 3081 } catch (RuntimeException e) { 3082 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3083 Slog.wtf(TAG, "Package Manager Crash", e); 3084 } 3085 throw e; 3086 } 3087 } 3088 3089 static int[] appendInts(int[] cur, int[] add) { 3090 if (add == null) return cur; 3091 if (cur == null) return add; 3092 final int N = add.length; 3093 for (int i=0; i<N; i++) { 3094 cur = appendInt(cur, add[i]); 3095 } 3096 return cur; 3097 } 3098 3099 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3100 if (!sUserManager.exists(userId)) return null; 3101 if (ps == null) { 3102 return null; 3103 } 3104 final PackageParser.Package p = ps.pkg; 3105 if (p == null) { 3106 return null; 3107 } 3108 3109 final PermissionsState permissionsState = ps.getPermissionsState(); 3110 3111 final int[] gids = permissionsState.computeGids(userId); 3112 final Set<String> permissions = permissionsState.getPermissions(userId); 3113 final PackageUserState state = ps.readUserState(userId); 3114 3115 return PackageParser.generatePackageInfo(p, gids, flags, 3116 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3117 } 3118 3119 @Override 3120 public void checkPackageStartable(String packageName, int userId) { 3121 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3122 3123 synchronized (mPackages) { 3124 final PackageSetting ps = mSettings.mPackages.get(packageName); 3125 if (ps == null) { 3126 throw new SecurityException("Package " + packageName + " was not found!"); 3127 } 3128 3129 if (!ps.getInstalled(userId)) { 3130 throw new SecurityException( 3131 "Package " + packageName + " was not installed for user " + userId + "!"); 3132 } 3133 3134 if (mSafeMode && !ps.isSystem()) { 3135 throw new SecurityException("Package " + packageName + " not a system app!"); 3136 } 3137 3138 if (mFrozenPackages.contains(packageName)) { 3139 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3140 } 3141 3142 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3143 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3144 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3145 } 3146 } 3147 } 3148 3149 @Override 3150 public boolean isPackageAvailable(String packageName, int userId) { 3151 if (!sUserManager.exists(userId)) return false; 3152 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3153 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3154 synchronized (mPackages) { 3155 PackageParser.Package p = mPackages.get(packageName); 3156 if (p != null) { 3157 final PackageSetting ps = (PackageSetting) p.mExtras; 3158 if (ps != null) { 3159 final PackageUserState state = ps.readUserState(userId); 3160 if (state != null) { 3161 return PackageParser.isAvailable(state); 3162 } 3163 } 3164 } 3165 } 3166 return false; 3167 } 3168 3169 @Override 3170 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3171 if (!sUserManager.exists(userId)) return null; 3172 flags = updateFlagsForPackage(flags, userId, packageName); 3173 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3174 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3175 // reader 3176 synchronized (mPackages) { 3177 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3178 PackageParser.Package p = null; 3179 if (matchFactoryOnly) { 3180 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3181 if (ps != null) { 3182 return generatePackageInfo(ps, flags, userId); 3183 } 3184 } 3185 if (p == null) { 3186 p = mPackages.get(packageName); 3187 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3188 return null; 3189 } 3190 } 3191 if (DEBUG_PACKAGE_INFO) 3192 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3193 if (p != null) { 3194 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3195 } 3196 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3197 final PackageSetting ps = mSettings.mPackages.get(packageName); 3198 return generatePackageInfo(ps, flags, userId); 3199 } 3200 } 3201 return null; 3202 } 3203 3204 @Override 3205 public String[] currentToCanonicalPackageNames(String[] names) { 3206 String[] out = new String[names.length]; 3207 // reader 3208 synchronized (mPackages) { 3209 for (int i=names.length-1; i>=0; i--) { 3210 PackageSetting ps = mSettings.mPackages.get(names[i]); 3211 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3212 } 3213 } 3214 return out; 3215 } 3216 3217 @Override 3218 public String[] canonicalToCurrentPackageNames(String[] names) { 3219 String[] out = new String[names.length]; 3220 // reader 3221 synchronized (mPackages) { 3222 for (int i=names.length-1; i>=0; i--) { 3223 String cur = mSettings.mRenamedPackages.get(names[i]); 3224 out[i] = cur != null ? cur : names[i]; 3225 } 3226 } 3227 return out; 3228 } 3229 3230 @Override 3231 public int getPackageUid(String packageName, int flags, int userId) { 3232 if (!sUserManager.exists(userId)) return -1; 3233 flags = updateFlagsForPackage(flags, userId, packageName); 3234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3235 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3236 3237 // reader 3238 synchronized (mPackages) { 3239 final PackageParser.Package p = mPackages.get(packageName); 3240 if (p != null && p.isMatch(flags)) { 3241 return UserHandle.getUid(userId, p.applicationInfo.uid); 3242 } 3243 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3244 final PackageSetting ps = mSettings.mPackages.get(packageName); 3245 if (ps != null && ps.isMatch(flags)) { 3246 return UserHandle.getUid(userId, ps.appId); 3247 } 3248 } 3249 } 3250 3251 return -1; 3252 } 3253 3254 @Override 3255 public int[] getPackageGids(String packageName, int flags, int userId) { 3256 if (!sUserManager.exists(userId)) return null; 3257 flags = updateFlagsForPackage(flags, userId, packageName); 3258 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3259 false /* requireFullPermission */, false /* checkShell */, 3260 "getPackageGids"); 3261 3262 // reader 3263 synchronized (mPackages) { 3264 final PackageParser.Package p = mPackages.get(packageName); 3265 if (p != null && p.isMatch(flags)) { 3266 PackageSetting ps = (PackageSetting) p.mExtras; 3267 return ps.getPermissionsState().computeGids(userId); 3268 } 3269 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3270 final PackageSetting ps = mSettings.mPackages.get(packageName); 3271 if (ps != null && ps.isMatch(flags)) { 3272 return ps.getPermissionsState().computeGids(userId); 3273 } 3274 } 3275 } 3276 3277 return null; 3278 } 3279 3280 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3281 if (bp.perm != null) { 3282 return PackageParser.generatePermissionInfo(bp.perm, flags); 3283 } 3284 PermissionInfo pi = new PermissionInfo(); 3285 pi.name = bp.name; 3286 pi.packageName = bp.sourcePackage; 3287 pi.nonLocalizedLabel = bp.name; 3288 pi.protectionLevel = bp.protectionLevel; 3289 return pi; 3290 } 3291 3292 @Override 3293 public PermissionInfo getPermissionInfo(String name, int flags) { 3294 // reader 3295 synchronized (mPackages) { 3296 final BasePermission p = mSettings.mPermissions.get(name); 3297 if (p != null) { 3298 return generatePermissionInfo(p, flags); 3299 } 3300 return null; 3301 } 3302 } 3303 3304 @Override 3305 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3306 int flags) { 3307 // reader 3308 synchronized (mPackages) { 3309 if (group != null && !mPermissionGroups.containsKey(group)) { 3310 // This is thrown as NameNotFoundException 3311 return null; 3312 } 3313 3314 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3315 for (BasePermission p : mSettings.mPermissions.values()) { 3316 if (group == null) { 3317 if (p.perm == null || p.perm.info.group == null) { 3318 out.add(generatePermissionInfo(p, flags)); 3319 } 3320 } else { 3321 if (p.perm != null && group.equals(p.perm.info.group)) { 3322 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3323 } 3324 } 3325 } 3326 return new ParceledListSlice<>(out); 3327 } 3328 } 3329 3330 @Override 3331 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3332 // reader 3333 synchronized (mPackages) { 3334 return PackageParser.generatePermissionGroupInfo( 3335 mPermissionGroups.get(name), flags); 3336 } 3337 } 3338 3339 @Override 3340 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3341 // reader 3342 synchronized (mPackages) { 3343 final int N = mPermissionGroups.size(); 3344 ArrayList<PermissionGroupInfo> out 3345 = new ArrayList<PermissionGroupInfo>(N); 3346 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3347 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3348 } 3349 return new ParceledListSlice<>(out); 3350 } 3351 } 3352 3353 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3354 int userId) { 3355 if (!sUserManager.exists(userId)) return null; 3356 PackageSetting ps = mSettings.mPackages.get(packageName); 3357 if (ps != null) { 3358 if (ps.pkg == null) { 3359 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3360 if (pInfo != null) { 3361 return pInfo.applicationInfo; 3362 } 3363 return null; 3364 } 3365 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3366 ps.readUserState(userId), userId); 3367 } 3368 return null; 3369 } 3370 3371 @Override 3372 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3373 if (!sUserManager.exists(userId)) return null; 3374 flags = updateFlagsForApplication(flags, userId, packageName); 3375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3376 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3377 // writer 3378 synchronized (mPackages) { 3379 PackageParser.Package p = mPackages.get(packageName); 3380 if (DEBUG_PACKAGE_INFO) Log.v( 3381 TAG, "getApplicationInfo " + packageName 3382 + ": " + p); 3383 if (p != null) { 3384 PackageSetting ps = mSettings.mPackages.get(packageName); 3385 if (ps == null) return null; 3386 // Note: isEnabledLP() does not apply here - always return info 3387 return PackageParser.generateApplicationInfo( 3388 p, flags, ps.readUserState(userId), userId); 3389 } 3390 if ("android".equals(packageName)||"system".equals(packageName)) { 3391 return mAndroidApplication; 3392 } 3393 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3394 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3395 } 3396 } 3397 return null; 3398 } 3399 3400 @Override 3401 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3402 final IPackageDataObserver observer) { 3403 mContext.enforceCallingOrSelfPermission( 3404 android.Manifest.permission.CLEAR_APP_CACHE, null); 3405 // Queue up an async operation since clearing cache may take a little while. 3406 mHandler.post(new Runnable() { 3407 public void run() { 3408 mHandler.removeCallbacks(this); 3409 boolean success = true; 3410 synchronized (mInstallLock) { 3411 try { 3412 mInstaller.freeCache(volumeUuid, freeStorageSize); 3413 } catch (InstallerException e) { 3414 Slog.w(TAG, "Couldn't clear application caches: " + e); 3415 success = false; 3416 } 3417 } 3418 if (observer != null) { 3419 try { 3420 observer.onRemoveCompleted(null, success); 3421 } catch (RemoteException e) { 3422 Slog.w(TAG, "RemoveException when invoking call back"); 3423 } 3424 } 3425 } 3426 }); 3427 } 3428 3429 @Override 3430 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3431 final IntentSender pi) { 3432 mContext.enforceCallingOrSelfPermission( 3433 android.Manifest.permission.CLEAR_APP_CACHE, null); 3434 // Queue up an async operation since clearing cache may take a little while. 3435 mHandler.post(new Runnable() { 3436 public void run() { 3437 mHandler.removeCallbacks(this); 3438 boolean success = true; 3439 synchronized (mInstallLock) { 3440 try { 3441 mInstaller.freeCache(volumeUuid, freeStorageSize); 3442 } catch (InstallerException e) { 3443 Slog.w(TAG, "Couldn't clear application caches: " + e); 3444 success = false; 3445 } 3446 } 3447 if(pi != null) { 3448 try { 3449 // Callback via pending intent 3450 int code = success ? 1 : 0; 3451 pi.sendIntent(null, code, null, 3452 null, null); 3453 } catch (SendIntentException e1) { 3454 Slog.i(TAG, "Failed to send pending intent"); 3455 } 3456 } 3457 } 3458 }); 3459 } 3460 3461 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3462 synchronized (mInstallLock) { 3463 try { 3464 mInstaller.freeCache(volumeUuid, freeStorageSize); 3465 } catch (InstallerException e) { 3466 throw new IOException("Failed to free enough space", e); 3467 } 3468 } 3469 } 3470 3471 /** 3472 * Update given flags based on encryption status of current user. 3473 */ 3474 private int updateFlags(int flags, int userId) { 3475 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3476 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3477 // Caller expressed an explicit opinion about what encryption 3478 // aware/unaware components they want to see, so fall through and 3479 // give them what they want 3480 } else { 3481 // Caller expressed no opinion, so match based on user state 3482 if (StorageManager.isUserKeyUnlocked(userId)) { 3483 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3484 } else { 3485 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3486 } 3487 } 3488 return flags; 3489 } 3490 3491 /** 3492 * Update given flags when being used to request {@link PackageInfo}. 3493 */ 3494 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3495 boolean triaged = true; 3496 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3497 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3498 // Caller is asking for component details, so they'd better be 3499 // asking for specific encryption matching behavior, or be triaged 3500 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3501 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3502 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3503 triaged = false; 3504 } 3505 } 3506 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3507 | PackageManager.MATCH_SYSTEM_ONLY 3508 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3509 triaged = false; 3510 } 3511 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3512 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3513 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3514 } 3515 return updateFlags(flags, userId); 3516 } 3517 3518 /** 3519 * Update given flags when being used to request {@link ApplicationInfo}. 3520 */ 3521 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3522 return updateFlagsForPackage(flags, userId, cookie); 3523 } 3524 3525 /** 3526 * Update given flags when being used to request {@link ComponentInfo}. 3527 */ 3528 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3529 if (cookie instanceof Intent) { 3530 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3531 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3532 } 3533 } 3534 3535 boolean triaged = true; 3536 // Caller is asking for component details, so they'd better be 3537 // asking for specific encryption matching behavior, or be triaged 3538 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3539 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3540 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3541 triaged = false; 3542 } 3543 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3544 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3545 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3546 } 3547 3548 return updateFlags(flags, userId); 3549 } 3550 3551 /** 3552 * Update given flags when being used to request {@link ResolveInfo}. 3553 */ 3554 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3555 // Safe mode means we shouldn't match any third-party components 3556 if (mSafeMode) { 3557 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3558 } 3559 3560 return updateFlagsForComponent(flags, userId, cookie); 3561 } 3562 3563 @Override 3564 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3565 if (!sUserManager.exists(userId)) return null; 3566 flags = updateFlagsForComponent(flags, userId, component); 3567 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3568 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3569 synchronized (mPackages) { 3570 PackageParser.Activity a = mActivities.mActivities.get(component); 3571 3572 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3573 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3574 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3575 if (ps == null) return null; 3576 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3577 userId); 3578 } 3579 if (mResolveComponentName.equals(component)) { 3580 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3581 new PackageUserState(), userId); 3582 } 3583 } 3584 return null; 3585 } 3586 3587 @Override 3588 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3589 String resolvedType) { 3590 synchronized (mPackages) { 3591 if (component.equals(mResolveComponentName)) { 3592 // The resolver supports EVERYTHING! 3593 return true; 3594 } 3595 PackageParser.Activity a = mActivities.mActivities.get(component); 3596 if (a == null) { 3597 return false; 3598 } 3599 for (int i=0; i<a.intents.size(); i++) { 3600 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3601 intent.getData(), intent.getCategories(), TAG) >= 0) { 3602 return true; 3603 } 3604 } 3605 return false; 3606 } 3607 } 3608 3609 @Override 3610 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3611 if (!sUserManager.exists(userId)) return null; 3612 flags = updateFlagsForComponent(flags, userId, component); 3613 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3614 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3615 synchronized (mPackages) { 3616 PackageParser.Activity a = mReceivers.mActivities.get(component); 3617 if (DEBUG_PACKAGE_INFO) Log.v( 3618 TAG, "getReceiverInfo " + component + ": " + a); 3619 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3620 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3621 if (ps == null) return null; 3622 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3623 userId); 3624 } 3625 } 3626 return null; 3627 } 3628 3629 @Override 3630 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3631 if (!sUserManager.exists(userId)) return null; 3632 flags = updateFlagsForComponent(flags, userId, component); 3633 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3634 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3635 synchronized (mPackages) { 3636 PackageParser.Service s = mServices.mServices.get(component); 3637 if (DEBUG_PACKAGE_INFO) Log.v( 3638 TAG, "getServiceInfo " + component + ": " + s); 3639 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3640 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3641 if (ps == null) return null; 3642 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3643 userId); 3644 } 3645 } 3646 return null; 3647 } 3648 3649 @Override 3650 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3651 if (!sUserManager.exists(userId)) return null; 3652 flags = updateFlagsForComponent(flags, userId, component); 3653 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3654 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3655 synchronized (mPackages) { 3656 PackageParser.Provider p = mProviders.mProviders.get(component); 3657 if (DEBUG_PACKAGE_INFO) Log.v( 3658 TAG, "getProviderInfo " + component + ": " + p); 3659 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3660 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3661 if (ps == null) return null; 3662 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3663 userId); 3664 } 3665 } 3666 return null; 3667 } 3668 3669 @Override 3670 public String[] getSystemSharedLibraryNames() { 3671 Set<String> libSet; 3672 synchronized (mPackages) { 3673 libSet = mSharedLibraries.keySet(); 3674 int size = libSet.size(); 3675 if (size > 0) { 3676 String[] libs = new String[size]; 3677 libSet.toArray(libs); 3678 return libs; 3679 } 3680 } 3681 return null; 3682 } 3683 3684 @Override 3685 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3686 synchronized (mPackages) { 3687 return mServicesSystemSharedLibraryPackageName; 3688 } 3689 } 3690 3691 @Override 3692 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3693 synchronized (mPackages) { 3694 return mSharedSystemSharedLibraryPackageName; 3695 } 3696 } 3697 3698 @Override 3699 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3700 synchronized (mPackages) { 3701 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3702 3703 final FeatureInfo fi = new FeatureInfo(); 3704 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3705 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3706 res.add(fi); 3707 3708 return new ParceledListSlice<>(res); 3709 } 3710 } 3711 3712 @Override 3713 public boolean hasSystemFeature(String name, int version) { 3714 synchronized (mPackages) { 3715 final FeatureInfo feat = mAvailableFeatures.get(name); 3716 if (feat == null) { 3717 return false; 3718 } else { 3719 return feat.version >= version; 3720 } 3721 } 3722 } 3723 3724 @Override 3725 public int checkPermission(String permName, String pkgName, int userId) { 3726 if (!sUserManager.exists(userId)) { 3727 return PackageManager.PERMISSION_DENIED; 3728 } 3729 3730 synchronized (mPackages) { 3731 final PackageParser.Package p = mPackages.get(pkgName); 3732 if (p != null && p.mExtras != null) { 3733 final PackageSetting ps = (PackageSetting) p.mExtras; 3734 final PermissionsState permissionsState = ps.getPermissionsState(); 3735 if (permissionsState.hasPermission(permName, userId)) { 3736 return PackageManager.PERMISSION_GRANTED; 3737 } 3738 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3739 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3740 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3741 return PackageManager.PERMISSION_GRANTED; 3742 } 3743 } 3744 } 3745 3746 return PackageManager.PERMISSION_DENIED; 3747 } 3748 3749 @Override 3750 public int checkUidPermission(String permName, int uid) { 3751 final int userId = UserHandle.getUserId(uid); 3752 3753 if (!sUserManager.exists(userId)) { 3754 return PackageManager.PERMISSION_DENIED; 3755 } 3756 3757 synchronized (mPackages) { 3758 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3759 if (obj != null) { 3760 final SettingBase ps = (SettingBase) obj; 3761 final PermissionsState permissionsState = ps.getPermissionsState(); 3762 if (permissionsState.hasPermission(permName, userId)) { 3763 return PackageManager.PERMISSION_GRANTED; 3764 } 3765 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3766 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3767 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 } else { 3771 ArraySet<String> perms = mSystemPermissions.get(uid); 3772 if (perms != null) { 3773 if (perms.contains(permName)) { 3774 return PackageManager.PERMISSION_GRANTED; 3775 } 3776 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3777 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3778 return PackageManager.PERMISSION_GRANTED; 3779 } 3780 } 3781 } 3782 } 3783 3784 return PackageManager.PERMISSION_DENIED; 3785 } 3786 3787 @Override 3788 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3789 if (UserHandle.getCallingUserId() != userId) { 3790 mContext.enforceCallingPermission( 3791 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3792 "isPermissionRevokedByPolicy for user " + userId); 3793 } 3794 3795 if (checkPermission(permission, packageName, userId) 3796 == PackageManager.PERMISSION_GRANTED) { 3797 return false; 3798 } 3799 3800 final long identity = Binder.clearCallingIdentity(); 3801 try { 3802 final int flags = getPermissionFlags(permission, packageName, userId); 3803 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3804 } finally { 3805 Binder.restoreCallingIdentity(identity); 3806 } 3807 } 3808 3809 @Override 3810 public String getPermissionControllerPackageName() { 3811 synchronized (mPackages) { 3812 return mRequiredInstallerPackage; 3813 } 3814 } 3815 3816 /** 3817 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3818 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3819 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3820 * @param message the message to log on security exception 3821 */ 3822 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3823 boolean checkShell, String message) { 3824 if (userId < 0) { 3825 throw new IllegalArgumentException("Invalid userId " + userId); 3826 } 3827 if (checkShell) { 3828 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3829 } 3830 if (userId == UserHandle.getUserId(callingUid)) return; 3831 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3832 if (requireFullPermission) { 3833 mContext.enforceCallingOrSelfPermission( 3834 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3835 } else { 3836 try { 3837 mContext.enforceCallingOrSelfPermission( 3838 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3839 } catch (SecurityException se) { 3840 mContext.enforceCallingOrSelfPermission( 3841 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3842 } 3843 } 3844 } 3845 } 3846 3847 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3848 if (callingUid == Process.SHELL_UID) { 3849 if (userHandle >= 0 3850 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3851 throw new SecurityException("Shell does not have permission to access user " 3852 + userHandle); 3853 } else if (userHandle < 0) { 3854 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3855 + Debug.getCallers(3)); 3856 } 3857 } 3858 } 3859 3860 private BasePermission findPermissionTreeLP(String permName) { 3861 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3862 if (permName.startsWith(bp.name) && 3863 permName.length() > bp.name.length() && 3864 permName.charAt(bp.name.length()) == '.') { 3865 return bp; 3866 } 3867 } 3868 return null; 3869 } 3870 3871 private BasePermission checkPermissionTreeLP(String permName) { 3872 if (permName != null) { 3873 BasePermission bp = findPermissionTreeLP(permName); 3874 if (bp != null) { 3875 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3876 return bp; 3877 } 3878 throw new SecurityException("Calling uid " 3879 + Binder.getCallingUid() 3880 + " is not allowed to add to permission tree " 3881 + bp.name + " owned by uid " + bp.uid); 3882 } 3883 } 3884 throw new SecurityException("No permission tree found for " + permName); 3885 } 3886 3887 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3888 if (s1 == null) { 3889 return s2 == null; 3890 } 3891 if (s2 == null) { 3892 return false; 3893 } 3894 if (s1.getClass() != s2.getClass()) { 3895 return false; 3896 } 3897 return s1.equals(s2); 3898 } 3899 3900 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3901 if (pi1.icon != pi2.icon) return false; 3902 if (pi1.logo != pi2.logo) return false; 3903 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3904 if (!compareStrings(pi1.name, pi2.name)) return false; 3905 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3906 // We'll take care of setting this one. 3907 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3908 // These are not currently stored in settings. 3909 //if (!compareStrings(pi1.group, pi2.group)) return false; 3910 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3911 //if (pi1.labelRes != pi2.labelRes) return false; 3912 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3913 return true; 3914 } 3915 3916 int permissionInfoFootprint(PermissionInfo info) { 3917 int size = info.name.length(); 3918 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3919 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3920 return size; 3921 } 3922 3923 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3924 int size = 0; 3925 for (BasePermission perm : mSettings.mPermissions.values()) { 3926 if (perm.uid == tree.uid) { 3927 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3928 } 3929 } 3930 return size; 3931 } 3932 3933 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3934 // We calculate the max size of permissions defined by this uid and throw 3935 // if that plus the size of 'info' would exceed our stated maximum. 3936 if (tree.uid != Process.SYSTEM_UID) { 3937 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3938 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3939 throw new SecurityException("Permission tree size cap exceeded"); 3940 } 3941 } 3942 } 3943 3944 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3945 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3946 throw new SecurityException("Label must be specified in permission"); 3947 } 3948 BasePermission tree = checkPermissionTreeLP(info.name); 3949 BasePermission bp = mSettings.mPermissions.get(info.name); 3950 boolean added = bp == null; 3951 boolean changed = true; 3952 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3953 if (added) { 3954 enforcePermissionCapLocked(info, tree); 3955 bp = new BasePermission(info.name, tree.sourcePackage, 3956 BasePermission.TYPE_DYNAMIC); 3957 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3958 throw new SecurityException( 3959 "Not allowed to modify non-dynamic permission " 3960 + info.name); 3961 } else { 3962 if (bp.protectionLevel == fixedLevel 3963 && bp.perm.owner.equals(tree.perm.owner) 3964 && bp.uid == tree.uid 3965 && comparePermissionInfos(bp.perm.info, info)) { 3966 changed = false; 3967 } 3968 } 3969 bp.protectionLevel = fixedLevel; 3970 info = new PermissionInfo(info); 3971 info.protectionLevel = fixedLevel; 3972 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3973 bp.perm.info.packageName = tree.perm.info.packageName; 3974 bp.uid = tree.uid; 3975 if (added) { 3976 mSettings.mPermissions.put(info.name, bp); 3977 } 3978 if (changed) { 3979 if (!async) { 3980 mSettings.writeLPr(); 3981 } else { 3982 scheduleWriteSettingsLocked(); 3983 } 3984 } 3985 return added; 3986 } 3987 3988 @Override 3989 public boolean addPermission(PermissionInfo info) { 3990 synchronized (mPackages) { 3991 return addPermissionLocked(info, false); 3992 } 3993 } 3994 3995 @Override 3996 public boolean addPermissionAsync(PermissionInfo info) { 3997 synchronized (mPackages) { 3998 return addPermissionLocked(info, true); 3999 } 4000 } 4001 4002 @Override 4003 public void removePermission(String name) { 4004 synchronized (mPackages) { 4005 checkPermissionTreeLP(name); 4006 BasePermission bp = mSettings.mPermissions.get(name); 4007 if (bp != null) { 4008 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4009 throw new SecurityException( 4010 "Not allowed to modify non-dynamic permission " 4011 + name); 4012 } 4013 mSettings.mPermissions.remove(name); 4014 mSettings.writeLPr(); 4015 } 4016 } 4017 } 4018 4019 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4020 BasePermission bp) { 4021 int index = pkg.requestedPermissions.indexOf(bp.name); 4022 if (index == -1) { 4023 throw new SecurityException("Package " + pkg.packageName 4024 + " has not requested permission " + bp.name); 4025 } 4026 if (!bp.isRuntime() && !bp.isDevelopment()) { 4027 throw new SecurityException("Permission " + bp.name 4028 + " is not a changeable permission type"); 4029 } 4030 } 4031 4032 @Override 4033 public void grantRuntimePermission(String packageName, String name, final int userId) { 4034 if (!sUserManager.exists(userId)) { 4035 Log.e(TAG, "No such user:" + userId); 4036 return; 4037 } 4038 4039 mContext.enforceCallingOrSelfPermission( 4040 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4041 "grantRuntimePermission"); 4042 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4044 true /* requireFullPermission */, true /* checkShell */, 4045 "grantRuntimePermission"); 4046 4047 final int uid; 4048 final SettingBase sb; 4049 4050 synchronized (mPackages) { 4051 final PackageParser.Package pkg = mPackages.get(packageName); 4052 if (pkg == null) { 4053 throw new IllegalArgumentException("Unknown package: " + packageName); 4054 } 4055 4056 final BasePermission bp = mSettings.mPermissions.get(name); 4057 if (bp == null) { 4058 throw new IllegalArgumentException("Unknown permission: " + name); 4059 } 4060 4061 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4062 4063 // If a permission review is required for legacy apps we represent 4064 // their permissions as always granted runtime ones since we need 4065 // to keep the review required permission flag per user while an 4066 // install permission's state is shared across all users. 4067 if (Build.PERMISSIONS_REVIEW_REQUIRED 4068 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4069 && bp.isRuntime()) { 4070 return; 4071 } 4072 4073 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4074 sb = (SettingBase) pkg.mExtras; 4075 if (sb == null) { 4076 throw new IllegalArgumentException("Unknown package: " + packageName); 4077 } 4078 4079 final PermissionsState permissionsState = sb.getPermissionsState(); 4080 4081 final int flags = permissionsState.getPermissionFlags(name, userId); 4082 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4083 throw new SecurityException("Cannot grant system fixed permission " 4084 + name + " for package " + packageName); 4085 } 4086 4087 if (bp.isDevelopment()) { 4088 // Development permissions must be handled specially, since they are not 4089 // normal runtime permissions. For now they apply to all users. 4090 if (permissionsState.grantInstallPermission(bp) != 4091 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4092 scheduleWriteSettingsLocked(); 4093 } 4094 return; 4095 } 4096 4097 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4098 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4099 return; 4100 } 4101 4102 final int result = permissionsState.grantRuntimePermission(bp, userId); 4103 switch (result) { 4104 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4105 return; 4106 } 4107 4108 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4109 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4110 mHandler.post(new Runnable() { 4111 @Override 4112 public void run() { 4113 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4114 } 4115 }); 4116 } 4117 break; 4118 } 4119 4120 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4121 4122 // Not critical if that is lost - app has to request again. 4123 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4124 } 4125 4126 // Only need to do this if user is initialized. Otherwise it's a new user 4127 // and there are no processes running as the user yet and there's no need 4128 // to make an expensive call to remount processes for the changed permissions. 4129 if (READ_EXTERNAL_STORAGE.equals(name) 4130 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4131 final long token = Binder.clearCallingIdentity(); 4132 try { 4133 if (sUserManager.isInitialized(userId)) { 4134 MountServiceInternal mountServiceInternal = LocalServices.getService( 4135 MountServiceInternal.class); 4136 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4137 } 4138 } finally { 4139 Binder.restoreCallingIdentity(token); 4140 } 4141 } 4142 } 4143 4144 @Override 4145 public void revokeRuntimePermission(String packageName, String name, int userId) { 4146 if (!sUserManager.exists(userId)) { 4147 Log.e(TAG, "No such user:" + userId); 4148 return; 4149 } 4150 4151 mContext.enforceCallingOrSelfPermission( 4152 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4153 "revokeRuntimePermission"); 4154 4155 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4156 true /* requireFullPermission */, true /* checkShell */, 4157 "revokeRuntimePermission"); 4158 4159 final int appId; 4160 4161 synchronized (mPackages) { 4162 final PackageParser.Package pkg = mPackages.get(packageName); 4163 if (pkg == null) { 4164 throw new IllegalArgumentException("Unknown package: " + packageName); 4165 } 4166 4167 final BasePermission bp = mSettings.mPermissions.get(name); 4168 if (bp == null) { 4169 throw new IllegalArgumentException("Unknown permission: " + name); 4170 } 4171 4172 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4173 4174 // If a permission review is required for legacy apps we represent 4175 // their permissions as always granted runtime ones since we need 4176 // to keep the review required permission flag per user while an 4177 // install permission's state is shared across all users. 4178 if (Build.PERMISSIONS_REVIEW_REQUIRED 4179 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4180 && bp.isRuntime()) { 4181 return; 4182 } 4183 4184 SettingBase sb = (SettingBase) pkg.mExtras; 4185 if (sb == null) { 4186 throw new IllegalArgumentException("Unknown package: " + packageName); 4187 } 4188 4189 final PermissionsState permissionsState = sb.getPermissionsState(); 4190 4191 final int flags = permissionsState.getPermissionFlags(name, userId); 4192 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4193 throw new SecurityException("Cannot revoke system fixed permission " 4194 + name + " for package " + packageName); 4195 } 4196 4197 if (bp.isDevelopment()) { 4198 // Development permissions must be handled specially, since they are not 4199 // normal runtime permissions. For now they apply to all users. 4200 if (permissionsState.revokeInstallPermission(bp) != 4201 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4202 scheduleWriteSettingsLocked(); 4203 } 4204 return; 4205 } 4206 4207 if (permissionsState.revokeRuntimePermission(bp, userId) == 4208 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4209 return; 4210 } 4211 4212 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4213 4214 // Critical, after this call app should never have the permission. 4215 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4216 4217 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4218 } 4219 4220 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4221 } 4222 4223 @Override 4224 public void resetRuntimePermissions() { 4225 mContext.enforceCallingOrSelfPermission( 4226 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4227 "revokeRuntimePermission"); 4228 4229 int callingUid = Binder.getCallingUid(); 4230 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4231 mContext.enforceCallingOrSelfPermission( 4232 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4233 "resetRuntimePermissions"); 4234 } 4235 4236 synchronized (mPackages) { 4237 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4238 for (int userId : UserManagerService.getInstance().getUserIds()) { 4239 final int packageCount = mPackages.size(); 4240 for (int i = 0; i < packageCount; i++) { 4241 PackageParser.Package pkg = mPackages.valueAt(i); 4242 if (!(pkg.mExtras instanceof PackageSetting)) { 4243 continue; 4244 } 4245 PackageSetting ps = (PackageSetting) pkg.mExtras; 4246 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4247 } 4248 } 4249 } 4250 } 4251 4252 @Override 4253 public int getPermissionFlags(String name, String packageName, int userId) { 4254 if (!sUserManager.exists(userId)) { 4255 return 0; 4256 } 4257 4258 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4259 4260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4261 true /* requireFullPermission */, false /* checkShell */, 4262 "getPermissionFlags"); 4263 4264 synchronized (mPackages) { 4265 final PackageParser.Package pkg = mPackages.get(packageName); 4266 if (pkg == null) { 4267 throw new IllegalArgumentException("Unknown package: " + packageName); 4268 } 4269 4270 final BasePermission bp = mSettings.mPermissions.get(name); 4271 if (bp == null) { 4272 throw new IllegalArgumentException("Unknown permission: " + name); 4273 } 4274 4275 SettingBase sb = (SettingBase) pkg.mExtras; 4276 if (sb == null) { 4277 throw new IllegalArgumentException("Unknown package: " + packageName); 4278 } 4279 4280 PermissionsState permissionsState = sb.getPermissionsState(); 4281 return permissionsState.getPermissionFlags(name, userId); 4282 } 4283 } 4284 4285 @Override 4286 public void updatePermissionFlags(String name, String packageName, int flagMask, 4287 int flagValues, int userId) { 4288 if (!sUserManager.exists(userId)) { 4289 return; 4290 } 4291 4292 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4293 4294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4295 true /* requireFullPermission */, true /* checkShell */, 4296 "updatePermissionFlags"); 4297 4298 // Only the system can change these flags and nothing else. 4299 if (getCallingUid() != Process.SYSTEM_UID) { 4300 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4301 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4302 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4304 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4305 } 4306 4307 synchronized (mPackages) { 4308 final PackageParser.Package pkg = mPackages.get(packageName); 4309 if (pkg == null) { 4310 throw new IllegalArgumentException("Unknown package: " + packageName); 4311 } 4312 4313 final BasePermission bp = mSettings.mPermissions.get(name); 4314 if (bp == null) { 4315 throw new IllegalArgumentException("Unknown permission: " + name); 4316 } 4317 4318 SettingBase sb = (SettingBase) pkg.mExtras; 4319 if (sb == null) { 4320 throw new IllegalArgumentException("Unknown package: " + packageName); 4321 } 4322 4323 PermissionsState permissionsState = sb.getPermissionsState(); 4324 4325 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4326 4327 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4328 // Install and runtime permissions are stored in different places, 4329 // so figure out what permission changed and persist the change. 4330 if (permissionsState.getInstallPermissionState(name) != null) { 4331 scheduleWriteSettingsLocked(); 4332 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4333 || hadState) { 4334 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4335 } 4336 } 4337 } 4338 } 4339 4340 /** 4341 * Update the permission flags for all packages and runtime permissions of a user in order 4342 * to allow device or profile owner to remove POLICY_FIXED. 4343 */ 4344 @Override 4345 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4346 if (!sUserManager.exists(userId)) { 4347 return; 4348 } 4349 4350 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4351 4352 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4353 true /* requireFullPermission */, true /* checkShell */, 4354 "updatePermissionFlagsForAllApps"); 4355 4356 // Only the system can change system fixed flags. 4357 if (getCallingUid() != Process.SYSTEM_UID) { 4358 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4359 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4360 } 4361 4362 synchronized (mPackages) { 4363 boolean changed = false; 4364 final int packageCount = mPackages.size(); 4365 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4366 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4367 SettingBase sb = (SettingBase) pkg.mExtras; 4368 if (sb == null) { 4369 continue; 4370 } 4371 PermissionsState permissionsState = sb.getPermissionsState(); 4372 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4373 userId, flagMask, flagValues); 4374 } 4375 if (changed) { 4376 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4377 } 4378 } 4379 } 4380 4381 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4382 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4383 != PackageManager.PERMISSION_GRANTED 4384 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4385 != PackageManager.PERMISSION_GRANTED) { 4386 throw new SecurityException(message + " requires " 4387 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4388 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4389 } 4390 } 4391 4392 @Override 4393 public boolean shouldShowRequestPermissionRationale(String permissionName, 4394 String packageName, int userId) { 4395 if (UserHandle.getCallingUserId() != userId) { 4396 mContext.enforceCallingPermission( 4397 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4398 "canShowRequestPermissionRationale for user " + userId); 4399 } 4400 4401 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4402 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4403 return false; 4404 } 4405 4406 if (checkPermission(permissionName, packageName, userId) 4407 == PackageManager.PERMISSION_GRANTED) { 4408 return false; 4409 } 4410 4411 final int flags; 4412 4413 final long identity = Binder.clearCallingIdentity(); 4414 try { 4415 flags = getPermissionFlags(permissionName, 4416 packageName, userId); 4417 } finally { 4418 Binder.restoreCallingIdentity(identity); 4419 } 4420 4421 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4422 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4423 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4424 4425 if ((flags & fixedFlags) != 0) { 4426 return false; 4427 } 4428 4429 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4430 } 4431 4432 @Override 4433 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4434 mContext.enforceCallingOrSelfPermission( 4435 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4436 "addOnPermissionsChangeListener"); 4437 4438 synchronized (mPackages) { 4439 mOnPermissionChangeListeners.addListenerLocked(listener); 4440 } 4441 } 4442 4443 @Override 4444 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4445 synchronized (mPackages) { 4446 mOnPermissionChangeListeners.removeListenerLocked(listener); 4447 } 4448 } 4449 4450 @Override 4451 public boolean isProtectedBroadcast(String actionName) { 4452 synchronized (mPackages) { 4453 if (mProtectedBroadcasts.contains(actionName)) { 4454 return true; 4455 } else if (actionName != null) { 4456 // TODO: remove these terrible hacks 4457 if (actionName.startsWith("android.net.netmon.lingerExpired") 4458 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4459 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4460 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4461 return true; 4462 } 4463 } 4464 } 4465 return false; 4466 } 4467 4468 @Override 4469 public int checkSignatures(String pkg1, String pkg2) { 4470 synchronized (mPackages) { 4471 final PackageParser.Package p1 = mPackages.get(pkg1); 4472 final PackageParser.Package p2 = mPackages.get(pkg2); 4473 if (p1 == null || p1.mExtras == null 4474 || p2 == null || p2.mExtras == null) { 4475 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4476 } 4477 return compareSignatures(p1.mSignatures, p2.mSignatures); 4478 } 4479 } 4480 4481 @Override 4482 public int checkUidSignatures(int uid1, int uid2) { 4483 // Map to base uids. 4484 uid1 = UserHandle.getAppId(uid1); 4485 uid2 = UserHandle.getAppId(uid2); 4486 // reader 4487 synchronized (mPackages) { 4488 Signature[] s1; 4489 Signature[] s2; 4490 Object obj = mSettings.getUserIdLPr(uid1); 4491 if (obj != null) { 4492 if (obj instanceof SharedUserSetting) { 4493 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4494 } else if (obj instanceof PackageSetting) { 4495 s1 = ((PackageSetting)obj).signatures.mSignatures; 4496 } else { 4497 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4498 } 4499 } else { 4500 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4501 } 4502 obj = mSettings.getUserIdLPr(uid2); 4503 if (obj != null) { 4504 if (obj instanceof SharedUserSetting) { 4505 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4506 } else if (obj instanceof PackageSetting) { 4507 s2 = ((PackageSetting)obj).signatures.mSignatures; 4508 } else { 4509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4510 } 4511 } else { 4512 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4513 } 4514 return compareSignatures(s1, s2); 4515 } 4516 } 4517 4518 /** 4519 * This method should typically only be used when granting or revoking 4520 * permissions, since the app may immediately restart after this call. 4521 * <p> 4522 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4523 * guard your work against the app being relaunched. 4524 */ 4525 private void killUid(int appId, int userId, String reason) { 4526 final long identity = Binder.clearCallingIdentity(); 4527 try { 4528 IActivityManager am = ActivityManagerNative.getDefault(); 4529 if (am != null) { 4530 try { 4531 am.killUid(appId, userId, reason); 4532 } catch (RemoteException e) { 4533 /* ignore - same process */ 4534 } 4535 } 4536 } finally { 4537 Binder.restoreCallingIdentity(identity); 4538 } 4539 } 4540 4541 /** 4542 * Compares two sets of signatures. Returns: 4543 * <br /> 4544 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4545 * <br /> 4546 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4547 * <br /> 4548 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4549 * <br /> 4550 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4553 */ 4554 static int compareSignatures(Signature[] s1, Signature[] s2) { 4555 if (s1 == null) { 4556 return s2 == null 4557 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4558 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4559 } 4560 4561 if (s2 == null) { 4562 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4563 } 4564 4565 if (s1.length != s2.length) { 4566 return PackageManager.SIGNATURE_NO_MATCH; 4567 } 4568 4569 // Since both signature sets are of size 1, we can compare without HashSets. 4570 if (s1.length == 1) { 4571 return s1[0].equals(s2[0]) ? 4572 PackageManager.SIGNATURE_MATCH : 4573 PackageManager.SIGNATURE_NO_MATCH; 4574 } 4575 4576 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4577 for (Signature sig : s1) { 4578 set1.add(sig); 4579 } 4580 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4581 for (Signature sig : s2) { 4582 set2.add(sig); 4583 } 4584 // Make sure s2 contains all signatures in s1. 4585 if (set1.equals(set2)) { 4586 return PackageManager.SIGNATURE_MATCH; 4587 } 4588 return PackageManager.SIGNATURE_NO_MATCH; 4589 } 4590 4591 /** 4592 * If the database version for this type of package (internal storage or 4593 * external storage) is less than the version where package signatures 4594 * were updated, return true. 4595 */ 4596 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4597 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4598 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4599 } 4600 4601 /** 4602 * Used for backward compatibility to make sure any packages with 4603 * certificate chains get upgraded to the new style. {@code existingSigs} 4604 * will be in the old format (since they were stored on disk from before the 4605 * system upgrade) and {@code scannedSigs} will be in the newer format. 4606 */ 4607 private int compareSignaturesCompat(PackageSignatures existingSigs, 4608 PackageParser.Package scannedPkg) { 4609 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4610 return PackageManager.SIGNATURE_NO_MATCH; 4611 } 4612 4613 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4614 for (Signature sig : existingSigs.mSignatures) { 4615 existingSet.add(sig); 4616 } 4617 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4618 for (Signature sig : scannedPkg.mSignatures) { 4619 try { 4620 Signature[] chainSignatures = sig.getChainSignatures(); 4621 for (Signature chainSig : chainSignatures) { 4622 scannedCompatSet.add(chainSig); 4623 } 4624 } catch (CertificateEncodingException e) { 4625 scannedCompatSet.add(sig); 4626 } 4627 } 4628 /* 4629 * Make sure the expanded scanned set contains all signatures in the 4630 * existing one. 4631 */ 4632 if (scannedCompatSet.equals(existingSet)) { 4633 // Migrate the old signatures to the new scheme. 4634 existingSigs.assignSignatures(scannedPkg.mSignatures); 4635 // The new KeySets will be re-added later in the scanning process. 4636 synchronized (mPackages) { 4637 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4638 } 4639 return PackageManager.SIGNATURE_MATCH; 4640 } 4641 return PackageManager.SIGNATURE_NO_MATCH; 4642 } 4643 4644 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4645 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4646 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4647 } 4648 4649 private int compareSignaturesRecover(PackageSignatures existingSigs, 4650 PackageParser.Package scannedPkg) { 4651 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4652 return PackageManager.SIGNATURE_NO_MATCH; 4653 } 4654 4655 String msg = null; 4656 try { 4657 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4658 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4659 + scannedPkg.packageName); 4660 return PackageManager.SIGNATURE_MATCH; 4661 } 4662 } catch (CertificateException e) { 4663 msg = e.getMessage(); 4664 } 4665 4666 logCriticalInfo(Log.INFO, 4667 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4668 return PackageManager.SIGNATURE_NO_MATCH; 4669 } 4670 4671 @Override 4672 public List<String> getAllPackages() { 4673 synchronized (mPackages) { 4674 return new ArrayList<String>(mPackages.keySet()); 4675 } 4676 } 4677 4678 @Override 4679 public String[] getPackagesForUid(int uid) { 4680 uid = UserHandle.getAppId(uid); 4681 // reader 4682 synchronized (mPackages) { 4683 Object obj = mSettings.getUserIdLPr(uid); 4684 if (obj instanceof SharedUserSetting) { 4685 final SharedUserSetting sus = (SharedUserSetting) obj; 4686 final int N = sus.packages.size(); 4687 final String[] res = new String[N]; 4688 final Iterator<PackageSetting> it = sus.packages.iterator(); 4689 int i = 0; 4690 while (it.hasNext()) { 4691 res[i++] = it.next().name; 4692 } 4693 return res; 4694 } else if (obj instanceof PackageSetting) { 4695 final PackageSetting ps = (PackageSetting) obj; 4696 return new String[] { ps.name }; 4697 } 4698 } 4699 return null; 4700 } 4701 4702 @Override 4703 public String getNameForUid(int uid) { 4704 // reader 4705 synchronized (mPackages) { 4706 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4707 if (obj instanceof SharedUserSetting) { 4708 final SharedUserSetting sus = (SharedUserSetting) obj; 4709 return sus.name + ":" + sus.userId; 4710 } else if (obj instanceof PackageSetting) { 4711 final PackageSetting ps = (PackageSetting) obj; 4712 return ps.name; 4713 } 4714 } 4715 return null; 4716 } 4717 4718 @Override 4719 public int getUidForSharedUser(String sharedUserName) { 4720 if(sharedUserName == null) { 4721 return -1; 4722 } 4723 // reader 4724 synchronized (mPackages) { 4725 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4726 if (suid == null) { 4727 return -1; 4728 } 4729 return suid.userId; 4730 } 4731 } 4732 4733 @Override 4734 public int getFlagsForUid(int uid) { 4735 synchronized (mPackages) { 4736 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4737 if (obj instanceof SharedUserSetting) { 4738 final SharedUserSetting sus = (SharedUserSetting) obj; 4739 return sus.pkgFlags; 4740 } else if (obj instanceof PackageSetting) { 4741 final PackageSetting ps = (PackageSetting) obj; 4742 return ps.pkgFlags; 4743 } 4744 } 4745 return 0; 4746 } 4747 4748 @Override 4749 public int getPrivateFlagsForUid(int uid) { 4750 synchronized (mPackages) { 4751 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4752 if (obj instanceof SharedUserSetting) { 4753 final SharedUserSetting sus = (SharedUserSetting) obj; 4754 return sus.pkgPrivateFlags; 4755 } else if (obj instanceof PackageSetting) { 4756 final PackageSetting ps = (PackageSetting) obj; 4757 return ps.pkgPrivateFlags; 4758 } 4759 } 4760 return 0; 4761 } 4762 4763 @Override 4764 public boolean isUidPrivileged(int uid) { 4765 uid = UserHandle.getAppId(uid); 4766 // reader 4767 synchronized (mPackages) { 4768 Object obj = mSettings.getUserIdLPr(uid); 4769 if (obj instanceof SharedUserSetting) { 4770 final SharedUserSetting sus = (SharedUserSetting) obj; 4771 final Iterator<PackageSetting> it = sus.packages.iterator(); 4772 while (it.hasNext()) { 4773 if (it.next().isPrivileged()) { 4774 return true; 4775 } 4776 } 4777 } else if (obj instanceof PackageSetting) { 4778 final PackageSetting ps = (PackageSetting) obj; 4779 return ps.isPrivileged(); 4780 } 4781 } 4782 return false; 4783 } 4784 4785 @Override 4786 public String[] getAppOpPermissionPackages(String permissionName) { 4787 synchronized (mPackages) { 4788 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4789 if (pkgs == null) { 4790 return null; 4791 } 4792 return pkgs.toArray(new String[pkgs.size()]); 4793 } 4794 } 4795 4796 @Override 4797 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4798 int flags, int userId) { 4799 try { 4800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4801 4802 if (!sUserManager.exists(userId)) return null; 4803 flags = updateFlagsForResolve(flags, userId, intent); 4804 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4805 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4806 4807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4808 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4809 flags, userId); 4810 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4811 4812 final ResolveInfo bestChoice = 4813 chooseBestActivity(intent, resolvedType, flags, query, userId); 4814 4815 if (isEphemeralAllowed(intent, query, userId)) { 4816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4817 final EphemeralResolveInfo ai = 4818 getEphemeralResolveInfo(intent, resolvedType, userId); 4819 if (ai != null) { 4820 if (DEBUG_EPHEMERAL) { 4821 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4822 } 4823 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4824 bestChoice.ephemeralResolveInfo = ai; 4825 } 4826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4827 } 4828 return bestChoice; 4829 } finally { 4830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4831 } 4832 } 4833 4834 @Override 4835 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4836 IntentFilter filter, int match, ComponentName activity) { 4837 final int userId = UserHandle.getCallingUserId(); 4838 if (DEBUG_PREFERRED) { 4839 Log.v(TAG, "setLastChosenActivity intent=" + intent 4840 + " resolvedType=" + resolvedType 4841 + " flags=" + flags 4842 + " filter=" + filter 4843 + " match=" + match 4844 + " activity=" + activity); 4845 filter.dump(new PrintStreamPrinter(System.out), " "); 4846 } 4847 intent.setComponent(null); 4848 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4849 userId); 4850 // Find any earlier preferred or last chosen entries and nuke them 4851 findPreferredActivity(intent, resolvedType, 4852 flags, query, 0, false, true, false, userId); 4853 // Add the new activity as the last chosen for this filter 4854 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4855 "Setting last chosen"); 4856 } 4857 4858 @Override 4859 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4860 final int userId = UserHandle.getCallingUserId(); 4861 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4862 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4863 userId); 4864 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4865 false, false, false, userId); 4866 } 4867 4868 4869 private boolean isEphemeralAllowed( 4870 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4871 // Short circuit and return early if possible. 4872 if (DISABLE_EPHEMERAL_APPS) { 4873 return false; 4874 } 4875 final int callingUser = UserHandle.getCallingUserId(); 4876 if (callingUser != UserHandle.USER_SYSTEM) { 4877 return false; 4878 } 4879 if (mEphemeralResolverConnection == null) { 4880 return false; 4881 } 4882 if (intent.getComponent() != null) { 4883 return false; 4884 } 4885 if (intent.getPackage() != null) { 4886 return false; 4887 } 4888 final boolean isWebUri = hasWebURI(intent); 4889 if (!isWebUri) { 4890 return false; 4891 } 4892 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4893 synchronized (mPackages) { 4894 final int count = resolvedActivites.size(); 4895 for (int n = 0; n < count; n++) { 4896 ResolveInfo info = resolvedActivites.get(n); 4897 String packageName = info.activityInfo.packageName; 4898 PackageSetting ps = mSettings.mPackages.get(packageName); 4899 if (ps != null) { 4900 // Try to get the status from User settings first 4901 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4902 int status = (int) (packedStatus >> 32); 4903 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4904 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4905 if (DEBUG_EPHEMERAL) { 4906 Slog.v(TAG, "DENY ephemeral apps;" 4907 + " pkg: " + packageName + ", status: " + status); 4908 } 4909 return false; 4910 } 4911 } 4912 } 4913 } 4914 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4915 return true; 4916 } 4917 4918 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4919 int userId) { 4920 MessageDigest digest = null; 4921 try { 4922 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4923 } catch (NoSuchAlgorithmException e) { 4924 // If we can't create a digest, ignore ephemeral apps. 4925 return null; 4926 } 4927 4928 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4929 final byte[] digestBytes = digest.digest(hostBytes); 4930 int shaPrefix = 4931 digestBytes[0] << 24 4932 | digestBytes[1] << 16 4933 | digestBytes[2] << 8 4934 | digestBytes[3] << 0; 4935 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4936 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4937 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4938 // No hash prefix match; there are no ephemeral apps for this domain. 4939 return null; 4940 } 4941 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4942 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4943 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4944 continue; 4945 } 4946 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4947 // No filters; this should never happen. 4948 if (filters.isEmpty()) { 4949 continue; 4950 } 4951 // We have a domain match; resolve the filters to see if anything matches. 4952 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4953 for (int j = filters.size() - 1; j >= 0; --j) { 4954 final EphemeralResolveIntentInfo intentInfo = 4955 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4956 ephemeralResolver.addFilter(intentInfo); 4957 } 4958 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4959 intent, resolvedType, false /*defaultOnly*/, userId); 4960 if (!matchedResolveInfoList.isEmpty()) { 4961 return matchedResolveInfoList.get(0); 4962 } 4963 } 4964 // Hash or filter mis-match; no ephemeral apps for this domain. 4965 return null; 4966 } 4967 4968 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4969 int flags, List<ResolveInfo> query, int userId) { 4970 if (query != null) { 4971 final int N = query.size(); 4972 if (N == 1) { 4973 return query.get(0); 4974 } else if (N > 1) { 4975 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4976 // If there is more than one activity with the same priority, 4977 // then let the user decide between them. 4978 ResolveInfo r0 = query.get(0); 4979 ResolveInfo r1 = query.get(1); 4980 if (DEBUG_INTENT_MATCHING || debug) { 4981 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4982 + r1.activityInfo.name + "=" + r1.priority); 4983 } 4984 // If the first activity has a higher priority, or a different 4985 // default, then it is always desirable to pick it. 4986 if (r0.priority != r1.priority 4987 || r0.preferredOrder != r1.preferredOrder 4988 || r0.isDefault != r1.isDefault) { 4989 return query.get(0); 4990 } 4991 // If we have saved a preference for a preferred activity for 4992 // this Intent, use that. 4993 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4994 flags, query, r0.priority, true, false, debug, userId); 4995 if (ri != null) { 4996 return ri; 4997 } 4998 ri = new ResolveInfo(mResolveInfo); 4999 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5000 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5001 ri.activityInfo.applicationInfo = new ApplicationInfo( 5002 ri.activityInfo.applicationInfo); 5003 if (userId != 0) { 5004 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5005 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5006 } 5007 // Make sure that the resolver is displayable in car mode 5008 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5009 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5010 return ri; 5011 } 5012 } 5013 return null; 5014 } 5015 5016 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5017 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5018 final int N = query.size(); 5019 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5020 .get(userId); 5021 // Get the list of persistent preferred activities that handle the intent 5022 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5023 List<PersistentPreferredActivity> pprefs = ppir != null 5024 ? ppir.queryIntent(intent, resolvedType, 5025 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5026 : null; 5027 if (pprefs != null && pprefs.size() > 0) { 5028 final int M = pprefs.size(); 5029 for (int i=0; i<M; i++) { 5030 final PersistentPreferredActivity ppa = pprefs.get(i); 5031 if (DEBUG_PREFERRED || debug) { 5032 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5033 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5034 + "\n component=" + ppa.mComponent); 5035 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5036 } 5037 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5038 flags | MATCH_DISABLED_COMPONENTS, userId); 5039 if (DEBUG_PREFERRED || debug) { 5040 Slog.v(TAG, "Found persistent preferred activity:"); 5041 if (ai != null) { 5042 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5043 } else { 5044 Slog.v(TAG, " null"); 5045 } 5046 } 5047 if (ai == null) { 5048 // This previously registered persistent preferred activity 5049 // component is no longer known. Ignore it and do NOT remove it. 5050 continue; 5051 } 5052 for (int j=0; j<N; j++) { 5053 final ResolveInfo ri = query.get(j); 5054 if (!ri.activityInfo.applicationInfo.packageName 5055 .equals(ai.applicationInfo.packageName)) { 5056 continue; 5057 } 5058 if (!ri.activityInfo.name.equals(ai.name)) { 5059 continue; 5060 } 5061 // Found a persistent preference that can handle the intent. 5062 if (DEBUG_PREFERRED || debug) { 5063 Slog.v(TAG, "Returning persistent preferred activity: " + 5064 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5065 } 5066 return ri; 5067 } 5068 } 5069 } 5070 return null; 5071 } 5072 5073 // TODO: handle preferred activities missing while user has amnesia 5074 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5075 List<ResolveInfo> query, int priority, boolean always, 5076 boolean removeMatches, boolean debug, int userId) { 5077 if (!sUserManager.exists(userId)) return null; 5078 flags = updateFlagsForResolve(flags, userId, intent); 5079 // writer 5080 synchronized (mPackages) { 5081 if (intent.getSelector() != null) { 5082 intent = intent.getSelector(); 5083 } 5084 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5085 5086 // Try to find a matching persistent preferred activity. 5087 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5088 debug, userId); 5089 5090 // If a persistent preferred activity matched, use it. 5091 if (pri != null) { 5092 return pri; 5093 } 5094 5095 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5096 // Get the list of preferred activities that handle the intent 5097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5098 List<PreferredActivity> prefs = pir != null 5099 ? pir.queryIntent(intent, resolvedType, 5100 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5101 : null; 5102 if (prefs != null && prefs.size() > 0) { 5103 boolean changed = false; 5104 try { 5105 // First figure out how good the original match set is. 5106 // We will only allow preferred activities that came 5107 // from the same match quality. 5108 int match = 0; 5109 5110 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5111 5112 final int N = query.size(); 5113 for (int j=0; j<N; j++) { 5114 final ResolveInfo ri = query.get(j); 5115 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5116 + ": 0x" + Integer.toHexString(match)); 5117 if (ri.match > match) { 5118 match = ri.match; 5119 } 5120 } 5121 5122 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5123 + Integer.toHexString(match)); 5124 5125 match &= IntentFilter.MATCH_CATEGORY_MASK; 5126 final int M = prefs.size(); 5127 for (int i=0; i<M; i++) { 5128 final PreferredActivity pa = prefs.get(i); 5129 if (DEBUG_PREFERRED || debug) { 5130 Slog.v(TAG, "Checking PreferredActivity ds=" 5131 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5132 + "\n component=" + pa.mPref.mComponent); 5133 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5134 } 5135 if (pa.mPref.mMatch != match) { 5136 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5137 + Integer.toHexString(pa.mPref.mMatch)); 5138 continue; 5139 } 5140 // If it's not an "always" type preferred activity and that's what we're 5141 // looking for, skip it. 5142 if (always && !pa.mPref.mAlways) { 5143 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5144 continue; 5145 } 5146 final ActivityInfo ai = getActivityInfo( 5147 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5148 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5149 userId); 5150 if (DEBUG_PREFERRED || debug) { 5151 Slog.v(TAG, "Found preferred activity:"); 5152 if (ai != null) { 5153 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5154 } else { 5155 Slog.v(TAG, " null"); 5156 } 5157 } 5158 if (ai == null) { 5159 // This previously registered preferred activity 5160 // component is no longer known. Most likely an update 5161 // to the app was installed and in the new version this 5162 // component no longer exists. Clean it up by removing 5163 // it from the preferred activities list, and skip it. 5164 Slog.w(TAG, "Removing dangling preferred activity: " 5165 + pa.mPref.mComponent); 5166 pir.removeFilter(pa); 5167 changed = true; 5168 continue; 5169 } 5170 for (int j=0; j<N; j++) { 5171 final ResolveInfo ri = query.get(j); 5172 if (!ri.activityInfo.applicationInfo.packageName 5173 .equals(ai.applicationInfo.packageName)) { 5174 continue; 5175 } 5176 if (!ri.activityInfo.name.equals(ai.name)) { 5177 continue; 5178 } 5179 5180 if (removeMatches) { 5181 pir.removeFilter(pa); 5182 changed = true; 5183 if (DEBUG_PREFERRED) { 5184 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5185 } 5186 break; 5187 } 5188 5189 // Okay we found a previously set preferred or last chosen app. 5190 // If the result set is different from when this 5191 // was created, we need to clear it and re-ask the 5192 // user their preference, if we're looking for an "always" type entry. 5193 if (always && !pa.mPref.sameSet(query)) { 5194 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5195 + intent + " type " + resolvedType); 5196 if (DEBUG_PREFERRED) { 5197 Slog.v(TAG, "Removing preferred activity since set changed " 5198 + pa.mPref.mComponent); 5199 } 5200 pir.removeFilter(pa); 5201 // Re-add the filter as a "last chosen" entry (!always) 5202 PreferredActivity lastChosen = new PreferredActivity( 5203 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5204 pir.addFilter(lastChosen); 5205 changed = true; 5206 return null; 5207 } 5208 5209 // Yay! Either the set matched or we're looking for the last chosen 5210 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5211 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5212 return ri; 5213 } 5214 } 5215 } finally { 5216 if (changed) { 5217 if (DEBUG_PREFERRED) { 5218 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5219 } 5220 scheduleWritePackageRestrictionsLocked(userId); 5221 } 5222 } 5223 } 5224 } 5225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5226 return null; 5227 } 5228 5229 /* 5230 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5231 */ 5232 @Override 5233 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5234 int targetUserId) { 5235 mContext.enforceCallingOrSelfPermission( 5236 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5237 List<CrossProfileIntentFilter> matches = 5238 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5239 if (matches != null) { 5240 int size = matches.size(); 5241 for (int i = 0; i < size; i++) { 5242 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5243 } 5244 } 5245 if (hasWebURI(intent)) { 5246 // cross-profile app linking works only towards the parent. 5247 final UserInfo parent = getProfileParent(sourceUserId); 5248 synchronized(mPackages) { 5249 int flags = updateFlagsForResolve(0, parent.id, intent); 5250 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5251 intent, resolvedType, flags, sourceUserId, parent.id); 5252 return xpDomainInfo != null; 5253 } 5254 } 5255 return false; 5256 } 5257 5258 private UserInfo getProfileParent(int userId) { 5259 final long identity = Binder.clearCallingIdentity(); 5260 try { 5261 return sUserManager.getProfileParent(userId); 5262 } finally { 5263 Binder.restoreCallingIdentity(identity); 5264 } 5265 } 5266 5267 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5268 String resolvedType, int userId) { 5269 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5270 if (resolver != null) { 5271 return resolver.queryIntent(intent, resolvedType, false, userId); 5272 } 5273 return null; 5274 } 5275 5276 @Override 5277 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5278 String resolvedType, int flags, int userId) { 5279 try { 5280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5281 5282 return new ParceledListSlice<>( 5283 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5284 } finally { 5285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5286 } 5287 } 5288 5289 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5290 String resolvedType, int flags, int userId) { 5291 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5292 flags = updateFlagsForResolve(flags, userId, intent); 5293 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5294 false /* requireFullPermission */, false /* checkShell */, 5295 "query intent activities"); 5296 ComponentName comp = intent.getComponent(); 5297 if (comp == null) { 5298 if (intent.getSelector() != null) { 5299 intent = intent.getSelector(); 5300 comp = intent.getComponent(); 5301 } 5302 } 5303 5304 if (comp != null) { 5305 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5306 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5307 if (ai != null) { 5308 final ResolveInfo ri = new ResolveInfo(); 5309 ri.activityInfo = ai; 5310 list.add(ri); 5311 } 5312 return list; 5313 } 5314 5315 // reader 5316 synchronized (mPackages) { 5317 final String pkgName = intent.getPackage(); 5318 if (pkgName == null) { 5319 List<CrossProfileIntentFilter> matchingFilters = 5320 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5321 // Check for results that need to skip the current profile. 5322 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5323 resolvedType, flags, userId); 5324 if (xpResolveInfo != null) { 5325 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5326 result.add(xpResolveInfo); 5327 return filterIfNotSystemUser(result, userId); 5328 } 5329 5330 // Check for results in the current profile. 5331 List<ResolveInfo> result = mActivities.queryIntent( 5332 intent, resolvedType, flags, userId); 5333 result = filterIfNotSystemUser(result, userId); 5334 5335 // Check for cross profile results. 5336 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5337 xpResolveInfo = queryCrossProfileIntents( 5338 matchingFilters, intent, resolvedType, flags, userId, 5339 hasNonNegativePriorityResult); 5340 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5341 boolean isVisibleToUser = filterIfNotSystemUser( 5342 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5343 if (isVisibleToUser) { 5344 result.add(xpResolveInfo); 5345 Collections.sort(result, mResolvePrioritySorter); 5346 } 5347 } 5348 if (hasWebURI(intent)) { 5349 CrossProfileDomainInfo xpDomainInfo = null; 5350 final UserInfo parent = getProfileParent(userId); 5351 if (parent != null) { 5352 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5353 flags, userId, parent.id); 5354 } 5355 if (xpDomainInfo != null) { 5356 if (xpResolveInfo != null) { 5357 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5358 // in the result. 5359 result.remove(xpResolveInfo); 5360 } 5361 if (result.size() == 0) { 5362 result.add(xpDomainInfo.resolveInfo); 5363 return result; 5364 } 5365 } else if (result.size() <= 1) { 5366 return result; 5367 } 5368 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5369 xpDomainInfo, userId); 5370 Collections.sort(result, mResolvePrioritySorter); 5371 } 5372 return result; 5373 } 5374 final PackageParser.Package pkg = mPackages.get(pkgName); 5375 if (pkg != null) { 5376 return filterIfNotSystemUser( 5377 mActivities.queryIntentForPackage( 5378 intent, resolvedType, flags, pkg.activities, userId), 5379 userId); 5380 } 5381 return new ArrayList<ResolveInfo>(); 5382 } 5383 } 5384 5385 private static class CrossProfileDomainInfo { 5386 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5387 ResolveInfo resolveInfo; 5388 /* Best domain verification status of the activities found in the other profile */ 5389 int bestDomainVerificationStatus; 5390 } 5391 5392 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5393 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5394 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5395 sourceUserId)) { 5396 return null; 5397 } 5398 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5399 resolvedType, flags, parentUserId); 5400 5401 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5402 return null; 5403 } 5404 CrossProfileDomainInfo result = null; 5405 int size = resultTargetUser.size(); 5406 for (int i = 0; i < size; i++) { 5407 ResolveInfo riTargetUser = resultTargetUser.get(i); 5408 // Intent filter verification is only for filters that specify a host. So don't return 5409 // those that handle all web uris. 5410 if (riTargetUser.handleAllWebDataURI) { 5411 continue; 5412 } 5413 String packageName = riTargetUser.activityInfo.packageName; 5414 PackageSetting ps = mSettings.mPackages.get(packageName); 5415 if (ps == null) { 5416 continue; 5417 } 5418 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5419 int status = (int)(verificationState >> 32); 5420 if (result == null) { 5421 result = new CrossProfileDomainInfo(); 5422 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5423 sourceUserId, parentUserId); 5424 result.bestDomainVerificationStatus = status; 5425 } else { 5426 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5427 result.bestDomainVerificationStatus); 5428 } 5429 } 5430 // Don't consider matches with status NEVER across profiles. 5431 if (result != null && result.bestDomainVerificationStatus 5432 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5433 return null; 5434 } 5435 return result; 5436 } 5437 5438 /** 5439 * Verification statuses are ordered from the worse to the best, except for 5440 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5441 */ 5442 private int bestDomainVerificationStatus(int status1, int status2) { 5443 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5444 return status2; 5445 } 5446 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5447 return status1; 5448 } 5449 return (int) MathUtils.max(status1, status2); 5450 } 5451 5452 private boolean isUserEnabled(int userId) { 5453 long callingId = Binder.clearCallingIdentity(); 5454 try { 5455 UserInfo userInfo = sUserManager.getUserInfo(userId); 5456 return userInfo != null && userInfo.isEnabled(); 5457 } finally { 5458 Binder.restoreCallingIdentity(callingId); 5459 } 5460 } 5461 5462 /** 5463 * Filter out activities with systemUserOnly flag set, when current user is not System. 5464 * 5465 * @return filtered list 5466 */ 5467 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5468 if (userId == UserHandle.USER_SYSTEM) { 5469 return resolveInfos; 5470 } 5471 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5472 ResolveInfo info = resolveInfos.get(i); 5473 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5474 resolveInfos.remove(i); 5475 } 5476 } 5477 return resolveInfos; 5478 } 5479 5480 /** 5481 * @param resolveInfos list of resolve infos in descending priority order 5482 * @return if the list contains a resolve info with non-negative priority 5483 */ 5484 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5485 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5486 } 5487 5488 private static boolean hasWebURI(Intent intent) { 5489 if (intent.getData() == null) { 5490 return false; 5491 } 5492 final String scheme = intent.getScheme(); 5493 if (TextUtils.isEmpty(scheme)) { 5494 return false; 5495 } 5496 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5497 } 5498 5499 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5500 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5501 int userId) { 5502 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5503 5504 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5505 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5506 candidates.size()); 5507 } 5508 5509 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5510 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5511 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5512 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5513 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5514 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5515 5516 synchronized (mPackages) { 5517 final int count = candidates.size(); 5518 // First, try to use linked apps. Partition the candidates into four lists: 5519 // one for the final results, one for the "do not use ever", one for "undefined status" 5520 // and finally one for "browser app type". 5521 for (int n=0; n<count; n++) { 5522 ResolveInfo info = candidates.get(n); 5523 String packageName = info.activityInfo.packageName; 5524 PackageSetting ps = mSettings.mPackages.get(packageName); 5525 if (ps != null) { 5526 // Add to the special match all list (Browser use case) 5527 if (info.handleAllWebDataURI) { 5528 matchAllList.add(info); 5529 continue; 5530 } 5531 // Try to get the status from User settings first 5532 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5533 int status = (int)(packedStatus >> 32); 5534 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5535 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5536 if (DEBUG_DOMAIN_VERIFICATION) { 5537 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5538 + " : linkgen=" + linkGeneration); 5539 } 5540 // Use link-enabled generation as preferredOrder, i.e. 5541 // prefer newly-enabled over earlier-enabled. 5542 info.preferredOrder = linkGeneration; 5543 alwaysList.add(info); 5544 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5545 if (DEBUG_DOMAIN_VERIFICATION) { 5546 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5547 } 5548 neverList.add(info); 5549 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5550 if (DEBUG_DOMAIN_VERIFICATION) { 5551 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5552 } 5553 alwaysAskList.add(info); 5554 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5555 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5556 if (DEBUG_DOMAIN_VERIFICATION) { 5557 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5558 } 5559 undefinedList.add(info); 5560 } 5561 } 5562 } 5563 5564 // We'll want to include browser possibilities in a few cases 5565 boolean includeBrowser = false; 5566 5567 // First try to add the "always" resolution(s) for the current user, if any 5568 if (alwaysList.size() > 0) { 5569 result.addAll(alwaysList); 5570 } else { 5571 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5572 result.addAll(undefinedList); 5573 // Maybe add one for the other profile. 5574 if (xpDomainInfo != null && ( 5575 xpDomainInfo.bestDomainVerificationStatus 5576 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5577 result.add(xpDomainInfo.resolveInfo); 5578 } 5579 includeBrowser = true; 5580 } 5581 5582 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5583 // If there were 'always' entries their preferred order has been set, so we also 5584 // back that off to make the alternatives equivalent 5585 if (alwaysAskList.size() > 0) { 5586 for (ResolveInfo i : result) { 5587 i.preferredOrder = 0; 5588 } 5589 result.addAll(alwaysAskList); 5590 includeBrowser = true; 5591 } 5592 5593 if (includeBrowser) { 5594 // Also add browsers (all of them or only the default one) 5595 if (DEBUG_DOMAIN_VERIFICATION) { 5596 Slog.v(TAG, " ...including browsers in candidate set"); 5597 } 5598 if ((matchFlags & MATCH_ALL) != 0) { 5599 result.addAll(matchAllList); 5600 } else { 5601 // Browser/generic handling case. If there's a default browser, go straight 5602 // to that (but only if there is no other higher-priority match). 5603 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5604 int maxMatchPrio = 0; 5605 ResolveInfo defaultBrowserMatch = null; 5606 final int numCandidates = matchAllList.size(); 5607 for (int n = 0; n < numCandidates; n++) { 5608 ResolveInfo info = matchAllList.get(n); 5609 // track the highest overall match priority... 5610 if (info.priority > maxMatchPrio) { 5611 maxMatchPrio = info.priority; 5612 } 5613 // ...and the highest-priority default browser match 5614 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5615 if (defaultBrowserMatch == null 5616 || (defaultBrowserMatch.priority < info.priority)) { 5617 if (debug) { 5618 Slog.v(TAG, "Considering default browser match " + info); 5619 } 5620 defaultBrowserMatch = info; 5621 } 5622 } 5623 } 5624 if (defaultBrowserMatch != null 5625 && defaultBrowserMatch.priority >= maxMatchPrio 5626 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5627 { 5628 if (debug) { 5629 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5630 } 5631 result.add(defaultBrowserMatch); 5632 } else { 5633 result.addAll(matchAllList); 5634 } 5635 } 5636 5637 // If there is nothing selected, add all candidates and remove the ones that the user 5638 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5639 if (result.size() == 0) { 5640 result.addAll(candidates); 5641 result.removeAll(neverList); 5642 } 5643 } 5644 } 5645 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5646 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5647 result.size()); 5648 for (ResolveInfo info : result) { 5649 Slog.v(TAG, " + " + info.activityInfo); 5650 } 5651 } 5652 return result; 5653 } 5654 5655 // Returns a packed value as a long: 5656 // 5657 // high 'int'-sized word: link status: undefined/ask/never/always. 5658 // low 'int'-sized word: relative priority among 'always' results. 5659 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5660 long result = ps.getDomainVerificationStatusForUser(userId); 5661 // if none available, get the master status 5662 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5663 if (ps.getIntentFilterVerificationInfo() != null) { 5664 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5665 } 5666 } 5667 return result; 5668 } 5669 5670 private ResolveInfo querySkipCurrentProfileIntents( 5671 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5672 int flags, int sourceUserId) { 5673 if (matchingFilters != null) { 5674 int size = matchingFilters.size(); 5675 for (int i = 0; i < size; i ++) { 5676 CrossProfileIntentFilter filter = matchingFilters.get(i); 5677 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5678 // Checking if there are activities in the target user that can handle the 5679 // intent. 5680 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5681 resolvedType, flags, sourceUserId); 5682 if (resolveInfo != null) { 5683 return resolveInfo; 5684 } 5685 } 5686 } 5687 } 5688 return null; 5689 } 5690 5691 // Return matching ResolveInfo in target user if any. 5692 private ResolveInfo queryCrossProfileIntents( 5693 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5694 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5695 if (matchingFilters != null) { 5696 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5697 // match the same intent. For performance reasons, it is better not to 5698 // run queryIntent twice for the same userId 5699 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5700 int size = matchingFilters.size(); 5701 for (int i = 0; i < size; i++) { 5702 CrossProfileIntentFilter filter = matchingFilters.get(i); 5703 int targetUserId = filter.getTargetUserId(); 5704 boolean skipCurrentProfile = 5705 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5706 boolean skipCurrentProfileIfNoMatchFound = 5707 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5708 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5709 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5710 // Checking if there are activities in the target user that can handle the 5711 // intent. 5712 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5713 resolvedType, flags, sourceUserId); 5714 if (resolveInfo != null) return resolveInfo; 5715 alreadyTriedUserIds.put(targetUserId, true); 5716 } 5717 } 5718 } 5719 return null; 5720 } 5721 5722 /** 5723 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5724 * will forward the intent to the filter's target user. 5725 * Otherwise, returns null. 5726 */ 5727 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5728 String resolvedType, int flags, int sourceUserId) { 5729 int targetUserId = filter.getTargetUserId(); 5730 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5731 resolvedType, flags, targetUserId); 5732 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5733 // If all the matches in the target profile are suspended, return null. 5734 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5735 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5736 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5737 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5738 targetUserId); 5739 } 5740 } 5741 } 5742 return null; 5743 } 5744 5745 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5746 int sourceUserId, int targetUserId) { 5747 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5748 long ident = Binder.clearCallingIdentity(); 5749 boolean targetIsProfile; 5750 try { 5751 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5752 } finally { 5753 Binder.restoreCallingIdentity(ident); 5754 } 5755 String className; 5756 if (targetIsProfile) { 5757 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5758 } else { 5759 className = FORWARD_INTENT_TO_PARENT; 5760 } 5761 ComponentName forwardingActivityComponentName = new ComponentName( 5762 mAndroidApplication.packageName, className); 5763 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5764 sourceUserId); 5765 if (!targetIsProfile) { 5766 forwardingActivityInfo.showUserIcon = targetUserId; 5767 forwardingResolveInfo.noResourceId = true; 5768 } 5769 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5770 forwardingResolveInfo.priority = 0; 5771 forwardingResolveInfo.preferredOrder = 0; 5772 forwardingResolveInfo.match = 0; 5773 forwardingResolveInfo.isDefault = true; 5774 forwardingResolveInfo.filter = filter; 5775 forwardingResolveInfo.targetUserId = targetUserId; 5776 return forwardingResolveInfo; 5777 } 5778 5779 @Override 5780 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5781 Intent[] specifics, String[] specificTypes, Intent intent, 5782 String resolvedType, int flags, int userId) { 5783 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5784 specificTypes, intent, resolvedType, flags, userId)); 5785 } 5786 5787 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5788 Intent[] specifics, String[] specificTypes, Intent intent, 5789 String resolvedType, int flags, int userId) { 5790 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5791 flags = updateFlagsForResolve(flags, userId, intent); 5792 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5793 false /* requireFullPermission */, false /* checkShell */, 5794 "query intent activity options"); 5795 final String resultsAction = intent.getAction(); 5796 5797 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5798 | PackageManager.GET_RESOLVED_FILTER, userId); 5799 5800 if (DEBUG_INTENT_MATCHING) { 5801 Log.v(TAG, "Query " + intent + ": " + results); 5802 } 5803 5804 int specificsPos = 0; 5805 int N; 5806 5807 // todo: note that the algorithm used here is O(N^2). This 5808 // isn't a problem in our current environment, but if we start running 5809 // into situations where we have more than 5 or 10 matches then this 5810 // should probably be changed to something smarter... 5811 5812 // First we go through and resolve each of the specific items 5813 // that were supplied, taking care of removing any corresponding 5814 // duplicate items in the generic resolve list. 5815 if (specifics != null) { 5816 for (int i=0; i<specifics.length; i++) { 5817 final Intent sintent = specifics[i]; 5818 if (sintent == null) { 5819 continue; 5820 } 5821 5822 if (DEBUG_INTENT_MATCHING) { 5823 Log.v(TAG, "Specific #" + i + ": " + sintent); 5824 } 5825 5826 String action = sintent.getAction(); 5827 if (resultsAction != null && resultsAction.equals(action)) { 5828 // If this action was explicitly requested, then don't 5829 // remove things that have it. 5830 action = null; 5831 } 5832 5833 ResolveInfo ri = null; 5834 ActivityInfo ai = null; 5835 5836 ComponentName comp = sintent.getComponent(); 5837 if (comp == null) { 5838 ri = resolveIntent( 5839 sintent, 5840 specificTypes != null ? specificTypes[i] : null, 5841 flags, userId); 5842 if (ri == null) { 5843 continue; 5844 } 5845 if (ri == mResolveInfo) { 5846 // ACK! Must do something better with this. 5847 } 5848 ai = ri.activityInfo; 5849 comp = new ComponentName(ai.applicationInfo.packageName, 5850 ai.name); 5851 } else { 5852 ai = getActivityInfo(comp, flags, userId); 5853 if (ai == null) { 5854 continue; 5855 } 5856 } 5857 5858 // Look for any generic query activities that are duplicates 5859 // of this specific one, and remove them from the results. 5860 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5861 N = results.size(); 5862 int j; 5863 for (j=specificsPos; j<N; j++) { 5864 ResolveInfo sri = results.get(j); 5865 if ((sri.activityInfo.name.equals(comp.getClassName()) 5866 && sri.activityInfo.applicationInfo.packageName.equals( 5867 comp.getPackageName())) 5868 || (action != null && sri.filter.matchAction(action))) { 5869 results.remove(j); 5870 if (DEBUG_INTENT_MATCHING) Log.v( 5871 TAG, "Removing duplicate item from " + j 5872 + " due to specific " + specificsPos); 5873 if (ri == null) { 5874 ri = sri; 5875 } 5876 j--; 5877 N--; 5878 } 5879 } 5880 5881 // Add this specific item to its proper place. 5882 if (ri == null) { 5883 ri = new ResolveInfo(); 5884 ri.activityInfo = ai; 5885 } 5886 results.add(specificsPos, ri); 5887 ri.specificIndex = i; 5888 specificsPos++; 5889 } 5890 } 5891 5892 // Now we go through the remaining generic results and remove any 5893 // duplicate actions that are found here. 5894 N = results.size(); 5895 for (int i=specificsPos; i<N-1; i++) { 5896 final ResolveInfo rii = results.get(i); 5897 if (rii.filter == null) { 5898 continue; 5899 } 5900 5901 // Iterate over all of the actions of this result's intent 5902 // filter... typically this should be just one. 5903 final Iterator<String> it = rii.filter.actionsIterator(); 5904 if (it == null) { 5905 continue; 5906 } 5907 while (it.hasNext()) { 5908 final String action = it.next(); 5909 if (resultsAction != null && resultsAction.equals(action)) { 5910 // If this action was explicitly requested, then don't 5911 // remove things that have it. 5912 continue; 5913 } 5914 for (int j=i+1; j<N; j++) { 5915 final ResolveInfo rij = results.get(j); 5916 if (rij.filter != null && rij.filter.hasAction(action)) { 5917 results.remove(j); 5918 if (DEBUG_INTENT_MATCHING) Log.v( 5919 TAG, "Removing duplicate item from " + j 5920 + " due to action " + action + " at " + i); 5921 j--; 5922 N--; 5923 } 5924 } 5925 } 5926 5927 // If the caller didn't request filter information, drop it now 5928 // so we don't have to marshall/unmarshall it. 5929 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5930 rii.filter = null; 5931 } 5932 } 5933 5934 // Filter out the caller activity if so requested. 5935 if (caller != null) { 5936 N = results.size(); 5937 for (int i=0; i<N; i++) { 5938 ActivityInfo ainfo = results.get(i).activityInfo; 5939 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5940 && caller.getClassName().equals(ainfo.name)) { 5941 results.remove(i); 5942 break; 5943 } 5944 } 5945 } 5946 5947 // If the caller didn't request filter information, 5948 // drop them now so we don't have to 5949 // marshall/unmarshall it. 5950 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5951 N = results.size(); 5952 for (int i=0; i<N; i++) { 5953 results.get(i).filter = null; 5954 } 5955 } 5956 5957 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5958 return results; 5959 } 5960 5961 @Override 5962 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5963 String resolvedType, int flags, int userId) { 5964 return new ParceledListSlice<>( 5965 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5966 } 5967 5968 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5969 String resolvedType, int flags, int userId) { 5970 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5971 flags = updateFlagsForResolve(flags, userId, intent); 5972 ComponentName comp = intent.getComponent(); 5973 if (comp == null) { 5974 if (intent.getSelector() != null) { 5975 intent = intent.getSelector(); 5976 comp = intent.getComponent(); 5977 } 5978 } 5979 if (comp != null) { 5980 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5981 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5982 if (ai != null) { 5983 ResolveInfo ri = new ResolveInfo(); 5984 ri.activityInfo = ai; 5985 list.add(ri); 5986 } 5987 return list; 5988 } 5989 5990 // reader 5991 synchronized (mPackages) { 5992 String pkgName = intent.getPackage(); 5993 if (pkgName == null) { 5994 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5995 } 5996 final PackageParser.Package pkg = mPackages.get(pkgName); 5997 if (pkg != null) { 5998 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5999 userId); 6000 } 6001 return Collections.emptyList(); 6002 } 6003 } 6004 6005 @Override 6006 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6007 if (!sUserManager.exists(userId)) return null; 6008 flags = updateFlagsForResolve(flags, userId, intent); 6009 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6010 if (query != null) { 6011 if (query.size() >= 1) { 6012 // If there is more than one service with the same priority, 6013 // just arbitrarily pick the first one. 6014 return query.get(0); 6015 } 6016 } 6017 return null; 6018 } 6019 6020 @Override 6021 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6022 String resolvedType, int flags, int userId) { 6023 return new ParceledListSlice<>( 6024 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6025 } 6026 6027 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6028 String resolvedType, int flags, int userId) { 6029 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6030 flags = updateFlagsForResolve(flags, userId, intent); 6031 ComponentName comp = intent.getComponent(); 6032 if (comp == null) { 6033 if (intent.getSelector() != null) { 6034 intent = intent.getSelector(); 6035 comp = intent.getComponent(); 6036 } 6037 } 6038 if (comp != null) { 6039 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6040 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6041 if (si != null) { 6042 final ResolveInfo ri = new ResolveInfo(); 6043 ri.serviceInfo = si; 6044 list.add(ri); 6045 } 6046 return list; 6047 } 6048 6049 // reader 6050 synchronized (mPackages) { 6051 String pkgName = intent.getPackage(); 6052 if (pkgName == null) { 6053 return mServices.queryIntent(intent, resolvedType, flags, userId); 6054 } 6055 final PackageParser.Package pkg = mPackages.get(pkgName); 6056 if (pkg != null) { 6057 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6058 userId); 6059 } 6060 return Collections.emptyList(); 6061 } 6062 } 6063 6064 @Override 6065 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6066 String resolvedType, int flags, int userId) { 6067 return new ParceledListSlice<>( 6068 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6069 } 6070 6071 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6072 Intent intent, String resolvedType, int flags, int userId) { 6073 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6074 flags = updateFlagsForResolve(flags, userId, intent); 6075 ComponentName comp = intent.getComponent(); 6076 if (comp == null) { 6077 if (intent.getSelector() != null) { 6078 intent = intent.getSelector(); 6079 comp = intent.getComponent(); 6080 } 6081 } 6082 if (comp != null) { 6083 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6084 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6085 if (pi != null) { 6086 final ResolveInfo ri = new ResolveInfo(); 6087 ri.providerInfo = pi; 6088 list.add(ri); 6089 } 6090 return list; 6091 } 6092 6093 // reader 6094 synchronized (mPackages) { 6095 String pkgName = intent.getPackage(); 6096 if (pkgName == null) { 6097 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6098 } 6099 final PackageParser.Package pkg = mPackages.get(pkgName); 6100 if (pkg != null) { 6101 return mProviders.queryIntentForPackage( 6102 intent, resolvedType, flags, pkg.providers, userId); 6103 } 6104 return Collections.emptyList(); 6105 } 6106 } 6107 6108 @Override 6109 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6110 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6111 flags = updateFlagsForPackage(flags, userId, null); 6112 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6113 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6114 true /* requireFullPermission */, false /* checkShell */, 6115 "get installed packages"); 6116 6117 // writer 6118 synchronized (mPackages) { 6119 ArrayList<PackageInfo> list; 6120 if (listUninstalled) { 6121 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6122 for (PackageSetting ps : mSettings.mPackages.values()) { 6123 final PackageInfo pi; 6124 if (ps.pkg != null) { 6125 pi = generatePackageInfo(ps, flags, userId); 6126 } else { 6127 pi = generatePackageInfo(ps, flags, userId); 6128 } 6129 if (pi != null) { 6130 list.add(pi); 6131 } 6132 } 6133 } else { 6134 list = new ArrayList<PackageInfo>(mPackages.size()); 6135 for (PackageParser.Package p : mPackages.values()) { 6136 final PackageInfo pi = 6137 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6138 if (pi != null) { 6139 list.add(pi); 6140 } 6141 } 6142 } 6143 6144 return new ParceledListSlice<PackageInfo>(list); 6145 } 6146 } 6147 6148 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6149 String[] permissions, boolean[] tmp, int flags, int userId) { 6150 int numMatch = 0; 6151 final PermissionsState permissionsState = ps.getPermissionsState(); 6152 for (int i=0; i<permissions.length; i++) { 6153 final String permission = permissions[i]; 6154 if (permissionsState.hasPermission(permission, userId)) { 6155 tmp[i] = true; 6156 numMatch++; 6157 } else { 6158 tmp[i] = false; 6159 } 6160 } 6161 if (numMatch == 0) { 6162 return; 6163 } 6164 final PackageInfo pi; 6165 if (ps.pkg != null) { 6166 pi = generatePackageInfo(ps, flags, userId); 6167 } else { 6168 pi = generatePackageInfo(ps, flags, userId); 6169 } 6170 // The above might return null in cases of uninstalled apps or install-state 6171 // skew across users/profiles. 6172 if (pi != null) { 6173 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6174 if (numMatch == permissions.length) { 6175 pi.requestedPermissions = permissions; 6176 } else { 6177 pi.requestedPermissions = new String[numMatch]; 6178 numMatch = 0; 6179 for (int i=0; i<permissions.length; i++) { 6180 if (tmp[i]) { 6181 pi.requestedPermissions[numMatch] = permissions[i]; 6182 numMatch++; 6183 } 6184 } 6185 } 6186 } 6187 list.add(pi); 6188 } 6189 } 6190 6191 @Override 6192 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6193 String[] permissions, int flags, int userId) { 6194 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6195 flags = updateFlagsForPackage(flags, userId, permissions); 6196 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6197 6198 // writer 6199 synchronized (mPackages) { 6200 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6201 boolean[] tmpBools = new boolean[permissions.length]; 6202 if (listUninstalled) { 6203 for (PackageSetting ps : mSettings.mPackages.values()) { 6204 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6205 } 6206 } else { 6207 for (PackageParser.Package pkg : mPackages.values()) { 6208 PackageSetting ps = (PackageSetting)pkg.mExtras; 6209 if (ps != null) { 6210 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6211 userId); 6212 } 6213 } 6214 } 6215 6216 return new ParceledListSlice<PackageInfo>(list); 6217 } 6218 } 6219 6220 @Override 6221 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6222 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6223 flags = updateFlagsForApplication(flags, userId, null); 6224 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6225 6226 // writer 6227 synchronized (mPackages) { 6228 ArrayList<ApplicationInfo> list; 6229 if (listUninstalled) { 6230 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6231 for (PackageSetting ps : mSettings.mPackages.values()) { 6232 ApplicationInfo ai; 6233 if (ps.pkg != null) { 6234 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6235 ps.readUserState(userId), userId); 6236 } else { 6237 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6238 } 6239 if (ai != null) { 6240 list.add(ai); 6241 } 6242 } 6243 } else { 6244 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6245 for (PackageParser.Package p : mPackages.values()) { 6246 if (p.mExtras != null) { 6247 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6248 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6249 if (ai != null) { 6250 list.add(ai); 6251 } 6252 } 6253 } 6254 } 6255 6256 return new ParceledListSlice<ApplicationInfo>(list); 6257 } 6258 } 6259 6260 @Override 6261 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6262 if (DISABLE_EPHEMERAL_APPS) { 6263 return null; 6264 } 6265 6266 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6267 "getEphemeralApplications"); 6268 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6269 true /* requireFullPermission */, false /* checkShell */, 6270 "getEphemeralApplications"); 6271 synchronized (mPackages) { 6272 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6273 .getEphemeralApplicationsLPw(userId); 6274 if (ephemeralApps != null) { 6275 return new ParceledListSlice<>(ephemeralApps); 6276 } 6277 } 6278 return null; 6279 } 6280 6281 @Override 6282 public boolean isEphemeralApplication(String packageName, int userId) { 6283 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6284 true /* requireFullPermission */, false /* checkShell */, 6285 "isEphemeral"); 6286 if (DISABLE_EPHEMERAL_APPS) { 6287 return false; 6288 } 6289 6290 if (!isCallerSameApp(packageName)) { 6291 return false; 6292 } 6293 synchronized (mPackages) { 6294 PackageParser.Package pkg = mPackages.get(packageName); 6295 if (pkg != null) { 6296 return pkg.applicationInfo.isEphemeralApp(); 6297 } 6298 } 6299 return false; 6300 } 6301 6302 @Override 6303 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6304 if (DISABLE_EPHEMERAL_APPS) { 6305 return null; 6306 } 6307 6308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6309 true /* requireFullPermission */, false /* checkShell */, 6310 "getCookie"); 6311 if (!isCallerSameApp(packageName)) { 6312 return null; 6313 } 6314 synchronized (mPackages) { 6315 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6316 packageName, userId); 6317 } 6318 } 6319 6320 @Override 6321 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6322 if (DISABLE_EPHEMERAL_APPS) { 6323 return true; 6324 } 6325 6326 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6327 true /* requireFullPermission */, true /* checkShell */, 6328 "setCookie"); 6329 if (!isCallerSameApp(packageName)) { 6330 return false; 6331 } 6332 synchronized (mPackages) { 6333 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6334 packageName, cookie, userId); 6335 } 6336 } 6337 6338 @Override 6339 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6340 if (DISABLE_EPHEMERAL_APPS) { 6341 return null; 6342 } 6343 6344 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6345 "getEphemeralApplicationIcon"); 6346 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6347 true /* requireFullPermission */, false /* checkShell */, 6348 "getEphemeralApplicationIcon"); 6349 synchronized (mPackages) { 6350 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6351 packageName, userId); 6352 } 6353 } 6354 6355 private boolean isCallerSameApp(String packageName) { 6356 PackageParser.Package pkg = mPackages.get(packageName); 6357 return pkg != null 6358 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6359 } 6360 6361 @Override 6362 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6363 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6364 } 6365 6366 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6367 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6368 6369 // reader 6370 synchronized (mPackages) { 6371 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6372 final int userId = UserHandle.getCallingUserId(); 6373 while (i.hasNext()) { 6374 final PackageParser.Package p = i.next(); 6375 if (p.applicationInfo == null) continue; 6376 6377 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6378 && !p.applicationInfo.isDirectBootAware(); 6379 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6380 && p.applicationInfo.isDirectBootAware(); 6381 6382 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6383 && (!mSafeMode || isSystemApp(p)) 6384 && (matchesUnaware || matchesAware)) { 6385 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6386 if (ps != null) { 6387 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6388 ps.readUserState(userId), userId); 6389 if (ai != null) { 6390 finalList.add(ai); 6391 } 6392 } 6393 } 6394 } 6395 } 6396 6397 return finalList; 6398 } 6399 6400 @Override 6401 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6402 if (!sUserManager.exists(userId)) return null; 6403 flags = updateFlagsForComponent(flags, userId, name); 6404 // reader 6405 synchronized (mPackages) { 6406 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6407 PackageSetting ps = provider != null 6408 ? mSettings.mPackages.get(provider.owner.packageName) 6409 : null; 6410 return ps != null 6411 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6412 ? PackageParser.generateProviderInfo(provider, flags, 6413 ps.readUserState(userId), userId) 6414 : null; 6415 } 6416 } 6417 6418 /** 6419 * @deprecated 6420 */ 6421 @Deprecated 6422 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6423 // reader 6424 synchronized (mPackages) { 6425 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6426 .entrySet().iterator(); 6427 final int userId = UserHandle.getCallingUserId(); 6428 while (i.hasNext()) { 6429 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6430 PackageParser.Provider p = entry.getValue(); 6431 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6432 6433 if (ps != null && p.syncable 6434 && (!mSafeMode || (p.info.applicationInfo.flags 6435 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6436 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6437 ps.readUserState(userId), userId); 6438 if (info != null) { 6439 outNames.add(entry.getKey()); 6440 outInfo.add(info); 6441 } 6442 } 6443 } 6444 } 6445 } 6446 6447 @Override 6448 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6449 int uid, int flags) { 6450 final int userId = processName != null ? UserHandle.getUserId(uid) 6451 : UserHandle.getCallingUserId(); 6452 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6453 flags = updateFlagsForComponent(flags, userId, processName); 6454 6455 ArrayList<ProviderInfo> finalList = null; 6456 // reader 6457 synchronized (mPackages) { 6458 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6459 while (i.hasNext()) { 6460 final PackageParser.Provider p = i.next(); 6461 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6462 if (ps != null && p.info.authority != null 6463 && (processName == null 6464 || (p.info.processName.equals(processName) 6465 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6466 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6467 if (finalList == null) { 6468 finalList = new ArrayList<ProviderInfo>(3); 6469 } 6470 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6471 ps.readUserState(userId), userId); 6472 if (info != null) { 6473 finalList.add(info); 6474 } 6475 } 6476 } 6477 } 6478 6479 if (finalList != null) { 6480 Collections.sort(finalList, mProviderInitOrderSorter); 6481 return new ParceledListSlice<ProviderInfo>(finalList); 6482 } 6483 6484 return ParceledListSlice.emptyList(); 6485 } 6486 6487 @Override 6488 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6489 // reader 6490 synchronized (mPackages) { 6491 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6492 return PackageParser.generateInstrumentationInfo(i, flags); 6493 } 6494 } 6495 6496 @Override 6497 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6498 String targetPackage, int flags) { 6499 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6500 } 6501 6502 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6503 int flags) { 6504 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6505 6506 // reader 6507 synchronized (mPackages) { 6508 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6509 while (i.hasNext()) { 6510 final PackageParser.Instrumentation p = i.next(); 6511 if (targetPackage == null 6512 || targetPackage.equals(p.info.targetPackage)) { 6513 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6514 flags); 6515 if (ii != null) { 6516 finalList.add(ii); 6517 } 6518 } 6519 } 6520 } 6521 6522 return finalList; 6523 } 6524 6525 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6526 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6527 if (overlays == null) { 6528 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6529 return; 6530 } 6531 for (PackageParser.Package opkg : overlays.values()) { 6532 // Not much to do if idmap fails: we already logged the error 6533 // and we certainly don't want to abort installation of pkg simply 6534 // because an overlay didn't fit properly. For these reasons, 6535 // ignore the return value of createIdmapForPackagePairLI. 6536 createIdmapForPackagePairLI(pkg, opkg); 6537 } 6538 } 6539 6540 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6541 PackageParser.Package opkg) { 6542 if (!opkg.mTrustedOverlay) { 6543 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6544 opkg.baseCodePath + ": overlay not trusted"); 6545 return false; 6546 } 6547 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6548 if (overlaySet == null) { 6549 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6550 opkg.baseCodePath + " but target package has no known overlays"); 6551 return false; 6552 } 6553 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6554 // TODO: generate idmap for split APKs 6555 try { 6556 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6557 } catch (InstallerException e) { 6558 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6559 + opkg.baseCodePath); 6560 return false; 6561 } 6562 PackageParser.Package[] overlayArray = 6563 overlaySet.values().toArray(new PackageParser.Package[0]); 6564 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6565 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6566 return p1.mOverlayPriority - p2.mOverlayPriority; 6567 } 6568 }; 6569 Arrays.sort(overlayArray, cmp); 6570 6571 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6572 int i = 0; 6573 for (PackageParser.Package p : overlayArray) { 6574 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6575 } 6576 return true; 6577 } 6578 6579 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6580 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6581 try { 6582 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6583 } finally { 6584 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6585 } 6586 } 6587 6588 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6589 final File[] files = dir.listFiles(); 6590 if (ArrayUtils.isEmpty(files)) { 6591 Log.d(TAG, "No files in app dir " + dir); 6592 return; 6593 } 6594 6595 if (DEBUG_PACKAGE_SCANNING) { 6596 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6597 + " flags=0x" + Integer.toHexString(parseFlags)); 6598 } 6599 6600 for (File file : files) { 6601 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6602 && !PackageInstallerService.isStageName(file.getName()); 6603 if (!isPackage) { 6604 // Ignore entries which are not packages 6605 continue; 6606 } 6607 try { 6608 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6609 scanFlags, currentTime, null); 6610 } catch (PackageManagerException e) { 6611 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6612 6613 // Delete invalid userdata apps 6614 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6615 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6616 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6617 removeCodePathLI(file); 6618 } 6619 } 6620 } 6621 } 6622 6623 private static File getSettingsProblemFile() { 6624 File dataDir = Environment.getDataDirectory(); 6625 File systemDir = new File(dataDir, "system"); 6626 File fname = new File(systemDir, "uiderrors.txt"); 6627 return fname; 6628 } 6629 6630 static void reportSettingsProblem(int priority, String msg) { 6631 logCriticalInfo(priority, msg); 6632 } 6633 6634 static void logCriticalInfo(int priority, String msg) { 6635 Slog.println(priority, TAG, msg); 6636 EventLogTags.writePmCriticalInfo(msg); 6637 try { 6638 File fname = getSettingsProblemFile(); 6639 FileOutputStream out = new FileOutputStream(fname, true); 6640 PrintWriter pw = new FastPrintWriter(out); 6641 SimpleDateFormat formatter = new SimpleDateFormat(); 6642 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6643 pw.println(dateString + ": " + msg); 6644 pw.close(); 6645 FileUtils.setPermissions( 6646 fname.toString(), 6647 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6648 -1, -1); 6649 } catch (java.io.IOException e) { 6650 } 6651 } 6652 6653 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6654 final int policyFlags) throws PackageManagerException { 6655 if (ps != null 6656 && ps.codePath.equals(srcFile) 6657 && ps.timeStamp == srcFile.lastModified() 6658 && !isCompatSignatureUpdateNeeded(pkg) 6659 && !isRecoverSignatureUpdateNeeded(pkg)) { 6660 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6661 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6662 ArraySet<PublicKey> signingKs; 6663 synchronized (mPackages) { 6664 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6665 } 6666 if (ps.signatures.mSignatures != null 6667 && ps.signatures.mSignatures.length != 0 6668 && signingKs != null) { 6669 // Optimization: reuse the existing cached certificates 6670 // if the package appears to be unchanged. 6671 pkg.mSignatures = ps.signatures.mSignatures; 6672 pkg.mSigningKeys = signingKs; 6673 return; 6674 } 6675 6676 Slog.w(TAG, "PackageSetting for " + ps.name 6677 + " is missing signatures. Collecting certs again to recover them."); 6678 } else { 6679 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6680 } 6681 6682 try { 6683 PackageParser.collectCertificates(pkg, policyFlags); 6684 } catch (PackageParserException e) { 6685 throw PackageManagerException.from(e); 6686 } 6687 } 6688 6689 /** 6690 * Traces a package scan. 6691 * @see #scanPackageLI(File, int, int, long, UserHandle) 6692 */ 6693 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6694 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6695 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6696 try { 6697 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6698 } finally { 6699 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6700 } 6701 } 6702 6703 /** 6704 * Scans a package and returns the newly parsed package. 6705 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6706 */ 6707 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6708 long currentTime, UserHandle user) throws PackageManagerException { 6709 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6710 PackageParser pp = new PackageParser(); 6711 pp.setSeparateProcesses(mSeparateProcesses); 6712 pp.setOnlyCoreApps(mOnlyCore); 6713 pp.setDisplayMetrics(mMetrics); 6714 6715 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6716 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6717 } 6718 6719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6720 final PackageParser.Package pkg; 6721 try { 6722 pkg = pp.parsePackage(scanFile, parseFlags); 6723 } catch (PackageParserException e) { 6724 throw PackageManagerException.from(e); 6725 } finally { 6726 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6727 } 6728 6729 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6730 } 6731 6732 /** 6733 * Scans a package and returns the newly parsed package. 6734 * @throws PackageManagerException on a parse error. 6735 */ 6736 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6737 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6738 throws PackageManagerException { 6739 // If the package has children and this is the first dive in the function 6740 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6741 // packages (parent and children) would be successfully scanned before the 6742 // actual scan since scanning mutates internal state and we want to atomically 6743 // install the package and its children. 6744 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6745 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6746 scanFlags |= SCAN_CHECK_ONLY; 6747 } 6748 } else { 6749 scanFlags &= ~SCAN_CHECK_ONLY; 6750 } 6751 6752 // Scan the parent 6753 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6754 scanFlags, currentTime, user); 6755 6756 // Scan the children 6757 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6758 for (int i = 0; i < childCount; i++) { 6759 PackageParser.Package childPackage = pkg.childPackages.get(i); 6760 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6761 currentTime, user); 6762 } 6763 6764 6765 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6766 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6767 } 6768 6769 return scannedPkg; 6770 } 6771 6772 /** 6773 * Scans a package and returns the newly parsed package. 6774 * @throws PackageManagerException on a parse error. 6775 */ 6776 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6777 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6778 throws PackageManagerException { 6779 PackageSetting ps = null; 6780 PackageSetting updatedPkg; 6781 // reader 6782 synchronized (mPackages) { 6783 // Look to see if we already know about this package. 6784 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6785 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6786 // This package has been renamed to its original name. Let's 6787 // use that. 6788 ps = mSettings.peekPackageLPr(oldName); 6789 } 6790 // If there was no original package, see one for the real package name. 6791 if (ps == null) { 6792 ps = mSettings.peekPackageLPr(pkg.packageName); 6793 } 6794 // Check to see if this package could be hiding/updating a system 6795 // package. Must look for it either under the original or real 6796 // package name depending on our state. 6797 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6798 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6799 6800 // If this is a package we don't know about on the system partition, we 6801 // may need to remove disabled child packages on the system partition 6802 // or may need to not add child packages if the parent apk is updated 6803 // on the data partition and no longer defines this child package. 6804 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6805 // If this is a parent package for an updated system app and this system 6806 // app got an OTA update which no longer defines some of the child packages 6807 // we have to prune them from the disabled system packages. 6808 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6809 if (disabledPs != null) { 6810 final int scannedChildCount = (pkg.childPackages != null) 6811 ? pkg.childPackages.size() : 0; 6812 final int disabledChildCount = disabledPs.childPackageNames != null 6813 ? disabledPs.childPackageNames.size() : 0; 6814 for (int i = 0; i < disabledChildCount; i++) { 6815 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6816 boolean disabledPackageAvailable = false; 6817 for (int j = 0; j < scannedChildCount; j++) { 6818 PackageParser.Package childPkg = pkg.childPackages.get(j); 6819 if (childPkg.packageName.equals(disabledChildPackageName)) { 6820 disabledPackageAvailable = true; 6821 break; 6822 } 6823 } 6824 if (!disabledPackageAvailable) { 6825 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6826 } 6827 } 6828 } 6829 } 6830 } 6831 6832 boolean updatedPkgBetter = false; 6833 // First check if this is a system package that may involve an update 6834 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6835 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6836 // it needs to drop FLAG_PRIVILEGED. 6837 if (locationIsPrivileged(scanFile)) { 6838 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6839 } else { 6840 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6841 } 6842 6843 if (ps != null && !ps.codePath.equals(scanFile)) { 6844 // The path has changed from what was last scanned... check the 6845 // version of the new path against what we have stored to determine 6846 // what to do. 6847 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6848 if (pkg.mVersionCode <= ps.versionCode) { 6849 // The system package has been updated and the code path does not match 6850 // Ignore entry. Skip it. 6851 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6852 + " ignored: updated version " + ps.versionCode 6853 + " better than this " + pkg.mVersionCode); 6854 if (!updatedPkg.codePath.equals(scanFile)) { 6855 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6856 + ps.name + " changing from " + updatedPkg.codePathString 6857 + " to " + scanFile); 6858 updatedPkg.codePath = scanFile; 6859 updatedPkg.codePathString = scanFile.toString(); 6860 updatedPkg.resourcePath = scanFile; 6861 updatedPkg.resourcePathString = scanFile.toString(); 6862 } 6863 updatedPkg.pkg = pkg; 6864 updatedPkg.versionCode = pkg.mVersionCode; 6865 6866 // Update the disabled system child packages to point to the package too. 6867 final int childCount = updatedPkg.childPackageNames != null 6868 ? updatedPkg.childPackageNames.size() : 0; 6869 for (int i = 0; i < childCount; i++) { 6870 String childPackageName = updatedPkg.childPackageNames.get(i); 6871 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6872 childPackageName); 6873 if (updatedChildPkg != null) { 6874 updatedChildPkg.pkg = pkg; 6875 updatedChildPkg.versionCode = pkg.mVersionCode; 6876 } 6877 } 6878 6879 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6880 + scanFile + " ignored: updated version " + ps.versionCode 6881 + " better than this " + pkg.mVersionCode); 6882 } else { 6883 // The current app on the system partition is better than 6884 // what we have updated to on the data partition; switch 6885 // back to the system partition version. 6886 // At this point, its safely assumed that package installation for 6887 // apps in system partition will go through. If not there won't be a working 6888 // version of the app 6889 // writer 6890 synchronized (mPackages) { 6891 // Just remove the loaded entries from package lists. 6892 mPackages.remove(ps.name); 6893 } 6894 6895 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6896 + " reverting from " + ps.codePathString 6897 + ": new version " + pkg.mVersionCode 6898 + " better than installed " + ps.versionCode); 6899 6900 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6901 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6902 synchronized (mInstallLock) { 6903 args.cleanUpResourcesLI(); 6904 } 6905 synchronized (mPackages) { 6906 mSettings.enableSystemPackageLPw(ps.name); 6907 } 6908 updatedPkgBetter = true; 6909 } 6910 } 6911 } 6912 6913 if (updatedPkg != null) { 6914 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6915 // initially 6916 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6917 6918 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6919 // flag set initially 6920 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6921 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6922 } 6923 } 6924 6925 // Verify certificates against what was last scanned 6926 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6927 6928 /* 6929 * A new system app appeared, but we already had a non-system one of the 6930 * same name installed earlier. 6931 */ 6932 boolean shouldHideSystemApp = false; 6933 if (updatedPkg == null && ps != null 6934 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6935 /* 6936 * Check to make sure the signatures match first. If they don't, 6937 * wipe the installed application and its data. 6938 */ 6939 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6940 != PackageManager.SIGNATURE_MATCH) { 6941 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6942 + " signatures don't match existing userdata copy; removing"); 6943 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6944 "scanPackageInternalLI")) { 6945 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6946 } 6947 ps = null; 6948 } else { 6949 /* 6950 * If the newly-added system app is an older version than the 6951 * already installed version, hide it. It will be scanned later 6952 * and re-added like an update. 6953 */ 6954 if (pkg.mVersionCode <= ps.versionCode) { 6955 shouldHideSystemApp = true; 6956 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6957 + " but new version " + pkg.mVersionCode + " better than installed " 6958 + ps.versionCode + "; hiding system"); 6959 } else { 6960 /* 6961 * The newly found system app is a newer version that the 6962 * one previously installed. Simply remove the 6963 * already-installed application and replace it with our own 6964 * while keeping the application data. 6965 */ 6966 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6967 + " reverting from " + ps.codePathString + ": new version " 6968 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6969 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6970 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6971 synchronized (mInstallLock) { 6972 args.cleanUpResourcesLI(); 6973 } 6974 } 6975 } 6976 } 6977 6978 // The apk is forward locked (not public) if its code and resources 6979 // are kept in different files. (except for app in either system or 6980 // vendor path). 6981 // TODO grab this value from PackageSettings 6982 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6983 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6984 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6985 } 6986 } 6987 6988 // TODO: extend to support forward-locked splits 6989 String resourcePath = null; 6990 String baseResourcePath = null; 6991 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6992 if (ps != null && ps.resourcePathString != null) { 6993 resourcePath = ps.resourcePathString; 6994 baseResourcePath = ps.resourcePathString; 6995 } else { 6996 // Should not happen at all. Just log an error. 6997 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6998 } 6999 } else { 7000 resourcePath = pkg.codePath; 7001 baseResourcePath = pkg.baseCodePath; 7002 } 7003 7004 // Set application objects path explicitly. 7005 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7006 pkg.setApplicationInfoCodePath(pkg.codePath); 7007 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7008 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7009 pkg.setApplicationInfoResourcePath(resourcePath); 7010 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7011 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7012 7013 // Note that we invoke the following method only if we are about to unpack an application 7014 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7015 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7016 7017 /* 7018 * If the system app should be overridden by a previously installed 7019 * data, hide the system app now and let the /data/app scan pick it up 7020 * again. 7021 */ 7022 if (shouldHideSystemApp) { 7023 synchronized (mPackages) { 7024 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7025 } 7026 } 7027 7028 return scannedPkg; 7029 } 7030 7031 private static String fixProcessName(String defProcessName, 7032 String processName, int uid) { 7033 if (processName == null) { 7034 return defProcessName; 7035 } 7036 return processName; 7037 } 7038 7039 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7040 throws PackageManagerException { 7041 if (pkgSetting.signatures.mSignatures != null) { 7042 // Already existing package. Make sure signatures match 7043 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7044 == PackageManager.SIGNATURE_MATCH; 7045 if (!match) { 7046 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7047 == PackageManager.SIGNATURE_MATCH; 7048 } 7049 if (!match) { 7050 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7051 == PackageManager.SIGNATURE_MATCH; 7052 } 7053 if (!match) { 7054 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7055 + pkg.packageName + " signatures do not match the " 7056 + "previously installed version; ignoring!"); 7057 } 7058 } 7059 7060 // Check for shared user signatures 7061 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7062 // Already existing package. Make sure signatures match 7063 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7064 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7065 if (!match) { 7066 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7067 == PackageManager.SIGNATURE_MATCH; 7068 } 7069 if (!match) { 7070 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7071 == PackageManager.SIGNATURE_MATCH; 7072 } 7073 if (!match) { 7074 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7075 "Package " + pkg.packageName 7076 + " has no signatures that match those in shared user " 7077 + pkgSetting.sharedUser.name + "; ignoring!"); 7078 } 7079 } 7080 } 7081 7082 /** 7083 * Enforces that only the system UID or root's UID can call a method exposed 7084 * via Binder. 7085 * 7086 * @param message used as message if SecurityException is thrown 7087 * @throws SecurityException if the caller is not system or root 7088 */ 7089 private static final void enforceSystemOrRoot(String message) { 7090 final int uid = Binder.getCallingUid(); 7091 if (uid != Process.SYSTEM_UID && uid != 0) { 7092 throw new SecurityException(message); 7093 } 7094 } 7095 7096 @Override 7097 public void performFstrimIfNeeded() { 7098 enforceSystemOrRoot("Only the system can request fstrim"); 7099 7100 // Before everything else, see whether we need to fstrim. 7101 try { 7102 IMountService ms = PackageHelper.getMountService(); 7103 if (ms != null) { 7104 final boolean isUpgrade = isUpgrade(); 7105 boolean doTrim = isUpgrade; 7106 if (doTrim) { 7107 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7108 } else { 7109 final long interval = android.provider.Settings.Global.getLong( 7110 mContext.getContentResolver(), 7111 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7112 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7113 if (interval > 0) { 7114 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7115 if (timeSinceLast > interval) { 7116 doTrim = true; 7117 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7118 + "; running immediately"); 7119 } 7120 } 7121 } 7122 if (doTrim) { 7123 if (!isFirstBoot()) { 7124 try { 7125 ActivityManagerNative.getDefault().showBootMessage( 7126 mContext.getResources().getString( 7127 R.string.android_upgrading_fstrim), true); 7128 } catch (RemoteException e) { 7129 } 7130 } 7131 ms.runMaintenance(); 7132 } 7133 } else { 7134 Slog.e(TAG, "Mount service unavailable!"); 7135 } 7136 } catch (RemoteException e) { 7137 // Can't happen; MountService is local 7138 } 7139 } 7140 7141 @Override 7142 public void updatePackagesIfNeeded() { 7143 enforceSystemOrRoot("Only the system can request package update"); 7144 7145 // We need to re-extract after an OTA. 7146 boolean causeUpgrade = isUpgrade(); 7147 7148 // First boot or factory reset. 7149 // Note: we also handle devices that are upgrading to N right now as if it is their 7150 // first boot, as they do not have profile data. 7151 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7152 7153 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7154 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7155 7156 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7157 return; 7158 } 7159 7160 List<PackageParser.Package> pkgs; 7161 synchronized (mPackages) { 7162 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7163 } 7164 7165 int curr = 0; 7166 int total = pkgs.size(); 7167 for (PackageParser.Package pkg : pkgs) { 7168 curr++; 7169 7170 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7171 if (DEBUG_DEXOPT) { 7172 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7173 } 7174 continue; 7175 } 7176 7177 if (DEBUG_DEXOPT) { 7178 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7179 } 7180 7181 if (!isFirstBoot()) { 7182 try { 7183 ActivityManagerNative.getDefault().showBootMessage( 7184 mContext.getResources().getString(R.string.android_upgrading_apk, 7185 curr, total), true); 7186 } catch (RemoteException e) { 7187 } 7188 } 7189 7190 performDexOpt(pkg.packageName, 7191 null /* instructionSet */, 7192 true /* checkProfiles */, 7193 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7194 false /* force */); 7195 } 7196 } 7197 7198 @Override 7199 public void notifyPackageUse(String packageName, int reason) { 7200 synchronized (mPackages) { 7201 PackageParser.Package p = mPackages.get(packageName); 7202 if (p == null) { 7203 return; 7204 } 7205 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7206 } 7207 } 7208 7209 // TODO: this is not used nor needed. Delete it. 7210 @Override 7211 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7212 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7213 getFullCompilerFilter(), false /* force */); 7214 } 7215 7216 @Override 7217 public boolean performDexOpt(String packageName, String instructionSet, 7218 boolean checkProfiles, int compileReason, boolean force) { 7219 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7220 getCompilerFilterForReason(compileReason), force); 7221 } 7222 7223 @Override 7224 public boolean performDexOptMode(String packageName, String instructionSet, 7225 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7226 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7227 targetCompilerFilter, force); 7228 } 7229 7230 private boolean performDexOptTraced(String packageName, String instructionSet, 7231 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7232 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7233 try { 7234 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7235 targetCompilerFilter, force); 7236 } finally { 7237 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7238 } 7239 } 7240 7241 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7242 // if the package can now be considered up to date for the given filter. 7243 private boolean performDexOptInternal(String packageName, String instructionSet, 7244 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7245 PackageParser.Package p; 7246 final String targetInstructionSet; 7247 synchronized (mPackages) { 7248 p = mPackages.get(packageName); 7249 if (p == null) { 7250 return false; 7251 } 7252 mPackageUsage.write(false); 7253 7254 targetInstructionSet = instructionSet != null ? instructionSet : 7255 getPrimaryInstructionSet(p.applicationInfo); 7256 } 7257 long callingId = Binder.clearCallingIdentity(); 7258 try { 7259 synchronized (mInstallLock) { 7260 final String[] instructionSets = new String[] { targetInstructionSet }; 7261 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7262 checkProfiles, targetCompilerFilter, force); 7263 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7264 } 7265 } finally { 7266 Binder.restoreCallingIdentity(callingId); 7267 } 7268 } 7269 7270 public ArraySet<String> getOptimizablePackages() { 7271 ArraySet<String> pkgs = new ArraySet<String>(); 7272 synchronized (mPackages) { 7273 for (PackageParser.Package p : mPackages.values()) { 7274 if (PackageDexOptimizer.canOptimizePackage(p)) { 7275 pkgs.add(p.packageName); 7276 } 7277 } 7278 } 7279 return pkgs; 7280 } 7281 7282 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7283 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7284 boolean force) { 7285 // Select the dex optimizer based on the force parameter. 7286 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7287 // allocate an object here. 7288 PackageDexOptimizer pdo = force 7289 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7290 : mPackageDexOptimizer; 7291 7292 // Optimize all dependencies first. Note: we ignore the return value and march on 7293 // on errors. 7294 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7295 if (!deps.isEmpty()) { 7296 for (PackageParser.Package depPackage : deps) { 7297 // TODO: Analyze and investigate if we (should) profile libraries. 7298 // Currently this will do a full compilation of the library by default. 7299 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7300 false /* checkProfiles */, 7301 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7302 } 7303 } 7304 7305 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7306 targetCompilerFilter); 7307 } 7308 7309 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7310 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7311 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7312 Set<String> collectedNames = new HashSet<>(); 7313 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7314 7315 retValue.remove(p); 7316 7317 return retValue; 7318 } else { 7319 return Collections.emptyList(); 7320 } 7321 } 7322 7323 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7324 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7325 if (!collectedNames.contains(p.packageName)) { 7326 collectedNames.add(p.packageName); 7327 collected.add(p); 7328 7329 if (p.usesLibraries != null) { 7330 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7331 } 7332 if (p.usesOptionalLibraries != null) { 7333 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7334 collectedNames); 7335 } 7336 } 7337 } 7338 7339 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7340 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7341 for (String libName : libs) { 7342 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7343 if (libPkg != null) { 7344 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7345 } 7346 } 7347 } 7348 7349 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7350 synchronized (mPackages) { 7351 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7352 if (lib != null && lib.apk != null) { 7353 return mPackages.get(lib.apk); 7354 } 7355 } 7356 return null; 7357 } 7358 7359 public void shutdown() { 7360 mPackageUsage.write(true); 7361 } 7362 7363 @Override 7364 public void forceDexOpt(String packageName) { 7365 enforceSystemOrRoot("forceDexOpt"); 7366 7367 PackageParser.Package pkg; 7368 synchronized (mPackages) { 7369 pkg = mPackages.get(packageName); 7370 if (pkg == null) { 7371 throw new IllegalArgumentException("Unknown package: " + packageName); 7372 } 7373 } 7374 7375 synchronized (mInstallLock) { 7376 final String[] instructionSets = new String[] { 7377 getPrimaryInstructionSet(pkg.applicationInfo) }; 7378 7379 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7380 7381 // Whoever is calling forceDexOpt wants a fully compiled package. 7382 // Don't use profiles since that may cause compilation to be skipped. 7383 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7384 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7385 true /* force */); 7386 7387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7388 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7389 throw new IllegalStateException("Failed to dexopt: " + res); 7390 } 7391 } 7392 } 7393 7394 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7395 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7396 Slog.w(TAG, "Unable to update from " + oldPkg.name 7397 + " to " + newPkg.packageName 7398 + ": old package not in system partition"); 7399 return false; 7400 } else if (mPackages.get(oldPkg.name) != null) { 7401 Slog.w(TAG, "Unable to update from " + oldPkg.name 7402 + " to " + newPkg.packageName 7403 + ": old package still exists"); 7404 return false; 7405 } 7406 return true; 7407 } 7408 7409 void removeCodePathLI(File codePath) { 7410 if (codePath.isDirectory()) { 7411 try { 7412 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7413 } catch (InstallerException e) { 7414 Slog.w(TAG, "Failed to remove code path", e); 7415 } 7416 } else { 7417 codePath.delete(); 7418 } 7419 } 7420 7421 private int[] resolveUserIds(int userId) { 7422 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7423 } 7424 7425 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7426 if (pkg == null) { 7427 Slog.wtf(TAG, "Package was null!", new Throwable()); 7428 return; 7429 } 7430 clearAppDataLeafLIF(pkg, userId, flags); 7431 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7432 for (int i = 0; i < childCount; i++) { 7433 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7434 } 7435 } 7436 7437 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7438 final PackageSetting ps; 7439 synchronized (mPackages) { 7440 ps = mSettings.mPackages.get(pkg.packageName); 7441 } 7442 for (int realUserId : resolveUserIds(userId)) { 7443 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7444 try { 7445 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7446 ceDataInode); 7447 } catch (InstallerException e) { 7448 Slog.w(TAG, String.valueOf(e)); 7449 } 7450 } 7451 } 7452 7453 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7454 if (pkg == null) { 7455 Slog.wtf(TAG, "Package was null!", new Throwable()); 7456 return; 7457 } 7458 destroyAppDataLeafLIF(pkg, userId, flags); 7459 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7460 for (int i = 0; i < childCount; i++) { 7461 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7462 } 7463 } 7464 7465 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7466 final PackageSetting ps; 7467 synchronized (mPackages) { 7468 ps = mSettings.mPackages.get(pkg.packageName); 7469 } 7470 for (int realUserId : resolveUserIds(userId)) { 7471 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7472 try { 7473 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7474 ceDataInode); 7475 } catch (InstallerException e) { 7476 Slog.w(TAG, String.valueOf(e)); 7477 } 7478 } 7479 } 7480 7481 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7482 if (pkg == null) { 7483 Slog.wtf(TAG, "Package was null!", new Throwable()); 7484 return; 7485 } 7486 destroyAppProfilesLeafLIF(pkg); 7487 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7488 for (int i = 0; i < childCount; i++) { 7489 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7490 } 7491 } 7492 7493 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7494 try { 7495 mInstaller.destroyAppProfiles(pkg.packageName); 7496 } catch (InstallerException e) { 7497 Slog.w(TAG, String.valueOf(e)); 7498 } 7499 } 7500 7501 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7502 if (pkg == null) { 7503 Slog.wtf(TAG, "Package was null!", new Throwable()); 7504 return; 7505 } 7506 clearAppProfilesLeafLIF(pkg); 7507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7508 for (int i = 0; i < childCount; i++) { 7509 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7510 } 7511 } 7512 7513 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7514 try { 7515 mInstaller.clearAppProfiles(pkg.packageName); 7516 } catch (InstallerException e) { 7517 Slog.w(TAG, String.valueOf(e)); 7518 } 7519 } 7520 7521 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7522 long lastUpdateTime) { 7523 // Set parent install/update time 7524 PackageSetting ps = (PackageSetting) pkg.mExtras; 7525 if (ps != null) { 7526 ps.firstInstallTime = firstInstallTime; 7527 ps.lastUpdateTime = lastUpdateTime; 7528 } 7529 // Set children install/update time 7530 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7531 for (int i = 0; i < childCount; i++) { 7532 PackageParser.Package childPkg = pkg.childPackages.get(i); 7533 ps = (PackageSetting) childPkg.mExtras; 7534 if (ps != null) { 7535 ps.firstInstallTime = firstInstallTime; 7536 ps.lastUpdateTime = lastUpdateTime; 7537 } 7538 } 7539 } 7540 7541 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7542 PackageParser.Package changingLib) { 7543 if (file.path != null) { 7544 usesLibraryFiles.add(file.path); 7545 return; 7546 } 7547 PackageParser.Package p = mPackages.get(file.apk); 7548 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7549 // If we are doing this while in the middle of updating a library apk, 7550 // then we need to make sure to use that new apk for determining the 7551 // dependencies here. (We haven't yet finished committing the new apk 7552 // to the package manager state.) 7553 if (p == null || p.packageName.equals(changingLib.packageName)) { 7554 p = changingLib; 7555 } 7556 } 7557 if (p != null) { 7558 usesLibraryFiles.addAll(p.getAllCodePaths()); 7559 } 7560 } 7561 7562 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7563 PackageParser.Package changingLib) throws PackageManagerException { 7564 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7565 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7566 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7567 for (int i=0; i<N; i++) { 7568 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7569 if (file == null) { 7570 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7571 "Package " + pkg.packageName + " requires unavailable shared library " 7572 + pkg.usesLibraries.get(i) + "; failing!"); 7573 } 7574 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7575 } 7576 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7577 for (int i=0; i<N; i++) { 7578 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7579 if (file == null) { 7580 Slog.w(TAG, "Package " + pkg.packageName 7581 + " desires unavailable shared library " 7582 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7583 } else { 7584 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7585 } 7586 } 7587 N = usesLibraryFiles.size(); 7588 if (N > 0) { 7589 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7590 } else { 7591 pkg.usesLibraryFiles = null; 7592 } 7593 } 7594 } 7595 7596 private static boolean hasString(List<String> list, List<String> which) { 7597 if (list == null) { 7598 return false; 7599 } 7600 for (int i=list.size()-1; i>=0; i--) { 7601 for (int j=which.size()-1; j>=0; j--) { 7602 if (which.get(j).equals(list.get(i))) { 7603 return true; 7604 } 7605 } 7606 } 7607 return false; 7608 } 7609 7610 private void updateAllSharedLibrariesLPw() { 7611 for (PackageParser.Package pkg : mPackages.values()) { 7612 try { 7613 updateSharedLibrariesLPw(pkg, null); 7614 } catch (PackageManagerException e) { 7615 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7616 } 7617 } 7618 } 7619 7620 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7621 PackageParser.Package changingPkg) { 7622 ArrayList<PackageParser.Package> res = null; 7623 for (PackageParser.Package pkg : mPackages.values()) { 7624 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7625 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7626 if (res == null) { 7627 res = new ArrayList<PackageParser.Package>(); 7628 } 7629 res.add(pkg); 7630 try { 7631 updateSharedLibrariesLPw(pkg, changingPkg); 7632 } catch (PackageManagerException e) { 7633 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7634 } 7635 } 7636 } 7637 return res; 7638 } 7639 7640 /** 7641 * Derive the value of the {@code cpuAbiOverride} based on the provided 7642 * value and an optional stored value from the package settings. 7643 */ 7644 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7645 String cpuAbiOverride = null; 7646 7647 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7648 cpuAbiOverride = null; 7649 } else if (abiOverride != null) { 7650 cpuAbiOverride = abiOverride; 7651 } else if (settings != null) { 7652 cpuAbiOverride = settings.cpuAbiOverrideString; 7653 } 7654 7655 return cpuAbiOverride; 7656 } 7657 7658 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7659 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7660 throws PackageManagerException { 7661 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7662 // If the package has children and this is the first dive in the function 7663 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7664 // whether all packages (parent and children) would be successfully scanned 7665 // before the actual scan since scanning mutates internal state and we want 7666 // to atomically install the package and its children. 7667 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7668 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7669 scanFlags |= SCAN_CHECK_ONLY; 7670 } 7671 } else { 7672 scanFlags &= ~SCAN_CHECK_ONLY; 7673 } 7674 7675 final PackageParser.Package scannedPkg; 7676 try { 7677 // Scan the parent 7678 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7679 // Scan the children 7680 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7681 for (int i = 0; i < childCount; i++) { 7682 PackageParser.Package childPkg = pkg.childPackages.get(i); 7683 scanPackageLI(childPkg, policyFlags, 7684 scanFlags, currentTime, user); 7685 } 7686 } finally { 7687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7688 } 7689 7690 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7691 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7692 } 7693 7694 return scannedPkg; 7695 } 7696 7697 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7698 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7699 boolean success = false; 7700 try { 7701 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7702 currentTime, user); 7703 success = true; 7704 return res; 7705 } finally { 7706 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7707 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7708 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7709 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7710 destroyAppProfilesLIF(pkg); 7711 } 7712 } 7713 } 7714 7715 /** 7716 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7717 */ 7718 private static boolean apkHasCode(String fileName) { 7719 StrictJarFile jarFile = null; 7720 try { 7721 jarFile = new StrictJarFile(fileName, 7722 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7723 return jarFile.findEntry("classes.dex") != null; 7724 } catch (IOException ignore) { 7725 } finally { 7726 try { 7727 jarFile.close(); 7728 } catch (IOException ignore) {} 7729 } 7730 return false; 7731 } 7732 7733 /** 7734 * Enforces code policy for the package. This ensures that if an APK has 7735 * declared hasCode="true" in its manifest that the APK actually contains 7736 * code. 7737 * 7738 * @throws PackageManagerException If bytecode could not be found when it should exist 7739 */ 7740 private static void enforceCodePolicy(PackageParser.Package pkg) 7741 throws PackageManagerException { 7742 final boolean shouldHaveCode = 7743 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7744 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7745 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7746 "Package " + pkg.baseCodePath + " code is missing"); 7747 } 7748 7749 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7750 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7751 final boolean splitShouldHaveCode = 7752 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7753 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7754 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7755 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7756 } 7757 } 7758 } 7759 } 7760 7761 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7762 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7763 throws PackageManagerException { 7764 final File scanFile = new File(pkg.codePath); 7765 if (pkg.applicationInfo.getCodePath() == null || 7766 pkg.applicationInfo.getResourcePath() == null) { 7767 // Bail out. The resource and code paths haven't been set. 7768 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7769 "Code and resource paths haven't been set correctly"); 7770 } 7771 7772 // Apply policy 7773 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7774 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7775 if (pkg.applicationInfo.isDirectBootAware()) { 7776 // we're direct boot aware; set for all components 7777 for (PackageParser.Service s : pkg.services) { 7778 s.info.encryptionAware = s.info.directBootAware = true; 7779 } 7780 for (PackageParser.Provider p : pkg.providers) { 7781 p.info.encryptionAware = p.info.directBootAware = true; 7782 } 7783 for (PackageParser.Activity a : pkg.activities) { 7784 a.info.encryptionAware = a.info.directBootAware = true; 7785 } 7786 for (PackageParser.Activity r : pkg.receivers) { 7787 r.info.encryptionAware = r.info.directBootAware = true; 7788 } 7789 } 7790 } else { 7791 // Only allow system apps to be flagged as core apps. 7792 pkg.coreApp = false; 7793 // clear flags not applicable to regular apps 7794 pkg.applicationInfo.privateFlags &= 7795 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7796 pkg.applicationInfo.privateFlags &= 7797 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7798 } 7799 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7800 7801 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7802 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7803 } 7804 7805 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7806 enforceCodePolicy(pkg); 7807 } 7808 7809 if (mCustomResolverComponentName != null && 7810 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7811 setUpCustomResolverActivity(pkg); 7812 } 7813 7814 if (pkg.packageName.equals("android")) { 7815 synchronized (mPackages) { 7816 if (mAndroidApplication != null) { 7817 Slog.w(TAG, "*************************************************"); 7818 Slog.w(TAG, "Core android package being redefined. Skipping."); 7819 Slog.w(TAG, " file=" + scanFile); 7820 Slog.w(TAG, "*************************************************"); 7821 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7822 "Core android package being redefined. Skipping."); 7823 } 7824 7825 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7826 // Set up information for our fall-back user intent resolution activity. 7827 mPlatformPackage = pkg; 7828 pkg.mVersionCode = mSdkVersion; 7829 mAndroidApplication = pkg.applicationInfo; 7830 7831 if (!mResolverReplaced) { 7832 mResolveActivity.applicationInfo = mAndroidApplication; 7833 mResolveActivity.name = ResolverActivity.class.getName(); 7834 mResolveActivity.packageName = mAndroidApplication.packageName; 7835 mResolveActivity.processName = "system:ui"; 7836 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7837 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7838 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7839 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7840 mResolveActivity.exported = true; 7841 mResolveActivity.enabled = true; 7842 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7843 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7844 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7845 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7846 | ActivityInfo.CONFIG_ORIENTATION 7847 | ActivityInfo.CONFIG_KEYBOARD 7848 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7849 mResolveInfo.activityInfo = mResolveActivity; 7850 mResolveInfo.priority = 0; 7851 mResolveInfo.preferredOrder = 0; 7852 mResolveInfo.match = 0; 7853 mResolveComponentName = new ComponentName( 7854 mAndroidApplication.packageName, mResolveActivity.name); 7855 } 7856 } 7857 } 7858 } 7859 7860 if (DEBUG_PACKAGE_SCANNING) { 7861 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7862 Log.d(TAG, "Scanning package " + pkg.packageName); 7863 } 7864 7865 synchronized (mPackages) { 7866 if (mPackages.containsKey(pkg.packageName) 7867 || mSharedLibraries.containsKey(pkg.packageName)) { 7868 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7869 "Application package " + pkg.packageName 7870 + " already installed. Skipping duplicate."); 7871 } 7872 7873 // If we're only installing presumed-existing packages, require that the 7874 // scanned APK is both already known and at the path previously established 7875 // for it. Previously unknown packages we pick up normally, but if we have an 7876 // a priori expectation about this package's install presence, enforce it. 7877 // With a singular exception for new system packages. When an OTA contains 7878 // a new system package, we allow the codepath to change from a system location 7879 // to the user-installed location. If we don't allow this change, any newer, 7880 // user-installed version of the application will be ignored. 7881 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7882 if (mExpectingBetter.containsKey(pkg.packageName)) { 7883 logCriticalInfo(Log.WARN, 7884 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7885 } else { 7886 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7887 if (known != null) { 7888 if (DEBUG_PACKAGE_SCANNING) { 7889 Log.d(TAG, "Examining " + pkg.codePath 7890 + " and requiring known paths " + known.codePathString 7891 + " & " + known.resourcePathString); 7892 } 7893 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7894 || !pkg.applicationInfo.getResourcePath().equals( 7895 known.resourcePathString)) { 7896 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7897 "Application package " + pkg.packageName 7898 + " found at " + pkg.applicationInfo.getCodePath() 7899 + " but expected at " + known.codePathString 7900 + "; ignoring."); 7901 } 7902 } 7903 } 7904 } 7905 } 7906 7907 // Initialize package source and resource directories 7908 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7909 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7910 7911 SharedUserSetting suid = null; 7912 PackageSetting pkgSetting = null; 7913 7914 if (!isSystemApp(pkg)) { 7915 // Only system apps can use these features. 7916 pkg.mOriginalPackages = null; 7917 pkg.mRealPackage = null; 7918 pkg.mAdoptPermissions = null; 7919 } 7920 7921 // Getting the package setting may have a side-effect, so if we 7922 // are only checking if scan would succeed, stash a copy of the 7923 // old setting to restore at the end. 7924 PackageSetting nonMutatedPs = null; 7925 7926 // writer 7927 synchronized (mPackages) { 7928 if (pkg.mSharedUserId != null) { 7929 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7930 if (suid == null) { 7931 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7932 "Creating application package " + pkg.packageName 7933 + " for shared user failed"); 7934 } 7935 if (DEBUG_PACKAGE_SCANNING) { 7936 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7937 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7938 + "): packages=" + suid.packages); 7939 } 7940 } 7941 7942 // Check if we are renaming from an original package name. 7943 PackageSetting origPackage = null; 7944 String realName = null; 7945 if (pkg.mOriginalPackages != null) { 7946 // This package may need to be renamed to a previously 7947 // installed name. Let's check on that... 7948 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7949 if (pkg.mOriginalPackages.contains(renamed)) { 7950 // This package had originally been installed as the 7951 // original name, and we have already taken care of 7952 // transitioning to the new one. Just update the new 7953 // one to continue using the old name. 7954 realName = pkg.mRealPackage; 7955 if (!pkg.packageName.equals(renamed)) { 7956 // Callers into this function may have already taken 7957 // care of renaming the package; only do it here if 7958 // it is not already done. 7959 pkg.setPackageName(renamed); 7960 } 7961 7962 } else { 7963 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7964 if ((origPackage = mSettings.peekPackageLPr( 7965 pkg.mOriginalPackages.get(i))) != null) { 7966 // We do have the package already installed under its 7967 // original name... should we use it? 7968 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7969 // New package is not compatible with original. 7970 origPackage = null; 7971 continue; 7972 } else if (origPackage.sharedUser != null) { 7973 // Make sure uid is compatible between packages. 7974 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7975 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7976 + " to " + pkg.packageName + ": old uid " 7977 + origPackage.sharedUser.name 7978 + " differs from " + pkg.mSharedUserId); 7979 origPackage = null; 7980 continue; 7981 } 7982 // TODO: Add case when shared user id is added [b/28144775] 7983 } else { 7984 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7985 + pkg.packageName + " to old name " + origPackage.name); 7986 } 7987 break; 7988 } 7989 } 7990 } 7991 } 7992 7993 if (mTransferedPackages.contains(pkg.packageName)) { 7994 Slog.w(TAG, "Package " + pkg.packageName 7995 + " was transferred to another, but its .apk remains"); 7996 } 7997 7998 // See comments in nonMutatedPs declaration 7999 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8000 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8001 if (foundPs != null) { 8002 nonMutatedPs = new PackageSetting(foundPs); 8003 } 8004 } 8005 8006 // Just create the setting, don't add it yet. For already existing packages 8007 // the PkgSetting exists already and doesn't have to be created. 8008 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8009 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8010 pkg.applicationInfo.primaryCpuAbi, 8011 pkg.applicationInfo.secondaryCpuAbi, 8012 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8013 user, false); 8014 if (pkgSetting == null) { 8015 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8016 "Creating application package " + pkg.packageName + " failed"); 8017 } 8018 8019 if (pkgSetting.origPackage != null) { 8020 // If we are first transitioning from an original package, 8021 // fix up the new package's name now. We need to do this after 8022 // looking up the package under its new name, so getPackageLP 8023 // can take care of fiddling things correctly. 8024 pkg.setPackageName(origPackage.name); 8025 8026 // File a report about this. 8027 String msg = "New package " + pkgSetting.realName 8028 + " renamed to replace old package " + pkgSetting.name; 8029 reportSettingsProblem(Log.WARN, msg); 8030 8031 // Make a note of it. 8032 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8033 mTransferedPackages.add(origPackage.name); 8034 } 8035 8036 // No longer need to retain this. 8037 pkgSetting.origPackage = null; 8038 } 8039 8040 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8041 // Make a note of it. 8042 mTransferedPackages.add(pkg.packageName); 8043 } 8044 8045 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8047 } 8048 8049 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8050 // Check all shared libraries and map to their actual file path. 8051 // We only do this here for apps not on a system dir, because those 8052 // are the only ones that can fail an install due to this. We 8053 // will take care of the system apps by updating all of their 8054 // library paths after the scan is done. 8055 updateSharedLibrariesLPw(pkg, null); 8056 } 8057 8058 if (mFoundPolicyFile) { 8059 SELinuxMMAC.assignSeinfoValue(pkg); 8060 } 8061 8062 pkg.applicationInfo.uid = pkgSetting.appId; 8063 pkg.mExtras = pkgSetting; 8064 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8065 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8066 // We just determined the app is signed correctly, so bring 8067 // over the latest parsed certs. 8068 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8069 } else { 8070 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8071 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8072 "Package " + pkg.packageName + " upgrade keys do not match the " 8073 + "previously installed version"); 8074 } else { 8075 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8076 String msg = "System package " + pkg.packageName 8077 + " signature changed; retaining data."; 8078 reportSettingsProblem(Log.WARN, msg); 8079 } 8080 } 8081 } else { 8082 try { 8083 verifySignaturesLP(pkgSetting, pkg); 8084 // We just determined the app is signed correctly, so bring 8085 // over the latest parsed certs. 8086 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8087 } catch (PackageManagerException e) { 8088 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8089 throw e; 8090 } 8091 // The signature has changed, but this package is in the system 8092 // image... let's recover! 8093 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8094 // However... if this package is part of a shared user, but it 8095 // doesn't match the signature of the shared user, let's fail. 8096 // What this means is that you can't change the signatures 8097 // associated with an overall shared user, which doesn't seem all 8098 // that unreasonable. 8099 if (pkgSetting.sharedUser != null) { 8100 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8101 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8102 throw new PackageManagerException( 8103 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8104 "Signature mismatch for shared user: " 8105 + pkgSetting.sharedUser); 8106 } 8107 } 8108 // File a report about this. 8109 String msg = "System package " + pkg.packageName 8110 + " signature changed; retaining data."; 8111 reportSettingsProblem(Log.WARN, msg); 8112 } 8113 } 8114 // Verify that this new package doesn't have any content providers 8115 // that conflict with existing packages. Only do this if the 8116 // package isn't already installed, since we don't want to break 8117 // things that are installed. 8118 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8119 final int N = pkg.providers.size(); 8120 int i; 8121 for (i=0; i<N; i++) { 8122 PackageParser.Provider p = pkg.providers.get(i); 8123 if (p.info.authority != null) { 8124 String names[] = p.info.authority.split(";"); 8125 for (int j = 0; j < names.length; j++) { 8126 if (mProvidersByAuthority.containsKey(names[j])) { 8127 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8128 final String otherPackageName = 8129 ((other != null && other.getComponentName() != null) ? 8130 other.getComponentName().getPackageName() : "?"); 8131 throw new PackageManagerException( 8132 INSTALL_FAILED_CONFLICTING_PROVIDER, 8133 "Can't install because provider name " + names[j] 8134 + " (in package " + pkg.applicationInfo.packageName 8135 + ") is already used by " + otherPackageName); 8136 } 8137 } 8138 } 8139 } 8140 } 8141 8142 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8143 // This package wants to adopt ownership of permissions from 8144 // another package. 8145 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8146 final String origName = pkg.mAdoptPermissions.get(i); 8147 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8148 if (orig != null) { 8149 if (verifyPackageUpdateLPr(orig, pkg)) { 8150 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8151 + pkg.packageName); 8152 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8153 } 8154 } 8155 } 8156 } 8157 } 8158 8159 final String pkgName = pkg.packageName; 8160 8161 final long scanFileTime = scanFile.lastModified(); 8162 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8163 pkg.applicationInfo.processName = fixProcessName( 8164 pkg.applicationInfo.packageName, 8165 pkg.applicationInfo.processName, 8166 pkg.applicationInfo.uid); 8167 8168 if (pkg != mPlatformPackage) { 8169 // Get all of our default paths setup 8170 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8171 } 8172 8173 final String path = scanFile.getPath(); 8174 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8175 8176 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8177 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8178 8179 // Some system apps still use directory structure for native libraries 8180 // in which case we might end up not detecting abi solely based on apk 8181 // structure. Try to detect abi based on directory structure. 8182 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8183 pkg.applicationInfo.primaryCpuAbi == null) { 8184 setBundledAppAbisAndRoots(pkg, pkgSetting); 8185 setNativeLibraryPaths(pkg); 8186 } 8187 8188 } else { 8189 if ((scanFlags & SCAN_MOVE) != 0) { 8190 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8191 // but we already have this packages package info in the PackageSetting. We just 8192 // use that and derive the native library path based on the new codepath. 8193 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8194 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8195 } 8196 8197 // Set native library paths again. For moves, the path will be updated based on the 8198 // ABIs we've determined above. For non-moves, the path will be updated based on the 8199 // ABIs we determined during compilation, but the path will depend on the final 8200 // package path (after the rename away from the stage path). 8201 setNativeLibraryPaths(pkg); 8202 } 8203 8204 // This is a special case for the "system" package, where the ABI is 8205 // dictated by the zygote configuration (and init.rc). We should keep track 8206 // of this ABI so that we can deal with "normal" applications that run under 8207 // the same UID correctly. 8208 if (mPlatformPackage == pkg) { 8209 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8210 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8211 } 8212 8213 // If there's a mismatch between the abi-override in the package setting 8214 // and the abiOverride specified for the install. Warn about this because we 8215 // would've already compiled the app without taking the package setting into 8216 // account. 8217 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8218 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8219 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8220 " for package " + pkg.packageName); 8221 } 8222 } 8223 8224 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8225 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8226 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8227 8228 // Copy the derived override back to the parsed package, so that we can 8229 // update the package settings accordingly. 8230 pkg.cpuAbiOverride = cpuAbiOverride; 8231 8232 if (DEBUG_ABI_SELECTION) { 8233 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8234 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8235 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8236 } 8237 8238 // Push the derived path down into PackageSettings so we know what to 8239 // clean up at uninstall time. 8240 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8241 8242 if (DEBUG_ABI_SELECTION) { 8243 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8244 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8245 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8246 } 8247 8248 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8249 // We don't do this here during boot because we can do it all 8250 // at once after scanning all existing packages. 8251 // 8252 // We also do this *before* we perform dexopt on this package, so that 8253 // we can avoid redundant dexopts, and also to make sure we've got the 8254 // code and package path correct. 8255 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8256 pkg, true /* boot complete */); 8257 } 8258 8259 if (mFactoryTest && pkg.requestedPermissions.contains( 8260 android.Manifest.permission.FACTORY_TEST)) { 8261 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8262 } 8263 8264 ArrayList<PackageParser.Package> clientLibPkgs = null; 8265 8266 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8267 if (nonMutatedPs != null) { 8268 synchronized (mPackages) { 8269 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8270 } 8271 } 8272 return pkg; 8273 } 8274 8275 // Only privileged apps and updated privileged apps can add child packages. 8276 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8277 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8278 throw new PackageManagerException("Only privileged apps and updated " 8279 + "privileged apps can add child packages. Ignoring package " 8280 + pkg.packageName); 8281 } 8282 final int childCount = pkg.childPackages.size(); 8283 for (int i = 0; i < childCount; i++) { 8284 PackageParser.Package childPkg = pkg.childPackages.get(i); 8285 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8286 childPkg.packageName)) { 8287 throw new PackageManagerException("Cannot override a child package of " 8288 + "another disabled system app. Ignoring package " + pkg.packageName); 8289 } 8290 } 8291 } 8292 8293 // writer 8294 synchronized (mPackages) { 8295 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8296 // Only system apps can add new shared libraries. 8297 if (pkg.libraryNames != null) { 8298 for (int i=0; i<pkg.libraryNames.size(); i++) { 8299 String name = pkg.libraryNames.get(i); 8300 boolean allowed = false; 8301 if (pkg.isUpdatedSystemApp()) { 8302 // New library entries can only be added through the 8303 // system image. This is important to get rid of a lot 8304 // of nasty edge cases: for example if we allowed a non- 8305 // system update of the app to add a library, then uninstalling 8306 // the update would make the library go away, and assumptions 8307 // we made such as through app install filtering would now 8308 // have allowed apps on the device which aren't compatible 8309 // with it. Better to just have the restriction here, be 8310 // conservative, and create many fewer cases that can negatively 8311 // impact the user experience. 8312 final PackageSetting sysPs = mSettings 8313 .getDisabledSystemPkgLPr(pkg.packageName); 8314 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8315 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8316 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8317 allowed = true; 8318 break; 8319 } 8320 } 8321 } 8322 } else { 8323 allowed = true; 8324 } 8325 if (allowed) { 8326 if (!mSharedLibraries.containsKey(name)) { 8327 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8328 } else if (!name.equals(pkg.packageName)) { 8329 Slog.w(TAG, "Package " + pkg.packageName + " library " 8330 + name + " already exists; skipping"); 8331 } 8332 } else { 8333 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8334 + name + " that is not declared on system image; skipping"); 8335 } 8336 } 8337 if ((scanFlags & SCAN_BOOTING) == 0) { 8338 // If we are not booting, we need to update any applications 8339 // that are clients of our shared library. If we are booting, 8340 // this will all be done once the scan is complete. 8341 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8342 } 8343 } 8344 } 8345 } 8346 8347 if ((scanFlags & SCAN_BOOTING) != 0) { 8348 // No apps can run during boot scan, so they don't need to be frozen 8349 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8350 // Caller asked to not kill app, so it's probably not frozen 8351 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8352 // Caller asked us to ignore frozen check for some reason; they 8353 // probably didn't know the package name 8354 } else { 8355 // We're doing major surgery on this package, so it better be frozen 8356 // right now to keep it from launching 8357 checkPackageFrozen(pkgName); 8358 } 8359 8360 // Also need to kill any apps that are dependent on the library. 8361 if (clientLibPkgs != null) { 8362 for (int i=0; i<clientLibPkgs.size(); i++) { 8363 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8364 killApplication(clientPkg.applicationInfo.packageName, 8365 clientPkg.applicationInfo.uid, "update lib"); 8366 } 8367 } 8368 8369 // Make sure we're not adding any bogus keyset info 8370 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8371 ksms.assertScannedPackageValid(pkg); 8372 8373 // writer 8374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8375 8376 boolean createIdmapFailed = false; 8377 synchronized (mPackages) { 8378 // We don't expect installation to fail beyond this point 8379 8380 // Add the new setting to mSettings 8381 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8382 // Add the new setting to mPackages 8383 mPackages.put(pkg.applicationInfo.packageName, pkg); 8384 // Make sure we don't accidentally delete its data. 8385 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8386 while (iter.hasNext()) { 8387 PackageCleanItem item = iter.next(); 8388 if (pkgName.equals(item.packageName)) { 8389 iter.remove(); 8390 } 8391 } 8392 8393 // Take care of first install / last update times. 8394 if (currentTime != 0) { 8395 if (pkgSetting.firstInstallTime == 0) { 8396 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8397 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8398 pkgSetting.lastUpdateTime = currentTime; 8399 } 8400 } else if (pkgSetting.firstInstallTime == 0) { 8401 // We need *something*. Take time time stamp of the file. 8402 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8403 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8404 if (scanFileTime != pkgSetting.timeStamp) { 8405 // A package on the system image has changed; consider this 8406 // to be an update. 8407 pkgSetting.lastUpdateTime = scanFileTime; 8408 } 8409 } 8410 8411 // Add the package's KeySets to the global KeySetManagerService 8412 ksms.addScannedPackageLPw(pkg); 8413 8414 int N = pkg.providers.size(); 8415 StringBuilder r = null; 8416 int i; 8417 for (i=0; i<N; i++) { 8418 PackageParser.Provider p = pkg.providers.get(i); 8419 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8420 p.info.processName, pkg.applicationInfo.uid); 8421 mProviders.addProvider(p); 8422 p.syncable = p.info.isSyncable; 8423 if (p.info.authority != null) { 8424 String names[] = p.info.authority.split(";"); 8425 p.info.authority = null; 8426 for (int j = 0; j < names.length; j++) { 8427 if (j == 1 && p.syncable) { 8428 // We only want the first authority for a provider to possibly be 8429 // syncable, so if we already added this provider using a different 8430 // authority clear the syncable flag. We copy the provider before 8431 // changing it because the mProviders object contains a reference 8432 // to a provider that we don't want to change. 8433 // Only do this for the second authority since the resulting provider 8434 // object can be the same for all future authorities for this provider. 8435 p = new PackageParser.Provider(p); 8436 p.syncable = false; 8437 } 8438 if (!mProvidersByAuthority.containsKey(names[j])) { 8439 mProvidersByAuthority.put(names[j], p); 8440 if (p.info.authority == null) { 8441 p.info.authority = names[j]; 8442 } else { 8443 p.info.authority = p.info.authority + ";" + names[j]; 8444 } 8445 if (DEBUG_PACKAGE_SCANNING) { 8446 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8447 Log.d(TAG, "Registered content provider: " + names[j] 8448 + ", className = " + p.info.name + ", isSyncable = " 8449 + p.info.isSyncable); 8450 } 8451 } else { 8452 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8453 Slog.w(TAG, "Skipping provider name " + names[j] + 8454 " (in package " + pkg.applicationInfo.packageName + 8455 "): name already used by " 8456 + ((other != null && other.getComponentName() != null) 8457 ? other.getComponentName().getPackageName() : "?")); 8458 } 8459 } 8460 } 8461 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8462 if (r == null) { 8463 r = new StringBuilder(256); 8464 } else { 8465 r.append(' '); 8466 } 8467 r.append(p.info.name); 8468 } 8469 } 8470 if (r != null) { 8471 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8472 } 8473 8474 N = pkg.services.size(); 8475 r = null; 8476 for (i=0; i<N; i++) { 8477 PackageParser.Service s = pkg.services.get(i); 8478 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8479 s.info.processName, pkg.applicationInfo.uid); 8480 mServices.addService(s); 8481 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8482 if (r == null) { 8483 r = new StringBuilder(256); 8484 } else { 8485 r.append(' '); 8486 } 8487 r.append(s.info.name); 8488 } 8489 } 8490 if (r != null) { 8491 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8492 } 8493 8494 N = pkg.receivers.size(); 8495 r = null; 8496 for (i=0; i<N; i++) { 8497 PackageParser.Activity a = pkg.receivers.get(i); 8498 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8499 a.info.processName, pkg.applicationInfo.uid); 8500 mReceivers.addActivity(a, "receiver"); 8501 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8502 if (r == null) { 8503 r = new StringBuilder(256); 8504 } else { 8505 r.append(' '); 8506 } 8507 r.append(a.info.name); 8508 } 8509 } 8510 if (r != null) { 8511 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8512 } 8513 8514 N = pkg.activities.size(); 8515 r = null; 8516 for (i=0; i<N; i++) { 8517 PackageParser.Activity a = pkg.activities.get(i); 8518 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8519 a.info.processName, pkg.applicationInfo.uid); 8520 mActivities.addActivity(a, "activity"); 8521 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8522 if (r == null) { 8523 r = new StringBuilder(256); 8524 } else { 8525 r.append(' '); 8526 } 8527 r.append(a.info.name); 8528 } 8529 } 8530 if (r != null) { 8531 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8532 } 8533 8534 N = pkg.permissionGroups.size(); 8535 r = null; 8536 for (i=0; i<N; i++) { 8537 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8538 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8539 if (cur == null) { 8540 mPermissionGroups.put(pg.info.name, pg); 8541 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8542 if (r == null) { 8543 r = new StringBuilder(256); 8544 } else { 8545 r.append(' '); 8546 } 8547 r.append(pg.info.name); 8548 } 8549 } else { 8550 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8551 + pg.info.packageName + " ignored: original from " 8552 + cur.info.packageName); 8553 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8554 if (r == null) { 8555 r = new StringBuilder(256); 8556 } else { 8557 r.append(' '); 8558 } 8559 r.append("DUP:"); 8560 r.append(pg.info.name); 8561 } 8562 } 8563 } 8564 if (r != null) { 8565 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8566 } 8567 8568 N = pkg.permissions.size(); 8569 r = null; 8570 for (i=0; i<N; i++) { 8571 PackageParser.Permission p = pkg.permissions.get(i); 8572 8573 // Assume by default that we did not install this permission into the system. 8574 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8575 8576 // Now that permission groups have a special meaning, we ignore permission 8577 // groups for legacy apps to prevent unexpected behavior. In particular, 8578 // permissions for one app being granted to someone just becase they happen 8579 // to be in a group defined by another app (before this had no implications). 8580 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8581 p.group = mPermissionGroups.get(p.info.group); 8582 // Warn for a permission in an unknown group. 8583 if (p.info.group != null && p.group == null) { 8584 Slog.w(TAG, "Permission " + p.info.name + " from package " 8585 + p.info.packageName + " in an unknown group " + p.info.group); 8586 } 8587 } 8588 8589 ArrayMap<String, BasePermission> permissionMap = 8590 p.tree ? mSettings.mPermissionTrees 8591 : mSettings.mPermissions; 8592 BasePermission bp = permissionMap.get(p.info.name); 8593 8594 // Allow system apps to redefine non-system permissions 8595 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8596 final boolean currentOwnerIsSystem = (bp.perm != null 8597 && isSystemApp(bp.perm.owner)); 8598 if (isSystemApp(p.owner)) { 8599 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8600 // It's a built-in permission and no owner, take ownership now 8601 bp.packageSetting = pkgSetting; 8602 bp.perm = p; 8603 bp.uid = pkg.applicationInfo.uid; 8604 bp.sourcePackage = p.info.packageName; 8605 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8606 } else if (!currentOwnerIsSystem) { 8607 String msg = "New decl " + p.owner + " of permission " 8608 + p.info.name + " is system; overriding " + bp.sourcePackage; 8609 reportSettingsProblem(Log.WARN, msg); 8610 bp = null; 8611 } 8612 } 8613 } 8614 8615 if (bp == null) { 8616 bp = new BasePermission(p.info.name, p.info.packageName, 8617 BasePermission.TYPE_NORMAL); 8618 permissionMap.put(p.info.name, bp); 8619 } 8620 8621 if (bp.perm == null) { 8622 if (bp.sourcePackage == null 8623 || bp.sourcePackage.equals(p.info.packageName)) { 8624 BasePermission tree = findPermissionTreeLP(p.info.name); 8625 if (tree == null 8626 || tree.sourcePackage.equals(p.info.packageName)) { 8627 bp.packageSetting = pkgSetting; 8628 bp.perm = p; 8629 bp.uid = pkg.applicationInfo.uid; 8630 bp.sourcePackage = p.info.packageName; 8631 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8632 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8633 if (r == null) { 8634 r = new StringBuilder(256); 8635 } else { 8636 r.append(' '); 8637 } 8638 r.append(p.info.name); 8639 } 8640 } else { 8641 Slog.w(TAG, "Permission " + p.info.name + " from package " 8642 + p.info.packageName + " ignored: base tree " 8643 + tree.name + " is from package " 8644 + tree.sourcePackage); 8645 } 8646 } else { 8647 Slog.w(TAG, "Permission " + p.info.name + " from package " 8648 + p.info.packageName + " ignored: original from " 8649 + bp.sourcePackage); 8650 } 8651 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8652 if (r == null) { 8653 r = new StringBuilder(256); 8654 } else { 8655 r.append(' '); 8656 } 8657 r.append("DUP:"); 8658 r.append(p.info.name); 8659 } 8660 if (bp.perm == p) { 8661 bp.protectionLevel = p.info.protectionLevel; 8662 } 8663 } 8664 8665 if (r != null) { 8666 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8667 } 8668 8669 N = pkg.instrumentation.size(); 8670 r = null; 8671 for (i=0; i<N; i++) { 8672 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8673 a.info.packageName = pkg.applicationInfo.packageName; 8674 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8675 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8676 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8677 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8678 a.info.dataDir = pkg.applicationInfo.dataDir; 8679 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8680 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8681 8682 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8683 // need other information about the application, like the ABI and what not ? 8684 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8685 mInstrumentation.put(a.getComponentName(), a); 8686 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8687 if (r == null) { 8688 r = new StringBuilder(256); 8689 } else { 8690 r.append(' '); 8691 } 8692 r.append(a.info.name); 8693 } 8694 } 8695 if (r != null) { 8696 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8697 } 8698 8699 if (pkg.protectedBroadcasts != null) { 8700 N = pkg.protectedBroadcasts.size(); 8701 for (i=0; i<N; i++) { 8702 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8703 } 8704 } 8705 8706 pkgSetting.setTimeStamp(scanFileTime); 8707 8708 // Create idmap files for pairs of (packages, overlay packages). 8709 // Note: "android", ie framework-res.apk, is handled by native layers. 8710 if (pkg.mOverlayTarget != null) { 8711 // This is an overlay package. 8712 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8713 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8714 mOverlays.put(pkg.mOverlayTarget, 8715 new ArrayMap<String, PackageParser.Package>()); 8716 } 8717 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8718 map.put(pkg.packageName, pkg); 8719 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8720 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8721 createIdmapFailed = true; 8722 } 8723 } 8724 } else if (mOverlays.containsKey(pkg.packageName) && 8725 !pkg.packageName.equals("android")) { 8726 // This is a regular package, with one or more known overlay packages. 8727 createIdmapsForPackageLI(pkg); 8728 } 8729 } 8730 8731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8732 8733 if (createIdmapFailed) { 8734 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8735 "scanPackageLI failed to createIdmap"); 8736 } 8737 return pkg; 8738 } 8739 8740 /** 8741 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8742 * is derived purely on the basis of the contents of {@code scanFile} and 8743 * {@code cpuAbiOverride}. 8744 * 8745 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8746 */ 8747 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8748 String cpuAbiOverride, boolean extractLibs) 8749 throws PackageManagerException { 8750 // TODO: We can probably be smarter about this stuff. For installed apps, 8751 // we can calculate this information at install time once and for all. For 8752 // system apps, we can probably assume that this information doesn't change 8753 // after the first boot scan. As things stand, we do lots of unnecessary work. 8754 8755 // Give ourselves some initial paths; we'll come back for another 8756 // pass once we've determined ABI below. 8757 setNativeLibraryPaths(pkg); 8758 8759 // We would never need to extract libs for forward-locked and external packages, 8760 // since the container service will do it for us. We shouldn't attempt to 8761 // extract libs from system app when it was not updated. 8762 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8763 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8764 extractLibs = false; 8765 } 8766 8767 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8768 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8769 8770 NativeLibraryHelper.Handle handle = null; 8771 try { 8772 handle = NativeLibraryHelper.Handle.create(pkg); 8773 // TODO(multiArch): This can be null for apps that didn't go through the 8774 // usual installation process. We can calculate it again, like we 8775 // do during install time. 8776 // 8777 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8778 // unnecessary. 8779 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8780 8781 // Null out the abis so that they can be recalculated. 8782 pkg.applicationInfo.primaryCpuAbi = null; 8783 pkg.applicationInfo.secondaryCpuAbi = null; 8784 if (isMultiArch(pkg.applicationInfo)) { 8785 // Warn if we've set an abiOverride for multi-lib packages.. 8786 // By definition, we need to copy both 32 and 64 bit libraries for 8787 // such packages. 8788 if (pkg.cpuAbiOverride != null 8789 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8790 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8791 } 8792 8793 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8794 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8795 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8796 if (extractLibs) { 8797 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8798 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8799 useIsaSpecificSubdirs); 8800 } else { 8801 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8802 } 8803 } 8804 8805 maybeThrowExceptionForMultiArchCopy( 8806 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8807 8808 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8809 if (extractLibs) { 8810 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8811 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8812 useIsaSpecificSubdirs); 8813 } else { 8814 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8815 } 8816 } 8817 8818 maybeThrowExceptionForMultiArchCopy( 8819 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8820 8821 if (abi64 >= 0) { 8822 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8823 } 8824 8825 if (abi32 >= 0) { 8826 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8827 if (abi64 >= 0) { 8828 if (pkg.use32bitAbi) { 8829 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8830 pkg.applicationInfo.primaryCpuAbi = abi; 8831 } else { 8832 pkg.applicationInfo.secondaryCpuAbi = abi; 8833 } 8834 } else { 8835 pkg.applicationInfo.primaryCpuAbi = abi; 8836 } 8837 } 8838 8839 } else { 8840 String[] abiList = (cpuAbiOverride != null) ? 8841 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8842 8843 // Enable gross and lame hacks for apps that are built with old 8844 // SDK tools. We must scan their APKs for renderscript bitcode and 8845 // not launch them if it's present. Don't bother checking on devices 8846 // that don't have 64 bit support. 8847 boolean needsRenderScriptOverride = false; 8848 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8849 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8850 abiList = Build.SUPPORTED_32_BIT_ABIS; 8851 needsRenderScriptOverride = true; 8852 } 8853 8854 final int copyRet; 8855 if (extractLibs) { 8856 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8857 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8858 } else { 8859 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8860 } 8861 8862 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8863 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8864 "Error unpackaging native libs for app, errorCode=" + copyRet); 8865 } 8866 8867 if (copyRet >= 0) { 8868 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8869 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8870 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8871 } else if (needsRenderScriptOverride) { 8872 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8873 } 8874 } 8875 } catch (IOException ioe) { 8876 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8877 } finally { 8878 IoUtils.closeQuietly(handle); 8879 } 8880 8881 // Now that we've calculated the ABIs and determined if it's an internal app, 8882 // we will go ahead and populate the nativeLibraryPath. 8883 setNativeLibraryPaths(pkg); 8884 } 8885 8886 /** 8887 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8888 * i.e, so that all packages can be run inside a single process if required. 8889 * 8890 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8891 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8892 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8893 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8894 * updating a package that belongs to a shared user. 8895 * 8896 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8897 * adds unnecessary complexity. 8898 */ 8899 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8900 PackageParser.Package scannedPackage, boolean bootComplete) { 8901 String requiredInstructionSet = null; 8902 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8903 requiredInstructionSet = VMRuntime.getInstructionSet( 8904 scannedPackage.applicationInfo.primaryCpuAbi); 8905 } 8906 8907 PackageSetting requirer = null; 8908 for (PackageSetting ps : packagesForUser) { 8909 // If packagesForUser contains scannedPackage, we skip it. This will happen 8910 // when scannedPackage is an update of an existing package. Without this check, 8911 // we will never be able to change the ABI of any package belonging to a shared 8912 // user, even if it's compatible with other packages. 8913 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8914 if (ps.primaryCpuAbiString == null) { 8915 continue; 8916 } 8917 8918 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8919 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8920 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8921 // this but there's not much we can do. 8922 String errorMessage = "Instruction set mismatch, " 8923 + ((requirer == null) ? "[caller]" : requirer) 8924 + " requires " + requiredInstructionSet + " whereas " + ps 8925 + " requires " + instructionSet; 8926 Slog.w(TAG, errorMessage); 8927 } 8928 8929 if (requiredInstructionSet == null) { 8930 requiredInstructionSet = instructionSet; 8931 requirer = ps; 8932 } 8933 } 8934 } 8935 8936 if (requiredInstructionSet != null) { 8937 String adjustedAbi; 8938 if (requirer != null) { 8939 // requirer != null implies that either scannedPackage was null or that scannedPackage 8940 // did not require an ABI, in which case we have to adjust scannedPackage to match 8941 // the ABI of the set (which is the same as requirer's ABI) 8942 adjustedAbi = requirer.primaryCpuAbiString; 8943 if (scannedPackage != null) { 8944 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8945 } 8946 } else { 8947 // requirer == null implies that we're updating all ABIs in the set to 8948 // match scannedPackage. 8949 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8950 } 8951 8952 for (PackageSetting ps : packagesForUser) { 8953 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8954 if (ps.primaryCpuAbiString != null) { 8955 continue; 8956 } 8957 8958 ps.primaryCpuAbiString = adjustedAbi; 8959 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8960 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8961 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8962 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8963 + " (requirer=" 8964 + (requirer == null ? "null" : requirer.pkg.packageName) 8965 + ", scannedPackage=" 8966 + (scannedPackage != null ? scannedPackage.packageName : "null") 8967 + ")"); 8968 try { 8969 mInstaller.rmdex(ps.codePathString, 8970 getDexCodeInstructionSet(getPreferredInstructionSet())); 8971 } catch (InstallerException ignored) { 8972 } 8973 } 8974 } 8975 } 8976 } 8977 } 8978 8979 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8980 synchronized (mPackages) { 8981 mResolverReplaced = true; 8982 // Set up information for custom user intent resolution activity. 8983 mResolveActivity.applicationInfo = pkg.applicationInfo; 8984 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8985 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8986 mResolveActivity.processName = pkg.applicationInfo.packageName; 8987 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8988 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8989 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8990 mResolveActivity.theme = 0; 8991 mResolveActivity.exported = true; 8992 mResolveActivity.enabled = true; 8993 mResolveInfo.activityInfo = mResolveActivity; 8994 mResolveInfo.priority = 0; 8995 mResolveInfo.preferredOrder = 0; 8996 mResolveInfo.match = 0; 8997 mResolveComponentName = mCustomResolverComponentName; 8998 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8999 mResolveComponentName); 9000 } 9001 } 9002 9003 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9004 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9005 9006 // Set up information for ephemeral installer activity 9007 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9008 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9009 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9010 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9011 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9012 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9013 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9014 mEphemeralInstallerActivity.theme = 0; 9015 mEphemeralInstallerActivity.exported = true; 9016 mEphemeralInstallerActivity.enabled = true; 9017 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9018 mEphemeralInstallerInfo.priority = 0; 9019 mEphemeralInstallerInfo.preferredOrder = 0; 9020 mEphemeralInstallerInfo.match = 0; 9021 9022 if (DEBUG_EPHEMERAL) { 9023 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9024 } 9025 } 9026 9027 private static String calculateBundledApkRoot(final String codePathString) { 9028 final File codePath = new File(codePathString); 9029 final File codeRoot; 9030 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9031 codeRoot = Environment.getRootDirectory(); 9032 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9033 codeRoot = Environment.getOemDirectory(); 9034 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9035 codeRoot = Environment.getVendorDirectory(); 9036 } else { 9037 // Unrecognized code path; take its top real segment as the apk root: 9038 // e.g. /something/app/blah.apk => /something 9039 try { 9040 File f = codePath.getCanonicalFile(); 9041 File parent = f.getParentFile(); // non-null because codePath is a file 9042 File tmp; 9043 while ((tmp = parent.getParentFile()) != null) { 9044 f = parent; 9045 parent = tmp; 9046 } 9047 codeRoot = f; 9048 Slog.w(TAG, "Unrecognized code path " 9049 + codePath + " - using " + codeRoot); 9050 } catch (IOException e) { 9051 // Can't canonicalize the code path -- shenanigans? 9052 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9053 return Environment.getRootDirectory().getPath(); 9054 } 9055 } 9056 return codeRoot.getPath(); 9057 } 9058 9059 /** 9060 * Derive and set the location of native libraries for the given package, 9061 * which varies depending on where and how the package was installed. 9062 */ 9063 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9064 final ApplicationInfo info = pkg.applicationInfo; 9065 final String codePath = pkg.codePath; 9066 final File codeFile = new File(codePath); 9067 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9068 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9069 9070 info.nativeLibraryRootDir = null; 9071 info.nativeLibraryRootRequiresIsa = false; 9072 info.nativeLibraryDir = null; 9073 info.secondaryNativeLibraryDir = null; 9074 9075 if (isApkFile(codeFile)) { 9076 // Monolithic install 9077 if (bundledApp) { 9078 // If "/system/lib64/apkname" exists, assume that is the per-package 9079 // native library directory to use; otherwise use "/system/lib/apkname". 9080 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9081 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9082 getPrimaryInstructionSet(info)); 9083 9084 // This is a bundled system app so choose the path based on the ABI. 9085 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9086 // is just the default path. 9087 final String apkName = deriveCodePathName(codePath); 9088 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9089 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9090 apkName).getAbsolutePath(); 9091 9092 if (info.secondaryCpuAbi != null) { 9093 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9094 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9095 secondaryLibDir, apkName).getAbsolutePath(); 9096 } 9097 } else if (asecApp) { 9098 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9099 .getAbsolutePath(); 9100 } else { 9101 final String apkName = deriveCodePathName(codePath); 9102 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9103 .getAbsolutePath(); 9104 } 9105 9106 info.nativeLibraryRootRequiresIsa = false; 9107 info.nativeLibraryDir = info.nativeLibraryRootDir; 9108 } else { 9109 // Cluster install 9110 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9111 info.nativeLibraryRootRequiresIsa = true; 9112 9113 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9114 getPrimaryInstructionSet(info)).getAbsolutePath(); 9115 9116 if (info.secondaryCpuAbi != null) { 9117 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9118 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9119 } 9120 } 9121 } 9122 9123 /** 9124 * Calculate the abis and roots for a bundled app. These can uniquely 9125 * be determined from the contents of the system partition, i.e whether 9126 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9127 * of this information, and instead assume that the system was built 9128 * sensibly. 9129 */ 9130 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9131 PackageSetting pkgSetting) { 9132 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9133 9134 // If "/system/lib64/apkname" exists, assume that is the per-package 9135 // native library directory to use; otherwise use "/system/lib/apkname". 9136 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9137 setBundledAppAbi(pkg, apkRoot, apkName); 9138 // pkgSetting might be null during rescan following uninstall of updates 9139 // to a bundled app, so accommodate that possibility. The settings in 9140 // that case will be established later from the parsed package. 9141 // 9142 // If the settings aren't null, sync them up with what we've just derived. 9143 // note that apkRoot isn't stored in the package settings. 9144 if (pkgSetting != null) { 9145 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9146 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9147 } 9148 } 9149 9150 /** 9151 * Deduces the ABI of a bundled app and sets the relevant fields on the 9152 * parsed pkg object. 9153 * 9154 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9155 * under which system libraries are installed. 9156 * @param apkName the name of the installed package. 9157 */ 9158 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9159 final File codeFile = new File(pkg.codePath); 9160 9161 final boolean has64BitLibs; 9162 final boolean has32BitLibs; 9163 if (isApkFile(codeFile)) { 9164 // Monolithic install 9165 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9166 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9167 } else { 9168 // Cluster install 9169 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9170 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9171 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9172 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9173 has64BitLibs = (new File(rootDir, isa)).exists(); 9174 } else { 9175 has64BitLibs = false; 9176 } 9177 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9178 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9179 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9180 has32BitLibs = (new File(rootDir, isa)).exists(); 9181 } else { 9182 has32BitLibs = false; 9183 } 9184 } 9185 9186 if (has64BitLibs && !has32BitLibs) { 9187 // The package has 64 bit libs, but not 32 bit libs. Its primary 9188 // ABI should be 64 bit. We can safely assume here that the bundled 9189 // native libraries correspond to the most preferred ABI in the list. 9190 9191 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9192 pkg.applicationInfo.secondaryCpuAbi = null; 9193 } else if (has32BitLibs && !has64BitLibs) { 9194 // The package has 32 bit libs but not 64 bit libs. Its primary 9195 // ABI should be 32 bit. 9196 9197 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9198 pkg.applicationInfo.secondaryCpuAbi = null; 9199 } else if (has32BitLibs && has64BitLibs) { 9200 // The application has both 64 and 32 bit bundled libraries. We check 9201 // here that the app declares multiArch support, and warn if it doesn't. 9202 // 9203 // We will be lenient here and record both ABIs. The primary will be the 9204 // ABI that's higher on the list, i.e, a device that's configured to prefer 9205 // 64 bit apps will see a 64 bit primary ABI, 9206 9207 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9208 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9209 } 9210 9211 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9212 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9213 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9214 } else { 9215 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9216 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9217 } 9218 } else { 9219 pkg.applicationInfo.primaryCpuAbi = null; 9220 pkg.applicationInfo.secondaryCpuAbi = null; 9221 } 9222 } 9223 9224 private void killApplication(String pkgName, int appId, String reason) { 9225 // Request the ActivityManager to kill the process(only for existing packages) 9226 // so that we do not end up in a confused state while the user is still using the older 9227 // version of the application while the new one gets installed. 9228 final long token = Binder.clearCallingIdentity(); 9229 try { 9230 IActivityManager am = ActivityManagerNative.getDefault(); 9231 if (am != null) { 9232 try { 9233 am.killApplicationWithAppId(pkgName, appId, reason); 9234 } catch (RemoteException e) { 9235 } 9236 } 9237 } finally { 9238 Binder.restoreCallingIdentity(token); 9239 } 9240 } 9241 9242 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9243 // Remove the parent package setting 9244 PackageSetting ps = (PackageSetting) pkg.mExtras; 9245 if (ps != null) { 9246 removePackageLI(ps, chatty); 9247 } 9248 // Remove the child package setting 9249 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9250 for (int i = 0; i < childCount; i++) { 9251 PackageParser.Package childPkg = pkg.childPackages.get(i); 9252 ps = (PackageSetting) childPkg.mExtras; 9253 if (ps != null) { 9254 removePackageLI(ps, chatty); 9255 } 9256 } 9257 } 9258 9259 void removePackageLI(PackageSetting ps, boolean chatty) { 9260 if (DEBUG_INSTALL) { 9261 if (chatty) 9262 Log.d(TAG, "Removing package " + ps.name); 9263 } 9264 9265 // writer 9266 synchronized (mPackages) { 9267 mPackages.remove(ps.name); 9268 final PackageParser.Package pkg = ps.pkg; 9269 if (pkg != null) { 9270 cleanPackageDataStructuresLILPw(pkg, chatty); 9271 } 9272 } 9273 } 9274 9275 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9276 if (DEBUG_INSTALL) { 9277 if (chatty) 9278 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9279 } 9280 9281 // writer 9282 synchronized (mPackages) { 9283 // Remove the parent package 9284 mPackages.remove(pkg.applicationInfo.packageName); 9285 cleanPackageDataStructuresLILPw(pkg, chatty); 9286 9287 // Remove the child packages 9288 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9289 for (int i = 0; i < childCount; i++) { 9290 PackageParser.Package childPkg = pkg.childPackages.get(i); 9291 mPackages.remove(childPkg.applicationInfo.packageName); 9292 cleanPackageDataStructuresLILPw(childPkg, chatty); 9293 } 9294 } 9295 } 9296 9297 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9298 int N = pkg.providers.size(); 9299 StringBuilder r = null; 9300 int i; 9301 for (i=0; i<N; i++) { 9302 PackageParser.Provider p = pkg.providers.get(i); 9303 mProviders.removeProvider(p); 9304 if (p.info.authority == null) { 9305 9306 /* There was another ContentProvider with this authority when 9307 * this app was installed so this authority is null, 9308 * Ignore it as we don't have to unregister the provider. 9309 */ 9310 continue; 9311 } 9312 String names[] = p.info.authority.split(";"); 9313 for (int j = 0; j < names.length; j++) { 9314 if (mProvidersByAuthority.get(names[j]) == p) { 9315 mProvidersByAuthority.remove(names[j]); 9316 if (DEBUG_REMOVE) { 9317 if (chatty) 9318 Log.d(TAG, "Unregistered content provider: " + names[j] 9319 + ", className = " + p.info.name + ", isSyncable = " 9320 + p.info.isSyncable); 9321 } 9322 } 9323 } 9324 if (DEBUG_REMOVE && chatty) { 9325 if (r == null) { 9326 r = new StringBuilder(256); 9327 } else { 9328 r.append(' '); 9329 } 9330 r.append(p.info.name); 9331 } 9332 } 9333 if (r != null) { 9334 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9335 } 9336 9337 N = pkg.services.size(); 9338 r = null; 9339 for (i=0; i<N; i++) { 9340 PackageParser.Service s = pkg.services.get(i); 9341 mServices.removeService(s); 9342 if (chatty) { 9343 if (r == null) { 9344 r = new StringBuilder(256); 9345 } else { 9346 r.append(' '); 9347 } 9348 r.append(s.info.name); 9349 } 9350 } 9351 if (r != null) { 9352 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9353 } 9354 9355 N = pkg.receivers.size(); 9356 r = null; 9357 for (i=0; i<N; i++) { 9358 PackageParser.Activity a = pkg.receivers.get(i); 9359 mReceivers.removeActivity(a, "receiver"); 9360 if (DEBUG_REMOVE && chatty) { 9361 if (r == null) { 9362 r = new StringBuilder(256); 9363 } else { 9364 r.append(' '); 9365 } 9366 r.append(a.info.name); 9367 } 9368 } 9369 if (r != null) { 9370 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9371 } 9372 9373 N = pkg.activities.size(); 9374 r = null; 9375 for (i=0; i<N; i++) { 9376 PackageParser.Activity a = pkg.activities.get(i); 9377 mActivities.removeActivity(a, "activity"); 9378 if (DEBUG_REMOVE && chatty) { 9379 if (r == null) { 9380 r = new StringBuilder(256); 9381 } else { 9382 r.append(' '); 9383 } 9384 r.append(a.info.name); 9385 } 9386 } 9387 if (r != null) { 9388 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9389 } 9390 9391 N = pkg.permissions.size(); 9392 r = null; 9393 for (i=0; i<N; i++) { 9394 PackageParser.Permission p = pkg.permissions.get(i); 9395 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9396 if (bp == null) { 9397 bp = mSettings.mPermissionTrees.get(p.info.name); 9398 } 9399 if (bp != null && bp.perm == p) { 9400 bp.perm = null; 9401 if (DEBUG_REMOVE && chatty) { 9402 if (r == null) { 9403 r = new StringBuilder(256); 9404 } else { 9405 r.append(' '); 9406 } 9407 r.append(p.info.name); 9408 } 9409 } 9410 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9411 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9412 if (appOpPkgs != null) { 9413 appOpPkgs.remove(pkg.packageName); 9414 } 9415 } 9416 } 9417 if (r != null) { 9418 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9419 } 9420 9421 N = pkg.requestedPermissions.size(); 9422 r = null; 9423 for (i=0; i<N; i++) { 9424 String perm = pkg.requestedPermissions.get(i); 9425 BasePermission bp = mSettings.mPermissions.get(perm); 9426 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9427 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9428 if (appOpPkgs != null) { 9429 appOpPkgs.remove(pkg.packageName); 9430 if (appOpPkgs.isEmpty()) { 9431 mAppOpPermissionPackages.remove(perm); 9432 } 9433 } 9434 } 9435 } 9436 if (r != null) { 9437 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9438 } 9439 9440 N = pkg.instrumentation.size(); 9441 r = null; 9442 for (i=0; i<N; i++) { 9443 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9444 mInstrumentation.remove(a.getComponentName()); 9445 if (DEBUG_REMOVE && chatty) { 9446 if (r == null) { 9447 r = new StringBuilder(256); 9448 } else { 9449 r.append(' '); 9450 } 9451 r.append(a.info.name); 9452 } 9453 } 9454 if (r != null) { 9455 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9456 } 9457 9458 r = null; 9459 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9460 // Only system apps can hold shared libraries. 9461 if (pkg.libraryNames != null) { 9462 for (i=0; i<pkg.libraryNames.size(); i++) { 9463 String name = pkg.libraryNames.get(i); 9464 SharedLibraryEntry cur = mSharedLibraries.get(name); 9465 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9466 mSharedLibraries.remove(name); 9467 if (DEBUG_REMOVE && chatty) { 9468 if (r == null) { 9469 r = new StringBuilder(256); 9470 } else { 9471 r.append(' '); 9472 } 9473 r.append(name); 9474 } 9475 } 9476 } 9477 } 9478 } 9479 if (r != null) { 9480 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9481 } 9482 } 9483 9484 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9485 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9486 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9487 return true; 9488 } 9489 } 9490 return false; 9491 } 9492 9493 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9494 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9495 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9496 9497 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9498 // Update the parent permissions 9499 updatePermissionsLPw(pkg.packageName, pkg, flags); 9500 // Update the child permissions 9501 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9502 for (int i = 0; i < childCount; i++) { 9503 PackageParser.Package childPkg = pkg.childPackages.get(i); 9504 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9505 } 9506 } 9507 9508 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9509 int flags) { 9510 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9511 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9512 } 9513 9514 private void updatePermissionsLPw(String changingPkg, 9515 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9516 // Make sure there are no dangling permission trees. 9517 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9518 while (it.hasNext()) { 9519 final BasePermission bp = it.next(); 9520 if (bp.packageSetting == null) { 9521 // We may not yet have parsed the package, so just see if 9522 // we still know about its settings. 9523 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9524 } 9525 if (bp.packageSetting == null) { 9526 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9527 + " from package " + bp.sourcePackage); 9528 it.remove(); 9529 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9530 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9531 Slog.i(TAG, "Removing old permission tree: " + bp.name 9532 + " from package " + bp.sourcePackage); 9533 flags |= UPDATE_PERMISSIONS_ALL; 9534 it.remove(); 9535 } 9536 } 9537 } 9538 9539 // Make sure all dynamic permissions have been assigned to a package, 9540 // and make sure there are no dangling permissions. 9541 it = mSettings.mPermissions.values().iterator(); 9542 while (it.hasNext()) { 9543 final BasePermission bp = it.next(); 9544 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9545 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9546 + bp.name + " pkg=" + bp.sourcePackage 9547 + " info=" + bp.pendingInfo); 9548 if (bp.packageSetting == null && bp.pendingInfo != null) { 9549 final BasePermission tree = findPermissionTreeLP(bp.name); 9550 if (tree != null && tree.perm != null) { 9551 bp.packageSetting = tree.packageSetting; 9552 bp.perm = new PackageParser.Permission(tree.perm.owner, 9553 new PermissionInfo(bp.pendingInfo)); 9554 bp.perm.info.packageName = tree.perm.info.packageName; 9555 bp.perm.info.name = bp.name; 9556 bp.uid = tree.uid; 9557 } 9558 } 9559 } 9560 if (bp.packageSetting == null) { 9561 // We may not yet have parsed the package, so just see if 9562 // we still know about its settings. 9563 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9564 } 9565 if (bp.packageSetting == null) { 9566 Slog.w(TAG, "Removing dangling permission: " + bp.name 9567 + " from package " + bp.sourcePackage); 9568 it.remove(); 9569 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9570 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9571 Slog.i(TAG, "Removing old permission: " + bp.name 9572 + " from package " + bp.sourcePackage); 9573 flags |= UPDATE_PERMISSIONS_ALL; 9574 it.remove(); 9575 } 9576 } 9577 } 9578 9579 // Now update the permissions for all packages, in particular 9580 // replace the granted permissions of the system packages. 9581 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9582 for (PackageParser.Package pkg : mPackages.values()) { 9583 if (pkg != pkgInfo) { 9584 // Only replace for packages on requested volume 9585 final String volumeUuid = getVolumeUuidForPackage(pkg); 9586 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9587 && Objects.equals(replaceVolumeUuid, volumeUuid); 9588 grantPermissionsLPw(pkg, replace, changingPkg); 9589 } 9590 } 9591 } 9592 9593 if (pkgInfo != null) { 9594 // Only replace for packages on requested volume 9595 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9596 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9597 && Objects.equals(replaceVolumeUuid, volumeUuid); 9598 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9599 } 9600 } 9601 9602 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9603 String packageOfInterest) { 9604 // IMPORTANT: There are two types of permissions: install and runtime. 9605 // Install time permissions are granted when the app is installed to 9606 // all device users and users added in the future. Runtime permissions 9607 // are granted at runtime explicitly to specific users. Normal and signature 9608 // protected permissions are install time permissions. Dangerous permissions 9609 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9610 // otherwise they are runtime permissions. This function does not manage 9611 // runtime permissions except for the case an app targeting Lollipop MR1 9612 // being upgraded to target a newer SDK, in which case dangerous permissions 9613 // are transformed from install time to runtime ones. 9614 9615 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9616 if (ps == null) { 9617 return; 9618 } 9619 9620 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9621 9622 PermissionsState permissionsState = ps.getPermissionsState(); 9623 PermissionsState origPermissions = permissionsState; 9624 9625 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9626 9627 boolean runtimePermissionsRevoked = false; 9628 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9629 9630 boolean changedInstallPermission = false; 9631 9632 if (replace) { 9633 ps.installPermissionsFixed = false; 9634 if (!ps.isSharedUser()) { 9635 origPermissions = new PermissionsState(permissionsState); 9636 permissionsState.reset(); 9637 } else { 9638 // We need to know only about runtime permission changes since the 9639 // calling code always writes the install permissions state but 9640 // the runtime ones are written only if changed. The only cases of 9641 // changed runtime permissions here are promotion of an install to 9642 // runtime and revocation of a runtime from a shared user. 9643 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9644 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9645 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9646 runtimePermissionsRevoked = true; 9647 } 9648 } 9649 } 9650 9651 permissionsState.setGlobalGids(mGlobalGids); 9652 9653 final int N = pkg.requestedPermissions.size(); 9654 for (int i=0; i<N; i++) { 9655 final String name = pkg.requestedPermissions.get(i); 9656 final BasePermission bp = mSettings.mPermissions.get(name); 9657 9658 if (DEBUG_INSTALL) { 9659 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9660 } 9661 9662 if (bp == null || bp.packageSetting == null) { 9663 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9664 Slog.w(TAG, "Unknown permission " + name 9665 + " in package " + pkg.packageName); 9666 } 9667 continue; 9668 } 9669 9670 final String perm = bp.name; 9671 boolean allowedSig = false; 9672 int grant = GRANT_DENIED; 9673 9674 // Keep track of app op permissions. 9675 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9676 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9677 if (pkgs == null) { 9678 pkgs = new ArraySet<>(); 9679 mAppOpPermissionPackages.put(bp.name, pkgs); 9680 } 9681 pkgs.add(pkg.packageName); 9682 } 9683 9684 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9685 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9686 >= Build.VERSION_CODES.M; 9687 switch (level) { 9688 case PermissionInfo.PROTECTION_NORMAL: { 9689 // For all apps normal permissions are install time ones. 9690 grant = GRANT_INSTALL; 9691 } break; 9692 9693 case PermissionInfo.PROTECTION_DANGEROUS: { 9694 // If a permission review is required for legacy apps we represent 9695 // their permissions as always granted runtime ones since we need 9696 // to keep the review required permission flag per user while an 9697 // install permission's state is shared across all users. 9698 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9699 // For legacy apps dangerous permissions are install time ones. 9700 grant = GRANT_INSTALL; 9701 } else if (origPermissions.hasInstallPermission(bp.name)) { 9702 // For legacy apps that became modern, install becomes runtime. 9703 grant = GRANT_UPGRADE; 9704 } else if (mPromoteSystemApps 9705 && isSystemApp(ps) 9706 && mExistingSystemPackages.contains(ps.name)) { 9707 // For legacy system apps, install becomes runtime. 9708 // We cannot check hasInstallPermission() for system apps since those 9709 // permissions were granted implicitly and not persisted pre-M. 9710 grant = GRANT_UPGRADE; 9711 } else { 9712 // For modern apps keep runtime permissions unchanged. 9713 grant = GRANT_RUNTIME; 9714 } 9715 } break; 9716 9717 case PermissionInfo.PROTECTION_SIGNATURE: { 9718 // For all apps signature permissions are install time ones. 9719 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9720 if (allowedSig) { 9721 grant = GRANT_INSTALL; 9722 } 9723 } break; 9724 } 9725 9726 if (DEBUG_INSTALL) { 9727 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9728 } 9729 9730 if (grant != GRANT_DENIED) { 9731 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9732 // If this is an existing, non-system package, then 9733 // we can't add any new permissions to it. 9734 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9735 // Except... if this is a permission that was added 9736 // to the platform (note: need to only do this when 9737 // updating the platform). 9738 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9739 grant = GRANT_DENIED; 9740 } 9741 } 9742 } 9743 9744 switch (grant) { 9745 case GRANT_INSTALL: { 9746 // Revoke this as runtime permission to handle the case of 9747 // a runtime permission being downgraded to an install one. 9748 // Also in permission review mode we keep dangerous permissions 9749 // for legacy apps 9750 for (int userId : UserManagerService.getInstance().getUserIds()) { 9751 if (origPermissions.getRuntimePermissionState( 9752 bp.name, userId) != null) { 9753 // Revoke the runtime permission and clear the flags. 9754 origPermissions.revokeRuntimePermission(bp, userId); 9755 origPermissions.updatePermissionFlags(bp, userId, 9756 PackageManager.MASK_PERMISSION_FLAGS, 0); 9757 // If we revoked a permission permission, we have to write. 9758 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9759 changedRuntimePermissionUserIds, userId); 9760 } 9761 } 9762 // Grant an install permission. 9763 if (permissionsState.grantInstallPermission(bp) != 9764 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9765 changedInstallPermission = true; 9766 } 9767 } break; 9768 9769 case GRANT_RUNTIME: { 9770 // Grant previously granted runtime permissions. 9771 for (int userId : UserManagerService.getInstance().getUserIds()) { 9772 PermissionState permissionState = origPermissions 9773 .getRuntimePermissionState(bp.name, userId); 9774 int flags = permissionState != null 9775 ? permissionState.getFlags() : 0; 9776 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9777 if (permissionsState.grantRuntimePermission(bp, userId) == 9778 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9779 // If we cannot put the permission as it was, we have to write. 9780 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9781 changedRuntimePermissionUserIds, userId); 9782 } 9783 // If the app supports runtime permissions no need for a review. 9784 if (Build.PERMISSIONS_REVIEW_REQUIRED 9785 && appSupportsRuntimePermissions 9786 && (flags & PackageManager 9787 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9788 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9789 // Since we changed the flags, we have to write. 9790 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9791 changedRuntimePermissionUserIds, userId); 9792 } 9793 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9794 && !appSupportsRuntimePermissions) { 9795 // For legacy apps that need a permission review, every new 9796 // runtime permission is granted but it is pending a review. 9797 // We also need to review only platform defined runtime 9798 // permissions as these are the only ones the platform knows 9799 // how to disable the API to simulate revocation as legacy 9800 // apps don't expect to run with revoked permissions. 9801 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9802 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9803 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9804 // We changed the flags, hence have to write. 9805 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9806 changedRuntimePermissionUserIds, userId); 9807 } 9808 } 9809 if (permissionsState.grantRuntimePermission(bp, userId) 9810 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9811 // We changed the permission, hence have to write. 9812 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9813 changedRuntimePermissionUserIds, userId); 9814 } 9815 } 9816 // Propagate the permission flags. 9817 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9818 } 9819 } break; 9820 9821 case GRANT_UPGRADE: { 9822 // Grant runtime permissions for a previously held install permission. 9823 PermissionState permissionState = origPermissions 9824 .getInstallPermissionState(bp.name); 9825 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9826 9827 if (origPermissions.revokeInstallPermission(bp) 9828 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9829 // We will be transferring the permission flags, so clear them. 9830 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9831 PackageManager.MASK_PERMISSION_FLAGS, 0); 9832 changedInstallPermission = true; 9833 } 9834 9835 // If the permission is not to be promoted to runtime we ignore it and 9836 // also its other flags as they are not applicable to install permissions. 9837 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9838 for (int userId : currentUserIds) { 9839 if (permissionsState.grantRuntimePermission(bp, userId) != 9840 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9841 // Transfer the permission flags. 9842 permissionsState.updatePermissionFlags(bp, userId, 9843 flags, flags); 9844 // If we granted the permission, we have to write. 9845 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9846 changedRuntimePermissionUserIds, userId); 9847 } 9848 } 9849 } 9850 } break; 9851 9852 default: { 9853 if (packageOfInterest == null 9854 || packageOfInterest.equals(pkg.packageName)) { 9855 Slog.w(TAG, "Not granting permission " + perm 9856 + " to package " + pkg.packageName 9857 + " because it was previously installed without"); 9858 } 9859 } break; 9860 } 9861 } else { 9862 if (permissionsState.revokeInstallPermission(bp) != 9863 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9864 // Also drop the permission flags. 9865 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9866 PackageManager.MASK_PERMISSION_FLAGS, 0); 9867 changedInstallPermission = true; 9868 Slog.i(TAG, "Un-granting permission " + perm 9869 + " from package " + pkg.packageName 9870 + " (protectionLevel=" + bp.protectionLevel 9871 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9872 + ")"); 9873 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9874 // Don't print warning for app op permissions, since it is fine for them 9875 // not to be granted, there is a UI for the user to decide. 9876 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9877 Slog.w(TAG, "Not granting permission " + perm 9878 + " to package " + pkg.packageName 9879 + " (protectionLevel=" + bp.protectionLevel 9880 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9881 + ")"); 9882 } 9883 } 9884 } 9885 } 9886 9887 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9888 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9889 // This is the first that we have heard about this package, so the 9890 // permissions we have now selected are fixed until explicitly 9891 // changed. 9892 ps.installPermissionsFixed = true; 9893 } 9894 9895 // Persist the runtime permissions state for users with changes. If permissions 9896 // were revoked because no app in the shared user declares them we have to 9897 // write synchronously to avoid losing runtime permissions state. 9898 for (int userId : changedRuntimePermissionUserIds) { 9899 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9900 } 9901 9902 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9903 } 9904 9905 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9906 boolean allowed = false; 9907 final int NP = PackageParser.NEW_PERMISSIONS.length; 9908 for (int ip=0; ip<NP; ip++) { 9909 final PackageParser.NewPermissionInfo npi 9910 = PackageParser.NEW_PERMISSIONS[ip]; 9911 if (npi.name.equals(perm) 9912 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9913 allowed = true; 9914 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9915 + pkg.packageName); 9916 break; 9917 } 9918 } 9919 return allowed; 9920 } 9921 9922 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9923 BasePermission bp, PermissionsState origPermissions) { 9924 boolean allowed; 9925 allowed = (compareSignatures( 9926 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9927 == PackageManager.SIGNATURE_MATCH) 9928 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9929 == PackageManager.SIGNATURE_MATCH); 9930 if (!allowed && (bp.protectionLevel 9931 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9932 if (isSystemApp(pkg)) { 9933 // For updated system applications, a system permission 9934 // is granted only if it had been defined by the original application. 9935 if (pkg.isUpdatedSystemApp()) { 9936 final PackageSetting sysPs = mSettings 9937 .getDisabledSystemPkgLPr(pkg.packageName); 9938 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9939 // If the original was granted this permission, we take 9940 // that grant decision as read and propagate it to the 9941 // update. 9942 if (sysPs.isPrivileged()) { 9943 allowed = true; 9944 } 9945 } else { 9946 // The system apk may have been updated with an older 9947 // version of the one on the data partition, but which 9948 // granted a new system permission that it didn't have 9949 // before. In this case we do want to allow the app to 9950 // now get the new permission if the ancestral apk is 9951 // privileged to get it. 9952 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9953 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9954 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9955 allowed = true; 9956 break; 9957 } 9958 } 9959 } 9960 // Also if a privileged parent package on the system image or any of 9961 // its children requested a privileged permission, the updated child 9962 // packages can also get the permission. 9963 if (pkg.parentPackage != null) { 9964 final PackageSetting disabledSysParentPs = mSettings 9965 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9966 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9967 && disabledSysParentPs.isPrivileged()) { 9968 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9969 allowed = true; 9970 } else if (disabledSysParentPs.pkg.childPackages != null) { 9971 final int count = disabledSysParentPs.pkg.childPackages.size(); 9972 for (int i = 0; i < count; i++) { 9973 PackageParser.Package disabledSysChildPkg = 9974 disabledSysParentPs.pkg.childPackages.get(i); 9975 if (isPackageRequestingPermission(disabledSysChildPkg, 9976 perm)) { 9977 allowed = true; 9978 break; 9979 } 9980 } 9981 } 9982 } 9983 } 9984 } 9985 } else { 9986 allowed = isPrivilegedApp(pkg); 9987 } 9988 } 9989 } 9990 if (!allowed) { 9991 if (!allowed && (bp.protectionLevel 9992 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9993 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9994 // If this was a previously normal/dangerous permission that got moved 9995 // to a system permission as part of the runtime permission redesign, then 9996 // we still want to blindly grant it to old apps. 9997 allowed = true; 9998 } 9999 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10000 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10001 // If this permission is to be granted to the system installer and 10002 // this app is an installer, then it gets the permission. 10003 allowed = true; 10004 } 10005 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10006 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10007 // If this permission is to be granted to the system verifier and 10008 // this app is a verifier, then it gets the permission. 10009 allowed = true; 10010 } 10011 if (!allowed && (bp.protectionLevel 10012 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10013 && isSystemApp(pkg)) { 10014 // Any pre-installed system app is allowed to get this permission. 10015 allowed = true; 10016 } 10017 if (!allowed && (bp.protectionLevel 10018 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10019 // For development permissions, a development permission 10020 // is granted only if it was already granted. 10021 allowed = origPermissions.hasInstallPermission(perm); 10022 } 10023 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10024 && pkg.packageName.equals(mSetupWizardPackage)) { 10025 // If this permission is to be granted to the system setup wizard and 10026 // this app is a setup wizard, then it gets the permission. 10027 allowed = true; 10028 } 10029 } 10030 return allowed; 10031 } 10032 10033 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10034 final int permCount = pkg.requestedPermissions.size(); 10035 for (int j = 0; j < permCount; j++) { 10036 String requestedPermission = pkg.requestedPermissions.get(j); 10037 if (permission.equals(requestedPermission)) { 10038 return true; 10039 } 10040 } 10041 return false; 10042 } 10043 10044 final class ActivityIntentResolver 10045 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10046 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10047 boolean defaultOnly, int userId) { 10048 if (!sUserManager.exists(userId)) return null; 10049 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10050 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10051 } 10052 10053 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10054 int userId) { 10055 if (!sUserManager.exists(userId)) return null; 10056 mFlags = flags; 10057 return super.queryIntent(intent, resolvedType, 10058 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10059 } 10060 10061 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10062 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10063 if (!sUserManager.exists(userId)) return null; 10064 if (packageActivities == null) { 10065 return null; 10066 } 10067 mFlags = flags; 10068 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10069 final int N = packageActivities.size(); 10070 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10071 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10072 10073 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10074 for (int i = 0; i < N; ++i) { 10075 intentFilters = packageActivities.get(i).intents; 10076 if (intentFilters != null && intentFilters.size() > 0) { 10077 PackageParser.ActivityIntentInfo[] array = 10078 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10079 intentFilters.toArray(array); 10080 listCut.add(array); 10081 } 10082 } 10083 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10084 } 10085 10086 /** 10087 * Finds a privileged activity that matches the specified activity names. 10088 */ 10089 private PackageParser.Activity findMatchingActivity( 10090 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10091 for (PackageParser.Activity sysActivity : activityList) { 10092 if (sysActivity.info.name.equals(activityInfo.name)) { 10093 return sysActivity; 10094 } 10095 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10096 return sysActivity; 10097 } 10098 if (sysActivity.info.targetActivity != null) { 10099 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10100 return sysActivity; 10101 } 10102 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10103 return sysActivity; 10104 } 10105 } 10106 } 10107 return null; 10108 } 10109 10110 public class IterGenerator<E> { 10111 public Iterator<E> generate(ActivityIntentInfo info) { 10112 return null; 10113 } 10114 } 10115 10116 public class ActionIterGenerator extends IterGenerator<String> { 10117 @Override 10118 public Iterator<String> generate(ActivityIntentInfo info) { 10119 return info.actionsIterator(); 10120 } 10121 } 10122 10123 public class CategoriesIterGenerator extends IterGenerator<String> { 10124 @Override 10125 public Iterator<String> generate(ActivityIntentInfo info) { 10126 return info.categoriesIterator(); 10127 } 10128 } 10129 10130 public class SchemesIterGenerator extends IterGenerator<String> { 10131 @Override 10132 public Iterator<String> generate(ActivityIntentInfo info) { 10133 return info.schemesIterator(); 10134 } 10135 } 10136 10137 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10138 @Override 10139 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10140 return info.authoritiesIterator(); 10141 } 10142 } 10143 10144 /** 10145 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10146 * MODIFIED. Do not pass in a list that should not be changed. 10147 */ 10148 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10149 IterGenerator<T> generator, Iterator<T> searchIterator) { 10150 // loop through the set of actions; every one must be found in the intent filter 10151 while (searchIterator.hasNext()) { 10152 // we must have at least one filter in the list to consider a match 10153 if (intentList.size() == 0) { 10154 break; 10155 } 10156 10157 final T searchAction = searchIterator.next(); 10158 10159 // loop through the set of intent filters 10160 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10161 while (intentIter.hasNext()) { 10162 final ActivityIntentInfo intentInfo = intentIter.next(); 10163 boolean selectionFound = false; 10164 10165 // loop through the intent filter's selection criteria; at least one 10166 // of them must match the searched criteria 10167 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10168 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10169 final T intentSelection = intentSelectionIter.next(); 10170 if (intentSelection != null && intentSelection.equals(searchAction)) { 10171 selectionFound = true; 10172 break; 10173 } 10174 } 10175 10176 // the selection criteria wasn't found in this filter's set; this filter 10177 // is not a potential match 10178 if (!selectionFound) { 10179 intentIter.remove(); 10180 } 10181 } 10182 } 10183 } 10184 10185 private boolean isProtectedAction(ActivityIntentInfo filter) { 10186 final Iterator<String> actionsIter = filter.actionsIterator(); 10187 while (actionsIter != null && actionsIter.hasNext()) { 10188 final String filterAction = actionsIter.next(); 10189 if (PROTECTED_ACTIONS.contains(filterAction)) { 10190 return true; 10191 } 10192 } 10193 return false; 10194 } 10195 10196 /** 10197 * Adjusts the priority of the given intent filter according to policy. 10198 * <p> 10199 * <ul> 10200 * <li>The priority for non privileged applications is capped to '0'</li> 10201 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10202 * <li>The priority for unbundled updates to privileged applications is capped to the 10203 * priority defined on the system partition</li> 10204 * </ul> 10205 * <p> 10206 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10207 * allowed to obtain any priority on any action. 10208 */ 10209 private void adjustPriority( 10210 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10211 // nothing to do; priority is fine as-is 10212 if (intent.getPriority() <= 0) { 10213 return; 10214 } 10215 10216 final ActivityInfo activityInfo = intent.activity.info; 10217 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10218 10219 final boolean privilegedApp = 10220 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10221 if (!privilegedApp) { 10222 // non-privileged applications can never define a priority >0 10223 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10224 + " package: " + applicationInfo.packageName 10225 + " activity: " + intent.activity.className 10226 + " origPrio: " + intent.getPriority()); 10227 intent.setPriority(0); 10228 return; 10229 } 10230 10231 if (systemActivities == null) { 10232 // the system package is not disabled; we're parsing the system partition 10233 if (isProtectedAction(intent)) { 10234 if (mDeferProtectedFilters) { 10235 // We can't deal with these just yet. No component should ever obtain a 10236 // >0 priority for a protected actions, with ONE exception -- the setup 10237 // wizard. The setup wizard, however, cannot be known until we're able to 10238 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10239 // until all intent filters have been processed. Chicken, meet egg. 10240 // Let the filter temporarily have a high priority and rectify the 10241 // priorities after all system packages have been scanned. 10242 mProtectedFilters.add(intent); 10243 if (DEBUG_FILTERS) { 10244 Slog.i(TAG, "Protected action; save for later;" 10245 + " package: " + applicationInfo.packageName 10246 + " activity: " + intent.activity.className 10247 + " origPrio: " + intent.getPriority()); 10248 } 10249 return; 10250 } else { 10251 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10252 Slog.i(TAG, "No setup wizard;" 10253 + " All protected intents capped to priority 0"); 10254 } 10255 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10256 if (DEBUG_FILTERS) { 10257 Slog.i(TAG, "Found setup wizard;" 10258 + " allow priority " + intent.getPriority() + ";" 10259 + " package: " + intent.activity.info.packageName 10260 + " activity: " + intent.activity.className 10261 + " priority: " + intent.getPriority()); 10262 } 10263 // setup wizard gets whatever it wants 10264 return; 10265 } 10266 Slog.w(TAG, "Protected action; cap priority to 0;" 10267 + " package: " + intent.activity.info.packageName 10268 + " activity: " + intent.activity.className 10269 + " origPrio: " + intent.getPriority()); 10270 intent.setPriority(0); 10271 return; 10272 } 10273 } 10274 // privileged apps on the system image get whatever priority they request 10275 return; 10276 } 10277 10278 // privileged app unbundled update ... try to find the same activity 10279 final PackageParser.Activity foundActivity = 10280 findMatchingActivity(systemActivities, activityInfo); 10281 if (foundActivity == null) { 10282 // this is a new activity; it cannot obtain >0 priority 10283 if (DEBUG_FILTERS) { 10284 Slog.i(TAG, "New activity; cap priority to 0;" 10285 + " package: " + applicationInfo.packageName 10286 + " activity: " + intent.activity.className 10287 + " origPrio: " + intent.getPriority()); 10288 } 10289 intent.setPriority(0); 10290 return; 10291 } 10292 10293 // found activity, now check for filter equivalence 10294 10295 // a shallow copy is enough; we modify the list, not its contents 10296 final List<ActivityIntentInfo> intentListCopy = 10297 new ArrayList<>(foundActivity.intents); 10298 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10299 10300 // find matching action subsets 10301 final Iterator<String> actionsIterator = intent.actionsIterator(); 10302 if (actionsIterator != null) { 10303 getIntentListSubset( 10304 intentListCopy, new ActionIterGenerator(), actionsIterator); 10305 if (intentListCopy.size() == 0) { 10306 // no more intents to match; we're not equivalent 10307 if (DEBUG_FILTERS) { 10308 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10309 + " package: " + applicationInfo.packageName 10310 + " activity: " + intent.activity.className 10311 + " origPrio: " + intent.getPriority()); 10312 } 10313 intent.setPriority(0); 10314 return; 10315 } 10316 } 10317 10318 // find matching category subsets 10319 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10320 if (categoriesIterator != null) { 10321 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10322 categoriesIterator); 10323 if (intentListCopy.size() == 0) { 10324 // no more intents to match; we're not equivalent 10325 if (DEBUG_FILTERS) { 10326 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10327 + " package: " + applicationInfo.packageName 10328 + " activity: " + intent.activity.className 10329 + " origPrio: " + intent.getPriority()); 10330 } 10331 intent.setPriority(0); 10332 return; 10333 } 10334 } 10335 10336 // find matching schemes subsets 10337 final Iterator<String> schemesIterator = intent.schemesIterator(); 10338 if (schemesIterator != null) { 10339 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10340 schemesIterator); 10341 if (intentListCopy.size() == 0) { 10342 // no more intents to match; we're not equivalent 10343 if (DEBUG_FILTERS) { 10344 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10345 + " package: " + applicationInfo.packageName 10346 + " activity: " + intent.activity.className 10347 + " origPrio: " + intent.getPriority()); 10348 } 10349 intent.setPriority(0); 10350 return; 10351 } 10352 } 10353 10354 // find matching authorities subsets 10355 final Iterator<IntentFilter.AuthorityEntry> 10356 authoritiesIterator = intent.authoritiesIterator(); 10357 if (authoritiesIterator != null) { 10358 getIntentListSubset(intentListCopy, 10359 new AuthoritiesIterGenerator(), 10360 authoritiesIterator); 10361 if (intentListCopy.size() == 0) { 10362 // no more intents to match; we're not equivalent 10363 if (DEBUG_FILTERS) { 10364 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10365 + " package: " + applicationInfo.packageName 10366 + " activity: " + intent.activity.className 10367 + " origPrio: " + intent.getPriority()); 10368 } 10369 intent.setPriority(0); 10370 return; 10371 } 10372 } 10373 10374 // we found matching filter(s); app gets the max priority of all intents 10375 int cappedPriority = 0; 10376 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10377 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10378 } 10379 if (intent.getPriority() > cappedPriority) { 10380 if (DEBUG_FILTERS) { 10381 Slog.i(TAG, "Found matching filter(s);" 10382 + " cap priority to " + cappedPriority + ";" 10383 + " package: " + applicationInfo.packageName 10384 + " activity: " + intent.activity.className 10385 + " origPrio: " + intent.getPriority()); 10386 } 10387 intent.setPriority(cappedPriority); 10388 return; 10389 } 10390 // all this for nothing; the requested priority was <= what was on the system 10391 } 10392 10393 public final void addActivity(PackageParser.Activity a, String type) { 10394 mActivities.put(a.getComponentName(), a); 10395 if (DEBUG_SHOW_INFO) 10396 Log.v( 10397 TAG, " " + type + " " + 10398 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10399 if (DEBUG_SHOW_INFO) 10400 Log.v(TAG, " Class=" + a.info.name); 10401 final int NI = a.intents.size(); 10402 for (int j=0; j<NI; j++) { 10403 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10404 if ("activity".equals(type)) { 10405 final PackageSetting ps = 10406 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10407 final List<PackageParser.Activity> systemActivities = 10408 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10409 adjustPriority(systemActivities, intent); 10410 } 10411 if (DEBUG_SHOW_INFO) { 10412 Log.v(TAG, " IntentFilter:"); 10413 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10414 } 10415 if (!intent.debugCheck()) { 10416 Log.w(TAG, "==> For Activity " + a.info.name); 10417 } 10418 addFilter(intent); 10419 } 10420 } 10421 10422 public final void removeActivity(PackageParser.Activity a, String type) { 10423 mActivities.remove(a.getComponentName()); 10424 if (DEBUG_SHOW_INFO) { 10425 Log.v(TAG, " " + type + " " 10426 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10427 : a.info.name) + ":"); 10428 Log.v(TAG, " Class=" + a.info.name); 10429 } 10430 final int NI = a.intents.size(); 10431 for (int j=0; j<NI; j++) { 10432 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10433 if (DEBUG_SHOW_INFO) { 10434 Log.v(TAG, " IntentFilter:"); 10435 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10436 } 10437 removeFilter(intent); 10438 } 10439 } 10440 10441 @Override 10442 protected boolean allowFilterResult( 10443 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10444 ActivityInfo filterAi = filter.activity.info; 10445 for (int i=dest.size()-1; i>=0; i--) { 10446 ActivityInfo destAi = dest.get(i).activityInfo; 10447 if (destAi.name == filterAi.name 10448 && destAi.packageName == filterAi.packageName) { 10449 return false; 10450 } 10451 } 10452 return true; 10453 } 10454 10455 @Override 10456 protected ActivityIntentInfo[] newArray(int size) { 10457 return new ActivityIntentInfo[size]; 10458 } 10459 10460 @Override 10461 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10462 if (!sUserManager.exists(userId)) return true; 10463 PackageParser.Package p = filter.activity.owner; 10464 if (p != null) { 10465 PackageSetting ps = (PackageSetting)p.mExtras; 10466 if (ps != null) { 10467 // System apps are never considered stopped for purposes of 10468 // filtering, because there may be no way for the user to 10469 // actually re-launch them. 10470 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10471 && ps.getStopped(userId); 10472 } 10473 } 10474 return false; 10475 } 10476 10477 @Override 10478 protected boolean isPackageForFilter(String packageName, 10479 PackageParser.ActivityIntentInfo info) { 10480 return packageName.equals(info.activity.owner.packageName); 10481 } 10482 10483 @Override 10484 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10485 int match, int userId) { 10486 if (!sUserManager.exists(userId)) return null; 10487 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10488 return null; 10489 } 10490 final PackageParser.Activity activity = info.activity; 10491 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10492 if (ps == null) { 10493 return null; 10494 } 10495 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10496 ps.readUserState(userId), userId); 10497 if (ai == null) { 10498 return null; 10499 } 10500 final ResolveInfo res = new ResolveInfo(); 10501 res.activityInfo = ai; 10502 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10503 res.filter = info; 10504 } 10505 if (info != null) { 10506 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10507 } 10508 res.priority = info.getPriority(); 10509 res.preferredOrder = activity.owner.mPreferredOrder; 10510 //System.out.println("Result: " + res.activityInfo.className + 10511 // " = " + res.priority); 10512 res.match = match; 10513 res.isDefault = info.hasDefault; 10514 res.labelRes = info.labelRes; 10515 res.nonLocalizedLabel = info.nonLocalizedLabel; 10516 if (userNeedsBadging(userId)) { 10517 res.noResourceId = true; 10518 } else { 10519 res.icon = info.icon; 10520 } 10521 res.iconResourceId = info.icon; 10522 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10523 return res; 10524 } 10525 10526 @Override 10527 protected void sortResults(List<ResolveInfo> results) { 10528 Collections.sort(results, mResolvePrioritySorter); 10529 } 10530 10531 @Override 10532 protected void dumpFilter(PrintWriter out, String prefix, 10533 PackageParser.ActivityIntentInfo filter) { 10534 out.print(prefix); out.print( 10535 Integer.toHexString(System.identityHashCode(filter.activity))); 10536 out.print(' '); 10537 filter.activity.printComponentShortName(out); 10538 out.print(" filter "); 10539 out.println(Integer.toHexString(System.identityHashCode(filter))); 10540 } 10541 10542 @Override 10543 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10544 return filter.activity; 10545 } 10546 10547 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10548 PackageParser.Activity activity = (PackageParser.Activity)label; 10549 out.print(prefix); out.print( 10550 Integer.toHexString(System.identityHashCode(activity))); 10551 out.print(' '); 10552 activity.printComponentShortName(out); 10553 if (count > 1) { 10554 out.print(" ("); out.print(count); out.print(" filters)"); 10555 } 10556 out.println(); 10557 } 10558 10559 // Keys are String (activity class name), values are Activity. 10560 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10561 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10562 private int mFlags; 10563 } 10564 10565 private final class ServiceIntentResolver 10566 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10567 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10568 boolean defaultOnly, int userId) { 10569 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10570 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10571 } 10572 10573 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10574 int userId) { 10575 if (!sUserManager.exists(userId)) return null; 10576 mFlags = flags; 10577 return super.queryIntent(intent, resolvedType, 10578 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10579 } 10580 10581 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10582 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10583 if (!sUserManager.exists(userId)) return null; 10584 if (packageServices == null) { 10585 return null; 10586 } 10587 mFlags = flags; 10588 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10589 final int N = packageServices.size(); 10590 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10591 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10592 10593 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10594 for (int i = 0; i < N; ++i) { 10595 intentFilters = packageServices.get(i).intents; 10596 if (intentFilters != null && intentFilters.size() > 0) { 10597 PackageParser.ServiceIntentInfo[] array = 10598 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10599 intentFilters.toArray(array); 10600 listCut.add(array); 10601 } 10602 } 10603 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10604 } 10605 10606 public final void addService(PackageParser.Service s) { 10607 mServices.put(s.getComponentName(), s); 10608 if (DEBUG_SHOW_INFO) { 10609 Log.v(TAG, " " 10610 + (s.info.nonLocalizedLabel != null 10611 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10612 Log.v(TAG, " Class=" + s.info.name); 10613 } 10614 final int NI = s.intents.size(); 10615 int j; 10616 for (j=0; j<NI; j++) { 10617 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10618 if (DEBUG_SHOW_INFO) { 10619 Log.v(TAG, " IntentFilter:"); 10620 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10621 } 10622 if (!intent.debugCheck()) { 10623 Log.w(TAG, "==> For Service " + s.info.name); 10624 } 10625 addFilter(intent); 10626 } 10627 } 10628 10629 public final void removeService(PackageParser.Service s) { 10630 mServices.remove(s.getComponentName()); 10631 if (DEBUG_SHOW_INFO) { 10632 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10633 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10634 Log.v(TAG, " Class=" + s.info.name); 10635 } 10636 final int NI = s.intents.size(); 10637 int j; 10638 for (j=0; j<NI; j++) { 10639 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10640 if (DEBUG_SHOW_INFO) { 10641 Log.v(TAG, " IntentFilter:"); 10642 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10643 } 10644 removeFilter(intent); 10645 } 10646 } 10647 10648 @Override 10649 protected boolean allowFilterResult( 10650 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10651 ServiceInfo filterSi = filter.service.info; 10652 for (int i=dest.size()-1; i>=0; i--) { 10653 ServiceInfo destAi = dest.get(i).serviceInfo; 10654 if (destAi.name == filterSi.name 10655 && destAi.packageName == filterSi.packageName) { 10656 return false; 10657 } 10658 } 10659 return true; 10660 } 10661 10662 @Override 10663 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10664 return new PackageParser.ServiceIntentInfo[size]; 10665 } 10666 10667 @Override 10668 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10669 if (!sUserManager.exists(userId)) return true; 10670 PackageParser.Package p = filter.service.owner; 10671 if (p != null) { 10672 PackageSetting ps = (PackageSetting)p.mExtras; 10673 if (ps != null) { 10674 // System apps are never considered stopped for purposes of 10675 // filtering, because there may be no way for the user to 10676 // actually re-launch them. 10677 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10678 && ps.getStopped(userId); 10679 } 10680 } 10681 return false; 10682 } 10683 10684 @Override 10685 protected boolean isPackageForFilter(String packageName, 10686 PackageParser.ServiceIntentInfo info) { 10687 return packageName.equals(info.service.owner.packageName); 10688 } 10689 10690 @Override 10691 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10692 int match, int userId) { 10693 if (!sUserManager.exists(userId)) return null; 10694 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10695 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10696 return null; 10697 } 10698 final PackageParser.Service service = info.service; 10699 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10700 if (ps == null) { 10701 return null; 10702 } 10703 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10704 ps.readUserState(userId), userId); 10705 if (si == null) { 10706 return null; 10707 } 10708 final ResolveInfo res = new ResolveInfo(); 10709 res.serviceInfo = si; 10710 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10711 res.filter = filter; 10712 } 10713 res.priority = info.getPriority(); 10714 res.preferredOrder = service.owner.mPreferredOrder; 10715 res.match = match; 10716 res.isDefault = info.hasDefault; 10717 res.labelRes = info.labelRes; 10718 res.nonLocalizedLabel = info.nonLocalizedLabel; 10719 res.icon = info.icon; 10720 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10721 return res; 10722 } 10723 10724 @Override 10725 protected void sortResults(List<ResolveInfo> results) { 10726 Collections.sort(results, mResolvePrioritySorter); 10727 } 10728 10729 @Override 10730 protected void dumpFilter(PrintWriter out, String prefix, 10731 PackageParser.ServiceIntentInfo filter) { 10732 out.print(prefix); out.print( 10733 Integer.toHexString(System.identityHashCode(filter.service))); 10734 out.print(' '); 10735 filter.service.printComponentShortName(out); 10736 out.print(" filter "); 10737 out.println(Integer.toHexString(System.identityHashCode(filter))); 10738 } 10739 10740 @Override 10741 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10742 return filter.service; 10743 } 10744 10745 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10746 PackageParser.Service service = (PackageParser.Service)label; 10747 out.print(prefix); out.print( 10748 Integer.toHexString(System.identityHashCode(service))); 10749 out.print(' '); 10750 service.printComponentShortName(out); 10751 if (count > 1) { 10752 out.print(" ("); out.print(count); out.print(" filters)"); 10753 } 10754 out.println(); 10755 } 10756 10757// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10758// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10759// final List<ResolveInfo> retList = Lists.newArrayList(); 10760// while (i.hasNext()) { 10761// final ResolveInfo resolveInfo = (ResolveInfo) i; 10762// if (isEnabledLP(resolveInfo.serviceInfo)) { 10763// retList.add(resolveInfo); 10764// } 10765// } 10766// return retList; 10767// } 10768 10769 // Keys are String (activity class name), values are Activity. 10770 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10771 = new ArrayMap<ComponentName, PackageParser.Service>(); 10772 private int mFlags; 10773 }; 10774 10775 private final class ProviderIntentResolver 10776 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10777 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10778 boolean defaultOnly, int userId) { 10779 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10780 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10781 } 10782 10783 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10784 int userId) { 10785 if (!sUserManager.exists(userId)) 10786 return null; 10787 mFlags = flags; 10788 return super.queryIntent(intent, resolvedType, 10789 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10790 } 10791 10792 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10793 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10794 if (!sUserManager.exists(userId)) 10795 return null; 10796 if (packageProviders == null) { 10797 return null; 10798 } 10799 mFlags = flags; 10800 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10801 final int N = packageProviders.size(); 10802 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10803 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10804 10805 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10806 for (int i = 0; i < N; ++i) { 10807 intentFilters = packageProviders.get(i).intents; 10808 if (intentFilters != null && intentFilters.size() > 0) { 10809 PackageParser.ProviderIntentInfo[] array = 10810 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10811 intentFilters.toArray(array); 10812 listCut.add(array); 10813 } 10814 } 10815 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10816 } 10817 10818 public final void addProvider(PackageParser.Provider p) { 10819 if (mProviders.containsKey(p.getComponentName())) { 10820 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10821 return; 10822 } 10823 10824 mProviders.put(p.getComponentName(), p); 10825 if (DEBUG_SHOW_INFO) { 10826 Log.v(TAG, " " 10827 + (p.info.nonLocalizedLabel != null 10828 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10829 Log.v(TAG, " Class=" + p.info.name); 10830 } 10831 final int NI = p.intents.size(); 10832 int j; 10833 for (j = 0; j < NI; j++) { 10834 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10835 if (DEBUG_SHOW_INFO) { 10836 Log.v(TAG, " IntentFilter:"); 10837 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10838 } 10839 if (!intent.debugCheck()) { 10840 Log.w(TAG, "==> For Provider " + p.info.name); 10841 } 10842 addFilter(intent); 10843 } 10844 } 10845 10846 public final void removeProvider(PackageParser.Provider p) { 10847 mProviders.remove(p.getComponentName()); 10848 if (DEBUG_SHOW_INFO) { 10849 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10850 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10851 Log.v(TAG, " Class=" + p.info.name); 10852 } 10853 final int NI = p.intents.size(); 10854 int j; 10855 for (j = 0; j < NI; j++) { 10856 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10857 if (DEBUG_SHOW_INFO) { 10858 Log.v(TAG, " IntentFilter:"); 10859 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10860 } 10861 removeFilter(intent); 10862 } 10863 } 10864 10865 @Override 10866 protected boolean allowFilterResult( 10867 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10868 ProviderInfo filterPi = filter.provider.info; 10869 for (int i = dest.size() - 1; i >= 0; i--) { 10870 ProviderInfo destPi = dest.get(i).providerInfo; 10871 if (destPi.name == filterPi.name 10872 && destPi.packageName == filterPi.packageName) { 10873 return false; 10874 } 10875 } 10876 return true; 10877 } 10878 10879 @Override 10880 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10881 return new PackageParser.ProviderIntentInfo[size]; 10882 } 10883 10884 @Override 10885 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10886 if (!sUserManager.exists(userId)) 10887 return true; 10888 PackageParser.Package p = filter.provider.owner; 10889 if (p != null) { 10890 PackageSetting ps = (PackageSetting) p.mExtras; 10891 if (ps != null) { 10892 // System apps are never considered stopped for purposes of 10893 // filtering, because there may be no way for the user to 10894 // actually re-launch them. 10895 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10896 && ps.getStopped(userId); 10897 } 10898 } 10899 return false; 10900 } 10901 10902 @Override 10903 protected boolean isPackageForFilter(String packageName, 10904 PackageParser.ProviderIntentInfo info) { 10905 return packageName.equals(info.provider.owner.packageName); 10906 } 10907 10908 @Override 10909 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10910 int match, int userId) { 10911 if (!sUserManager.exists(userId)) 10912 return null; 10913 final PackageParser.ProviderIntentInfo info = filter; 10914 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10915 return null; 10916 } 10917 final PackageParser.Provider provider = info.provider; 10918 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10919 if (ps == null) { 10920 return null; 10921 } 10922 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10923 ps.readUserState(userId), userId); 10924 if (pi == null) { 10925 return null; 10926 } 10927 final ResolveInfo res = new ResolveInfo(); 10928 res.providerInfo = pi; 10929 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10930 res.filter = filter; 10931 } 10932 res.priority = info.getPriority(); 10933 res.preferredOrder = provider.owner.mPreferredOrder; 10934 res.match = match; 10935 res.isDefault = info.hasDefault; 10936 res.labelRes = info.labelRes; 10937 res.nonLocalizedLabel = info.nonLocalizedLabel; 10938 res.icon = info.icon; 10939 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10940 return res; 10941 } 10942 10943 @Override 10944 protected void sortResults(List<ResolveInfo> results) { 10945 Collections.sort(results, mResolvePrioritySorter); 10946 } 10947 10948 @Override 10949 protected void dumpFilter(PrintWriter out, String prefix, 10950 PackageParser.ProviderIntentInfo filter) { 10951 out.print(prefix); 10952 out.print( 10953 Integer.toHexString(System.identityHashCode(filter.provider))); 10954 out.print(' '); 10955 filter.provider.printComponentShortName(out); 10956 out.print(" filter "); 10957 out.println(Integer.toHexString(System.identityHashCode(filter))); 10958 } 10959 10960 @Override 10961 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10962 return filter.provider; 10963 } 10964 10965 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10966 PackageParser.Provider provider = (PackageParser.Provider)label; 10967 out.print(prefix); out.print( 10968 Integer.toHexString(System.identityHashCode(provider))); 10969 out.print(' '); 10970 provider.printComponentShortName(out); 10971 if (count > 1) { 10972 out.print(" ("); out.print(count); out.print(" filters)"); 10973 } 10974 out.println(); 10975 } 10976 10977 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10978 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10979 private int mFlags; 10980 } 10981 10982 private static final class EphemeralIntentResolver 10983 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10984 @Override 10985 protected EphemeralResolveIntentInfo[] newArray(int size) { 10986 return new EphemeralResolveIntentInfo[size]; 10987 } 10988 10989 @Override 10990 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10991 return true; 10992 } 10993 10994 @Override 10995 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10996 int userId) { 10997 if (!sUserManager.exists(userId)) { 10998 return null; 10999 } 11000 return info.getEphemeralResolveInfo(); 11001 } 11002 } 11003 11004 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11005 new Comparator<ResolveInfo>() { 11006 public int compare(ResolveInfo r1, ResolveInfo r2) { 11007 int v1 = r1.priority; 11008 int v2 = r2.priority; 11009 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11010 if (v1 != v2) { 11011 return (v1 > v2) ? -1 : 1; 11012 } 11013 v1 = r1.preferredOrder; 11014 v2 = r2.preferredOrder; 11015 if (v1 != v2) { 11016 return (v1 > v2) ? -1 : 1; 11017 } 11018 if (r1.isDefault != r2.isDefault) { 11019 return r1.isDefault ? -1 : 1; 11020 } 11021 v1 = r1.match; 11022 v2 = r2.match; 11023 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11024 if (v1 != v2) { 11025 return (v1 > v2) ? -1 : 1; 11026 } 11027 if (r1.system != r2.system) { 11028 return r1.system ? -1 : 1; 11029 } 11030 if (r1.activityInfo != null) { 11031 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11032 } 11033 if (r1.serviceInfo != null) { 11034 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11035 } 11036 if (r1.providerInfo != null) { 11037 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11038 } 11039 return 0; 11040 } 11041 }; 11042 11043 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11044 new Comparator<ProviderInfo>() { 11045 public int compare(ProviderInfo p1, ProviderInfo p2) { 11046 final int v1 = p1.initOrder; 11047 final int v2 = p2.initOrder; 11048 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11049 } 11050 }; 11051 11052 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11053 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11054 final int[] userIds) { 11055 mHandler.post(new Runnable() { 11056 @Override 11057 public void run() { 11058 try { 11059 final IActivityManager am = ActivityManagerNative.getDefault(); 11060 if (am == null) return; 11061 final int[] resolvedUserIds; 11062 if (userIds == null) { 11063 resolvedUserIds = am.getRunningUserIds(); 11064 } else { 11065 resolvedUserIds = userIds; 11066 } 11067 for (int id : resolvedUserIds) { 11068 final Intent intent = new Intent(action, 11069 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11070 if (extras != null) { 11071 intent.putExtras(extras); 11072 } 11073 if (targetPkg != null) { 11074 intent.setPackage(targetPkg); 11075 } 11076 // Modify the UID when posting to other users 11077 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11078 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11079 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11080 intent.putExtra(Intent.EXTRA_UID, uid); 11081 } 11082 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11083 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11084 if (DEBUG_BROADCASTS) { 11085 RuntimeException here = new RuntimeException("here"); 11086 here.fillInStackTrace(); 11087 Slog.d(TAG, "Sending to user " + id + ": " 11088 + intent.toShortString(false, true, false, false) 11089 + " " + intent.getExtras(), here); 11090 } 11091 am.broadcastIntent(null, intent, null, finishedReceiver, 11092 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11093 null, finishedReceiver != null, false, id); 11094 } 11095 } catch (RemoteException ex) { 11096 } 11097 } 11098 }); 11099 } 11100 11101 /** 11102 * Check if the external storage media is available. This is true if there 11103 * is a mounted external storage medium or if the external storage is 11104 * emulated. 11105 */ 11106 private boolean isExternalMediaAvailable() { 11107 return mMediaMounted || Environment.isExternalStorageEmulated(); 11108 } 11109 11110 @Override 11111 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11112 // writer 11113 synchronized (mPackages) { 11114 if (!isExternalMediaAvailable()) { 11115 // If the external storage is no longer mounted at this point, 11116 // the caller may not have been able to delete all of this 11117 // packages files and can not delete any more. Bail. 11118 return null; 11119 } 11120 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11121 if (lastPackage != null) { 11122 pkgs.remove(lastPackage); 11123 } 11124 if (pkgs.size() > 0) { 11125 return pkgs.get(0); 11126 } 11127 } 11128 return null; 11129 } 11130 11131 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11132 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11133 userId, andCode ? 1 : 0, packageName); 11134 if (mSystemReady) { 11135 msg.sendToTarget(); 11136 } else { 11137 if (mPostSystemReadyMessages == null) { 11138 mPostSystemReadyMessages = new ArrayList<>(); 11139 } 11140 mPostSystemReadyMessages.add(msg); 11141 } 11142 } 11143 11144 void startCleaningPackages() { 11145 // reader 11146 if (!isExternalMediaAvailable()) { 11147 return; 11148 } 11149 synchronized (mPackages) { 11150 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11151 return; 11152 } 11153 } 11154 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11155 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11156 IActivityManager am = ActivityManagerNative.getDefault(); 11157 if (am != null) { 11158 try { 11159 am.startService(null, intent, null, mContext.getOpPackageName(), 11160 UserHandle.USER_SYSTEM); 11161 } catch (RemoteException e) { 11162 } 11163 } 11164 } 11165 11166 @Override 11167 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11168 int installFlags, String installerPackageName, int userId) { 11169 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11170 11171 final int callingUid = Binder.getCallingUid(); 11172 enforceCrossUserPermission(callingUid, userId, 11173 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11174 11175 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11176 try { 11177 if (observer != null) { 11178 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11179 } 11180 } catch (RemoteException re) { 11181 } 11182 return; 11183 } 11184 11185 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11186 installFlags |= PackageManager.INSTALL_FROM_ADB; 11187 11188 } else { 11189 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11190 // about installerPackageName. 11191 11192 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11193 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11194 } 11195 11196 UserHandle user; 11197 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11198 user = UserHandle.ALL; 11199 } else { 11200 user = new UserHandle(userId); 11201 } 11202 11203 // Only system components can circumvent runtime permissions when installing. 11204 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11205 && mContext.checkCallingOrSelfPermission(Manifest.permission 11206 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11207 throw new SecurityException("You need the " 11208 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11209 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11210 } 11211 11212 final File originFile = new File(originPath); 11213 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11214 11215 final Message msg = mHandler.obtainMessage(INIT_COPY); 11216 final VerificationInfo verificationInfo = new VerificationInfo( 11217 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11218 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11219 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11220 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11221 null /*certificates*/); 11222 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11223 msg.obj = params; 11224 11225 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11226 System.identityHashCode(msg.obj)); 11227 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11228 System.identityHashCode(msg.obj)); 11229 11230 mHandler.sendMessage(msg); 11231 } 11232 11233 void installStage(String packageName, File stagedDir, String stagedCid, 11234 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11235 String installerPackageName, int installerUid, UserHandle user, 11236 Certificate[][] certificates) { 11237 if (DEBUG_EPHEMERAL) { 11238 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11239 Slog.d(TAG, "Ephemeral install of " + packageName); 11240 } 11241 } 11242 final VerificationInfo verificationInfo = new VerificationInfo( 11243 sessionParams.originatingUri, sessionParams.referrerUri, 11244 sessionParams.originatingUid, installerUid); 11245 11246 final OriginInfo origin; 11247 if (stagedDir != null) { 11248 origin = OriginInfo.fromStagedFile(stagedDir); 11249 } else { 11250 origin = OriginInfo.fromStagedContainer(stagedCid); 11251 } 11252 11253 final Message msg = mHandler.obtainMessage(INIT_COPY); 11254 final InstallParams params = new InstallParams(origin, null, observer, 11255 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11256 verificationInfo, user, sessionParams.abiOverride, 11257 sessionParams.grantedRuntimePermissions, certificates); 11258 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11259 msg.obj = params; 11260 11261 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11262 System.identityHashCode(msg.obj)); 11263 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11264 System.identityHashCode(msg.obj)); 11265 11266 mHandler.sendMessage(msg); 11267 } 11268 11269 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11270 int userId) { 11271 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11272 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11273 } 11274 11275 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11276 int appId, int userId) { 11277 Bundle extras = new Bundle(1); 11278 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11279 11280 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11281 packageName, extras, 0, null, null, new int[] {userId}); 11282 try { 11283 IActivityManager am = ActivityManagerNative.getDefault(); 11284 if (isSystem && am.isUserRunning(userId, 0)) { 11285 // The just-installed/enabled app is bundled on the system, so presumed 11286 // to be able to run automatically without needing an explicit launch. 11287 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11288 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11289 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11290 .setPackage(packageName); 11291 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11292 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11293 } 11294 } catch (RemoteException e) { 11295 // shouldn't happen 11296 Slog.w(TAG, "Unable to bootstrap installed package", e); 11297 } 11298 } 11299 11300 @Override 11301 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11302 int userId) { 11303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11304 PackageSetting pkgSetting; 11305 final int uid = Binder.getCallingUid(); 11306 enforceCrossUserPermission(uid, userId, 11307 true /* requireFullPermission */, true /* checkShell */, 11308 "setApplicationHiddenSetting for user " + userId); 11309 11310 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11311 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11312 return false; 11313 } 11314 11315 long callingId = Binder.clearCallingIdentity(); 11316 try { 11317 boolean sendAdded = false; 11318 boolean sendRemoved = false; 11319 // writer 11320 synchronized (mPackages) { 11321 pkgSetting = mSettings.mPackages.get(packageName); 11322 if (pkgSetting == null) { 11323 return false; 11324 } 11325 if (pkgSetting.getHidden(userId) != hidden) { 11326 pkgSetting.setHidden(hidden, userId); 11327 mSettings.writePackageRestrictionsLPr(userId); 11328 if (hidden) { 11329 sendRemoved = true; 11330 } else { 11331 sendAdded = true; 11332 } 11333 } 11334 } 11335 if (sendAdded) { 11336 sendPackageAddedForUser(packageName, pkgSetting, userId); 11337 return true; 11338 } 11339 if (sendRemoved) { 11340 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11341 "hiding pkg"); 11342 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11343 return true; 11344 } 11345 } finally { 11346 Binder.restoreCallingIdentity(callingId); 11347 } 11348 return false; 11349 } 11350 11351 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11352 int userId) { 11353 final PackageRemovedInfo info = new PackageRemovedInfo(); 11354 info.removedPackage = packageName; 11355 info.removedUsers = new int[] {userId}; 11356 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11357 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11358 } 11359 11360 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11361 if (pkgList.length > 0) { 11362 Bundle extras = new Bundle(1); 11363 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11364 11365 sendPackageBroadcast( 11366 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11367 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11368 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11369 new int[] {userId}); 11370 } 11371 } 11372 11373 /** 11374 * Returns true if application is not found or there was an error. Otherwise it returns 11375 * the hidden state of the package for the given user. 11376 */ 11377 @Override 11378 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11379 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11381 true /* requireFullPermission */, false /* checkShell */, 11382 "getApplicationHidden for user " + userId); 11383 PackageSetting pkgSetting; 11384 long callingId = Binder.clearCallingIdentity(); 11385 try { 11386 // writer 11387 synchronized (mPackages) { 11388 pkgSetting = mSettings.mPackages.get(packageName); 11389 if (pkgSetting == null) { 11390 return true; 11391 } 11392 return pkgSetting.getHidden(userId); 11393 } 11394 } finally { 11395 Binder.restoreCallingIdentity(callingId); 11396 } 11397 } 11398 11399 /** 11400 * @hide 11401 */ 11402 @Override 11403 public int installExistingPackageAsUser(String packageName, int userId) { 11404 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11405 null); 11406 PackageSetting pkgSetting; 11407 final int uid = Binder.getCallingUid(); 11408 enforceCrossUserPermission(uid, userId, 11409 true /* requireFullPermission */, true /* checkShell */, 11410 "installExistingPackage for user " + userId); 11411 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11412 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11413 } 11414 11415 long callingId = Binder.clearCallingIdentity(); 11416 try { 11417 boolean installed = false; 11418 11419 // writer 11420 synchronized (mPackages) { 11421 pkgSetting = mSettings.mPackages.get(packageName); 11422 if (pkgSetting == null) { 11423 return PackageManager.INSTALL_FAILED_INVALID_URI; 11424 } 11425 if (!pkgSetting.getInstalled(userId)) { 11426 pkgSetting.setInstalled(true, userId); 11427 pkgSetting.setHidden(false, userId); 11428 mSettings.writePackageRestrictionsLPr(userId); 11429 installed = true; 11430 } 11431 } 11432 11433 if (installed) { 11434 if (pkgSetting.pkg != null) { 11435 synchronized (mInstallLock) { 11436 // We don't need to freeze for a brand new install 11437 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11438 } 11439 } 11440 sendPackageAddedForUser(packageName, pkgSetting, userId); 11441 } 11442 } finally { 11443 Binder.restoreCallingIdentity(callingId); 11444 } 11445 11446 return PackageManager.INSTALL_SUCCEEDED; 11447 } 11448 11449 boolean isUserRestricted(int userId, String restrictionKey) { 11450 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11451 if (restrictions.getBoolean(restrictionKey, false)) { 11452 Log.w(TAG, "User is restricted: " + restrictionKey); 11453 return true; 11454 } 11455 return false; 11456 } 11457 11458 @Override 11459 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11460 int userId) { 11461 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11462 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11463 true /* requireFullPermission */, true /* checkShell */, 11464 "setPackagesSuspended for user " + userId); 11465 11466 if (ArrayUtils.isEmpty(packageNames)) { 11467 return packageNames; 11468 } 11469 11470 // List of package names for whom the suspended state has changed. 11471 List<String> changedPackages = new ArrayList<>(packageNames.length); 11472 // List of package names for whom the suspended state is not set as requested in this 11473 // method. 11474 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11475 for (int i = 0; i < packageNames.length; i++) { 11476 String packageName = packageNames[i]; 11477 long callingId = Binder.clearCallingIdentity(); 11478 try { 11479 boolean changed = false; 11480 final int appId; 11481 synchronized (mPackages) { 11482 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11483 if (pkgSetting == null) { 11484 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11485 + "\". Skipping suspending/un-suspending."); 11486 unactionedPackages.add(packageName); 11487 continue; 11488 } 11489 appId = pkgSetting.appId; 11490 if (pkgSetting.getSuspended(userId) != suspended) { 11491 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11492 unactionedPackages.add(packageName); 11493 continue; 11494 } 11495 pkgSetting.setSuspended(suspended, userId); 11496 mSettings.writePackageRestrictionsLPr(userId); 11497 changed = true; 11498 changedPackages.add(packageName); 11499 } 11500 } 11501 11502 if (changed && suspended) { 11503 killApplication(packageName, UserHandle.getUid(userId, appId), 11504 "suspending package"); 11505 } 11506 } finally { 11507 Binder.restoreCallingIdentity(callingId); 11508 } 11509 } 11510 11511 if (!changedPackages.isEmpty()) { 11512 sendPackagesSuspendedForUser(changedPackages.toArray( 11513 new String[changedPackages.size()]), userId, suspended); 11514 } 11515 11516 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11517 } 11518 11519 @Override 11520 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11521 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11522 true /* requireFullPermission */, false /* checkShell */, 11523 "isPackageSuspendedForUser for user " + userId); 11524 synchronized (mPackages) { 11525 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11526 if (pkgSetting == null) { 11527 throw new IllegalArgumentException("Unknown target package: " + packageName); 11528 } 11529 return pkgSetting.getSuspended(userId); 11530 } 11531 } 11532 11533 /** 11534 * TODO: cache and disallow blocking the active dialer. 11535 * 11536 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11537 */ 11538 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11539 if (isPackageDeviceAdmin(packageName, userId)) { 11540 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11541 + "\": has an active device admin"); 11542 return false; 11543 } 11544 11545 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11546 if (packageName.equals(activeLauncherPackageName)) { 11547 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11548 + "\": contains the active launcher"); 11549 return false; 11550 } 11551 11552 if (packageName.equals(mRequiredInstallerPackage)) { 11553 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11554 + "\": required for package installation"); 11555 return false; 11556 } 11557 11558 if (packageName.equals(mRequiredVerifierPackage)) { 11559 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11560 + "\": required for package verification"); 11561 return false; 11562 } 11563 11564 final PackageParser.Package pkg = mPackages.get(packageName); 11565 if (pkg != null && isPrivilegedApp(pkg)) { 11566 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11567 + "\": is a privileged app"); 11568 return false; 11569 } 11570 11571 return true; 11572 } 11573 11574 private String getActiveLauncherPackageName(int userId) { 11575 Intent intent = new Intent(Intent.ACTION_MAIN); 11576 intent.addCategory(Intent.CATEGORY_HOME); 11577 ResolveInfo resolveInfo = resolveIntent( 11578 intent, 11579 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11580 PackageManager.MATCH_DEFAULT_ONLY, 11581 userId); 11582 11583 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11584 } 11585 11586 @Override 11587 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11588 mContext.enforceCallingOrSelfPermission( 11589 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11590 "Only package verification agents can verify applications"); 11591 11592 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11593 final PackageVerificationResponse response = new PackageVerificationResponse( 11594 verificationCode, Binder.getCallingUid()); 11595 msg.arg1 = id; 11596 msg.obj = response; 11597 mHandler.sendMessage(msg); 11598 } 11599 11600 @Override 11601 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11602 long millisecondsToDelay) { 11603 mContext.enforceCallingOrSelfPermission( 11604 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11605 "Only package verification agents can extend verification timeouts"); 11606 11607 final PackageVerificationState state = mPendingVerification.get(id); 11608 final PackageVerificationResponse response = new PackageVerificationResponse( 11609 verificationCodeAtTimeout, Binder.getCallingUid()); 11610 11611 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11612 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11613 } 11614 if (millisecondsToDelay < 0) { 11615 millisecondsToDelay = 0; 11616 } 11617 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11618 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11619 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11620 } 11621 11622 if ((state != null) && !state.timeoutExtended()) { 11623 state.extendTimeout(); 11624 11625 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11626 msg.arg1 = id; 11627 msg.obj = response; 11628 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11629 } 11630 } 11631 11632 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11633 int verificationCode, UserHandle user) { 11634 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11635 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11636 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11637 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11638 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11639 11640 mContext.sendBroadcastAsUser(intent, user, 11641 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11642 } 11643 11644 private ComponentName matchComponentForVerifier(String packageName, 11645 List<ResolveInfo> receivers) { 11646 ActivityInfo targetReceiver = null; 11647 11648 final int NR = receivers.size(); 11649 for (int i = 0; i < NR; i++) { 11650 final ResolveInfo info = receivers.get(i); 11651 if (info.activityInfo == null) { 11652 continue; 11653 } 11654 11655 if (packageName.equals(info.activityInfo.packageName)) { 11656 targetReceiver = info.activityInfo; 11657 break; 11658 } 11659 } 11660 11661 if (targetReceiver == null) { 11662 return null; 11663 } 11664 11665 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11666 } 11667 11668 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11669 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11670 if (pkgInfo.verifiers.length == 0) { 11671 return null; 11672 } 11673 11674 final int N = pkgInfo.verifiers.length; 11675 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11676 for (int i = 0; i < N; i++) { 11677 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11678 11679 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11680 receivers); 11681 if (comp == null) { 11682 continue; 11683 } 11684 11685 final int verifierUid = getUidForVerifier(verifierInfo); 11686 if (verifierUid == -1) { 11687 continue; 11688 } 11689 11690 if (DEBUG_VERIFY) { 11691 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11692 + " with the correct signature"); 11693 } 11694 sufficientVerifiers.add(comp); 11695 verificationState.addSufficientVerifier(verifierUid); 11696 } 11697 11698 return sufficientVerifiers; 11699 } 11700 11701 private int getUidForVerifier(VerifierInfo verifierInfo) { 11702 synchronized (mPackages) { 11703 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11704 if (pkg == null) { 11705 return -1; 11706 } else if (pkg.mSignatures.length != 1) { 11707 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11708 + " has more than one signature; ignoring"); 11709 return -1; 11710 } 11711 11712 /* 11713 * If the public key of the package's signature does not match 11714 * our expected public key, then this is a different package and 11715 * we should skip. 11716 */ 11717 11718 final byte[] expectedPublicKey; 11719 try { 11720 final Signature verifierSig = pkg.mSignatures[0]; 11721 final PublicKey publicKey = verifierSig.getPublicKey(); 11722 expectedPublicKey = publicKey.getEncoded(); 11723 } catch (CertificateException e) { 11724 return -1; 11725 } 11726 11727 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11728 11729 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11730 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11731 + " does not have the expected public key; ignoring"); 11732 return -1; 11733 } 11734 11735 return pkg.applicationInfo.uid; 11736 } 11737 } 11738 11739 @Override 11740 public void finishPackageInstall(int token, boolean didLaunch) { 11741 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11742 11743 if (DEBUG_INSTALL) { 11744 Slog.v(TAG, "BM finishing package install for " + token); 11745 } 11746 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11747 11748 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11749 mHandler.sendMessage(msg); 11750 } 11751 11752 /** 11753 * Get the verification agent timeout. 11754 * 11755 * @return verification timeout in milliseconds 11756 */ 11757 private long getVerificationTimeout() { 11758 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11759 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11760 DEFAULT_VERIFICATION_TIMEOUT); 11761 } 11762 11763 /** 11764 * Get the default verification agent response code. 11765 * 11766 * @return default verification response code 11767 */ 11768 private int getDefaultVerificationResponse() { 11769 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11770 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11771 DEFAULT_VERIFICATION_RESPONSE); 11772 } 11773 11774 /** 11775 * Check whether or not package verification has been enabled. 11776 * 11777 * @return true if verification should be performed 11778 */ 11779 private boolean isVerificationEnabled(int userId, int installFlags) { 11780 if (!DEFAULT_VERIFY_ENABLE) { 11781 return false; 11782 } 11783 // Ephemeral apps don't get the full verification treatment 11784 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11785 if (DEBUG_EPHEMERAL) { 11786 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11787 } 11788 return false; 11789 } 11790 11791 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11792 11793 // Check if installing from ADB 11794 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11795 // Do not run verification in a test harness environment 11796 if (ActivityManager.isRunningInTestHarness()) { 11797 return false; 11798 } 11799 if (ensureVerifyAppsEnabled) { 11800 return true; 11801 } 11802 // Check if the developer does not want package verification for ADB installs 11803 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11804 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11805 return false; 11806 } 11807 } 11808 11809 if (ensureVerifyAppsEnabled) { 11810 return true; 11811 } 11812 11813 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11814 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11815 } 11816 11817 @Override 11818 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11819 throws RemoteException { 11820 mContext.enforceCallingOrSelfPermission( 11821 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11822 "Only intentfilter verification agents can verify applications"); 11823 11824 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11825 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11826 Binder.getCallingUid(), verificationCode, failedDomains); 11827 msg.arg1 = id; 11828 msg.obj = response; 11829 mHandler.sendMessage(msg); 11830 } 11831 11832 @Override 11833 public int getIntentVerificationStatus(String packageName, int userId) { 11834 synchronized (mPackages) { 11835 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11836 } 11837 } 11838 11839 @Override 11840 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11841 mContext.enforceCallingOrSelfPermission( 11842 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11843 11844 boolean result = false; 11845 synchronized (mPackages) { 11846 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11847 } 11848 if (result) { 11849 scheduleWritePackageRestrictionsLocked(userId); 11850 } 11851 return result; 11852 } 11853 11854 @Override 11855 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11856 String packageName) { 11857 synchronized (mPackages) { 11858 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11859 } 11860 } 11861 11862 @Override 11863 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11864 if (TextUtils.isEmpty(packageName)) { 11865 return ParceledListSlice.emptyList(); 11866 } 11867 synchronized (mPackages) { 11868 PackageParser.Package pkg = mPackages.get(packageName); 11869 if (pkg == null || pkg.activities == null) { 11870 return ParceledListSlice.emptyList(); 11871 } 11872 final int count = pkg.activities.size(); 11873 ArrayList<IntentFilter> result = new ArrayList<>(); 11874 for (int n=0; n<count; n++) { 11875 PackageParser.Activity activity = pkg.activities.get(n); 11876 if (activity.intents != null && activity.intents.size() > 0) { 11877 result.addAll(activity.intents); 11878 } 11879 } 11880 return new ParceledListSlice<>(result); 11881 } 11882 } 11883 11884 @Override 11885 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11886 mContext.enforceCallingOrSelfPermission( 11887 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11888 11889 synchronized (mPackages) { 11890 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11891 if (packageName != null) { 11892 result |= updateIntentVerificationStatus(packageName, 11893 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11894 userId); 11895 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11896 packageName, userId); 11897 } 11898 return result; 11899 } 11900 } 11901 11902 @Override 11903 public String getDefaultBrowserPackageName(int userId) { 11904 synchronized (mPackages) { 11905 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11906 } 11907 } 11908 11909 /** 11910 * Get the "allow unknown sources" setting. 11911 * 11912 * @return the current "allow unknown sources" setting 11913 */ 11914 private int getUnknownSourcesSettings() { 11915 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11916 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11917 -1); 11918 } 11919 11920 @Override 11921 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11922 final int uid = Binder.getCallingUid(); 11923 // writer 11924 synchronized (mPackages) { 11925 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11926 if (targetPackageSetting == null) { 11927 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11928 } 11929 11930 PackageSetting installerPackageSetting; 11931 if (installerPackageName != null) { 11932 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11933 if (installerPackageSetting == null) { 11934 throw new IllegalArgumentException("Unknown installer package: " 11935 + installerPackageName); 11936 } 11937 } else { 11938 installerPackageSetting = null; 11939 } 11940 11941 Signature[] callerSignature; 11942 Object obj = mSettings.getUserIdLPr(uid); 11943 if (obj != null) { 11944 if (obj instanceof SharedUserSetting) { 11945 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11946 } else if (obj instanceof PackageSetting) { 11947 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11948 } else { 11949 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11950 } 11951 } else { 11952 throw new SecurityException("Unknown calling UID: " + uid); 11953 } 11954 11955 // Verify: can't set installerPackageName to a package that is 11956 // not signed with the same cert as the caller. 11957 if (installerPackageSetting != null) { 11958 if (compareSignatures(callerSignature, 11959 installerPackageSetting.signatures.mSignatures) 11960 != PackageManager.SIGNATURE_MATCH) { 11961 throw new SecurityException( 11962 "Caller does not have same cert as new installer package " 11963 + installerPackageName); 11964 } 11965 } 11966 11967 // Verify: if target already has an installer package, it must 11968 // be signed with the same cert as the caller. 11969 if (targetPackageSetting.installerPackageName != null) { 11970 PackageSetting setting = mSettings.mPackages.get( 11971 targetPackageSetting.installerPackageName); 11972 // If the currently set package isn't valid, then it's always 11973 // okay to change it. 11974 if (setting != null) { 11975 if (compareSignatures(callerSignature, 11976 setting.signatures.mSignatures) 11977 != PackageManager.SIGNATURE_MATCH) { 11978 throw new SecurityException( 11979 "Caller does not have same cert as old installer package " 11980 + targetPackageSetting.installerPackageName); 11981 } 11982 } 11983 } 11984 11985 // Okay! 11986 targetPackageSetting.installerPackageName = installerPackageName; 11987 if (installerPackageName != null) { 11988 mSettings.mInstallerPackages.add(installerPackageName); 11989 } 11990 scheduleWriteSettingsLocked(); 11991 } 11992 } 11993 11994 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11995 // Queue up an async operation since the package installation may take a little while. 11996 mHandler.post(new Runnable() { 11997 public void run() { 11998 mHandler.removeCallbacks(this); 11999 // Result object to be returned 12000 PackageInstalledInfo res = new PackageInstalledInfo(); 12001 res.setReturnCode(currentStatus); 12002 res.uid = -1; 12003 res.pkg = null; 12004 res.removedInfo = null; 12005 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12006 args.doPreInstall(res.returnCode); 12007 synchronized (mInstallLock) { 12008 installPackageTracedLI(args, res); 12009 } 12010 args.doPostInstall(res.returnCode, res.uid); 12011 } 12012 12013 // A restore should be performed at this point if (a) the install 12014 // succeeded, (b) the operation is not an update, and (c) the new 12015 // package has not opted out of backup participation. 12016 final boolean update = res.removedInfo != null 12017 && res.removedInfo.removedPackage != null; 12018 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12019 boolean doRestore = !update 12020 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12021 12022 // Set up the post-install work request bookkeeping. This will be used 12023 // and cleaned up by the post-install event handling regardless of whether 12024 // there's a restore pass performed. Token values are >= 1. 12025 int token; 12026 if (mNextInstallToken < 0) mNextInstallToken = 1; 12027 token = mNextInstallToken++; 12028 12029 PostInstallData data = new PostInstallData(args, res); 12030 mRunningInstalls.put(token, data); 12031 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12032 12033 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12034 // Pass responsibility to the Backup Manager. It will perform a 12035 // restore if appropriate, then pass responsibility back to the 12036 // Package Manager to run the post-install observer callbacks 12037 // and broadcasts. 12038 IBackupManager bm = IBackupManager.Stub.asInterface( 12039 ServiceManager.getService(Context.BACKUP_SERVICE)); 12040 if (bm != null) { 12041 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12042 + " to BM for possible restore"); 12043 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12044 try { 12045 // TODO: http://b/22388012 12046 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12047 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12048 } else { 12049 doRestore = false; 12050 } 12051 } catch (RemoteException e) { 12052 // can't happen; the backup manager is local 12053 } catch (Exception e) { 12054 Slog.e(TAG, "Exception trying to enqueue restore", e); 12055 doRestore = false; 12056 } 12057 } else { 12058 Slog.e(TAG, "Backup Manager not found!"); 12059 doRestore = false; 12060 } 12061 } 12062 12063 if (!doRestore) { 12064 // No restore possible, or the Backup Manager was mysteriously not 12065 // available -- just fire the post-install work request directly. 12066 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12067 12068 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12069 12070 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12071 mHandler.sendMessage(msg); 12072 } 12073 } 12074 }); 12075 } 12076 12077 /** 12078 * Callback from PackageSettings whenever an app is first transitioned out of the 12079 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12080 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12081 * here whether the app is the target of an ongoing install, and only send the 12082 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12083 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12084 * handling. 12085 */ 12086 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12087 // Serialize this with the rest of the install-process message chain. In the 12088 // restore-at-install case, this Runnable will necessarily run before the 12089 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12090 // are coherent. In the non-restore case, the app has already completed install 12091 // and been launched through some other means, so it is not in a problematic 12092 // state for observers to see the FIRST_LAUNCH signal. 12093 mHandler.post(new Runnable() { 12094 @Override 12095 public void run() { 12096 for (int i = 0; i < mRunningInstalls.size(); i++) { 12097 final PostInstallData data = mRunningInstalls.valueAt(i); 12098 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12099 // right package; but is it for the right user? 12100 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12101 if (userId == data.res.newUsers[uIndex]) { 12102 if (DEBUG_BACKUP) { 12103 Slog.i(TAG, "Package " + pkgName 12104 + " being restored so deferring FIRST_LAUNCH"); 12105 } 12106 return; 12107 } 12108 } 12109 } 12110 } 12111 // didn't find it, so not being restored 12112 if (DEBUG_BACKUP) { 12113 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12114 } 12115 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12116 } 12117 }); 12118 } 12119 12120 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12121 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12122 installerPkg, null, userIds); 12123 } 12124 12125 private abstract class HandlerParams { 12126 private static final int MAX_RETRIES = 4; 12127 12128 /** 12129 * Number of times startCopy() has been attempted and had a non-fatal 12130 * error. 12131 */ 12132 private int mRetries = 0; 12133 12134 /** User handle for the user requesting the information or installation. */ 12135 private final UserHandle mUser; 12136 String traceMethod; 12137 int traceCookie; 12138 12139 HandlerParams(UserHandle user) { 12140 mUser = user; 12141 } 12142 12143 UserHandle getUser() { 12144 return mUser; 12145 } 12146 12147 HandlerParams setTraceMethod(String traceMethod) { 12148 this.traceMethod = traceMethod; 12149 return this; 12150 } 12151 12152 HandlerParams setTraceCookie(int traceCookie) { 12153 this.traceCookie = traceCookie; 12154 return this; 12155 } 12156 12157 final boolean startCopy() { 12158 boolean res; 12159 try { 12160 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12161 12162 if (++mRetries > MAX_RETRIES) { 12163 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12164 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12165 handleServiceError(); 12166 return false; 12167 } else { 12168 handleStartCopy(); 12169 res = true; 12170 } 12171 } catch (RemoteException e) { 12172 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12173 mHandler.sendEmptyMessage(MCS_RECONNECT); 12174 res = false; 12175 } 12176 handleReturnCode(); 12177 return res; 12178 } 12179 12180 final void serviceError() { 12181 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12182 handleServiceError(); 12183 handleReturnCode(); 12184 } 12185 12186 abstract void handleStartCopy() throws RemoteException; 12187 abstract void handleServiceError(); 12188 abstract void handleReturnCode(); 12189 } 12190 12191 class MeasureParams extends HandlerParams { 12192 private final PackageStats mStats; 12193 private boolean mSuccess; 12194 12195 private final IPackageStatsObserver mObserver; 12196 12197 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12198 super(new UserHandle(stats.userHandle)); 12199 mObserver = observer; 12200 mStats = stats; 12201 } 12202 12203 @Override 12204 public String toString() { 12205 return "MeasureParams{" 12206 + Integer.toHexString(System.identityHashCode(this)) 12207 + " " + mStats.packageName + "}"; 12208 } 12209 12210 @Override 12211 void handleStartCopy() throws RemoteException { 12212 synchronized (mInstallLock) { 12213 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12214 } 12215 12216 if (mSuccess) { 12217 final boolean mounted; 12218 if (Environment.isExternalStorageEmulated()) { 12219 mounted = true; 12220 } else { 12221 final String status = Environment.getExternalStorageState(); 12222 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12223 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12224 } 12225 12226 if (mounted) { 12227 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12228 12229 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12230 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12231 12232 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12233 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12234 12235 // Always subtract cache size, since it's a subdirectory 12236 mStats.externalDataSize -= mStats.externalCacheSize; 12237 12238 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12239 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12240 12241 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12242 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12243 } 12244 } 12245 } 12246 12247 @Override 12248 void handleReturnCode() { 12249 if (mObserver != null) { 12250 try { 12251 mObserver.onGetStatsCompleted(mStats, mSuccess); 12252 } catch (RemoteException e) { 12253 Slog.i(TAG, "Observer no longer exists."); 12254 } 12255 } 12256 } 12257 12258 @Override 12259 void handleServiceError() { 12260 Slog.e(TAG, "Could not measure application " + mStats.packageName 12261 + " external storage"); 12262 } 12263 } 12264 12265 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12266 throws RemoteException { 12267 long result = 0; 12268 for (File path : paths) { 12269 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12270 } 12271 return result; 12272 } 12273 12274 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12275 for (File path : paths) { 12276 try { 12277 mcs.clearDirectory(path.getAbsolutePath()); 12278 } catch (RemoteException e) { 12279 } 12280 } 12281 } 12282 12283 static class OriginInfo { 12284 /** 12285 * Location where install is coming from, before it has been 12286 * copied/renamed into place. This could be a single monolithic APK 12287 * file, or a cluster directory. This location may be untrusted. 12288 */ 12289 final File file; 12290 final String cid; 12291 12292 /** 12293 * Flag indicating that {@link #file} or {@link #cid} has already been 12294 * staged, meaning downstream users don't need to defensively copy the 12295 * contents. 12296 */ 12297 final boolean staged; 12298 12299 /** 12300 * Flag indicating that {@link #file} or {@link #cid} is an already 12301 * installed app that is being moved. 12302 */ 12303 final boolean existing; 12304 12305 final String resolvedPath; 12306 final File resolvedFile; 12307 12308 static OriginInfo fromNothing() { 12309 return new OriginInfo(null, null, false, false); 12310 } 12311 12312 static OriginInfo fromUntrustedFile(File file) { 12313 return new OriginInfo(file, null, false, false); 12314 } 12315 12316 static OriginInfo fromExistingFile(File file) { 12317 return new OriginInfo(file, null, false, true); 12318 } 12319 12320 static OriginInfo fromStagedFile(File file) { 12321 return new OriginInfo(file, null, true, false); 12322 } 12323 12324 static OriginInfo fromStagedContainer(String cid) { 12325 return new OriginInfo(null, cid, true, false); 12326 } 12327 12328 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12329 this.file = file; 12330 this.cid = cid; 12331 this.staged = staged; 12332 this.existing = existing; 12333 12334 if (cid != null) { 12335 resolvedPath = PackageHelper.getSdDir(cid); 12336 resolvedFile = new File(resolvedPath); 12337 } else if (file != null) { 12338 resolvedPath = file.getAbsolutePath(); 12339 resolvedFile = file; 12340 } else { 12341 resolvedPath = null; 12342 resolvedFile = null; 12343 } 12344 } 12345 } 12346 12347 static class MoveInfo { 12348 final int moveId; 12349 final String fromUuid; 12350 final String toUuid; 12351 final String packageName; 12352 final String dataAppName; 12353 final int appId; 12354 final String seinfo; 12355 final int targetSdkVersion; 12356 12357 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12358 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12359 this.moveId = moveId; 12360 this.fromUuid = fromUuid; 12361 this.toUuid = toUuid; 12362 this.packageName = packageName; 12363 this.dataAppName = dataAppName; 12364 this.appId = appId; 12365 this.seinfo = seinfo; 12366 this.targetSdkVersion = targetSdkVersion; 12367 } 12368 } 12369 12370 static class VerificationInfo { 12371 /** A constant used to indicate that a uid value is not present. */ 12372 public static final int NO_UID = -1; 12373 12374 /** URI referencing where the package was downloaded from. */ 12375 final Uri originatingUri; 12376 12377 /** HTTP referrer URI associated with the originatingURI. */ 12378 final Uri referrer; 12379 12380 /** UID of the application that the install request originated from. */ 12381 final int originatingUid; 12382 12383 /** UID of application requesting the install */ 12384 final int installerUid; 12385 12386 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12387 this.originatingUri = originatingUri; 12388 this.referrer = referrer; 12389 this.originatingUid = originatingUid; 12390 this.installerUid = installerUid; 12391 } 12392 } 12393 12394 class InstallParams extends HandlerParams { 12395 final OriginInfo origin; 12396 final MoveInfo move; 12397 final IPackageInstallObserver2 observer; 12398 int installFlags; 12399 final String installerPackageName; 12400 final String volumeUuid; 12401 private InstallArgs mArgs; 12402 private int mRet; 12403 final String packageAbiOverride; 12404 final String[] grantedRuntimePermissions; 12405 final VerificationInfo verificationInfo; 12406 final Certificate[][] certificates; 12407 12408 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12409 int installFlags, String installerPackageName, String volumeUuid, 12410 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12411 String[] grantedPermissions, Certificate[][] certificates) { 12412 super(user); 12413 this.origin = origin; 12414 this.move = move; 12415 this.observer = observer; 12416 this.installFlags = installFlags; 12417 this.installerPackageName = installerPackageName; 12418 this.volumeUuid = volumeUuid; 12419 this.verificationInfo = verificationInfo; 12420 this.packageAbiOverride = packageAbiOverride; 12421 this.grantedRuntimePermissions = grantedPermissions; 12422 this.certificates = certificates; 12423 } 12424 12425 @Override 12426 public String toString() { 12427 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12428 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12429 } 12430 12431 private int installLocationPolicy(PackageInfoLite pkgLite) { 12432 String packageName = pkgLite.packageName; 12433 int installLocation = pkgLite.installLocation; 12434 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12435 // reader 12436 synchronized (mPackages) { 12437 // Currently installed package which the new package is attempting to replace or 12438 // null if no such package is installed. 12439 PackageParser.Package installedPkg = mPackages.get(packageName); 12440 // Package which currently owns the data which the new package will own if installed. 12441 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12442 // will be null whereas dataOwnerPkg will contain information about the package 12443 // which was uninstalled while keeping its data. 12444 PackageParser.Package dataOwnerPkg = installedPkg; 12445 if (dataOwnerPkg == null) { 12446 PackageSetting ps = mSettings.mPackages.get(packageName); 12447 if (ps != null) { 12448 dataOwnerPkg = ps.pkg; 12449 } 12450 } 12451 12452 if (dataOwnerPkg != null) { 12453 // If installed, the package will get access to data left on the device by its 12454 // predecessor. As a security measure, this is permited only if this is not a 12455 // version downgrade or if the predecessor package is marked as debuggable and 12456 // a downgrade is explicitly requested. 12457 // 12458 // On debuggable platform builds, downgrades are permitted even for 12459 // non-debuggable packages to make testing easier. Debuggable platform builds do 12460 // not offer security guarantees and thus it's OK to disable some security 12461 // mechanisms to make debugging/testing easier on those builds. However, even on 12462 // debuggable builds downgrades of packages are permitted only if requested via 12463 // installFlags. This is because we aim to keep the behavior of debuggable 12464 // platform builds as close as possible to the behavior of non-debuggable 12465 // platform builds. 12466 final boolean downgradeRequested = 12467 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12468 final boolean packageDebuggable = 12469 (dataOwnerPkg.applicationInfo.flags 12470 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12471 final boolean downgradePermitted = 12472 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12473 if (!downgradePermitted) { 12474 try { 12475 checkDowngrade(dataOwnerPkg, pkgLite); 12476 } catch (PackageManagerException e) { 12477 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12478 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12479 } 12480 } 12481 } 12482 12483 if (installedPkg != null) { 12484 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12485 // Check for updated system application. 12486 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12487 if (onSd) { 12488 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12489 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12490 } 12491 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12492 } else { 12493 if (onSd) { 12494 // Install flag overrides everything. 12495 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12496 } 12497 // If current upgrade specifies particular preference 12498 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12499 // Application explicitly specified internal. 12500 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12501 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12502 // App explictly prefers external. Let policy decide 12503 } else { 12504 // Prefer previous location 12505 if (isExternal(installedPkg)) { 12506 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12507 } 12508 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12509 } 12510 } 12511 } else { 12512 // Invalid install. Return error code 12513 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12514 } 12515 } 12516 } 12517 // All the special cases have been taken care of. 12518 // Return result based on recommended install location. 12519 if (onSd) { 12520 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12521 } 12522 return pkgLite.recommendedInstallLocation; 12523 } 12524 12525 /* 12526 * Invoke remote method to get package information and install 12527 * location values. Override install location based on default 12528 * policy if needed and then create install arguments based 12529 * on the install location. 12530 */ 12531 public void handleStartCopy() throws RemoteException { 12532 int ret = PackageManager.INSTALL_SUCCEEDED; 12533 12534 // If we're already staged, we've firmly committed to an install location 12535 if (origin.staged) { 12536 if (origin.file != null) { 12537 installFlags |= PackageManager.INSTALL_INTERNAL; 12538 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12539 } else if (origin.cid != null) { 12540 installFlags |= PackageManager.INSTALL_EXTERNAL; 12541 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12542 } else { 12543 throw new IllegalStateException("Invalid stage location"); 12544 } 12545 } 12546 12547 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12548 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12549 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12550 PackageInfoLite pkgLite = null; 12551 12552 if (onInt && onSd) { 12553 // Check if both bits are set. 12554 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12555 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12556 } else if (onSd && ephemeral) { 12557 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12558 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12559 } else { 12560 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12561 packageAbiOverride); 12562 12563 if (DEBUG_EPHEMERAL && ephemeral) { 12564 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12565 } 12566 12567 /* 12568 * If we have too little free space, try to free cache 12569 * before giving up. 12570 */ 12571 if (!origin.staged && pkgLite.recommendedInstallLocation 12572 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12573 // TODO: focus freeing disk space on the target device 12574 final StorageManager storage = StorageManager.from(mContext); 12575 final long lowThreshold = storage.getStorageLowBytes( 12576 Environment.getDataDirectory()); 12577 12578 final long sizeBytes = mContainerService.calculateInstalledSize( 12579 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12580 12581 try { 12582 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12583 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12584 installFlags, packageAbiOverride); 12585 } catch (InstallerException e) { 12586 Slog.w(TAG, "Failed to free cache", e); 12587 } 12588 12589 /* 12590 * The cache free must have deleted the file we 12591 * downloaded to install. 12592 * 12593 * TODO: fix the "freeCache" call to not delete 12594 * the file we care about. 12595 */ 12596 if (pkgLite.recommendedInstallLocation 12597 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12598 pkgLite.recommendedInstallLocation 12599 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12600 } 12601 } 12602 } 12603 12604 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12605 int loc = pkgLite.recommendedInstallLocation; 12606 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12607 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12608 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12609 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12610 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12611 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12612 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12613 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12614 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12615 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12616 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12617 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12618 } else { 12619 // Override with defaults if needed. 12620 loc = installLocationPolicy(pkgLite); 12621 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12622 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12623 } else if (!onSd && !onInt) { 12624 // Override install location with flags 12625 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12626 // Set the flag to install on external media. 12627 installFlags |= PackageManager.INSTALL_EXTERNAL; 12628 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12629 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12630 if (DEBUG_EPHEMERAL) { 12631 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12632 } 12633 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12634 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12635 |PackageManager.INSTALL_INTERNAL); 12636 } else { 12637 // Make sure the flag for installing on external 12638 // media is unset 12639 installFlags |= PackageManager.INSTALL_INTERNAL; 12640 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12641 } 12642 } 12643 } 12644 } 12645 12646 final InstallArgs args = createInstallArgs(this); 12647 mArgs = args; 12648 12649 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12650 // TODO: http://b/22976637 12651 // Apps installed for "all" users use the device owner to verify the app 12652 UserHandle verifierUser = getUser(); 12653 if (verifierUser == UserHandle.ALL) { 12654 verifierUser = UserHandle.SYSTEM; 12655 } 12656 12657 /* 12658 * Determine if we have any installed package verifiers. If we 12659 * do, then we'll defer to them to verify the packages. 12660 */ 12661 final int requiredUid = mRequiredVerifierPackage == null ? -1 12662 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12663 verifierUser.getIdentifier()); 12664 if (!origin.existing && requiredUid != -1 12665 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12666 final Intent verification = new Intent( 12667 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12668 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12669 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12670 PACKAGE_MIME_TYPE); 12671 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12672 12673 // Query all live verifiers based on current user state 12674 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12675 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12676 12677 if (DEBUG_VERIFY) { 12678 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12679 + verification.toString() + " with " + pkgLite.verifiers.length 12680 + " optional verifiers"); 12681 } 12682 12683 final int verificationId = mPendingVerificationToken++; 12684 12685 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12686 12687 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12688 installerPackageName); 12689 12690 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12691 installFlags); 12692 12693 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12694 pkgLite.packageName); 12695 12696 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12697 pkgLite.versionCode); 12698 12699 if (verificationInfo != null) { 12700 if (verificationInfo.originatingUri != null) { 12701 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12702 verificationInfo.originatingUri); 12703 } 12704 if (verificationInfo.referrer != null) { 12705 verification.putExtra(Intent.EXTRA_REFERRER, 12706 verificationInfo.referrer); 12707 } 12708 if (verificationInfo.originatingUid >= 0) { 12709 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12710 verificationInfo.originatingUid); 12711 } 12712 if (verificationInfo.installerUid >= 0) { 12713 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12714 verificationInfo.installerUid); 12715 } 12716 } 12717 12718 final PackageVerificationState verificationState = new PackageVerificationState( 12719 requiredUid, args); 12720 12721 mPendingVerification.append(verificationId, verificationState); 12722 12723 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12724 receivers, verificationState); 12725 12726 /* 12727 * If any sufficient verifiers were listed in the package 12728 * manifest, attempt to ask them. 12729 */ 12730 if (sufficientVerifiers != null) { 12731 final int N = sufficientVerifiers.size(); 12732 if (N == 0) { 12733 Slog.i(TAG, "Additional verifiers required, but none installed."); 12734 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12735 } else { 12736 for (int i = 0; i < N; i++) { 12737 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12738 12739 final Intent sufficientIntent = new Intent(verification); 12740 sufficientIntent.setComponent(verifierComponent); 12741 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12742 } 12743 } 12744 } 12745 12746 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12747 mRequiredVerifierPackage, receivers); 12748 if (ret == PackageManager.INSTALL_SUCCEEDED 12749 && mRequiredVerifierPackage != null) { 12750 Trace.asyncTraceBegin( 12751 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12752 /* 12753 * Send the intent to the required verification agent, 12754 * but only start the verification timeout after the 12755 * target BroadcastReceivers have run. 12756 */ 12757 verification.setComponent(requiredVerifierComponent); 12758 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12759 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12760 new BroadcastReceiver() { 12761 @Override 12762 public void onReceive(Context context, Intent intent) { 12763 final Message msg = mHandler 12764 .obtainMessage(CHECK_PENDING_VERIFICATION); 12765 msg.arg1 = verificationId; 12766 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12767 } 12768 }, null, 0, null, null); 12769 12770 /* 12771 * We don't want the copy to proceed until verification 12772 * succeeds, so null out this field. 12773 */ 12774 mArgs = null; 12775 } 12776 } else { 12777 /* 12778 * No package verification is enabled, so immediately start 12779 * the remote call to initiate copy using temporary file. 12780 */ 12781 ret = args.copyApk(mContainerService, true); 12782 } 12783 } 12784 12785 mRet = ret; 12786 } 12787 12788 @Override 12789 void handleReturnCode() { 12790 // If mArgs is null, then MCS couldn't be reached. When it 12791 // reconnects, it will try again to install. At that point, this 12792 // will succeed. 12793 if (mArgs != null) { 12794 processPendingInstall(mArgs, mRet); 12795 } 12796 } 12797 12798 @Override 12799 void handleServiceError() { 12800 mArgs = createInstallArgs(this); 12801 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12802 } 12803 12804 public boolean isForwardLocked() { 12805 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12806 } 12807 } 12808 12809 /** 12810 * Used during creation of InstallArgs 12811 * 12812 * @param installFlags package installation flags 12813 * @return true if should be installed on external storage 12814 */ 12815 private static boolean installOnExternalAsec(int installFlags) { 12816 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12817 return false; 12818 } 12819 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12820 return true; 12821 } 12822 return false; 12823 } 12824 12825 /** 12826 * Used during creation of InstallArgs 12827 * 12828 * @param installFlags package installation flags 12829 * @return true if should be installed as forward locked 12830 */ 12831 private static boolean installForwardLocked(int installFlags) { 12832 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12833 } 12834 12835 private InstallArgs createInstallArgs(InstallParams params) { 12836 if (params.move != null) { 12837 return new MoveInstallArgs(params); 12838 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12839 return new AsecInstallArgs(params); 12840 } else { 12841 return new FileInstallArgs(params); 12842 } 12843 } 12844 12845 /** 12846 * Create args that describe an existing installed package. Typically used 12847 * when cleaning up old installs, or used as a move source. 12848 */ 12849 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12850 String resourcePath, String[] instructionSets) { 12851 final boolean isInAsec; 12852 if (installOnExternalAsec(installFlags)) { 12853 /* Apps on SD card are always in ASEC containers. */ 12854 isInAsec = true; 12855 } else if (installForwardLocked(installFlags) 12856 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12857 /* 12858 * Forward-locked apps are only in ASEC containers if they're the 12859 * new style 12860 */ 12861 isInAsec = true; 12862 } else { 12863 isInAsec = false; 12864 } 12865 12866 if (isInAsec) { 12867 return new AsecInstallArgs(codePath, instructionSets, 12868 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12869 } else { 12870 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12871 } 12872 } 12873 12874 static abstract class InstallArgs { 12875 /** @see InstallParams#origin */ 12876 final OriginInfo origin; 12877 /** @see InstallParams#move */ 12878 final MoveInfo move; 12879 12880 final IPackageInstallObserver2 observer; 12881 // Always refers to PackageManager flags only 12882 final int installFlags; 12883 final String installerPackageName; 12884 final String volumeUuid; 12885 final UserHandle user; 12886 final String abiOverride; 12887 final String[] installGrantPermissions; 12888 /** If non-null, drop an async trace when the install completes */ 12889 final String traceMethod; 12890 final int traceCookie; 12891 final Certificate[][] certificates; 12892 12893 // The list of instruction sets supported by this app. This is currently 12894 // only used during the rmdex() phase to clean up resources. We can get rid of this 12895 // if we move dex files under the common app path. 12896 /* nullable */ String[] instructionSets; 12897 12898 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12899 int installFlags, String installerPackageName, String volumeUuid, 12900 UserHandle user, String[] instructionSets, 12901 String abiOverride, String[] installGrantPermissions, 12902 String traceMethod, int traceCookie, Certificate[][] certificates) { 12903 this.origin = origin; 12904 this.move = move; 12905 this.installFlags = installFlags; 12906 this.observer = observer; 12907 this.installerPackageName = installerPackageName; 12908 this.volumeUuid = volumeUuid; 12909 this.user = user; 12910 this.instructionSets = instructionSets; 12911 this.abiOverride = abiOverride; 12912 this.installGrantPermissions = installGrantPermissions; 12913 this.traceMethod = traceMethod; 12914 this.traceCookie = traceCookie; 12915 this.certificates = certificates; 12916 } 12917 12918 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12919 abstract int doPreInstall(int status); 12920 12921 /** 12922 * Rename package into final resting place. All paths on the given 12923 * scanned package should be updated to reflect the rename. 12924 */ 12925 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12926 abstract int doPostInstall(int status, int uid); 12927 12928 /** @see PackageSettingBase#codePathString */ 12929 abstract String getCodePath(); 12930 /** @see PackageSettingBase#resourcePathString */ 12931 abstract String getResourcePath(); 12932 12933 // Need installer lock especially for dex file removal. 12934 abstract void cleanUpResourcesLI(); 12935 abstract boolean doPostDeleteLI(boolean delete); 12936 12937 /** 12938 * Called before the source arguments are copied. This is used mostly 12939 * for MoveParams when it needs to read the source file to put it in the 12940 * destination. 12941 */ 12942 int doPreCopy() { 12943 return PackageManager.INSTALL_SUCCEEDED; 12944 } 12945 12946 /** 12947 * Called after the source arguments are copied. This is used mostly for 12948 * MoveParams when it needs to read the source file to put it in the 12949 * destination. 12950 */ 12951 int doPostCopy(int uid) { 12952 return PackageManager.INSTALL_SUCCEEDED; 12953 } 12954 12955 protected boolean isFwdLocked() { 12956 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12957 } 12958 12959 protected boolean isExternalAsec() { 12960 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12961 } 12962 12963 protected boolean isEphemeral() { 12964 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12965 } 12966 12967 UserHandle getUser() { 12968 return user; 12969 } 12970 } 12971 12972 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12973 if (!allCodePaths.isEmpty()) { 12974 if (instructionSets == null) { 12975 throw new IllegalStateException("instructionSet == null"); 12976 } 12977 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12978 for (String codePath : allCodePaths) { 12979 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12980 try { 12981 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12982 } catch (InstallerException ignored) { 12983 } 12984 } 12985 } 12986 } 12987 } 12988 12989 /** 12990 * Logic to handle installation of non-ASEC applications, including copying 12991 * and renaming logic. 12992 */ 12993 class FileInstallArgs extends InstallArgs { 12994 private File codeFile; 12995 private File resourceFile; 12996 12997 // Example topology: 12998 // /data/app/com.example/base.apk 12999 // /data/app/com.example/split_foo.apk 13000 // /data/app/com.example/lib/arm/libfoo.so 13001 // /data/app/com.example/lib/arm64/libfoo.so 13002 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13003 13004 /** New install */ 13005 FileInstallArgs(InstallParams params) { 13006 super(params.origin, params.move, params.observer, params.installFlags, 13007 params.installerPackageName, params.volumeUuid, 13008 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13009 params.grantedRuntimePermissions, 13010 params.traceMethod, params.traceCookie, params.certificates); 13011 if (isFwdLocked()) { 13012 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13013 } 13014 } 13015 13016 /** Existing install */ 13017 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13018 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13019 null, null, null, 0, null /*certificates*/); 13020 this.codeFile = (codePath != null) ? new File(codePath) : null; 13021 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13022 } 13023 13024 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13025 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13026 try { 13027 return doCopyApk(imcs, temp); 13028 } finally { 13029 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13030 } 13031 } 13032 13033 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13034 if (origin.staged) { 13035 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13036 codeFile = origin.file; 13037 resourceFile = origin.file; 13038 return PackageManager.INSTALL_SUCCEEDED; 13039 } 13040 13041 try { 13042 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13043 final File tempDir = 13044 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13045 codeFile = tempDir; 13046 resourceFile = tempDir; 13047 } catch (IOException e) { 13048 Slog.w(TAG, "Failed to create copy file: " + e); 13049 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13050 } 13051 13052 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13053 @Override 13054 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13055 if (!FileUtils.isValidExtFilename(name)) { 13056 throw new IllegalArgumentException("Invalid filename: " + name); 13057 } 13058 try { 13059 final File file = new File(codeFile, name); 13060 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13061 O_RDWR | O_CREAT, 0644); 13062 Os.chmod(file.getAbsolutePath(), 0644); 13063 return new ParcelFileDescriptor(fd); 13064 } catch (ErrnoException e) { 13065 throw new RemoteException("Failed to open: " + e.getMessage()); 13066 } 13067 } 13068 }; 13069 13070 int ret = PackageManager.INSTALL_SUCCEEDED; 13071 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13072 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13073 Slog.e(TAG, "Failed to copy package"); 13074 return ret; 13075 } 13076 13077 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13078 NativeLibraryHelper.Handle handle = null; 13079 try { 13080 handle = NativeLibraryHelper.Handle.create(codeFile); 13081 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13082 abiOverride); 13083 } catch (IOException e) { 13084 Slog.e(TAG, "Copying native libraries failed", e); 13085 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13086 } finally { 13087 IoUtils.closeQuietly(handle); 13088 } 13089 13090 return ret; 13091 } 13092 13093 int doPreInstall(int status) { 13094 if (status != PackageManager.INSTALL_SUCCEEDED) { 13095 cleanUp(); 13096 } 13097 return status; 13098 } 13099 13100 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13101 if (status != PackageManager.INSTALL_SUCCEEDED) { 13102 cleanUp(); 13103 return false; 13104 } 13105 13106 final File targetDir = codeFile.getParentFile(); 13107 final File beforeCodeFile = codeFile; 13108 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13109 13110 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13111 try { 13112 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13113 } catch (ErrnoException e) { 13114 Slog.w(TAG, "Failed to rename", e); 13115 return false; 13116 } 13117 13118 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13119 Slog.w(TAG, "Failed to restorecon"); 13120 return false; 13121 } 13122 13123 // Reflect the rename internally 13124 codeFile = afterCodeFile; 13125 resourceFile = afterCodeFile; 13126 13127 // Reflect the rename in scanned details 13128 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13129 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13130 afterCodeFile, pkg.baseCodePath)); 13131 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13132 afterCodeFile, pkg.splitCodePaths)); 13133 13134 // Reflect the rename in app info 13135 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13136 pkg.setApplicationInfoCodePath(pkg.codePath); 13137 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13138 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13139 pkg.setApplicationInfoResourcePath(pkg.codePath); 13140 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13141 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13142 13143 return true; 13144 } 13145 13146 int doPostInstall(int status, int uid) { 13147 if (status != PackageManager.INSTALL_SUCCEEDED) { 13148 cleanUp(); 13149 } 13150 return status; 13151 } 13152 13153 @Override 13154 String getCodePath() { 13155 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13156 } 13157 13158 @Override 13159 String getResourcePath() { 13160 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13161 } 13162 13163 private boolean cleanUp() { 13164 if (codeFile == null || !codeFile.exists()) { 13165 return false; 13166 } 13167 13168 removeCodePathLI(codeFile); 13169 13170 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13171 resourceFile.delete(); 13172 } 13173 13174 return true; 13175 } 13176 13177 void cleanUpResourcesLI() { 13178 // Try enumerating all code paths before deleting 13179 List<String> allCodePaths = Collections.EMPTY_LIST; 13180 if (codeFile != null && codeFile.exists()) { 13181 try { 13182 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13183 allCodePaths = pkg.getAllCodePaths(); 13184 } catch (PackageParserException e) { 13185 // Ignored; we tried our best 13186 } 13187 } 13188 13189 cleanUp(); 13190 removeDexFiles(allCodePaths, instructionSets); 13191 } 13192 13193 boolean doPostDeleteLI(boolean delete) { 13194 // XXX err, shouldn't we respect the delete flag? 13195 cleanUpResourcesLI(); 13196 return true; 13197 } 13198 } 13199 13200 private boolean isAsecExternal(String cid) { 13201 final String asecPath = PackageHelper.getSdFilesystem(cid); 13202 return !asecPath.startsWith(mAsecInternalPath); 13203 } 13204 13205 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13206 PackageManagerException { 13207 if (copyRet < 0) { 13208 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13209 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13210 throw new PackageManagerException(copyRet, message); 13211 } 13212 } 13213 } 13214 13215 /** 13216 * Extract the MountService "container ID" from the full code path of an 13217 * .apk. 13218 */ 13219 static String cidFromCodePath(String fullCodePath) { 13220 int eidx = fullCodePath.lastIndexOf("/"); 13221 String subStr1 = fullCodePath.substring(0, eidx); 13222 int sidx = subStr1.lastIndexOf("/"); 13223 return subStr1.substring(sidx+1, eidx); 13224 } 13225 13226 /** 13227 * Logic to handle installation of ASEC applications, including copying and 13228 * renaming logic. 13229 */ 13230 class AsecInstallArgs extends InstallArgs { 13231 static final String RES_FILE_NAME = "pkg.apk"; 13232 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13233 13234 String cid; 13235 String packagePath; 13236 String resourcePath; 13237 13238 /** New install */ 13239 AsecInstallArgs(InstallParams params) { 13240 super(params.origin, params.move, params.observer, params.installFlags, 13241 params.installerPackageName, params.volumeUuid, 13242 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13243 params.grantedRuntimePermissions, 13244 params.traceMethod, params.traceCookie, params.certificates); 13245 } 13246 13247 /** Existing install */ 13248 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13249 boolean isExternal, boolean isForwardLocked) { 13250 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13251 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13252 instructionSets, null, null, null, 0, null /*certificates*/); 13253 // Hackily pretend we're still looking at a full code path 13254 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13255 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13256 } 13257 13258 // Extract cid from fullCodePath 13259 int eidx = fullCodePath.lastIndexOf("/"); 13260 String subStr1 = fullCodePath.substring(0, eidx); 13261 int sidx = subStr1.lastIndexOf("/"); 13262 cid = subStr1.substring(sidx+1, eidx); 13263 setMountPath(subStr1); 13264 } 13265 13266 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13267 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13268 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13269 instructionSets, null, null, null, 0, null /*certificates*/); 13270 this.cid = cid; 13271 setMountPath(PackageHelper.getSdDir(cid)); 13272 } 13273 13274 void createCopyFile() { 13275 cid = mInstallerService.allocateExternalStageCidLegacy(); 13276 } 13277 13278 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13279 if (origin.staged && origin.cid != null) { 13280 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13281 cid = origin.cid; 13282 setMountPath(PackageHelper.getSdDir(cid)); 13283 return PackageManager.INSTALL_SUCCEEDED; 13284 } 13285 13286 if (temp) { 13287 createCopyFile(); 13288 } else { 13289 /* 13290 * Pre-emptively destroy the container since it's destroyed if 13291 * copying fails due to it existing anyway. 13292 */ 13293 PackageHelper.destroySdDir(cid); 13294 } 13295 13296 final String newMountPath = imcs.copyPackageToContainer( 13297 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13298 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13299 13300 if (newMountPath != null) { 13301 setMountPath(newMountPath); 13302 return PackageManager.INSTALL_SUCCEEDED; 13303 } else { 13304 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13305 } 13306 } 13307 13308 @Override 13309 String getCodePath() { 13310 return packagePath; 13311 } 13312 13313 @Override 13314 String getResourcePath() { 13315 return resourcePath; 13316 } 13317 13318 int doPreInstall(int status) { 13319 if (status != PackageManager.INSTALL_SUCCEEDED) { 13320 // Destroy container 13321 PackageHelper.destroySdDir(cid); 13322 } else { 13323 boolean mounted = PackageHelper.isContainerMounted(cid); 13324 if (!mounted) { 13325 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13326 Process.SYSTEM_UID); 13327 if (newMountPath != null) { 13328 setMountPath(newMountPath); 13329 } else { 13330 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13331 } 13332 } 13333 } 13334 return status; 13335 } 13336 13337 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13338 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13339 String newMountPath = null; 13340 if (PackageHelper.isContainerMounted(cid)) { 13341 // Unmount the container 13342 if (!PackageHelper.unMountSdDir(cid)) { 13343 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13344 return false; 13345 } 13346 } 13347 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13348 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13349 " which might be stale. Will try to clean up."); 13350 // Clean up the stale container and proceed to recreate. 13351 if (!PackageHelper.destroySdDir(newCacheId)) { 13352 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13353 return false; 13354 } 13355 // Successfully cleaned up stale container. Try to rename again. 13356 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13357 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13358 + " inspite of cleaning it up."); 13359 return false; 13360 } 13361 } 13362 if (!PackageHelper.isContainerMounted(newCacheId)) { 13363 Slog.w(TAG, "Mounting container " + newCacheId); 13364 newMountPath = PackageHelper.mountSdDir(newCacheId, 13365 getEncryptKey(), Process.SYSTEM_UID); 13366 } else { 13367 newMountPath = PackageHelper.getSdDir(newCacheId); 13368 } 13369 if (newMountPath == null) { 13370 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13371 return false; 13372 } 13373 Log.i(TAG, "Succesfully renamed " + cid + 13374 " to " + newCacheId + 13375 " at new path: " + newMountPath); 13376 cid = newCacheId; 13377 13378 final File beforeCodeFile = new File(packagePath); 13379 setMountPath(newMountPath); 13380 final File afterCodeFile = new File(packagePath); 13381 13382 // Reflect the rename in scanned details 13383 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13384 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13385 afterCodeFile, pkg.baseCodePath)); 13386 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13387 afterCodeFile, pkg.splitCodePaths)); 13388 13389 // Reflect the rename in app info 13390 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13391 pkg.setApplicationInfoCodePath(pkg.codePath); 13392 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13393 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13394 pkg.setApplicationInfoResourcePath(pkg.codePath); 13395 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13396 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13397 13398 return true; 13399 } 13400 13401 private void setMountPath(String mountPath) { 13402 final File mountFile = new File(mountPath); 13403 13404 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13405 if (monolithicFile.exists()) { 13406 packagePath = monolithicFile.getAbsolutePath(); 13407 if (isFwdLocked()) { 13408 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13409 } else { 13410 resourcePath = packagePath; 13411 } 13412 } else { 13413 packagePath = mountFile.getAbsolutePath(); 13414 resourcePath = packagePath; 13415 } 13416 } 13417 13418 int doPostInstall(int status, int uid) { 13419 if (status != PackageManager.INSTALL_SUCCEEDED) { 13420 cleanUp(); 13421 } else { 13422 final int groupOwner; 13423 final String protectedFile; 13424 if (isFwdLocked()) { 13425 groupOwner = UserHandle.getSharedAppGid(uid); 13426 protectedFile = RES_FILE_NAME; 13427 } else { 13428 groupOwner = -1; 13429 protectedFile = null; 13430 } 13431 13432 if (uid < Process.FIRST_APPLICATION_UID 13433 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13434 Slog.e(TAG, "Failed to finalize " + cid); 13435 PackageHelper.destroySdDir(cid); 13436 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13437 } 13438 13439 boolean mounted = PackageHelper.isContainerMounted(cid); 13440 if (!mounted) { 13441 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13442 } 13443 } 13444 return status; 13445 } 13446 13447 private void cleanUp() { 13448 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13449 13450 // Destroy secure container 13451 PackageHelper.destroySdDir(cid); 13452 } 13453 13454 private List<String> getAllCodePaths() { 13455 final File codeFile = new File(getCodePath()); 13456 if (codeFile != null && codeFile.exists()) { 13457 try { 13458 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13459 return pkg.getAllCodePaths(); 13460 } catch (PackageParserException e) { 13461 // Ignored; we tried our best 13462 } 13463 } 13464 return Collections.EMPTY_LIST; 13465 } 13466 13467 void cleanUpResourcesLI() { 13468 // Enumerate all code paths before deleting 13469 cleanUpResourcesLI(getAllCodePaths()); 13470 } 13471 13472 private void cleanUpResourcesLI(List<String> allCodePaths) { 13473 cleanUp(); 13474 removeDexFiles(allCodePaths, instructionSets); 13475 } 13476 13477 String getPackageName() { 13478 return getAsecPackageName(cid); 13479 } 13480 13481 boolean doPostDeleteLI(boolean delete) { 13482 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13483 final List<String> allCodePaths = getAllCodePaths(); 13484 boolean mounted = PackageHelper.isContainerMounted(cid); 13485 if (mounted) { 13486 // Unmount first 13487 if (PackageHelper.unMountSdDir(cid)) { 13488 mounted = false; 13489 } 13490 } 13491 if (!mounted && delete) { 13492 cleanUpResourcesLI(allCodePaths); 13493 } 13494 return !mounted; 13495 } 13496 13497 @Override 13498 int doPreCopy() { 13499 if (isFwdLocked()) { 13500 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13501 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13502 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13503 } 13504 } 13505 13506 return PackageManager.INSTALL_SUCCEEDED; 13507 } 13508 13509 @Override 13510 int doPostCopy(int uid) { 13511 if (isFwdLocked()) { 13512 if (uid < Process.FIRST_APPLICATION_UID 13513 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13514 RES_FILE_NAME)) { 13515 Slog.e(TAG, "Failed to finalize " + cid); 13516 PackageHelper.destroySdDir(cid); 13517 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13518 } 13519 } 13520 13521 return PackageManager.INSTALL_SUCCEEDED; 13522 } 13523 } 13524 13525 /** 13526 * Logic to handle movement of existing installed applications. 13527 */ 13528 class MoveInstallArgs extends InstallArgs { 13529 private File codeFile; 13530 private File resourceFile; 13531 13532 /** New install */ 13533 MoveInstallArgs(InstallParams params) { 13534 super(params.origin, params.move, params.observer, params.installFlags, 13535 params.installerPackageName, params.volumeUuid, 13536 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13537 params.grantedRuntimePermissions, 13538 params.traceMethod, params.traceCookie, params.certificates); 13539 } 13540 13541 int copyApk(IMediaContainerService imcs, boolean temp) { 13542 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13543 + move.fromUuid + " to " + move.toUuid); 13544 synchronized (mInstaller) { 13545 try { 13546 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13547 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13548 } catch (InstallerException e) { 13549 Slog.w(TAG, "Failed to move app", e); 13550 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13551 } 13552 } 13553 13554 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13555 resourceFile = codeFile; 13556 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13557 13558 return PackageManager.INSTALL_SUCCEEDED; 13559 } 13560 13561 int doPreInstall(int status) { 13562 if (status != PackageManager.INSTALL_SUCCEEDED) { 13563 cleanUp(move.toUuid); 13564 } 13565 return status; 13566 } 13567 13568 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13569 if (status != PackageManager.INSTALL_SUCCEEDED) { 13570 cleanUp(move.toUuid); 13571 return false; 13572 } 13573 13574 // Reflect the move in app info 13575 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13576 pkg.setApplicationInfoCodePath(pkg.codePath); 13577 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13578 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13579 pkg.setApplicationInfoResourcePath(pkg.codePath); 13580 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13581 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13582 13583 return true; 13584 } 13585 13586 int doPostInstall(int status, int uid) { 13587 if (status == PackageManager.INSTALL_SUCCEEDED) { 13588 cleanUp(move.fromUuid); 13589 } else { 13590 cleanUp(move.toUuid); 13591 } 13592 return status; 13593 } 13594 13595 @Override 13596 String getCodePath() { 13597 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13598 } 13599 13600 @Override 13601 String getResourcePath() { 13602 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13603 } 13604 13605 private boolean cleanUp(String volumeUuid) { 13606 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13607 move.dataAppName); 13608 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13609 final int[] userIds = sUserManager.getUserIds(); 13610 synchronized (mInstallLock) { 13611 // Clean up both app data and code 13612 // All package moves are frozen until finished 13613 for (int userId : userIds) { 13614 try { 13615 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13616 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13617 } catch (InstallerException e) { 13618 Slog.w(TAG, String.valueOf(e)); 13619 } 13620 } 13621 removeCodePathLI(codeFile); 13622 } 13623 return true; 13624 } 13625 13626 void cleanUpResourcesLI() { 13627 throw new UnsupportedOperationException(); 13628 } 13629 13630 boolean doPostDeleteLI(boolean delete) { 13631 throw new UnsupportedOperationException(); 13632 } 13633 } 13634 13635 static String getAsecPackageName(String packageCid) { 13636 int idx = packageCid.lastIndexOf("-"); 13637 if (idx == -1) { 13638 return packageCid; 13639 } 13640 return packageCid.substring(0, idx); 13641 } 13642 13643 // Utility method used to create code paths based on package name and available index. 13644 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13645 String idxStr = ""; 13646 int idx = 1; 13647 // Fall back to default value of idx=1 if prefix is not 13648 // part of oldCodePath 13649 if (oldCodePath != null) { 13650 String subStr = oldCodePath; 13651 // Drop the suffix right away 13652 if (suffix != null && subStr.endsWith(suffix)) { 13653 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13654 } 13655 // If oldCodePath already contains prefix find out the 13656 // ending index to either increment or decrement. 13657 int sidx = subStr.lastIndexOf(prefix); 13658 if (sidx != -1) { 13659 subStr = subStr.substring(sidx + prefix.length()); 13660 if (subStr != null) { 13661 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13662 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13663 } 13664 try { 13665 idx = Integer.parseInt(subStr); 13666 if (idx <= 1) { 13667 idx++; 13668 } else { 13669 idx--; 13670 } 13671 } catch(NumberFormatException e) { 13672 } 13673 } 13674 } 13675 } 13676 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13677 return prefix + idxStr; 13678 } 13679 13680 private File getNextCodePath(File targetDir, String packageName) { 13681 int suffix = 1; 13682 File result; 13683 do { 13684 result = new File(targetDir, packageName + "-" + suffix); 13685 suffix++; 13686 } while (result.exists()); 13687 return result; 13688 } 13689 13690 // Utility method that returns the relative package path with respect 13691 // to the installation directory. Like say for /data/data/com.test-1.apk 13692 // string com.test-1 is returned. 13693 static String deriveCodePathName(String codePath) { 13694 if (codePath == null) { 13695 return null; 13696 } 13697 final File codeFile = new File(codePath); 13698 final String name = codeFile.getName(); 13699 if (codeFile.isDirectory()) { 13700 return name; 13701 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13702 final int lastDot = name.lastIndexOf('.'); 13703 return name.substring(0, lastDot); 13704 } else { 13705 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13706 return null; 13707 } 13708 } 13709 13710 static class PackageInstalledInfo { 13711 String name; 13712 int uid; 13713 // The set of users that originally had this package installed. 13714 int[] origUsers; 13715 // The set of users that now have this package installed. 13716 int[] newUsers; 13717 PackageParser.Package pkg; 13718 int returnCode; 13719 String returnMsg; 13720 PackageRemovedInfo removedInfo; 13721 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13722 13723 public void setError(int code, String msg) { 13724 setReturnCode(code); 13725 setReturnMessage(msg); 13726 Slog.w(TAG, msg); 13727 } 13728 13729 public void setError(String msg, PackageParserException e) { 13730 setReturnCode(e.error); 13731 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13732 Slog.w(TAG, msg, e); 13733 } 13734 13735 public void setError(String msg, PackageManagerException e) { 13736 returnCode = e.error; 13737 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13738 Slog.w(TAG, msg, e); 13739 } 13740 13741 public void setReturnCode(int returnCode) { 13742 this.returnCode = returnCode; 13743 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13744 for (int i = 0; i < childCount; i++) { 13745 addedChildPackages.valueAt(i).returnCode = returnCode; 13746 } 13747 } 13748 13749 private void setReturnMessage(String returnMsg) { 13750 this.returnMsg = returnMsg; 13751 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13752 for (int i = 0; i < childCount; i++) { 13753 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13754 } 13755 } 13756 13757 // In some error cases we want to convey more info back to the observer 13758 String origPackage; 13759 String origPermission; 13760 } 13761 13762 /* 13763 * Install a non-existing package. 13764 */ 13765 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13766 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13767 PackageInstalledInfo res) { 13768 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13769 13770 // Remember this for later, in case we need to rollback this install 13771 String pkgName = pkg.packageName; 13772 13773 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13774 13775 synchronized(mPackages) { 13776 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13777 // A package with the same name is already installed, though 13778 // it has been renamed to an older name. The package we 13779 // are trying to install should be installed as an update to 13780 // the existing one, but that has not been requested, so bail. 13781 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13782 + " without first uninstalling package running as " 13783 + mSettings.mRenamedPackages.get(pkgName)); 13784 return; 13785 } 13786 if (mPackages.containsKey(pkgName)) { 13787 // Don't allow installation over an existing package with the same name. 13788 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13789 + " without first uninstalling."); 13790 return; 13791 } 13792 } 13793 13794 try { 13795 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13796 System.currentTimeMillis(), user); 13797 13798 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13799 13800 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13801 prepareAppDataAfterInstallLIF(newPackage); 13802 13803 } else { 13804 // Remove package from internal structures, but keep around any 13805 // data that might have already existed 13806 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13807 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13808 } 13809 } catch (PackageManagerException e) { 13810 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13811 } 13812 13813 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13814 } 13815 13816 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13817 // Can't rotate keys during boot or if sharedUser. 13818 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13819 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13820 return false; 13821 } 13822 // app is using upgradeKeySets; make sure all are valid 13823 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13824 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13825 for (int i = 0; i < upgradeKeySets.length; i++) { 13826 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13827 Slog.wtf(TAG, "Package " 13828 + (oldPs.name != null ? oldPs.name : "<null>") 13829 + " contains upgrade-key-set reference to unknown key-set: " 13830 + upgradeKeySets[i] 13831 + " reverting to signatures check."); 13832 return false; 13833 } 13834 } 13835 return true; 13836 } 13837 13838 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13839 // Upgrade keysets are being used. Determine if new package has a superset of the 13840 // required keys. 13841 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13842 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13843 for (int i = 0; i < upgradeKeySets.length; i++) { 13844 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13845 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13846 return true; 13847 } 13848 } 13849 return false; 13850 } 13851 13852 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13853 try (DigestInputStream digestStream = 13854 new DigestInputStream(new FileInputStream(file), digest)) { 13855 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13856 } 13857 } 13858 13859 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13860 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13861 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13862 13863 final PackageParser.Package oldPackage; 13864 final String pkgName = pkg.packageName; 13865 final int[] allUsers; 13866 final int[] installedUsers; 13867 13868 synchronized(mPackages) { 13869 oldPackage = mPackages.get(pkgName); 13870 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13871 13872 // don't allow upgrade to target a release SDK from a pre-release SDK 13873 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13874 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13875 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13876 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13877 if (oldTargetsPreRelease 13878 && !newTargetsPreRelease 13879 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13880 Slog.w(TAG, "Can't install package targeting released sdk"); 13881 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13882 return; 13883 } 13884 13885 // don't allow an upgrade from full to ephemeral 13886 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13887 if (isEphemeral && !oldIsEphemeral) { 13888 // can't downgrade from full to ephemeral 13889 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13890 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13891 return; 13892 } 13893 13894 // verify signatures are valid 13895 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13896 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13897 if (!checkUpgradeKeySetLP(ps, pkg)) { 13898 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13899 "New package not signed by keys specified by upgrade-keysets: " 13900 + pkgName); 13901 return; 13902 } 13903 } else { 13904 // default to original signature matching 13905 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13906 != PackageManager.SIGNATURE_MATCH) { 13907 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13908 "New package has a different signature: " + pkgName); 13909 return; 13910 } 13911 } 13912 13913 // don't allow a system upgrade unless the upgrade hash matches 13914 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13915 byte[] digestBytes = null; 13916 try { 13917 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13918 updateDigest(digest, new File(pkg.baseCodePath)); 13919 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13920 for (String path : pkg.splitCodePaths) { 13921 updateDigest(digest, new File(path)); 13922 } 13923 } 13924 digestBytes = digest.digest(); 13925 } catch (NoSuchAlgorithmException | IOException e) { 13926 res.setError(INSTALL_FAILED_INVALID_APK, 13927 "Could not compute hash: " + pkgName); 13928 return; 13929 } 13930 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13931 res.setError(INSTALL_FAILED_INVALID_APK, 13932 "New package fails restrict-update check: " + pkgName); 13933 return; 13934 } 13935 // retain upgrade restriction 13936 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13937 } 13938 13939 // Check for shared user id changes 13940 String invalidPackageName = 13941 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13942 if (invalidPackageName != null) { 13943 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13944 "Package " + invalidPackageName + " tried to change user " 13945 + oldPackage.mSharedUserId); 13946 return; 13947 } 13948 13949 // In case of rollback, remember per-user/profile install state 13950 allUsers = sUserManager.getUserIds(); 13951 installedUsers = ps.queryInstalledUsers(allUsers, true); 13952 } 13953 13954 // Update what is removed 13955 res.removedInfo = new PackageRemovedInfo(); 13956 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13957 res.removedInfo.removedPackage = oldPackage.packageName; 13958 res.removedInfo.isUpdate = true; 13959 res.removedInfo.origUsers = installedUsers; 13960 final int childCount = (oldPackage.childPackages != null) 13961 ? oldPackage.childPackages.size() : 0; 13962 for (int i = 0; i < childCount; i++) { 13963 boolean childPackageUpdated = false; 13964 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13965 if (res.addedChildPackages != null) { 13966 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13967 if (childRes != null) { 13968 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13969 childRes.removedInfo.removedPackage = childPkg.packageName; 13970 childRes.removedInfo.isUpdate = true; 13971 childPackageUpdated = true; 13972 } 13973 } 13974 if (!childPackageUpdated) { 13975 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13976 childRemovedRes.removedPackage = childPkg.packageName; 13977 childRemovedRes.isUpdate = false; 13978 childRemovedRes.dataRemoved = true; 13979 synchronized (mPackages) { 13980 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13981 if (childPs != null) { 13982 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13983 } 13984 } 13985 if (res.removedInfo.removedChildPackages == null) { 13986 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13987 } 13988 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13989 } 13990 } 13991 13992 boolean sysPkg = (isSystemApp(oldPackage)); 13993 if (sysPkg) { 13994 // Set the system/privileged flags as needed 13995 final boolean privileged = 13996 (oldPackage.applicationInfo.privateFlags 13997 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13998 final int systemPolicyFlags = policyFlags 13999 | PackageParser.PARSE_IS_SYSTEM 14000 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14001 14002 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14003 user, allUsers, installerPackageName, res); 14004 } else { 14005 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14006 user, allUsers, installerPackageName, res); 14007 } 14008 } 14009 14010 public List<String> getPreviousCodePaths(String packageName) { 14011 final PackageSetting ps = mSettings.mPackages.get(packageName); 14012 final List<String> result = new ArrayList<String>(); 14013 if (ps != null && ps.oldCodePaths != null) { 14014 result.addAll(ps.oldCodePaths); 14015 } 14016 return result; 14017 } 14018 14019 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14020 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14021 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14022 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14023 + deletedPackage); 14024 14025 String pkgName = deletedPackage.packageName; 14026 boolean deletedPkg = true; 14027 boolean addedPkg = false; 14028 boolean updatedSettings = false; 14029 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14030 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14031 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14032 14033 final long origUpdateTime = (pkg.mExtras != null) 14034 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14035 14036 // First delete the existing package while retaining the data directory 14037 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14038 res.removedInfo, true, pkg)) { 14039 // If the existing package wasn't successfully deleted 14040 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14041 deletedPkg = false; 14042 } else { 14043 // Successfully deleted the old package; proceed with replace. 14044 14045 // If deleted package lived in a container, give users a chance to 14046 // relinquish resources before killing. 14047 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14048 if (DEBUG_INSTALL) { 14049 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14050 } 14051 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14052 final ArrayList<String> pkgList = new ArrayList<String>(1); 14053 pkgList.add(deletedPackage.applicationInfo.packageName); 14054 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14055 } 14056 14057 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14058 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14059 clearAppProfilesLIF(pkg); 14060 14061 try { 14062 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14063 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14064 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14065 14066 // Update the in-memory copy of the previous code paths. 14067 PackageSetting ps = mSettings.mPackages.get(pkgName); 14068 if (!killApp) { 14069 if (ps.oldCodePaths == null) { 14070 ps.oldCodePaths = new ArraySet<>(); 14071 } 14072 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14073 if (deletedPackage.splitCodePaths != null) { 14074 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14075 } 14076 } else { 14077 ps.oldCodePaths = null; 14078 } 14079 if (ps.childPackageNames != null) { 14080 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14081 final String childPkgName = ps.childPackageNames.get(i); 14082 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14083 childPs.oldCodePaths = ps.oldCodePaths; 14084 } 14085 } 14086 prepareAppDataAfterInstallLIF(newPackage); 14087 addedPkg = true; 14088 } catch (PackageManagerException e) { 14089 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14090 } 14091 } 14092 14093 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14094 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14095 14096 // Revert all internal state mutations and added folders for the failed install 14097 if (addedPkg) { 14098 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14099 res.removedInfo, true, null); 14100 } 14101 14102 // Restore the old package 14103 if (deletedPkg) { 14104 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14105 File restoreFile = new File(deletedPackage.codePath); 14106 // Parse old package 14107 boolean oldExternal = isExternal(deletedPackage); 14108 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14109 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14110 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14111 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14112 try { 14113 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14114 null); 14115 } catch (PackageManagerException e) { 14116 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14117 + e.getMessage()); 14118 return; 14119 } 14120 14121 synchronized (mPackages) { 14122 // Ensure the installer package name up to date 14123 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14124 14125 // Update permissions for restored package 14126 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14127 14128 mSettings.writeLPr(); 14129 } 14130 14131 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14132 } 14133 } else { 14134 synchronized (mPackages) { 14135 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14136 if (ps != null) { 14137 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14138 if (res.removedInfo.removedChildPackages != null) { 14139 final int childCount = res.removedInfo.removedChildPackages.size(); 14140 // Iterate in reverse as we may modify the collection 14141 for (int i = childCount - 1; i >= 0; i--) { 14142 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14143 if (res.addedChildPackages.containsKey(childPackageName)) { 14144 res.removedInfo.removedChildPackages.removeAt(i); 14145 } else { 14146 PackageRemovedInfo childInfo = res.removedInfo 14147 .removedChildPackages.valueAt(i); 14148 childInfo.removedForAllUsers = mPackages.get( 14149 childInfo.removedPackage) == null; 14150 } 14151 } 14152 } 14153 } 14154 } 14155 } 14156 } 14157 14158 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14159 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14160 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14161 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14162 + ", old=" + deletedPackage); 14163 14164 final boolean disabledSystem; 14165 14166 // Remove existing system package 14167 removePackageLI(deletedPackage, true); 14168 14169 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14170 if (!disabledSystem) { 14171 // We didn't need to disable the .apk as a current system package, 14172 // which means we are replacing another update that is already 14173 // installed. We need to make sure to delete the older one's .apk. 14174 res.removedInfo.args = createInstallArgsForExisting(0, 14175 deletedPackage.applicationInfo.getCodePath(), 14176 deletedPackage.applicationInfo.getResourcePath(), 14177 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14178 } else { 14179 res.removedInfo.args = null; 14180 } 14181 14182 // Successfully disabled the old package. Now proceed with re-installation 14183 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14184 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14185 clearAppProfilesLIF(pkg); 14186 14187 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14188 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14189 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14190 14191 PackageParser.Package newPackage = null; 14192 try { 14193 // Add the package to the internal data structures 14194 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14195 14196 // Set the update and install times 14197 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14198 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14199 System.currentTimeMillis()); 14200 14201 // Update the package dynamic state if succeeded 14202 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14203 // Now that the install succeeded make sure we remove data 14204 // directories for any child package the update removed. 14205 final int deletedChildCount = (deletedPackage.childPackages != null) 14206 ? deletedPackage.childPackages.size() : 0; 14207 final int newChildCount = (newPackage.childPackages != null) 14208 ? newPackage.childPackages.size() : 0; 14209 for (int i = 0; i < deletedChildCount; i++) { 14210 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14211 boolean childPackageDeleted = true; 14212 for (int j = 0; j < newChildCount; j++) { 14213 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14214 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14215 childPackageDeleted = false; 14216 break; 14217 } 14218 } 14219 if (childPackageDeleted) { 14220 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14221 deletedChildPkg.packageName); 14222 if (ps != null && res.removedInfo.removedChildPackages != null) { 14223 PackageRemovedInfo removedChildRes = res.removedInfo 14224 .removedChildPackages.get(deletedChildPkg.packageName); 14225 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14226 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14227 } 14228 } 14229 } 14230 14231 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14232 prepareAppDataAfterInstallLIF(newPackage); 14233 } 14234 } catch (PackageManagerException e) { 14235 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14236 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14237 } 14238 14239 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14240 // Re installation failed. Restore old information 14241 // Remove new pkg information 14242 if (newPackage != null) { 14243 removeInstalledPackageLI(newPackage, true); 14244 } 14245 // Add back the old system package 14246 try { 14247 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14248 } catch (PackageManagerException e) { 14249 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14250 } 14251 14252 synchronized (mPackages) { 14253 if (disabledSystem) { 14254 enableSystemPackageLPw(deletedPackage); 14255 } 14256 14257 // Ensure the installer package name up to date 14258 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14259 14260 // Update permissions for restored package 14261 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14262 14263 mSettings.writeLPr(); 14264 } 14265 14266 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14267 + " after failed upgrade"); 14268 } 14269 } 14270 14271 /** 14272 * Checks whether the parent or any of the child packages have a change shared 14273 * user. For a package to be a valid update the shred users of the parent and 14274 * the children should match. We may later support changing child shared users. 14275 * @param oldPkg The updated package. 14276 * @param newPkg The update package. 14277 * @return The shared user that change between the versions. 14278 */ 14279 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14280 PackageParser.Package newPkg) { 14281 // Check parent shared user 14282 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14283 return newPkg.packageName; 14284 } 14285 // Check child shared users 14286 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14287 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14288 for (int i = 0; i < newChildCount; i++) { 14289 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14290 // If this child was present, did it have the same shared user? 14291 for (int j = 0; j < oldChildCount; j++) { 14292 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14293 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14294 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14295 return newChildPkg.packageName; 14296 } 14297 } 14298 } 14299 return null; 14300 } 14301 14302 private void removeNativeBinariesLI(PackageSetting ps) { 14303 // Remove the lib path for the parent package 14304 if (ps != null) { 14305 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14306 // Remove the lib path for the child packages 14307 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14308 for (int i = 0; i < childCount; i++) { 14309 PackageSetting childPs = null; 14310 synchronized (mPackages) { 14311 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14312 } 14313 if (childPs != null) { 14314 NativeLibraryHelper.removeNativeBinariesLI(childPs 14315 .legacyNativeLibraryPathString); 14316 } 14317 } 14318 } 14319 } 14320 14321 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14322 // Enable the parent package 14323 mSettings.enableSystemPackageLPw(pkg.packageName); 14324 // Enable the child packages 14325 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14326 for (int i = 0; i < childCount; i++) { 14327 PackageParser.Package childPkg = pkg.childPackages.get(i); 14328 mSettings.enableSystemPackageLPw(childPkg.packageName); 14329 } 14330 } 14331 14332 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14333 PackageParser.Package newPkg) { 14334 // Disable the parent package (parent always replaced) 14335 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14336 // Disable the child packages 14337 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14338 for (int i = 0; i < childCount; i++) { 14339 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14340 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14341 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14342 } 14343 return disabled; 14344 } 14345 14346 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14347 String installerPackageName) { 14348 // Enable the parent package 14349 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14350 // Enable the child packages 14351 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14352 for (int i = 0; i < childCount; i++) { 14353 PackageParser.Package childPkg = pkg.childPackages.get(i); 14354 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14355 } 14356 } 14357 14358 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14359 // Collect all used permissions in the UID 14360 ArraySet<String> usedPermissions = new ArraySet<>(); 14361 final int packageCount = su.packages.size(); 14362 for (int i = 0; i < packageCount; i++) { 14363 PackageSetting ps = su.packages.valueAt(i); 14364 if (ps.pkg == null) { 14365 continue; 14366 } 14367 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14368 for (int j = 0; j < requestedPermCount; j++) { 14369 String permission = ps.pkg.requestedPermissions.get(j); 14370 BasePermission bp = mSettings.mPermissions.get(permission); 14371 if (bp != null) { 14372 usedPermissions.add(permission); 14373 } 14374 } 14375 } 14376 14377 PermissionsState permissionsState = su.getPermissionsState(); 14378 // Prune install permissions 14379 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14380 final int installPermCount = installPermStates.size(); 14381 for (int i = installPermCount - 1; i >= 0; i--) { 14382 PermissionState permissionState = installPermStates.get(i); 14383 if (!usedPermissions.contains(permissionState.getName())) { 14384 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14385 if (bp != null) { 14386 permissionsState.revokeInstallPermission(bp); 14387 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14388 PackageManager.MASK_PERMISSION_FLAGS, 0); 14389 } 14390 } 14391 } 14392 14393 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14394 14395 // Prune runtime permissions 14396 for (int userId : allUserIds) { 14397 List<PermissionState> runtimePermStates = permissionsState 14398 .getRuntimePermissionStates(userId); 14399 final int runtimePermCount = runtimePermStates.size(); 14400 for (int i = runtimePermCount - 1; i >= 0; i--) { 14401 PermissionState permissionState = runtimePermStates.get(i); 14402 if (!usedPermissions.contains(permissionState.getName())) { 14403 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14404 if (bp != null) { 14405 permissionsState.revokeRuntimePermission(bp, userId); 14406 permissionsState.updatePermissionFlags(bp, userId, 14407 PackageManager.MASK_PERMISSION_FLAGS, 0); 14408 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14409 runtimePermissionChangedUserIds, userId); 14410 } 14411 } 14412 } 14413 } 14414 14415 return runtimePermissionChangedUserIds; 14416 } 14417 14418 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14419 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14420 // Update the parent package setting 14421 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14422 res, user); 14423 // Update the child packages setting 14424 final int childCount = (newPackage.childPackages != null) 14425 ? newPackage.childPackages.size() : 0; 14426 for (int i = 0; i < childCount; i++) { 14427 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14428 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14429 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14430 childRes.origUsers, childRes, user); 14431 } 14432 } 14433 14434 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14435 String installerPackageName, int[] allUsers, int[] installedForUsers, 14436 PackageInstalledInfo res, UserHandle user) { 14437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14438 14439 String pkgName = newPackage.packageName; 14440 synchronized (mPackages) { 14441 //write settings. the installStatus will be incomplete at this stage. 14442 //note that the new package setting would have already been 14443 //added to mPackages. It hasn't been persisted yet. 14444 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14446 mSettings.writeLPr(); 14447 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14448 } 14449 14450 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14451 synchronized (mPackages) { 14452 updatePermissionsLPw(newPackage.packageName, newPackage, 14453 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14454 ? UPDATE_PERMISSIONS_ALL : 0)); 14455 // For system-bundled packages, we assume that installing an upgraded version 14456 // of the package implies that the user actually wants to run that new code, 14457 // so we enable the package. 14458 PackageSetting ps = mSettings.mPackages.get(pkgName); 14459 final int userId = user.getIdentifier(); 14460 if (ps != null) { 14461 if (isSystemApp(newPackage)) { 14462 if (DEBUG_INSTALL) { 14463 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14464 } 14465 // Enable system package for requested users 14466 if (res.origUsers != null) { 14467 for (int origUserId : res.origUsers) { 14468 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14469 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14470 origUserId, installerPackageName); 14471 } 14472 } 14473 } 14474 // Also convey the prior install/uninstall state 14475 if (allUsers != null && installedForUsers != null) { 14476 for (int currentUserId : allUsers) { 14477 final boolean installed = ArrayUtils.contains( 14478 installedForUsers, currentUserId); 14479 if (DEBUG_INSTALL) { 14480 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14481 } 14482 ps.setInstalled(installed, currentUserId); 14483 } 14484 // these install state changes will be persisted in the 14485 // upcoming call to mSettings.writeLPr(). 14486 } 14487 } 14488 // It's implied that when a user requests installation, they want the app to be 14489 // installed and enabled. 14490 if (userId != UserHandle.USER_ALL) { 14491 ps.setInstalled(true, userId); 14492 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14493 } 14494 } 14495 res.name = pkgName; 14496 res.uid = newPackage.applicationInfo.uid; 14497 res.pkg = newPackage; 14498 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14499 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14500 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14501 //to update install status 14502 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14503 mSettings.writeLPr(); 14504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14505 } 14506 14507 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14508 } 14509 14510 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14511 try { 14512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14513 installPackageLI(args, res); 14514 } finally { 14515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14516 } 14517 } 14518 14519 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14520 final int installFlags = args.installFlags; 14521 final String installerPackageName = args.installerPackageName; 14522 final String volumeUuid = args.volumeUuid; 14523 final File tmpPackageFile = new File(args.getCodePath()); 14524 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14525 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14526 || (args.volumeUuid != null)); 14527 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14528 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14529 boolean replace = false; 14530 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14531 if (args.move != null) { 14532 // moving a complete application; perform an initial scan on the new install location 14533 scanFlags |= SCAN_INITIAL; 14534 } 14535 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14536 scanFlags |= SCAN_DONT_KILL_APP; 14537 } 14538 14539 // Result object to be returned 14540 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14541 14542 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14543 14544 // Sanity check 14545 if (ephemeral && (forwardLocked || onExternal)) { 14546 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14547 + " external=" + onExternal); 14548 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14549 return; 14550 } 14551 14552 // Retrieve PackageSettings and parse package 14553 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14554 | PackageParser.PARSE_ENFORCE_CODE 14555 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14556 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14557 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14558 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14559 PackageParser pp = new PackageParser(); 14560 pp.setSeparateProcesses(mSeparateProcesses); 14561 pp.setDisplayMetrics(mMetrics); 14562 14563 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14564 final PackageParser.Package pkg; 14565 try { 14566 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14567 } catch (PackageParserException e) { 14568 res.setError("Failed parse during installPackageLI", e); 14569 return; 14570 } finally { 14571 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14572 } 14573 14574 // If we are installing a clustered package add results for the children 14575 if (pkg.childPackages != null) { 14576 synchronized (mPackages) { 14577 final int childCount = pkg.childPackages.size(); 14578 for (int i = 0; i < childCount; i++) { 14579 PackageParser.Package childPkg = pkg.childPackages.get(i); 14580 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14581 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14582 childRes.pkg = childPkg; 14583 childRes.name = childPkg.packageName; 14584 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14585 if (childPs != null) { 14586 childRes.origUsers = childPs.queryInstalledUsers( 14587 sUserManager.getUserIds(), true); 14588 } 14589 if ((mPackages.containsKey(childPkg.packageName))) { 14590 childRes.removedInfo = new PackageRemovedInfo(); 14591 childRes.removedInfo.removedPackage = childPkg.packageName; 14592 } 14593 if (res.addedChildPackages == null) { 14594 res.addedChildPackages = new ArrayMap<>(); 14595 } 14596 res.addedChildPackages.put(childPkg.packageName, childRes); 14597 } 14598 } 14599 } 14600 14601 // If package doesn't declare API override, mark that we have an install 14602 // time CPU ABI override. 14603 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14604 pkg.cpuAbiOverride = args.abiOverride; 14605 } 14606 14607 String pkgName = res.name = pkg.packageName; 14608 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14609 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14610 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14611 return; 14612 } 14613 } 14614 14615 try { 14616 // either use what we've been given or parse directly from the APK 14617 if (args.certificates != null) { 14618 try { 14619 PackageParser.populateCertificates(pkg, args.certificates); 14620 } catch (PackageParserException e) { 14621 // there was something wrong with the certificates we were given; 14622 // try to pull them from the APK 14623 PackageParser.collectCertificates(pkg, parseFlags); 14624 } 14625 } else { 14626 PackageParser.collectCertificates(pkg, parseFlags); 14627 } 14628 } catch (PackageParserException e) { 14629 res.setError("Failed collect during installPackageLI", e); 14630 return; 14631 } 14632 14633 // Get rid of all references to package scan path via parser. 14634 pp = null; 14635 String oldCodePath = null; 14636 boolean systemApp = false; 14637 synchronized (mPackages) { 14638 // Check if installing already existing package 14639 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14640 String oldName = mSettings.mRenamedPackages.get(pkgName); 14641 if (pkg.mOriginalPackages != null 14642 && pkg.mOriginalPackages.contains(oldName) 14643 && mPackages.containsKey(oldName)) { 14644 // This package is derived from an original package, 14645 // and this device has been updating from that original 14646 // name. We must continue using the original name, so 14647 // rename the new package here. 14648 pkg.setPackageName(oldName); 14649 pkgName = pkg.packageName; 14650 replace = true; 14651 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14652 + oldName + " pkgName=" + pkgName); 14653 } else if (mPackages.containsKey(pkgName)) { 14654 // This package, under its official name, already exists 14655 // on the device; we should replace it. 14656 replace = true; 14657 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14658 } 14659 14660 // Child packages are installed through the parent package 14661 if (pkg.parentPackage != null) { 14662 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14663 "Package " + pkg.packageName + " is child of package " 14664 + pkg.parentPackage.parentPackage + ". Child packages " 14665 + "can be updated only through the parent package."); 14666 return; 14667 } 14668 14669 if (replace) { 14670 // Prevent apps opting out from runtime permissions 14671 PackageParser.Package oldPackage = mPackages.get(pkgName); 14672 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14673 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14674 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14675 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14676 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14677 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14678 + " doesn't support runtime permissions but the old" 14679 + " target SDK " + oldTargetSdk + " does."); 14680 return; 14681 } 14682 14683 // Prevent installing of child packages 14684 if (oldPackage.parentPackage != null) { 14685 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14686 "Package " + pkg.packageName + " is child of package " 14687 + oldPackage.parentPackage + ". Child packages " 14688 + "can be updated only through the parent package."); 14689 return; 14690 } 14691 } 14692 } 14693 14694 PackageSetting ps = mSettings.mPackages.get(pkgName); 14695 if (ps != null) { 14696 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14697 14698 // Quick sanity check that we're signed correctly if updating; 14699 // we'll check this again later when scanning, but we want to 14700 // bail early here before tripping over redefined permissions. 14701 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14702 if (!checkUpgradeKeySetLP(ps, pkg)) { 14703 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14704 + pkg.packageName + " upgrade keys do not match the " 14705 + "previously installed version"); 14706 return; 14707 } 14708 } else { 14709 try { 14710 verifySignaturesLP(ps, pkg); 14711 } catch (PackageManagerException e) { 14712 res.setError(e.error, e.getMessage()); 14713 return; 14714 } 14715 } 14716 14717 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14718 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14719 systemApp = (ps.pkg.applicationInfo.flags & 14720 ApplicationInfo.FLAG_SYSTEM) != 0; 14721 } 14722 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14723 } 14724 14725 // Check whether the newly-scanned package wants to define an already-defined perm 14726 int N = pkg.permissions.size(); 14727 for (int i = N-1; i >= 0; i--) { 14728 PackageParser.Permission perm = pkg.permissions.get(i); 14729 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14730 if (bp != null) { 14731 // If the defining package is signed with our cert, it's okay. This 14732 // also includes the "updating the same package" case, of course. 14733 // "updating same package" could also involve key-rotation. 14734 final boolean sigsOk; 14735 if (bp.sourcePackage.equals(pkg.packageName) 14736 && (bp.packageSetting instanceof PackageSetting) 14737 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14738 scanFlags))) { 14739 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14740 } else { 14741 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14742 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14743 } 14744 if (!sigsOk) { 14745 // If the owning package is the system itself, we log but allow 14746 // install to proceed; we fail the install on all other permission 14747 // redefinitions. 14748 if (!bp.sourcePackage.equals("android")) { 14749 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14750 + pkg.packageName + " attempting to redeclare permission " 14751 + perm.info.name + " already owned by " + bp.sourcePackage); 14752 res.origPermission = perm.info.name; 14753 res.origPackage = bp.sourcePackage; 14754 return; 14755 } else { 14756 Slog.w(TAG, "Package " + pkg.packageName 14757 + " attempting to redeclare system permission " 14758 + perm.info.name + "; ignoring new declaration"); 14759 pkg.permissions.remove(i); 14760 } 14761 } 14762 } 14763 } 14764 } 14765 14766 if (systemApp) { 14767 if (onExternal) { 14768 // Abort update; system app can't be replaced with app on sdcard 14769 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14770 "Cannot install updates to system apps on sdcard"); 14771 return; 14772 } else if (ephemeral) { 14773 // Abort update; system app can't be replaced with an ephemeral app 14774 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14775 "Cannot update a system app with an ephemeral app"); 14776 return; 14777 } 14778 } 14779 14780 if (args.move != null) { 14781 // We did an in-place move, so dex is ready to roll 14782 scanFlags |= SCAN_NO_DEX; 14783 scanFlags |= SCAN_MOVE; 14784 14785 synchronized (mPackages) { 14786 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14787 if (ps == null) { 14788 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14789 "Missing settings for moved package " + pkgName); 14790 } 14791 14792 // We moved the entire application as-is, so bring over the 14793 // previously derived ABI information. 14794 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14795 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14796 } 14797 14798 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14799 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14800 scanFlags |= SCAN_NO_DEX; 14801 14802 try { 14803 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14804 args.abiOverride : pkg.cpuAbiOverride); 14805 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14806 true /* extract libs */); 14807 } catch (PackageManagerException pme) { 14808 Slog.e(TAG, "Error deriving application ABI", pme); 14809 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14810 return; 14811 } 14812 14813 // Shared libraries for the package need to be updated. 14814 synchronized (mPackages) { 14815 try { 14816 updateSharedLibrariesLPw(pkg, null); 14817 } catch (PackageManagerException e) { 14818 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14819 } 14820 } 14821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14822 // Do not run PackageDexOptimizer through the local performDexOpt 14823 // method because `pkg` is not in `mPackages` yet. 14824 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14825 null /* instructionSets */, false /* checkProfiles */, 14826 getCompilerFilterForReason(REASON_INSTALL)); 14827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14828 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14829 String msg = "Extracting package failed for " + pkgName; 14830 res.setError(INSTALL_FAILED_DEXOPT, msg); 14831 return; 14832 } 14833 14834 // Notify BackgroundDexOptService that the package has been changed. 14835 // If this is an update of a package which used to fail to compile, 14836 // BDOS will remove it from its blacklist. 14837 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14838 } 14839 14840 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14841 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14842 return; 14843 } 14844 14845 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14846 14847 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14848 "installPackageLI")) { 14849 if (replace) { 14850 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14851 installerPackageName, res); 14852 } else { 14853 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14854 args.user, installerPackageName, volumeUuid, res); 14855 } 14856 } 14857 synchronized (mPackages) { 14858 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14859 if (ps != null) { 14860 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14861 } 14862 14863 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14864 for (int i = 0; i < childCount; i++) { 14865 PackageParser.Package childPkg = pkg.childPackages.get(i); 14866 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14867 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14868 if (childPs != null) { 14869 childRes.newUsers = childPs.queryInstalledUsers( 14870 sUserManager.getUserIds(), true); 14871 } 14872 } 14873 } 14874 } 14875 14876 private void startIntentFilterVerifications(int userId, boolean replacing, 14877 PackageParser.Package pkg) { 14878 if (mIntentFilterVerifierComponent == null) { 14879 Slog.w(TAG, "No IntentFilter verification will not be done as " 14880 + "there is no IntentFilterVerifier available!"); 14881 return; 14882 } 14883 14884 final int verifierUid = getPackageUid( 14885 mIntentFilterVerifierComponent.getPackageName(), 14886 MATCH_DEBUG_TRIAGED_MISSING, 14887 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14888 14889 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14890 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14891 mHandler.sendMessage(msg); 14892 14893 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14894 for (int i = 0; i < childCount; i++) { 14895 PackageParser.Package childPkg = pkg.childPackages.get(i); 14896 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14897 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14898 mHandler.sendMessage(msg); 14899 } 14900 } 14901 14902 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14903 PackageParser.Package pkg) { 14904 int size = pkg.activities.size(); 14905 if (size == 0) { 14906 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14907 "No activity, so no need to verify any IntentFilter!"); 14908 return; 14909 } 14910 14911 final boolean hasDomainURLs = hasDomainURLs(pkg); 14912 if (!hasDomainURLs) { 14913 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14914 "No domain URLs, so no need to verify any IntentFilter!"); 14915 return; 14916 } 14917 14918 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14919 + " if any IntentFilter from the " + size 14920 + " Activities needs verification ..."); 14921 14922 int count = 0; 14923 final String packageName = pkg.packageName; 14924 14925 synchronized (mPackages) { 14926 // If this is a new install and we see that we've already run verification for this 14927 // package, we have nothing to do: it means the state was restored from backup. 14928 if (!replacing) { 14929 IntentFilterVerificationInfo ivi = 14930 mSettings.getIntentFilterVerificationLPr(packageName); 14931 if (ivi != null) { 14932 if (DEBUG_DOMAIN_VERIFICATION) { 14933 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14934 + ivi.getStatusString()); 14935 } 14936 return; 14937 } 14938 } 14939 14940 // If any filters need to be verified, then all need to be. 14941 boolean needToVerify = false; 14942 for (PackageParser.Activity a : pkg.activities) { 14943 for (ActivityIntentInfo filter : a.intents) { 14944 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14945 if (DEBUG_DOMAIN_VERIFICATION) { 14946 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14947 } 14948 needToVerify = true; 14949 break; 14950 } 14951 } 14952 } 14953 14954 if (needToVerify) { 14955 final int verificationId = mIntentFilterVerificationToken++; 14956 for (PackageParser.Activity a : pkg.activities) { 14957 for (ActivityIntentInfo filter : a.intents) { 14958 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14959 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14960 "Verification needed for IntentFilter:" + filter.toString()); 14961 mIntentFilterVerifier.addOneIntentFilterVerification( 14962 verifierUid, userId, verificationId, filter, packageName); 14963 count++; 14964 } 14965 } 14966 } 14967 } 14968 } 14969 14970 if (count > 0) { 14971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14972 + " IntentFilter verification" + (count > 1 ? "s" : "") 14973 + " for userId:" + userId); 14974 mIntentFilterVerifier.startVerifications(userId); 14975 } else { 14976 if (DEBUG_DOMAIN_VERIFICATION) { 14977 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14978 } 14979 } 14980 } 14981 14982 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14983 final ComponentName cn = filter.activity.getComponentName(); 14984 final String packageName = cn.getPackageName(); 14985 14986 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14987 packageName); 14988 if (ivi == null) { 14989 return true; 14990 } 14991 int status = ivi.getStatus(); 14992 switch (status) { 14993 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14994 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14995 return true; 14996 14997 default: 14998 // Nothing to do 14999 return false; 15000 } 15001 } 15002 15003 private static boolean isMultiArch(ApplicationInfo info) { 15004 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15005 } 15006 15007 private static boolean isExternal(PackageParser.Package pkg) { 15008 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15009 } 15010 15011 private static boolean isExternal(PackageSetting ps) { 15012 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15013 } 15014 15015 private static boolean isEphemeral(PackageParser.Package pkg) { 15016 return pkg.applicationInfo.isEphemeralApp(); 15017 } 15018 15019 private static boolean isEphemeral(PackageSetting ps) { 15020 return ps.pkg != null && isEphemeral(ps.pkg); 15021 } 15022 15023 private static boolean isSystemApp(PackageParser.Package pkg) { 15024 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15025 } 15026 15027 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15028 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15029 } 15030 15031 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15032 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15033 } 15034 15035 private static boolean isSystemApp(PackageSetting ps) { 15036 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15037 } 15038 15039 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15040 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15041 } 15042 15043 private int packageFlagsToInstallFlags(PackageSetting ps) { 15044 int installFlags = 0; 15045 if (isEphemeral(ps)) { 15046 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15047 } 15048 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15049 // This existing package was an external ASEC install when we have 15050 // the external flag without a UUID 15051 installFlags |= PackageManager.INSTALL_EXTERNAL; 15052 } 15053 if (ps.isForwardLocked()) { 15054 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15055 } 15056 return installFlags; 15057 } 15058 15059 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15060 if (isExternal(pkg)) { 15061 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15062 return StorageManager.UUID_PRIMARY_PHYSICAL; 15063 } else { 15064 return pkg.volumeUuid; 15065 } 15066 } else { 15067 return StorageManager.UUID_PRIVATE_INTERNAL; 15068 } 15069 } 15070 15071 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15072 if (isExternal(pkg)) { 15073 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15074 return mSettings.getExternalVersion(); 15075 } else { 15076 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15077 } 15078 } else { 15079 return mSettings.getInternalVersion(); 15080 } 15081 } 15082 15083 private void deleteTempPackageFiles() { 15084 final FilenameFilter filter = new FilenameFilter() { 15085 public boolean accept(File dir, String name) { 15086 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15087 } 15088 }; 15089 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15090 file.delete(); 15091 } 15092 } 15093 15094 @Override 15095 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15096 int flags) { 15097 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15098 flags); 15099 } 15100 15101 @Override 15102 public void deletePackage(final String packageName, 15103 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15104 mContext.enforceCallingOrSelfPermission( 15105 android.Manifest.permission.DELETE_PACKAGES, null); 15106 Preconditions.checkNotNull(packageName); 15107 Preconditions.checkNotNull(observer); 15108 final int uid = Binder.getCallingUid(); 15109 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15110 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15111 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15112 mContext.enforceCallingOrSelfPermission( 15113 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15114 "deletePackage for user " + userId); 15115 } 15116 15117 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15118 try { 15119 observer.onPackageDeleted(packageName, 15120 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15121 } catch (RemoteException re) { 15122 } 15123 return; 15124 } 15125 15126 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15127 try { 15128 observer.onPackageDeleted(packageName, 15129 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15130 } catch (RemoteException re) { 15131 } 15132 return; 15133 } 15134 15135 if (DEBUG_REMOVE) { 15136 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15137 + " deleteAllUsers: " + deleteAllUsers ); 15138 } 15139 // Queue up an async operation since the package deletion may take a little while. 15140 mHandler.post(new Runnable() { 15141 public void run() { 15142 mHandler.removeCallbacks(this); 15143 int returnCode; 15144 if (!deleteAllUsers) { 15145 returnCode = deletePackageX(packageName, userId, deleteFlags); 15146 } else { 15147 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15148 // If nobody is blocking uninstall, proceed with delete for all users 15149 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15150 returnCode = deletePackageX(packageName, userId, deleteFlags); 15151 } else { 15152 // Otherwise uninstall individually for users with blockUninstalls=false 15153 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15154 for (int userId : users) { 15155 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15156 returnCode = deletePackageX(packageName, userId, userFlags); 15157 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15158 Slog.w(TAG, "Package delete failed for user " + userId 15159 + ", returnCode " + returnCode); 15160 } 15161 } 15162 } 15163 // The app has only been marked uninstalled for certain users. 15164 // We still need to report that delete was blocked 15165 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15166 } 15167 } 15168 try { 15169 observer.onPackageDeleted(packageName, returnCode, null); 15170 } catch (RemoteException e) { 15171 Log.i(TAG, "Observer no longer exists."); 15172 } //end catch 15173 } //end run 15174 }); 15175 } 15176 15177 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15178 int[] result = EMPTY_INT_ARRAY; 15179 for (int userId : userIds) { 15180 if (getBlockUninstallForUser(packageName, userId)) { 15181 result = ArrayUtils.appendInt(result, userId); 15182 } 15183 } 15184 return result; 15185 } 15186 15187 @Override 15188 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15189 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15190 } 15191 15192 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15193 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15194 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15195 try { 15196 if (dpm != null) { 15197 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15198 /* callingUserOnly =*/ false); 15199 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15200 : deviceOwnerComponentName.getPackageName(); 15201 // Does the package contains the device owner? 15202 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15203 // this check is probably not needed, since DO should be registered as a device 15204 // admin on some user too. (Original bug for this: b/17657954) 15205 if (packageName.equals(deviceOwnerPackageName)) { 15206 return true; 15207 } 15208 // Does it contain a device admin for any user? 15209 int[] users; 15210 if (userId == UserHandle.USER_ALL) { 15211 users = sUserManager.getUserIds(); 15212 } else { 15213 users = new int[]{userId}; 15214 } 15215 for (int i = 0; i < users.length; ++i) { 15216 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15217 return true; 15218 } 15219 } 15220 } 15221 } catch (RemoteException e) { 15222 } 15223 return false; 15224 } 15225 15226 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15227 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15228 } 15229 15230 /** 15231 * This method is an internal method that could be get invoked either 15232 * to delete an installed package or to clean up a failed installation. 15233 * After deleting an installed package, a broadcast is sent to notify any 15234 * listeners that the package has been removed. For cleaning up a failed 15235 * installation, the broadcast is not necessary since the package's 15236 * installation wouldn't have sent the initial broadcast either 15237 * The key steps in deleting a package are 15238 * deleting the package information in internal structures like mPackages, 15239 * deleting the packages base directories through installd 15240 * updating mSettings to reflect current status 15241 * persisting settings for later use 15242 * sending a broadcast if necessary 15243 */ 15244 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15245 final PackageRemovedInfo info = new PackageRemovedInfo(); 15246 final boolean res; 15247 15248 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15249 ? UserHandle.ALL : new UserHandle(userId); 15250 15251 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15252 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15253 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15254 } 15255 15256 PackageSetting uninstalledPs = null; 15257 15258 // for the uninstall-updates case and restricted profiles, remember the per- 15259 // user handle installed state 15260 int[] allUsers; 15261 synchronized (mPackages) { 15262 uninstalledPs = mSettings.mPackages.get(packageName); 15263 if (uninstalledPs == null) { 15264 Slog.w(TAG, "Not removing non-existent package " + packageName); 15265 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15266 } 15267 allUsers = sUserManager.getUserIds(); 15268 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15269 } 15270 15271 synchronized (mInstallLock) { 15272 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15273 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15274 "deletePackageX")) { 15275 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15276 deleteFlags | REMOVE_CHATTY, info, true, null); 15277 } 15278 synchronized (mPackages) { 15279 if (res) { 15280 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15281 } 15282 } 15283 } 15284 15285 if (res) { 15286 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15287 info.sendPackageRemovedBroadcasts(killApp); 15288 info.sendSystemPackageUpdatedBroadcasts(); 15289 info.sendSystemPackageAppearedBroadcasts(); 15290 } 15291 // Force a gc here. 15292 Runtime.getRuntime().gc(); 15293 // Delete the resources here after sending the broadcast to let 15294 // other processes clean up before deleting resources. 15295 if (info.args != null) { 15296 synchronized (mInstallLock) { 15297 info.args.doPostDeleteLI(true); 15298 } 15299 } 15300 15301 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15302 } 15303 15304 class PackageRemovedInfo { 15305 String removedPackage; 15306 int uid = -1; 15307 int removedAppId = -1; 15308 int[] origUsers; 15309 int[] removedUsers = null; 15310 boolean isRemovedPackageSystemUpdate = false; 15311 boolean isUpdate; 15312 boolean dataRemoved; 15313 boolean removedForAllUsers; 15314 // Clean up resources deleted packages. 15315 InstallArgs args = null; 15316 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15317 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15318 15319 void sendPackageRemovedBroadcasts(boolean killApp) { 15320 sendPackageRemovedBroadcastInternal(killApp); 15321 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15322 for (int i = 0; i < childCount; i++) { 15323 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15324 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15325 } 15326 } 15327 15328 void sendSystemPackageUpdatedBroadcasts() { 15329 if (isRemovedPackageSystemUpdate) { 15330 sendSystemPackageUpdatedBroadcastsInternal(); 15331 final int childCount = (removedChildPackages != null) 15332 ? removedChildPackages.size() : 0; 15333 for (int i = 0; i < childCount; i++) { 15334 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15335 if (childInfo.isRemovedPackageSystemUpdate) { 15336 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15337 } 15338 } 15339 } 15340 } 15341 15342 void sendSystemPackageAppearedBroadcasts() { 15343 final int packageCount = (appearedChildPackages != null) 15344 ? appearedChildPackages.size() : 0; 15345 for (int i = 0; i < packageCount; i++) { 15346 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15347 for (int userId : installedInfo.newUsers) { 15348 sendPackageAddedForUser(installedInfo.name, true, 15349 UserHandle.getAppId(installedInfo.uid), userId); 15350 } 15351 } 15352 } 15353 15354 private void sendSystemPackageUpdatedBroadcastsInternal() { 15355 Bundle extras = new Bundle(2); 15356 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15357 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15358 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15359 extras, 0, null, null, null); 15360 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15361 extras, 0, null, null, null); 15362 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15363 null, 0, removedPackage, null, null); 15364 } 15365 15366 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15367 Bundle extras = new Bundle(2); 15368 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15369 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15370 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15371 if (isUpdate || isRemovedPackageSystemUpdate) { 15372 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15373 } 15374 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15375 if (removedPackage != null) { 15376 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15377 extras, 0, null, null, removedUsers); 15378 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15379 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15380 removedPackage, extras, 0, null, null, removedUsers); 15381 } 15382 } 15383 if (removedAppId >= 0) { 15384 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15385 removedUsers); 15386 } 15387 } 15388 } 15389 15390 /* 15391 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15392 * flag is not set, the data directory is removed as well. 15393 * make sure this flag is set for partially installed apps. If not its meaningless to 15394 * delete a partially installed application. 15395 */ 15396 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15397 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15398 String packageName = ps.name; 15399 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15400 // Retrieve object to delete permissions for shared user later on 15401 final PackageParser.Package deletedPkg; 15402 final PackageSetting deletedPs; 15403 // reader 15404 synchronized (mPackages) { 15405 deletedPkg = mPackages.get(packageName); 15406 deletedPs = mSettings.mPackages.get(packageName); 15407 if (outInfo != null) { 15408 outInfo.removedPackage = packageName; 15409 outInfo.removedUsers = deletedPs != null 15410 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15411 : null; 15412 } 15413 } 15414 15415 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15416 15417 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15418 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15419 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15420 destroyAppProfilesLIF(deletedPkg); 15421 if (outInfo != null) { 15422 outInfo.dataRemoved = true; 15423 } 15424 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15425 } 15426 15427 // writer 15428 synchronized (mPackages) { 15429 if (deletedPs != null) { 15430 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15431 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15432 clearDefaultBrowserIfNeeded(packageName); 15433 if (outInfo != null) { 15434 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15435 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15436 } 15437 updatePermissionsLPw(deletedPs.name, null, 0); 15438 if (deletedPs.sharedUser != null) { 15439 // Remove permissions associated with package. Since runtime 15440 // permissions are per user we have to kill the removed package 15441 // or packages running under the shared user of the removed 15442 // package if revoking the permissions requested only by the removed 15443 // package is successful and this causes a change in gids. 15444 for (int userId : UserManagerService.getInstance().getUserIds()) { 15445 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15446 userId); 15447 if (userIdToKill == UserHandle.USER_ALL 15448 || userIdToKill >= UserHandle.USER_SYSTEM) { 15449 // If gids changed for this user, kill all affected packages. 15450 mHandler.post(new Runnable() { 15451 @Override 15452 public void run() { 15453 // This has to happen with no lock held. 15454 killApplication(deletedPs.name, deletedPs.appId, 15455 KILL_APP_REASON_GIDS_CHANGED); 15456 } 15457 }); 15458 break; 15459 } 15460 } 15461 } 15462 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15463 } 15464 // make sure to preserve per-user disabled state if this removal was just 15465 // a downgrade of a system app to the factory package 15466 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15467 if (DEBUG_REMOVE) { 15468 Slog.d(TAG, "Propagating install state across downgrade"); 15469 } 15470 for (int userId : allUserHandles) { 15471 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15472 if (DEBUG_REMOVE) { 15473 Slog.d(TAG, " user " + userId + " => " + installed); 15474 } 15475 ps.setInstalled(installed, userId); 15476 } 15477 } 15478 } 15479 // can downgrade to reader 15480 if (writeSettings) { 15481 // Save settings now 15482 mSettings.writeLPr(); 15483 } 15484 } 15485 if (outInfo != null) { 15486 // A user ID was deleted here. Go through all users and remove it 15487 // from KeyStore. 15488 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15489 } 15490 } 15491 15492 static boolean locationIsPrivileged(File path) { 15493 try { 15494 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15495 .getCanonicalPath(); 15496 return path.getCanonicalPath().startsWith(privilegedAppDir); 15497 } catch (IOException e) { 15498 Slog.e(TAG, "Unable to access code path " + path); 15499 } 15500 return false; 15501 } 15502 15503 /* 15504 * Tries to delete system package. 15505 */ 15506 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15507 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15508 boolean writeSettings) { 15509 if (deletedPs.parentPackageName != null) { 15510 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15511 return false; 15512 } 15513 15514 final boolean applyUserRestrictions 15515 = (allUserHandles != null) && (outInfo.origUsers != null); 15516 final PackageSetting disabledPs; 15517 // Confirm if the system package has been updated 15518 // An updated system app can be deleted. This will also have to restore 15519 // the system pkg from system partition 15520 // reader 15521 synchronized (mPackages) { 15522 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15523 } 15524 15525 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15526 + " disabledPs=" + disabledPs); 15527 15528 if (disabledPs == null) { 15529 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15530 return false; 15531 } else if (DEBUG_REMOVE) { 15532 Slog.d(TAG, "Deleting system pkg from data partition"); 15533 } 15534 15535 if (DEBUG_REMOVE) { 15536 if (applyUserRestrictions) { 15537 Slog.d(TAG, "Remembering install states:"); 15538 for (int userId : allUserHandles) { 15539 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15540 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15541 } 15542 } 15543 } 15544 15545 // Delete the updated package 15546 outInfo.isRemovedPackageSystemUpdate = true; 15547 if (outInfo.removedChildPackages != null) { 15548 final int childCount = (deletedPs.childPackageNames != null) 15549 ? deletedPs.childPackageNames.size() : 0; 15550 for (int i = 0; i < childCount; i++) { 15551 String childPackageName = deletedPs.childPackageNames.get(i); 15552 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15553 .contains(childPackageName)) { 15554 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15555 childPackageName); 15556 if (childInfo != null) { 15557 childInfo.isRemovedPackageSystemUpdate = true; 15558 } 15559 } 15560 } 15561 } 15562 15563 if (disabledPs.versionCode < deletedPs.versionCode) { 15564 // Delete data for downgrades 15565 flags &= ~PackageManager.DELETE_KEEP_DATA; 15566 } else { 15567 // Preserve data by setting flag 15568 flags |= PackageManager.DELETE_KEEP_DATA; 15569 } 15570 15571 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15572 outInfo, writeSettings, disabledPs.pkg); 15573 if (!ret) { 15574 return false; 15575 } 15576 15577 // writer 15578 synchronized (mPackages) { 15579 // Reinstate the old system package 15580 enableSystemPackageLPw(disabledPs.pkg); 15581 // Remove any native libraries from the upgraded package. 15582 removeNativeBinariesLI(deletedPs); 15583 } 15584 15585 // Install the system package 15586 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15587 int parseFlags = mDefParseFlags 15588 | PackageParser.PARSE_MUST_BE_APK 15589 | PackageParser.PARSE_IS_SYSTEM 15590 | PackageParser.PARSE_IS_SYSTEM_DIR; 15591 if (locationIsPrivileged(disabledPs.codePath)) { 15592 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15593 } 15594 15595 final PackageParser.Package newPkg; 15596 try { 15597 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15598 } catch (PackageManagerException e) { 15599 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15600 + e.getMessage()); 15601 return false; 15602 } 15603 15604 prepareAppDataAfterInstallLIF(newPkg); 15605 15606 // writer 15607 synchronized (mPackages) { 15608 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15609 15610 // Propagate the permissions state as we do not want to drop on the floor 15611 // runtime permissions. The update permissions method below will take 15612 // care of removing obsolete permissions and grant install permissions. 15613 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15614 updatePermissionsLPw(newPkg.packageName, newPkg, 15615 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15616 15617 if (applyUserRestrictions) { 15618 if (DEBUG_REMOVE) { 15619 Slog.d(TAG, "Propagating install state across reinstall"); 15620 } 15621 for (int userId : allUserHandles) { 15622 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15623 if (DEBUG_REMOVE) { 15624 Slog.d(TAG, " user " + userId + " => " + installed); 15625 } 15626 ps.setInstalled(installed, userId); 15627 15628 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15629 } 15630 // Regardless of writeSettings we need to ensure that this restriction 15631 // state propagation is persisted 15632 mSettings.writeAllUsersPackageRestrictionsLPr(); 15633 } 15634 // can downgrade to reader here 15635 if (writeSettings) { 15636 mSettings.writeLPr(); 15637 } 15638 } 15639 return true; 15640 } 15641 15642 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15643 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15644 PackageRemovedInfo outInfo, boolean writeSettings, 15645 PackageParser.Package replacingPackage) { 15646 synchronized (mPackages) { 15647 if (outInfo != null) { 15648 outInfo.uid = ps.appId; 15649 } 15650 15651 if (outInfo != null && outInfo.removedChildPackages != null) { 15652 final int childCount = (ps.childPackageNames != null) 15653 ? ps.childPackageNames.size() : 0; 15654 for (int i = 0; i < childCount; i++) { 15655 String childPackageName = ps.childPackageNames.get(i); 15656 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15657 if (childPs == null) { 15658 return false; 15659 } 15660 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15661 childPackageName); 15662 if (childInfo != null) { 15663 childInfo.uid = childPs.appId; 15664 } 15665 } 15666 } 15667 } 15668 15669 // Delete package data from internal structures and also remove data if flag is set 15670 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15671 15672 // Delete the child packages data 15673 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15674 for (int i = 0; i < childCount; i++) { 15675 PackageSetting childPs; 15676 synchronized (mPackages) { 15677 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15678 } 15679 if (childPs != null) { 15680 PackageRemovedInfo childOutInfo = (outInfo != null 15681 && outInfo.removedChildPackages != null) 15682 ? outInfo.removedChildPackages.get(childPs.name) : null; 15683 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15684 && (replacingPackage != null 15685 && !replacingPackage.hasChildPackage(childPs.name)) 15686 ? flags & ~DELETE_KEEP_DATA : flags; 15687 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15688 deleteFlags, writeSettings); 15689 } 15690 } 15691 15692 // Delete application code and resources only for parent packages 15693 if (ps.parentPackageName == null) { 15694 if (deleteCodeAndResources && (outInfo != null)) { 15695 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15696 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15697 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15698 } 15699 } 15700 15701 return true; 15702 } 15703 15704 @Override 15705 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15706 int userId) { 15707 mContext.enforceCallingOrSelfPermission( 15708 android.Manifest.permission.DELETE_PACKAGES, null); 15709 synchronized (mPackages) { 15710 PackageSetting ps = mSettings.mPackages.get(packageName); 15711 if (ps == null) { 15712 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15713 return false; 15714 } 15715 if (!ps.getInstalled(userId)) { 15716 // Can't block uninstall for an app that is not installed or enabled. 15717 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15718 return false; 15719 } 15720 ps.setBlockUninstall(blockUninstall, userId); 15721 mSettings.writePackageRestrictionsLPr(userId); 15722 } 15723 return true; 15724 } 15725 15726 @Override 15727 public boolean getBlockUninstallForUser(String packageName, int userId) { 15728 synchronized (mPackages) { 15729 PackageSetting ps = mSettings.mPackages.get(packageName); 15730 if (ps == null) { 15731 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15732 return false; 15733 } 15734 return ps.getBlockUninstall(userId); 15735 } 15736 } 15737 15738 @Override 15739 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15740 int callingUid = Binder.getCallingUid(); 15741 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15742 throw new SecurityException( 15743 "setRequiredForSystemUser can only be run by the system or root"); 15744 } 15745 synchronized (mPackages) { 15746 PackageSetting ps = mSettings.mPackages.get(packageName); 15747 if (ps == null) { 15748 Log.w(TAG, "Package doesn't exist: " + packageName); 15749 return false; 15750 } 15751 if (systemUserApp) { 15752 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15753 } else { 15754 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15755 } 15756 mSettings.writeLPr(); 15757 } 15758 return true; 15759 } 15760 15761 /* 15762 * This method handles package deletion in general 15763 */ 15764 private boolean deletePackageLIF(String packageName, UserHandle user, 15765 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15766 PackageRemovedInfo outInfo, boolean writeSettings, 15767 PackageParser.Package replacingPackage) { 15768 if (packageName == null) { 15769 Slog.w(TAG, "Attempt to delete null packageName."); 15770 return false; 15771 } 15772 15773 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15774 15775 PackageSetting ps; 15776 15777 synchronized (mPackages) { 15778 ps = mSettings.mPackages.get(packageName); 15779 if (ps == null) { 15780 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15781 return false; 15782 } 15783 15784 if (ps.parentPackageName != null && (!isSystemApp(ps) 15785 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15786 if (DEBUG_REMOVE) { 15787 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15788 + ((user == null) ? UserHandle.USER_ALL : user)); 15789 } 15790 final int removedUserId = (user != null) ? user.getIdentifier() 15791 : UserHandle.USER_ALL; 15792 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15793 return false; 15794 } 15795 markPackageUninstalledForUserLPw(ps, user); 15796 scheduleWritePackageRestrictionsLocked(user); 15797 return true; 15798 } 15799 } 15800 15801 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15802 && user.getIdentifier() != UserHandle.USER_ALL)) { 15803 // The caller is asking that the package only be deleted for a single 15804 // user. To do this, we just mark its uninstalled state and delete 15805 // its data. If this is a system app, we only allow this to happen if 15806 // they have set the special DELETE_SYSTEM_APP which requests different 15807 // semantics than normal for uninstalling system apps. 15808 markPackageUninstalledForUserLPw(ps, user); 15809 15810 if (!isSystemApp(ps)) { 15811 // Do not uninstall the APK if an app should be cached 15812 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15813 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15814 // Other user still have this package installed, so all 15815 // we need to do is clear this user's data and save that 15816 // it is uninstalled. 15817 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15818 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15819 return false; 15820 } 15821 scheduleWritePackageRestrictionsLocked(user); 15822 return true; 15823 } else { 15824 // We need to set it back to 'installed' so the uninstall 15825 // broadcasts will be sent correctly. 15826 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15827 ps.setInstalled(true, user.getIdentifier()); 15828 } 15829 } else { 15830 // This is a system app, so we assume that the 15831 // other users still have this package installed, so all 15832 // we need to do is clear this user's data and save that 15833 // it is uninstalled. 15834 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15835 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15836 return false; 15837 } 15838 scheduleWritePackageRestrictionsLocked(user); 15839 return true; 15840 } 15841 } 15842 15843 // If we are deleting a composite package for all users, keep track 15844 // of result for each child. 15845 if (ps.childPackageNames != null && outInfo != null) { 15846 synchronized (mPackages) { 15847 final int childCount = ps.childPackageNames.size(); 15848 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15849 for (int i = 0; i < childCount; i++) { 15850 String childPackageName = ps.childPackageNames.get(i); 15851 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15852 childInfo.removedPackage = childPackageName; 15853 outInfo.removedChildPackages.put(childPackageName, childInfo); 15854 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15855 if (childPs != null) { 15856 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15857 } 15858 } 15859 } 15860 } 15861 15862 boolean ret = false; 15863 if (isSystemApp(ps)) { 15864 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15865 // When an updated system application is deleted we delete the existing resources 15866 // as well and fall back to existing code in system partition 15867 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15868 } else { 15869 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15870 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15871 outInfo, writeSettings, replacingPackage); 15872 } 15873 15874 // Take a note whether we deleted the package for all users 15875 if (outInfo != null) { 15876 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15877 if (outInfo.removedChildPackages != null) { 15878 synchronized (mPackages) { 15879 final int childCount = outInfo.removedChildPackages.size(); 15880 for (int i = 0; i < childCount; i++) { 15881 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15882 if (childInfo != null) { 15883 childInfo.removedForAllUsers = mPackages.get( 15884 childInfo.removedPackage) == null; 15885 } 15886 } 15887 } 15888 } 15889 // If we uninstalled an update to a system app there may be some 15890 // child packages that appeared as they are declared in the system 15891 // app but were not declared in the update. 15892 if (isSystemApp(ps)) { 15893 synchronized (mPackages) { 15894 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15895 final int childCount = (updatedPs.childPackageNames != null) 15896 ? updatedPs.childPackageNames.size() : 0; 15897 for (int i = 0; i < childCount; i++) { 15898 String childPackageName = updatedPs.childPackageNames.get(i); 15899 if (outInfo.removedChildPackages == null 15900 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15901 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15902 if (childPs == null) { 15903 continue; 15904 } 15905 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15906 installRes.name = childPackageName; 15907 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15908 installRes.pkg = mPackages.get(childPackageName); 15909 installRes.uid = childPs.pkg.applicationInfo.uid; 15910 if (outInfo.appearedChildPackages == null) { 15911 outInfo.appearedChildPackages = new ArrayMap<>(); 15912 } 15913 outInfo.appearedChildPackages.put(childPackageName, installRes); 15914 } 15915 } 15916 } 15917 } 15918 } 15919 15920 return ret; 15921 } 15922 15923 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15924 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15925 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15926 for (int nextUserId : userIds) { 15927 if (DEBUG_REMOVE) { 15928 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15929 } 15930 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15931 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15932 false /*hidden*/, false /*suspended*/, null, null, null, 15933 false /*blockUninstall*/, 15934 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15935 } 15936 } 15937 15938 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15939 PackageRemovedInfo outInfo) { 15940 final PackageParser.Package pkg; 15941 synchronized (mPackages) { 15942 pkg = mPackages.get(ps.name); 15943 } 15944 15945 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15946 : new int[] {userId}; 15947 for (int nextUserId : userIds) { 15948 if (DEBUG_REMOVE) { 15949 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15950 + nextUserId); 15951 } 15952 15953 destroyAppDataLIF(pkg, userId, 15954 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15955 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15956 schedulePackageCleaning(ps.name, nextUserId, false); 15957 synchronized (mPackages) { 15958 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15959 scheduleWritePackageRestrictionsLocked(nextUserId); 15960 } 15961 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15962 } 15963 } 15964 15965 if (outInfo != null) { 15966 outInfo.removedPackage = ps.name; 15967 outInfo.removedAppId = ps.appId; 15968 outInfo.removedUsers = userIds; 15969 } 15970 15971 return true; 15972 } 15973 15974 private final class ClearStorageConnection implements ServiceConnection { 15975 IMediaContainerService mContainerService; 15976 15977 @Override 15978 public void onServiceConnected(ComponentName name, IBinder service) { 15979 synchronized (this) { 15980 mContainerService = IMediaContainerService.Stub.asInterface(service); 15981 notifyAll(); 15982 } 15983 } 15984 15985 @Override 15986 public void onServiceDisconnected(ComponentName name) { 15987 } 15988 } 15989 15990 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15991 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15992 15993 final boolean mounted; 15994 if (Environment.isExternalStorageEmulated()) { 15995 mounted = true; 15996 } else { 15997 final String status = Environment.getExternalStorageState(); 15998 15999 mounted = status.equals(Environment.MEDIA_MOUNTED) 16000 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16001 } 16002 16003 if (!mounted) { 16004 return; 16005 } 16006 16007 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16008 int[] users; 16009 if (userId == UserHandle.USER_ALL) { 16010 users = sUserManager.getUserIds(); 16011 } else { 16012 users = new int[] { userId }; 16013 } 16014 final ClearStorageConnection conn = new ClearStorageConnection(); 16015 if (mContext.bindServiceAsUser( 16016 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16017 try { 16018 for (int curUser : users) { 16019 long timeout = SystemClock.uptimeMillis() + 5000; 16020 synchronized (conn) { 16021 long now = SystemClock.uptimeMillis(); 16022 while (conn.mContainerService == null && now < timeout) { 16023 try { 16024 conn.wait(timeout - now); 16025 } catch (InterruptedException e) { 16026 } 16027 } 16028 } 16029 if (conn.mContainerService == null) { 16030 return; 16031 } 16032 16033 final UserEnvironment userEnv = new UserEnvironment(curUser); 16034 clearDirectory(conn.mContainerService, 16035 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16036 if (allData) { 16037 clearDirectory(conn.mContainerService, 16038 userEnv.buildExternalStorageAppDataDirs(packageName)); 16039 clearDirectory(conn.mContainerService, 16040 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16041 } 16042 } 16043 } finally { 16044 mContext.unbindService(conn); 16045 } 16046 } 16047 } 16048 16049 @Override 16050 public void clearApplicationProfileData(String packageName) { 16051 enforceSystemOrRoot("Only the system can clear all profile data"); 16052 16053 final PackageParser.Package pkg; 16054 synchronized (mPackages) { 16055 pkg = mPackages.get(packageName); 16056 } 16057 16058 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16059 synchronized (mInstallLock) { 16060 clearAppProfilesLIF(pkg); 16061 } 16062 } 16063 } 16064 16065 @Override 16066 public void clearApplicationUserData(final String packageName, 16067 final IPackageDataObserver observer, final int userId) { 16068 mContext.enforceCallingOrSelfPermission( 16069 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16070 16071 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16072 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16073 16074 final DevicePolicyManagerInternal dpmi = LocalServices 16075 .getService(DevicePolicyManagerInternal.class); 16076 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16077 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16078 } 16079 // Queue up an async operation since the package deletion may take a little while. 16080 mHandler.post(new Runnable() { 16081 public void run() { 16082 mHandler.removeCallbacks(this); 16083 final boolean succeeded; 16084 try (PackageFreezer freezer = freezePackage(packageName, 16085 "clearApplicationUserData")) { 16086 synchronized (mInstallLock) { 16087 succeeded = clearApplicationUserDataLIF(packageName, userId); 16088 } 16089 clearExternalStorageDataSync(packageName, userId, true); 16090 } 16091 if (succeeded) { 16092 // invoke DeviceStorageMonitor's update method to clear any notifications 16093 DeviceStorageMonitorInternal dsm = LocalServices 16094 .getService(DeviceStorageMonitorInternal.class); 16095 if (dsm != null) { 16096 dsm.checkMemory(); 16097 } 16098 } 16099 if(observer != null) { 16100 try { 16101 observer.onRemoveCompleted(packageName, succeeded); 16102 } catch (RemoteException e) { 16103 Log.i(TAG, "Observer no longer exists."); 16104 } 16105 } //end if observer 16106 } //end run 16107 }); 16108 } 16109 16110 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16111 if (packageName == null) { 16112 Slog.w(TAG, "Attempt to delete null packageName."); 16113 return false; 16114 } 16115 16116 // Try finding details about the requested package 16117 PackageParser.Package pkg; 16118 synchronized (mPackages) { 16119 pkg = mPackages.get(packageName); 16120 if (pkg == null) { 16121 final PackageSetting ps = mSettings.mPackages.get(packageName); 16122 if (ps != null) { 16123 pkg = ps.pkg; 16124 } 16125 } 16126 16127 if (pkg == null) { 16128 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16129 return false; 16130 } 16131 16132 PackageSetting ps = (PackageSetting) pkg.mExtras; 16133 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16134 } 16135 16136 clearAppDataLIF(pkg, userId, 16137 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16138 16139 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16140 removeKeystoreDataIfNeeded(userId, appId); 16141 16142 final UserManager um = mContext.getSystemService(UserManager.class); 16143 final int flags; 16144 if (um.isUserUnlockingOrUnlocked(userId)) { 16145 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16146 } else if (um.isUserRunning(userId)) { 16147 flags = StorageManager.FLAG_STORAGE_DE; 16148 } else { 16149 flags = 0; 16150 } 16151 prepareAppDataContentsLIF(pkg, userId, flags); 16152 16153 return true; 16154 } 16155 16156 /** 16157 * Reverts user permission state changes (permissions and flags) in 16158 * all packages for a given user. 16159 * 16160 * @param userId The device user for which to do a reset. 16161 */ 16162 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16163 final int packageCount = mPackages.size(); 16164 for (int i = 0; i < packageCount; i++) { 16165 PackageParser.Package pkg = mPackages.valueAt(i); 16166 PackageSetting ps = (PackageSetting) pkg.mExtras; 16167 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16168 } 16169 } 16170 16171 private void resetNetworkPolicies(int userId) { 16172 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16173 } 16174 16175 /** 16176 * Reverts user permission state changes (permissions and flags). 16177 * 16178 * @param ps The package for which to reset. 16179 * @param userId The device user for which to do a reset. 16180 */ 16181 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16182 final PackageSetting ps, final int userId) { 16183 if (ps.pkg == null) { 16184 return; 16185 } 16186 16187 // These are flags that can change base on user actions. 16188 final int userSettableMask = FLAG_PERMISSION_USER_SET 16189 | FLAG_PERMISSION_USER_FIXED 16190 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16191 | FLAG_PERMISSION_REVIEW_REQUIRED; 16192 16193 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16194 | FLAG_PERMISSION_POLICY_FIXED; 16195 16196 boolean writeInstallPermissions = false; 16197 boolean writeRuntimePermissions = false; 16198 16199 final int permissionCount = ps.pkg.requestedPermissions.size(); 16200 for (int i = 0; i < permissionCount; i++) { 16201 String permission = ps.pkg.requestedPermissions.get(i); 16202 16203 BasePermission bp = mSettings.mPermissions.get(permission); 16204 if (bp == null) { 16205 continue; 16206 } 16207 16208 // If shared user we just reset the state to which only this app contributed. 16209 if (ps.sharedUser != null) { 16210 boolean used = false; 16211 final int packageCount = ps.sharedUser.packages.size(); 16212 for (int j = 0; j < packageCount; j++) { 16213 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16214 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16215 && pkg.pkg.requestedPermissions.contains(permission)) { 16216 used = true; 16217 break; 16218 } 16219 } 16220 if (used) { 16221 continue; 16222 } 16223 } 16224 16225 PermissionsState permissionsState = ps.getPermissionsState(); 16226 16227 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16228 16229 // Always clear the user settable flags. 16230 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16231 bp.name) != null; 16232 // If permission review is enabled and this is a legacy app, mark the 16233 // permission as requiring a review as this is the initial state. 16234 int flags = 0; 16235 if (Build.PERMISSIONS_REVIEW_REQUIRED 16236 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16237 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16238 } 16239 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16240 if (hasInstallState) { 16241 writeInstallPermissions = true; 16242 } else { 16243 writeRuntimePermissions = true; 16244 } 16245 } 16246 16247 // Below is only runtime permission handling. 16248 if (!bp.isRuntime()) { 16249 continue; 16250 } 16251 16252 // Never clobber system or policy. 16253 if ((oldFlags & policyOrSystemFlags) != 0) { 16254 continue; 16255 } 16256 16257 // If this permission was granted by default, make sure it is. 16258 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16259 if (permissionsState.grantRuntimePermission(bp, userId) 16260 != PERMISSION_OPERATION_FAILURE) { 16261 writeRuntimePermissions = true; 16262 } 16263 // If permission review is enabled the permissions for a legacy apps 16264 // are represented as constantly granted runtime ones, so don't revoke. 16265 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16266 // Otherwise, reset the permission. 16267 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16268 switch (revokeResult) { 16269 case PERMISSION_OPERATION_SUCCESS: 16270 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16271 writeRuntimePermissions = true; 16272 final int appId = ps.appId; 16273 mHandler.post(new Runnable() { 16274 @Override 16275 public void run() { 16276 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16277 } 16278 }); 16279 } break; 16280 } 16281 } 16282 } 16283 16284 // Synchronously write as we are taking permissions away. 16285 if (writeRuntimePermissions) { 16286 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16287 } 16288 16289 // Synchronously write as we are taking permissions away. 16290 if (writeInstallPermissions) { 16291 mSettings.writeLPr(); 16292 } 16293 } 16294 16295 /** 16296 * Remove entries from the keystore daemon. Will only remove it if the 16297 * {@code appId} is valid. 16298 */ 16299 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16300 if (appId < 0) { 16301 return; 16302 } 16303 16304 final KeyStore keyStore = KeyStore.getInstance(); 16305 if (keyStore != null) { 16306 if (userId == UserHandle.USER_ALL) { 16307 for (final int individual : sUserManager.getUserIds()) { 16308 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16309 } 16310 } else { 16311 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16312 } 16313 } else { 16314 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16315 } 16316 } 16317 16318 @Override 16319 public void deleteApplicationCacheFiles(final String packageName, 16320 final IPackageDataObserver observer) { 16321 final int userId = UserHandle.getCallingUserId(); 16322 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16323 } 16324 16325 @Override 16326 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16327 final IPackageDataObserver observer) { 16328 mContext.enforceCallingOrSelfPermission( 16329 android.Manifest.permission.DELETE_CACHE_FILES, null); 16330 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16331 /* requireFullPermission= */ true, /* checkShell= */ false, 16332 "delete application cache files"); 16333 16334 final PackageParser.Package pkg; 16335 synchronized (mPackages) { 16336 pkg = mPackages.get(packageName); 16337 } 16338 16339 // Queue up an async operation since the package deletion may take a little while. 16340 mHandler.post(new Runnable() { 16341 public void run() { 16342 synchronized (mInstallLock) { 16343 final int flags = StorageManager.FLAG_STORAGE_DE 16344 | StorageManager.FLAG_STORAGE_CE; 16345 // We're only clearing cache files, so we don't care if the 16346 // app is unfrozen and still able to run 16347 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16348 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16349 } 16350 clearExternalStorageDataSync(packageName, userId, false); 16351 if (observer != null) { 16352 try { 16353 observer.onRemoveCompleted(packageName, true); 16354 } catch (RemoteException e) { 16355 Log.i(TAG, "Observer no longer exists."); 16356 } 16357 } 16358 } 16359 }); 16360 } 16361 16362 @Override 16363 public void getPackageSizeInfo(final String packageName, int userHandle, 16364 final IPackageStatsObserver observer) { 16365 mContext.enforceCallingOrSelfPermission( 16366 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16367 if (packageName == null) { 16368 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16369 } 16370 16371 PackageStats stats = new PackageStats(packageName, userHandle); 16372 16373 /* 16374 * Queue up an async operation since the package measurement may take a 16375 * little while. 16376 */ 16377 Message msg = mHandler.obtainMessage(INIT_COPY); 16378 msg.obj = new MeasureParams(stats, observer); 16379 mHandler.sendMessage(msg); 16380 } 16381 16382 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16383 final PackageSetting ps; 16384 synchronized (mPackages) { 16385 ps = mSettings.mPackages.get(packageName); 16386 if (ps == null) { 16387 Slog.w(TAG, "Failed to find settings for " + packageName); 16388 return false; 16389 } 16390 } 16391 try { 16392 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16393 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16394 ps.getCeDataInode(userId), ps.codePathString, stats); 16395 } catch (InstallerException e) { 16396 Slog.w(TAG, String.valueOf(e)); 16397 return false; 16398 } 16399 16400 // For now, ignore code size of packages on system partition 16401 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16402 stats.codeSize = 0; 16403 } 16404 16405 return true; 16406 } 16407 16408 private int getUidTargetSdkVersionLockedLPr(int uid) { 16409 Object obj = mSettings.getUserIdLPr(uid); 16410 if (obj instanceof SharedUserSetting) { 16411 final SharedUserSetting sus = (SharedUserSetting) obj; 16412 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16413 final Iterator<PackageSetting> it = sus.packages.iterator(); 16414 while (it.hasNext()) { 16415 final PackageSetting ps = it.next(); 16416 if (ps.pkg != null) { 16417 int v = ps.pkg.applicationInfo.targetSdkVersion; 16418 if (v < vers) vers = v; 16419 } 16420 } 16421 return vers; 16422 } else if (obj instanceof PackageSetting) { 16423 final PackageSetting ps = (PackageSetting) obj; 16424 if (ps.pkg != null) { 16425 return ps.pkg.applicationInfo.targetSdkVersion; 16426 } 16427 } 16428 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16429 } 16430 16431 @Override 16432 public void addPreferredActivity(IntentFilter filter, int match, 16433 ComponentName[] set, ComponentName activity, int userId) { 16434 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16435 "Adding preferred"); 16436 } 16437 16438 private void addPreferredActivityInternal(IntentFilter filter, int match, 16439 ComponentName[] set, ComponentName activity, boolean always, int userId, 16440 String opname) { 16441 // writer 16442 int callingUid = Binder.getCallingUid(); 16443 enforceCrossUserPermission(callingUid, userId, 16444 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16445 if (filter.countActions() == 0) { 16446 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16447 return; 16448 } 16449 synchronized (mPackages) { 16450 if (mContext.checkCallingOrSelfPermission( 16451 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16452 != PackageManager.PERMISSION_GRANTED) { 16453 if (getUidTargetSdkVersionLockedLPr(callingUid) 16454 < Build.VERSION_CODES.FROYO) { 16455 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16456 + callingUid); 16457 return; 16458 } 16459 mContext.enforceCallingOrSelfPermission( 16460 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16461 } 16462 16463 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16464 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16465 + userId + ":"); 16466 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16467 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16468 scheduleWritePackageRestrictionsLocked(userId); 16469 } 16470 } 16471 16472 @Override 16473 public void replacePreferredActivity(IntentFilter filter, int match, 16474 ComponentName[] set, ComponentName activity, int userId) { 16475 if (filter.countActions() != 1) { 16476 throw new IllegalArgumentException( 16477 "replacePreferredActivity expects filter to have only 1 action."); 16478 } 16479 if (filter.countDataAuthorities() != 0 16480 || filter.countDataPaths() != 0 16481 || filter.countDataSchemes() > 1 16482 || filter.countDataTypes() != 0) { 16483 throw new IllegalArgumentException( 16484 "replacePreferredActivity expects filter to have no data authorities, " + 16485 "paths, or types; and at most one scheme."); 16486 } 16487 16488 final int callingUid = Binder.getCallingUid(); 16489 enforceCrossUserPermission(callingUid, userId, 16490 true /* requireFullPermission */, false /* checkShell */, 16491 "replace preferred activity"); 16492 synchronized (mPackages) { 16493 if (mContext.checkCallingOrSelfPermission( 16494 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16495 != PackageManager.PERMISSION_GRANTED) { 16496 if (getUidTargetSdkVersionLockedLPr(callingUid) 16497 < Build.VERSION_CODES.FROYO) { 16498 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16499 + Binder.getCallingUid()); 16500 return; 16501 } 16502 mContext.enforceCallingOrSelfPermission( 16503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16504 } 16505 16506 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16507 if (pir != null) { 16508 // Get all of the existing entries that exactly match this filter. 16509 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16510 if (existing != null && existing.size() == 1) { 16511 PreferredActivity cur = existing.get(0); 16512 if (DEBUG_PREFERRED) { 16513 Slog.i(TAG, "Checking replace of preferred:"); 16514 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16515 if (!cur.mPref.mAlways) { 16516 Slog.i(TAG, " -- CUR; not mAlways!"); 16517 } else { 16518 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16519 Slog.i(TAG, " -- CUR: mSet=" 16520 + Arrays.toString(cur.mPref.mSetComponents)); 16521 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16522 Slog.i(TAG, " -- NEW: mMatch=" 16523 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16524 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16525 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16526 } 16527 } 16528 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16529 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16530 && cur.mPref.sameSet(set)) { 16531 // Setting the preferred activity to what it happens to be already 16532 if (DEBUG_PREFERRED) { 16533 Slog.i(TAG, "Replacing with same preferred activity " 16534 + cur.mPref.mShortComponent + " for user " 16535 + userId + ":"); 16536 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16537 } 16538 return; 16539 } 16540 } 16541 16542 if (existing != null) { 16543 if (DEBUG_PREFERRED) { 16544 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16546 } 16547 for (int i = 0; i < existing.size(); i++) { 16548 PreferredActivity pa = existing.get(i); 16549 if (DEBUG_PREFERRED) { 16550 Slog.i(TAG, "Removing existing preferred activity " 16551 + pa.mPref.mComponent + ":"); 16552 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16553 } 16554 pir.removeFilter(pa); 16555 } 16556 } 16557 } 16558 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16559 "Replacing preferred"); 16560 } 16561 } 16562 16563 @Override 16564 public void clearPackagePreferredActivities(String packageName) { 16565 final int uid = Binder.getCallingUid(); 16566 // writer 16567 synchronized (mPackages) { 16568 PackageParser.Package pkg = mPackages.get(packageName); 16569 if (pkg == null || pkg.applicationInfo.uid != uid) { 16570 if (mContext.checkCallingOrSelfPermission( 16571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16572 != PackageManager.PERMISSION_GRANTED) { 16573 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16574 < Build.VERSION_CODES.FROYO) { 16575 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16576 + Binder.getCallingUid()); 16577 return; 16578 } 16579 mContext.enforceCallingOrSelfPermission( 16580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16581 } 16582 } 16583 16584 int user = UserHandle.getCallingUserId(); 16585 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16586 scheduleWritePackageRestrictionsLocked(user); 16587 } 16588 } 16589 } 16590 16591 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16592 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16593 ArrayList<PreferredActivity> removed = null; 16594 boolean changed = false; 16595 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16596 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16597 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16598 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16599 continue; 16600 } 16601 Iterator<PreferredActivity> it = pir.filterIterator(); 16602 while (it.hasNext()) { 16603 PreferredActivity pa = it.next(); 16604 // Mark entry for removal only if it matches the package name 16605 // and the entry is of type "always". 16606 if (packageName == null || 16607 (pa.mPref.mComponent.getPackageName().equals(packageName) 16608 && pa.mPref.mAlways)) { 16609 if (removed == null) { 16610 removed = new ArrayList<PreferredActivity>(); 16611 } 16612 removed.add(pa); 16613 } 16614 } 16615 if (removed != null) { 16616 for (int j=0; j<removed.size(); j++) { 16617 PreferredActivity pa = removed.get(j); 16618 pir.removeFilter(pa); 16619 } 16620 changed = true; 16621 } 16622 } 16623 return changed; 16624 } 16625 16626 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16627 private void clearIntentFilterVerificationsLPw(int userId) { 16628 final int packageCount = mPackages.size(); 16629 for (int i = 0; i < packageCount; i++) { 16630 PackageParser.Package pkg = mPackages.valueAt(i); 16631 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16632 } 16633 } 16634 16635 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16636 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16637 if (userId == UserHandle.USER_ALL) { 16638 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16639 sUserManager.getUserIds())) { 16640 for (int oneUserId : sUserManager.getUserIds()) { 16641 scheduleWritePackageRestrictionsLocked(oneUserId); 16642 } 16643 } 16644 } else { 16645 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16646 scheduleWritePackageRestrictionsLocked(userId); 16647 } 16648 } 16649 } 16650 16651 void clearDefaultBrowserIfNeeded(String packageName) { 16652 for (int oneUserId : sUserManager.getUserIds()) { 16653 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16654 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16655 if (packageName.equals(defaultBrowserPackageName)) { 16656 setDefaultBrowserPackageName(null, oneUserId); 16657 } 16658 } 16659 } 16660 16661 @Override 16662 public void resetApplicationPreferences(int userId) { 16663 mContext.enforceCallingOrSelfPermission( 16664 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16665 final long identity = Binder.clearCallingIdentity(); 16666 // writer 16667 try { 16668 synchronized (mPackages) { 16669 clearPackagePreferredActivitiesLPw(null, userId); 16670 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16671 // TODO: We have to reset the default SMS and Phone. This requires 16672 // significant refactoring to keep all default apps in the package 16673 // manager (cleaner but more work) or have the services provide 16674 // callbacks to the package manager to request a default app reset. 16675 applyFactoryDefaultBrowserLPw(userId); 16676 clearIntentFilterVerificationsLPw(userId); 16677 primeDomainVerificationsLPw(userId); 16678 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16679 scheduleWritePackageRestrictionsLocked(userId); 16680 } 16681 resetNetworkPolicies(userId); 16682 } finally { 16683 Binder.restoreCallingIdentity(identity); 16684 } 16685 } 16686 16687 @Override 16688 public int getPreferredActivities(List<IntentFilter> outFilters, 16689 List<ComponentName> outActivities, String packageName) { 16690 16691 int num = 0; 16692 final int userId = UserHandle.getCallingUserId(); 16693 // reader 16694 synchronized (mPackages) { 16695 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16696 if (pir != null) { 16697 final Iterator<PreferredActivity> it = pir.filterIterator(); 16698 while (it.hasNext()) { 16699 final PreferredActivity pa = it.next(); 16700 if (packageName == null 16701 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16702 && pa.mPref.mAlways)) { 16703 if (outFilters != null) { 16704 outFilters.add(new IntentFilter(pa)); 16705 } 16706 if (outActivities != null) { 16707 outActivities.add(pa.mPref.mComponent); 16708 } 16709 } 16710 } 16711 } 16712 } 16713 16714 return num; 16715 } 16716 16717 @Override 16718 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16719 int userId) { 16720 int callingUid = Binder.getCallingUid(); 16721 if (callingUid != Process.SYSTEM_UID) { 16722 throw new SecurityException( 16723 "addPersistentPreferredActivity can only be run by the system"); 16724 } 16725 if (filter.countActions() == 0) { 16726 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16727 return; 16728 } 16729 synchronized (mPackages) { 16730 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16731 ":"); 16732 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16733 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16734 new PersistentPreferredActivity(filter, activity)); 16735 scheduleWritePackageRestrictionsLocked(userId); 16736 } 16737 } 16738 16739 @Override 16740 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16741 int callingUid = Binder.getCallingUid(); 16742 if (callingUid != Process.SYSTEM_UID) { 16743 throw new SecurityException( 16744 "clearPackagePersistentPreferredActivities can only be run by the system"); 16745 } 16746 ArrayList<PersistentPreferredActivity> removed = null; 16747 boolean changed = false; 16748 synchronized (mPackages) { 16749 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16750 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16751 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16752 .valueAt(i); 16753 if (userId != thisUserId) { 16754 continue; 16755 } 16756 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16757 while (it.hasNext()) { 16758 PersistentPreferredActivity ppa = it.next(); 16759 // Mark entry for removal only if it matches the package name. 16760 if (ppa.mComponent.getPackageName().equals(packageName)) { 16761 if (removed == null) { 16762 removed = new ArrayList<PersistentPreferredActivity>(); 16763 } 16764 removed.add(ppa); 16765 } 16766 } 16767 if (removed != null) { 16768 for (int j=0; j<removed.size(); j++) { 16769 PersistentPreferredActivity ppa = removed.get(j); 16770 ppir.removeFilter(ppa); 16771 } 16772 changed = true; 16773 } 16774 } 16775 16776 if (changed) { 16777 scheduleWritePackageRestrictionsLocked(userId); 16778 } 16779 } 16780 } 16781 16782 /** 16783 * Common machinery for picking apart a restored XML blob and passing 16784 * it to a caller-supplied functor to be applied to the running system. 16785 */ 16786 private void restoreFromXml(XmlPullParser parser, int userId, 16787 String expectedStartTag, BlobXmlRestorer functor) 16788 throws IOException, XmlPullParserException { 16789 int type; 16790 while ((type = parser.next()) != XmlPullParser.START_TAG 16791 && type != XmlPullParser.END_DOCUMENT) { 16792 } 16793 if (type != XmlPullParser.START_TAG) { 16794 // oops didn't find a start tag?! 16795 if (DEBUG_BACKUP) { 16796 Slog.e(TAG, "Didn't find start tag during restore"); 16797 } 16798 return; 16799 } 16800Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16801 // this is supposed to be TAG_PREFERRED_BACKUP 16802 if (!expectedStartTag.equals(parser.getName())) { 16803 if (DEBUG_BACKUP) { 16804 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16805 } 16806 return; 16807 } 16808 16809 // skip interfering stuff, then we're aligned with the backing implementation 16810 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16811Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16812 functor.apply(parser, userId); 16813 } 16814 16815 private interface BlobXmlRestorer { 16816 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16817 } 16818 16819 /** 16820 * Non-Binder method, support for the backup/restore mechanism: write the 16821 * full set of preferred activities in its canonical XML format. Returns the 16822 * XML output as a byte array, or null if there is none. 16823 */ 16824 @Override 16825 public byte[] getPreferredActivityBackup(int userId) { 16826 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16827 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16828 } 16829 16830 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16831 try { 16832 final XmlSerializer serializer = new FastXmlSerializer(); 16833 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16834 serializer.startDocument(null, true); 16835 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16836 16837 synchronized (mPackages) { 16838 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16839 } 16840 16841 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16842 serializer.endDocument(); 16843 serializer.flush(); 16844 } catch (Exception e) { 16845 if (DEBUG_BACKUP) { 16846 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16847 } 16848 return null; 16849 } 16850 16851 return dataStream.toByteArray(); 16852 } 16853 16854 @Override 16855 public void restorePreferredActivities(byte[] backup, int userId) { 16856 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16857 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16858 } 16859 16860 try { 16861 final XmlPullParser parser = Xml.newPullParser(); 16862 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16863 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16864 new BlobXmlRestorer() { 16865 @Override 16866 public void apply(XmlPullParser parser, int userId) 16867 throws XmlPullParserException, IOException { 16868 synchronized (mPackages) { 16869 mSettings.readPreferredActivitiesLPw(parser, userId); 16870 } 16871 } 16872 } ); 16873 } catch (Exception e) { 16874 if (DEBUG_BACKUP) { 16875 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16876 } 16877 } 16878 } 16879 16880 /** 16881 * Non-Binder method, support for the backup/restore mechanism: write the 16882 * default browser (etc) settings in its canonical XML format. Returns the default 16883 * browser XML representation as a byte array, or null if there is none. 16884 */ 16885 @Override 16886 public byte[] getDefaultAppsBackup(int userId) { 16887 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16888 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16889 } 16890 16891 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16892 try { 16893 final XmlSerializer serializer = new FastXmlSerializer(); 16894 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16895 serializer.startDocument(null, true); 16896 serializer.startTag(null, TAG_DEFAULT_APPS); 16897 16898 synchronized (mPackages) { 16899 mSettings.writeDefaultAppsLPr(serializer, userId); 16900 } 16901 16902 serializer.endTag(null, TAG_DEFAULT_APPS); 16903 serializer.endDocument(); 16904 serializer.flush(); 16905 } catch (Exception e) { 16906 if (DEBUG_BACKUP) { 16907 Slog.e(TAG, "Unable to write default apps for backup", e); 16908 } 16909 return null; 16910 } 16911 16912 return dataStream.toByteArray(); 16913 } 16914 16915 @Override 16916 public void restoreDefaultApps(byte[] backup, int userId) { 16917 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16918 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16919 } 16920 16921 try { 16922 final XmlPullParser parser = Xml.newPullParser(); 16923 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16924 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16925 new BlobXmlRestorer() { 16926 @Override 16927 public void apply(XmlPullParser parser, int userId) 16928 throws XmlPullParserException, IOException { 16929 synchronized (mPackages) { 16930 mSettings.readDefaultAppsLPw(parser, userId); 16931 } 16932 } 16933 } ); 16934 } catch (Exception e) { 16935 if (DEBUG_BACKUP) { 16936 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16937 } 16938 } 16939 } 16940 16941 @Override 16942 public byte[] getIntentFilterVerificationBackup(int userId) { 16943 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16944 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16945 } 16946 16947 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16948 try { 16949 final XmlSerializer serializer = new FastXmlSerializer(); 16950 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16951 serializer.startDocument(null, true); 16952 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16953 16954 synchronized (mPackages) { 16955 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16956 } 16957 16958 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16959 serializer.endDocument(); 16960 serializer.flush(); 16961 } catch (Exception e) { 16962 if (DEBUG_BACKUP) { 16963 Slog.e(TAG, "Unable to write default apps for backup", e); 16964 } 16965 return null; 16966 } 16967 16968 return dataStream.toByteArray(); 16969 } 16970 16971 @Override 16972 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16973 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16974 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16975 } 16976 16977 try { 16978 final XmlPullParser parser = Xml.newPullParser(); 16979 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16980 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16981 new BlobXmlRestorer() { 16982 @Override 16983 public void apply(XmlPullParser parser, int userId) 16984 throws XmlPullParserException, IOException { 16985 synchronized (mPackages) { 16986 mSettings.readAllDomainVerificationsLPr(parser, userId); 16987 mSettings.writeLPr(); 16988 } 16989 } 16990 } ); 16991 } catch (Exception e) { 16992 if (DEBUG_BACKUP) { 16993 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16994 } 16995 } 16996 } 16997 16998 @Override 16999 public byte[] getPermissionGrantBackup(int userId) { 17000 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17001 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17002 } 17003 17004 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17005 try { 17006 final XmlSerializer serializer = new FastXmlSerializer(); 17007 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17008 serializer.startDocument(null, true); 17009 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17010 17011 synchronized (mPackages) { 17012 serializeRuntimePermissionGrantsLPr(serializer, userId); 17013 } 17014 17015 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17016 serializer.endDocument(); 17017 serializer.flush(); 17018 } catch (Exception e) { 17019 if (DEBUG_BACKUP) { 17020 Slog.e(TAG, "Unable to write default apps for backup", e); 17021 } 17022 return null; 17023 } 17024 17025 return dataStream.toByteArray(); 17026 } 17027 17028 @Override 17029 public void restorePermissionGrants(byte[] backup, int userId) { 17030 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17031 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17032 } 17033 17034 try { 17035 final XmlPullParser parser = Xml.newPullParser(); 17036 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17037 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17038 new BlobXmlRestorer() { 17039 @Override 17040 public void apply(XmlPullParser parser, int userId) 17041 throws XmlPullParserException, IOException { 17042 synchronized (mPackages) { 17043 processRestoredPermissionGrantsLPr(parser, userId); 17044 } 17045 } 17046 } ); 17047 } catch (Exception e) { 17048 if (DEBUG_BACKUP) { 17049 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17050 } 17051 } 17052 } 17053 17054 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17055 throws IOException { 17056 serializer.startTag(null, TAG_ALL_GRANTS); 17057 17058 final int N = mSettings.mPackages.size(); 17059 for (int i = 0; i < N; i++) { 17060 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17061 boolean pkgGrantsKnown = false; 17062 17063 PermissionsState packagePerms = ps.getPermissionsState(); 17064 17065 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17066 final int grantFlags = state.getFlags(); 17067 // only look at grants that are not system/policy fixed 17068 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17069 final boolean isGranted = state.isGranted(); 17070 // And only back up the user-twiddled state bits 17071 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17072 final String packageName = mSettings.mPackages.keyAt(i); 17073 if (!pkgGrantsKnown) { 17074 serializer.startTag(null, TAG_GRANT); 17075 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17076 pkgGrantsKnown = true; 17077 } 17078 17079 final boolean userSet = 17080 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17081 final boolean userFixed = 17082 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17083 final boolean revoke = 17084 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17085 17086 serializer.startTag(null, TAG_PERMISSION); 17087 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17088 if (isGranted) { 17089 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17090 } 17091 if (userSet) { 17092 serializer.attribute(null, ATTR_USER_SET, "true"); 17093 } 17094 if (userFixed) { 17095 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17096 } 17097 if (revoke) { 17098 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17099 } 17100 serializer.endTag(null, TAG_PERMISSION); 17101 } 17102 } 17103 } 17104 17105 if (pkgGrantsKnown) { 17106 serializer.endTag(null, TAG_GRANT); 17107 } 17108 } 17109 17110 serializer.endTag(null, TAG_ALL_GRANTS); 17111 } 17112 17113 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17114 throws XmlPullParserException, IOException { 17115 String pkgName = null; 17116 int outerDepth = parser.getDepth(); 17117 int type; 17118 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17119 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17120 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17121 continue; 17122 } 17123 17124 final String tagName = parser.getName(); 17125 if (tagName.equals(TAG_GRANT)) { 17126 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17127 if (DEBUG_BACKUP) { 17128 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17129 } 17130 } else if (tagName.equals(TAG_PERMISSION)) { 17131 17132 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17133 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17134 17135 int newFlagSet = 0; 17136 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17137 newFlagSet |= FLAG_PERMISSION_USER_SET; 17138 } 17139 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17140 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17141 } 17142 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17143 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17144 } 17145 if (DEBUG_BACKUP) { 17146 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17147 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17148 } 17149 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17150 if (ps != null) { 17151 // Already installed so we apply the grant immediately 17152 if (DEBUG_BACKUP) { 17153 Slog.v(TAG, " + already installed; applying"); 17154 } 17155 PermissionsState perms = ps.getPermissionsState(); 17156 BasePermission bp = mSettings.mPermissions.get(permName); 17157 if (bp != null) { 17158 if (isGranted) { 17159 perms.grantRuntimePermission(bp, userId); 17160 } 17161 if (newFlagSet != 0) { 17162 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17163 } 17164 } 17165 } else { 17166 // Need to wait for post-restore install to apply the grant 17167 if (DEBUG_BACKUP) { 17168 Slog.v(TAG, " - not yet installed; saving for later"); 17169 } 17170 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17171 isGranted, newFlagSet, userId); 17172 } 17173 } else { 17174 PackageManagerService.reportSettingsProblem(Log.WARN, 17175 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17176 XmlUtils.skipCurrentTag(parser); 17177 } 17178 } 17179 17180 scheduleWriteSettingsLocked(); 17181 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17182 } 17183 17184 @Override 17185 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17186 int sourceUserId, int targetUserId, int flags) { 17187 mContext.enforceCallingOrSelfPermission( 17188 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17189 int callingUid = Binder.getCallingUid(); 17190 enforceOwnerRights(ownerPackage, callingUid); 17191 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17192 if (intentFilter.countActions() == 0) { 17193 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17194 return; 17195 } 17196 synchronized (mPackages) { 17197 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17198 ownerPackage, targetUserId, flags); 17199 CrossProfileIntentResolver resolver = 17200 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17201 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17202 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17203 if (existing != null) { 17204 int size = existing.size(); 17205 for (int i = 0; i < size; i++) { 17206 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17207 return; 17208 } 17209 } 17210 } 17211 resolver.addFilter(newFilter); 17212 scheduleWritePackageRestrictionsLocked(sourceUserId); 17213 } 17214 } 17215 17216 @Override 17217 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17218 mContext.enforceCallingOrSelfPermission( 17219 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17220 int callingUid = Binder.getCallingUid(); 17221 enforceOwnerRights(ownerPackage, callingUid); 17222 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17223 synchronized (mPackages) { 17224 CrossProfileIntentResolver resolver = 17225 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17226 ArraySet<CrossProfileIntentFilter> set = 17227 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17228 for (CrossProfileIntentFilter filter : set) { 17229 if (filter.getOwnerPackage().equals(ownerPackage)) { 17230 resolver.removeFilter(filter); 17231 } 17232 } 17233 scheduleWritePackageRestrictionsLocked(sourceUserId); 17234 } 17235 } 17236 17237 // Enforcing that callingUid is owning pkg on userId 17238 private void enforceOwnerRights(String pkg, int callingUid) { 17239 // The system owns everything. 17240 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17241 return; 17242 } 17243 int callingUserId = UserHandle.getUserId(callingUid); 17244 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17245 if (pi == null) { 17246 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17247 + callingUserId); 17248 } 17249 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17250 throw new SecurityException("Calling uid " + callingUid 17251 + " does not own package " + pkg); 17252 } 17253 } 17254 17255 @Override 17256 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17257 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17258 } 17259 17260 private Intent getHomeIntent() { 17261 Intent intent = new Intent(Intent.ACTION_MAIN); 17262 intent.addCategory(Intent.CATEGORY_HOME); 17263 return intent; 17264 } 17265 17266 private IntentFilter getHomeFilter() { 17267 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17268 filter.addCategory(Intent.CATEGORY_HOME); 17269 filter.addCategory(Intent.CATEGORY_DEFAULT); 17270 return filter; 17271 } 17272 17273 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17274 int userId) { 17275 Intent intent = getHomeIntent(); 17276 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17277 PackageManager.GET_META_DATA, userId); 17278 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17279 true, false, false, userId); 17280 17281 allHomeCandidates.clear(); 17282 if (list != null) { 17283 for (ResolveInfo ri : list) { 17284 allHomeCandidates.add(ri); 17285 } 17286 } 17287 return (preferred == null || preferred.activityInfo == null) 17288 ? null 17289 : new ComponentName(preferred.activityInfo.packageName, 17290 preferred.activityInfo.name); 17291 } 17292 17293 @Override 17294 public void setHomeActivity(ComponentName comp, int userId) { 17295 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17296 getHomeActivitiesAsUser(homeActivities, userId); 17297 17298 boolean found = false; 17299 17300 final int size = homeActivities.size(); 17301 final ComponentName[] set = new ComponentName[size]; 17302 for (int i = 0; i < size; i++) { 17303 final ResolveInfo candidate = homeActivities.get(i); 17304 final ActivityInfo info = candidate.activityInfo; 17305 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17306 set[i] = activityName; 17307 if (!found && activityName.equals(comp)) { 17308 found = true; 17309 } 17310 } 17311 if (!found) { 17312 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17313 + userId); 17314 } 17315 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17316 set, comp, userId); 17317 } 17318 17319 private @Nullable String getSetupWizardPackageName() { 17320 final Intent intent = new Intent(Intent.ACTION_MAIN); 17321 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17322 17323 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17324 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17325 | MATCH_DISABLED_COMPONENTS, 17326 UserHandle.myUserId()); 17327 if (matches.size() == 1) { 17328 return matches.get(0).getComponentInfo().packageName; 17329 } else { 17330 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17331 + ": matches=" + matches); 17332 return null; 17333 } 17334 } 17335 17336 @Override 17337 public void setApplicationEnabledSetting(String appPackageName, 17338 int newState, int flags, int userId, String callingPackage) { 17339 if (!sUserManager.exists(userId)) return; 17340 if (callingPackage == null) { 17341 callingPackage = Integer.toString(Binder.getCallingUid()); 17342 } 17343 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17344 } 17345 17346 @Override 17347 public void setComponentEnabledSetting(ComponentName componentName, 17348 int newState, int flags, int userId) { 17349 if (!sUserManager.exists(userId)) return; 17350 setEnabledSetting(componentName.getPackageName(), 17351 componentName.getClassName(), newState, flags, userId, null); 17352 } 17353 17354 private void setEnabledSetting(final String packageName, String className, int newState, 17355 final int flags, int userId, String callingPackage) { 17356 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17357 || newState == COMPONENT_ENABLED_STATE_ENABLED 17358 || newState == COMPONENT_ENABLED_STATE_DISABLED 17359 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17360 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17361 throw new IllegalArgumentException("Invalid new component state: " 17362 + newState); 17363 } 17364 PackageSetting pkgSetting; 17365 final int uid = Binder.getCallingUid(); 17366 final int permission; 17367 if (uid == Process.SYSTEM_UID) { 17368 permission = PackageManager.PERMISSION_GRANTED; 17369 } else { 17370 permission = mContext.checkCallingOrSelfPermission( 17371 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17372 } 17373 enforceCrossUserPermission(uid, userId, 17374 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17375 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17376 boolean sendNow = false; 17377 boolean isApp = (className == null); 17378 String componentName = isApp ? packageName : className; 17379 int packageUid = -1; 17380 ArrayList<String> components; 17381 17382 // writer 17383 synchronized (mPackages) { 17384 pkgSetting = mSettings.mPackages.get(packageName); 17385 if (pkgSetting == null) { 17386 if (className == null) { 17387 throw new IllegalArgumentException("Unknown package: " + packageName); 17388 } 17389 throw new IllegalArgumentException( 17390 "Unknown component: " + packageName + "/" + className); 17391 } 17392 // Allow root and verify that userId is not being specified by a different user 17393 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17394 throw new SecurityException( 17395 "Permission Denial: attempt to change component state from pid=" 17396 + Binder.getCallingPid() 17397 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17398 } 17399 if (className == null) { 17400 // We're dealing with an application/package level state change 17401 if (pkgSetting.getEnabled(userId) == newState) { 17402 // Nothing to do 17403 return; 17404 } 17405 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17406 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17407 // Don't care about who enables an app. 17408 callingPackage = null; 17409 } 17410 pkgSetting.setEnabled(newState, userId, callingPackage); 17411 // pkgSetting.pkg.mSetEnabled = newState; 17412 } else { 17413 // We're dealing with a component level state change 17414 // First, verify that this is a valid class name. 17415 PackageParser.Package pkg = pkgSetting.pkg; 17416 if (pkg == null || !pkg.hasComponentClassName(className)) { 17417 if (pkg != null && 17418 pkg.applicationInfo.targetSdkVersion >= 17419 Build.VERSION_CODES.JELLY_BEAN) { 17420 throw new IllegalArgumentException("Component class " + className 17421 + " does not exist in " + packageName); 17422 } else { 17423 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17424 + className + " does not exist in " + packageName); 17425 } 17426 } 17427 switch (newState) { 17428 case COMPONENT_ENABLED_STATE_ENABLED: 17429 if (!pkgSetting.enableComponentLPw(className, userId)) { 17430 return; 17431 } 17432 break; 17433 case COMPONENT_ENABLED_STATE_DISABLED: 17434 if (!pkgSetting.disableComponentLPw(className, userId)) { 17435 return; 17436 } 17437 break; 17438 case COMPONENT_ENABLED_STATE_DEFAULT: 17439 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17440 return; 17441 } 17442 break; 17443 default: 17444 Slog.e(TAG, "Invalid new component state: " + newState); 17445 return; 17446 } 17447 } 17448 scheduleWritePackageRestrictionsLocked(userId); 17449 components = mPendingBroadcasts.get(userId, packageName); 17450 final boolean newPackage = components == null; 17451 if (newPackage) { 17452 components = new ArrayList<String>(); 17453 } 17454 if (!components.contains(componentName)) { 17455 components.add(componentName); 17456 } 17457 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17458 sendNow = true; 17459 // Purge entry from pending broadcast list if another one exists already 17460 // since we are sending one right away. 17461 mPendingBroadcasts.remove(userId, packageName); 17462 } else { 17463 if (newPackage) { 17464 mPendingBroadcasts.put(userId, packageName, components); 17465 } 17466 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17467 // Schedule a message 17468 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17469 } 17470 } 17471 } 17472 17473 long callingId = Binder.clearCallingIdentity(); 17474 try { 17475 if (sendNow) { 17476 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17477 sendPackageChangedBroadcast(packageName, 17478 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17479 } 17480 } finally { 17481 Binder.restoreCallingIdentity(callingId); 17482 } 17483 } 17484 17485 @Override 17486 public void flushPackageRestrictionsAsUser(int userId) { 17487 if (!sUserManager.exists(userId)) { 17488 return; 17489 } 17490 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17491 false /* checkShell */, "flushPackageRestrictions"); 17492 synchronized (mPackages) { 17493 mSettings.writePackageRestrictionsLPr(userId); 17494 mDirtyUsers.remove(userId); 17495 if (mDirtyUsers.isEmpty()) { 17496 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17497 } 17498 } 17499 } 17500 17501 private void sendPackageChangedBroadcast(String packageName, 17502 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17503 if (DEBUG_INSTALL) 17504 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17505 + componentNames); 17506 Bundle extras = new Bundle(4); 17507 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17508 String nameList[] = new String[componentNames.size()]; 17509 componentNames.toArray(nameList); 17510 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17511 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17512 extras.putInt(Intent.EXTRA_UID, packageUid); 17513 // If this is not reporting a change of the overall package, then only send it 17514 // to registered receivers. We don't want to launch a swath of apps for every 17515 // little component state change. 17516 final int flags = !componentNames.contains(packageName) 17517 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17518 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17519 new int[] {UserHandle.getUserId(packageUid)}); 17520 } 17521 17522 @Override 17523 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17524 if (!sUserManager.exists(userId)) return; 17525 final int uid = Binder.getCallingUid(); 17526 final int permission = mContext.checkCallingOrSelfPermission( 17527 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17528 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17529 enforceCrossUserPermission(uid, userId, 17530 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17531 // writer 17532 synchronized (mPackages) { 17533 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17534 allowedByPermission, uid, userId)) { 17535 scheduleWritePackageRestrictionsLocked(userId); 17536 } 17537 } 17538 } 17539 17540 @Override 17541 public String getInstallerPackageName(String packageName) { 17542 // reader 17543 synchronized (mPackages) { 17544 return mSettings.getInstallerPackageNameLPr(packageName); 17545 } 17546 } 17547 17548 public boolean isOrphaned(String packageName) { 17549 // reader 17550 synchronized (mPackages) { 17551 return mSettings.isOrphaned(packageName); 17552 } 17553 } 17554 17555 @Override 17556 public int getApplicationEnabledSetting(String packageName, int userId) { 17557 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17558 int uid = Binder.getCallingUid(); 17559 enforceCrossUserPermission(uid, userId, 17560 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17561 // reader 17562 synchronized (mPackages) { 17563 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17564 } 17565 } 17566 17567 @Override 17568 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17569 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17570 int uid = Binder.getCallingUid(); 17571 enforceCrossUserPermission(uid, userId, 17572 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17573 // reader 17574 synchronized (mPackages) { 17575 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17576 } 17577 } 17578 17579 @Override 17580 public void enterSafeMode() { 17581 enforceSystemOrRoot("Only the system can request entering safe mode"); 17582 17583 if (!mSystemReady) { 17584 mSafeMode = true; 17585 } 17586 } 17587 17588 @Override 17589 public void systemReady() { 17590 mSystemReady = true; 17591 17592 // Read the compatibilty setting when the system is ready. 17593 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17594 mContext.getContentResolver(), 17595 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17596 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17597 if (DEBUG_SETTINGS) { 17598 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17599 } 17600 17601 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17602 17603 synchronized (mPackages) { 17604 // Verify that all of the preferred activity components actually 17605 // exist. It is possible for applications to be updated and at 17606 // that point remove a previously declared activity component that 17607 // had been set as a preferred activity. We try to clean this up 17608 // the next time we encounter that preferred activity, but it is 17609 // possible for the user flow to never be able to return to that 17610 // situation so here we do a sanity check to make sure we haven't 17611 // left any junk around. 17612 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17613 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17614 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17615 removed.clear(); 17616 for (PreferredActivity pa : pir.filterSet()) { 17617 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17618 removed.add(pa); 17619 } 17620 } 17621 if (removed.size() > 0) { 17622 for (int r=0; r<removed.size(); r++) { 17623 PreferredActivity pa = removed.get(r); 17624 Slog.w(TAG, "Removing dangling preferred activity: " 17625 + pa.mPref.mComponent); 17626 pir.removeFilter(pa); 17627 } 17628 mSettings.writePackageRestrictionsLPr( 17629 mSettings.mPreferredActivities.keyAt(i)); 17630 } 17631 } 17632 17633 for (int userId : UserManagerService.getInstance().getUserIds()) { 17634 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17635 grantPermissionsUserIds = ArrayUtils.appendInt( 17636 grantPermissionsUserIds, userId); 17637 } 17638 } 17639 } 17640 sUserManager.systemReady(); 17641 17642 // If we upgraded grant all default permissions before kicking off. 17643 for (int userId : grantPermissionsUserIds) { 17644 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17645 } 17646 17647 // Kick off any messages waiting for system ready 17648 if (mPostSystemReadyMessages != null) { 17649 for (Message msg : mPostSystemReadyMessages) { 17650 msg.sendToTarget(); 17651 } 17652 mPostSystemReadyMessages = null; 17653 } 17654 17655 // Watch for external volumes that come and go over time 17656 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17657 storage.registerListener(mStorageListener); 17658 17659 mInstallerService.systemReady(); 17660 mPackageDexOptimizer.systemReady(); 17661 17662 MountServiceInternal mountServiceInternal = LocalServices.getService( 17663 MountServiceInternal.class); 17664 mountServiceInternal.addExternalStoragePolicy( 17665 new MountServiceInternal.ExternalStorageMountPolicy() { 17666 @Override 17667 public int getMountMode(int uid, String packageName) { 17668 if (Process.isIsolated(uid)) { 17669 return Zygote.MOUNT_EXTERNAL_NONE; 17670 } 17671 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17672 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17673 } 17674 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17675 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17676 } 17677 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17678 return Zygote.MOUNT_EXTERNAL_READ; 17679 } 17680 return Zygote.MOUNT_EXTERNAL_WRITE; 17681 } 17682 17683 @Override 17684 public boolean hasExternalStorage(int uid, String packageName) { 17685 return true; 17686 } 17687 }); 17688 17689 // Now that we're mostly running, clean up stale users and apps 17690 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17691 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17692 } 17693 17694 @Override 17695 public boolean isSafeMode() { 17696 return mSafeMode; 17697 } 17698 17699 @Override 17700 public boolean hasSystemUidErrors() { 17701 return mHasSystemUidErrors; 17702 } 17703 17704 static String arrayToString(int[] array) { 17705 StringBuffer buf = new StringBuffer(128); 17706 buf.append('['); 17707 if (array != null) { 17708 for (int i=0; i<array.length; i++) { 17709 if (i > 0) buf.append(", "); 17710 buf.append(array[i]); 17711 } 17712 } 17713 buf.append(']'); 17714 return buf.toString(); 17715 } 17716 17717 static class DumpState { 17718 public static final int DUMP_LIBS = 1 << 0; 17719 public static final int DUMP_FEATURES = 1 << 1; 17720 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17721 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17722 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17723 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17724 public static final int DUMP_PERMISSIONS = 1 << 6; 17725 public static final int DUMP_PACKAGES = 1 << 7; 17726 public static final int DUMP_SHARED_USERS = 1 << 8; 17727 public static final int DUMP_MESSAGES = 1 << 9; 17728 public static final int DUMP_PROVIDERS = 1 << 10; 17729 public static final int DUMP_VERIFIERS = 1 << 11; 17730 public static final int DUMP_PREFERRED = 1 << 12; 17731 public static final int DUMP_PREFERRED_XML = 1 << 13; 17732 public static final int DUMP_KEYSETS = 1 << 14; 17733 public static final int DUMP_VERSION = 1 << 15; 17734 public static final int DUMP_INSTALLS = 1 << 16; 17735 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17736 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17737 public static final int DUMP_FROZEN = 1 << 19; 17738 17739 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17740 17741 private int mTypes; 17742 17743 private int mOptions; 17744 17745 private boolean mTitlePrinted; 17746 17747 private SharedUserSetting mSharedUser; 17748 17749 public boolean isDumping(int type) { 17750 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17751 return true; 17752 } 17753 17754 return (mTypes & type) != 0; 17755 } 17756 17757 public void setDump(int type) { 17758 mTypes |= type; 17759 } 17760 17761 public boolean isOptionEnabled(int option) { 17762 return (mOptions & option) != 0; 17763 } 17764 17765 public void setOptionEnabled(int option) { 17766 mOptions |= option; 17767 } 17768 17769 public boolean onTitlePrinted() { 17770 final boolean printed = mTitlePrinted; 17771 mTitlePrinted = true; 17772 return printed; 17773 } 17774 17775 public boolean getTitlePrinted() { 17776 return mTitlePrinted; 17777 } 17778 17779 public void setTitlePrinted(boolean enabled) { 17780 mTitlePrinted = enabled; 17781 } 17782 17783 public SharedUserSetting getSharedUser() { 17784 return mSharedUser; 17785 } 17786 17787 public void setSharedUser(SharedUserSetting user) { 17788 mSharedUser = user; 17789 } 17790 } 17791 17792 @Override 17793 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17794 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17795 (new PackageManagerShellCommand(this)).exec( 17796 this, in, out, err, args, resultReceiver); 17797 } 17798 17799 @Override 17800 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17801 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17802 != PackageManager.PERMISSION_GRANTED) { 17803 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17804 + Binder.getCallingPid() 17805 + ", uid=" + Binder.getCallingUid() 17806 + " without permission " 17807 + android.Manifest.permission.DUMP); 17808 return; 17809 } 17810 17811 DumpState dumpState = new DumpState(); 17812 boolean fullPreferred = false; 17813 boolean checkin = false; 17814 17815 String packageName = null; 17816 ArraySet<String> permissionNames = null; 17817 17818 int opti = 0; 17819 while (opti < args.length) { 17820 String opt = args[opti]; 17821 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17822 break; 17823 } 17824 opti++; 17825 17826 if ("-a".equals(opt)) { 17827 // Right now we only know how to print all. 17828 } else if ("-h".equals(opt)) { 17829 pw.println("Package manager dump options:"); 17830 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17831 pw.println(" --checkin: dump for a checkin"); 17832 pw.println(" -f: print details of intent filters"); 17833 pw.println(" -h: print this help"); 17834 pw.println(" cmd may be one of:"); 17835 pw.println(" l[ibraries]: list known shared libraries"); 17836 pw.println(" f[eatures]: list device features"); 17837 pw.println(" k[eysets]: print known keysets"); 17838 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17839 pw.println(" perm[issions]: dump permissions"); 17840 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17841 pw.println(" pref[erred]: print preferred package settings"); 17842 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17843 pw.println(" prov[iders]: dump content providers"); 17844 pw.println(" p[ackages]: dump installed packages"); 17845 pw.println(" s[hared-users]: dump shared user IDs"); 17846 pw.println(" m[essages]: print collected runtime messages"); 17847 pw.println(" v[erifiers]: print package verifier info"); 17848 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17849 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17850 pw.println(" version: print database version info"); 17851 pw.println(" write: write current settings now"); 17852 pw.println(" installs: details about install sessions"); 17853 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17854 pw.println(" <package.name>: info about given package"); 17855 return; 17856 } else if ("--checkin".equals(opt)) { 17857 checkin = true; 17858 } else if ("-f".equals(opt)) { 17859 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17860 } else { 17861 pw.println("Unknown argument: " + opt + "; use -h for help"); 17862 } 17863 } 17864 17865 // Is the caller requesting to dump a particular piece of data? 17866 if (opti < args.length) { 17867 String cmd = args[opti]; 17868 opti++; 17869 // Is this a package name? 17870 if ("android".equals(cmd) || cmd.contains(".")) { 17871 packageName = cmd; 17872 // When dumping a single package, we always dump all of its 17873 // filter information since the amount of data will be reasonable. 17874 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17875 } else if ("check-permission".equals(cmd)) { 17876 if (opti >= args.length) { 17877 pw.println("Error: check-permission missing permission argument"); 17878 return; 17879 } 17880 String perm = args[opti]; 17881 opti++; 17882 if (opti >= args.length) { 17883 pw.println("Error: check-permission missing package argument"); 17884 return; 17885 } 17886 String pkg = args[opti]; 17887 opti++; 17888 int user = UserHandle.getUserId(Binder.getCallingUid()); 17889 if (opti < args.length) { 17890 try { 17891 user = Integer.parseInt(args[opti]); 17892 } catch (NumberFormatException e) { 17893 pw.println("Error: check-permission user argument is not a number: " 17894 + args[opti]); 17895 return; 17896 } 17897 } 17898 pw.println(checkPermission(perm, pkg, user)); 17899 return; 17900 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17901 dumpState.setDump(DumpState.DUMP_LIBS); 17902 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17903 dumpState.setDump(DumpState.DUMP_FEATURES); 17904 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17905 if (opti >= args.length) { 17906 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17907 | DumpState.DUMP_SERVICE_RESOLVERS 17908 | DumpState.DUMP_RECEIVER_RESOLVERS 17909 | DumpState.DUMP_CONTENT_RESOLVERS); 17910 } else { 17911 while (opti < args.length) { 17912 String name = args[opti]; 17913 if ("a".equals(name) || "activity".equals(name)) { 17914 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17915 } else if ("s".equals(name) || "service".equals(name)) { 17916 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17917 } else if ("r".equals(name) || "receiver".equals(name)) { 17918 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17919 } else if ("c".equals(name) || "content".equals(name)) { 17920 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17921 } else { 17922 pw.println("Error: unknown resolver table type: " + name); 17923 return; 17924 } 17925 opti++; 17926 } 17927 } 17928 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17929 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17930 } else if ("permission".equals(cmd)) { 17931 if (opti >= args.length) { 17932 pw.println("Error: permission requires permission name"); 17933 return; 17934 } 17935 permissionNames = new ArraySet<>(); 17936 while (opti < args.length) { 17937 permissionNames.add(args[opti]); 17938 opti++; 17939 } 17940 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17941 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17942 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17943 dumpState.setDump(DumpState.DUMP_PREFERRED); 17944 } else if ("preferred-xml".equals(cmd)) { 17945 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17946 if (opti < args.length && "--full".equals(args[opti])) { 17947 fullPreferred = true; 17948 opti++; 17949 } 17950 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17951 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17952 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17953 dumpState.setDump(DumpState.DUMP_PACKAGES); 17954 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17955 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17956 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17957 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17958 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17959 dumpState.setDump(DumpState.DUMP_MESSAGES); 17960 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17961 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17962 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17963 || "intent-filter-verifiers".equals(cmd)) { 17964 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17965 } else if ("version".equals(cmd)) { 17966 dumpState.setDump(DumpState.DUMP_VERSION); 17967 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17968 dumpState.setDump(DumpState.DUMP_KEYSETS); 17969 } else if ("installs".equals(cmd)) { 17970 dumpState.setDump(DumpState.DUMP_INSTALLS); 17971 } else if ("frozen".equals(cmd)) { 17972 dumpState.setDump(DumpState.DUMP_FROZEN); 17973 } else if ("write".equals(cmd)) { 17974 synchronized (mPackages) { 17975 mSettings.writeLPr(); 17976 pw.println("Settings written."); 17977 return; 17978 } 17979 } 17980 } 17981 17982 if (checkin) { 17983 pw.println("vers,1"); 17984 } 17985 17986 // reader 17987 synchronized (mPackages) { 17988 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17989 if (!checkin) { 17990 if (dumpState.onTitlePrinted()) 17991 pw.println(); 17992 pw.println("Database versions:"); 17993 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17994 } 17995 } 17996 17997 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17998 if (!checkin) { 17999 if (dumpState.onTitlePrinted()) 18000 pw.println(); 18001 pw.println("Verifiers:"); 18002 pw.print(" Required: "); 18003 pw.print(mRequiredVerifierPackage); 18004 pw.print(" (uid="); 18005 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18006 UserHandle.USER_SYSTEM)); 18007 pw.println(")"); 18008 } else if (mRequiredVerifierPackage != null) { 18009 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18010 pw.print(","); 18011 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18012 UserHandle.USER_SYSTEM)); 18013 } 18014 } 18015 18016 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18017 packageName == null) { 18018 if (mIntentFilterVerifierComponent != null) { 18019 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18020 if (!checkin) { 18021 if (dumpState.onTitlePrinted()) 18022 pw.println(); 18023 pw.println("Intent Filter Verifier:"); 18024 pw.print(" Using: "); 18025 pw.print(verifierPackageName); 18026 pw.print(" (uid="); 18027 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18028 UserHandle.USER_SYSTEM)); 18029 pw.println(")"); 18030 } else if (verifierPackageName != null) { 18031 pw.print("ifv,"); pw.print(verifierPackageName); 18032 pw.print(","); 18033 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18034 UserHandle.USER_SYSTEM)); 18035 } 18036 } else { 18037 pw.println(); 18038 pw.println("No Intent Filter Verifier available!"); 18039 } 18040 } 18041 18042 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18043 boolean printedHeader = false; 18044 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18045 while (it.hasNext()) { 18046 String name = it.next(); 18047 SharedLibraryEntry ent = mSharedLibraries.get(name); 18048 if (!checkin) { 18049 if (!printedHeader) { 18050 if (dumpState.onTitlePrinted()) 18051 pw.println(); 18052 pw.println("Libraries:"); 18053 printedHeader = true; 18054 } 18055 pw.print(" "); 18056 } else { 18057 pw.print("lib,"); 18058 } 18059 pw.print(name); 18060 if (!checkin) { 18061 pw.print(" -> "); 18062 } 18063 if (ent.path != null) { 18064 if (!checkin) { 18065 pw.print("(jar) "); 18066 pw.print(ent.path); 18067 } else { 18068 pw.print(",jar,"); 18069 pw.print(ent.path); 18070 } 18071 } else { 18072 if (!checkin) { 18073 pw.print("(apk) "); 18074 pw.print(ent.apk); 18075 } else { 18076 pw.print(",apk,"); 18077 pw.print(ent.apk); 18078 } 18079 } 18080 pw.println(); 18081 } 18082 } 18083 18084 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18085 if (dumpState.onTitlePrinted()) 18086 pw.println(); 18087 if (!checkin) { 18088 pw.println("Features:"); 18089 } 18090 18091 for (FeatureInfo feat : mAvailableFeatures.values()) { 18092 if (checkin) { 18093 pw.print("feat,"); 18094 pw.print(feat.name); 18095 pw.print(","); 18096 pw.println(feat.version); 18097 } else { 18098 pw.print(" "); 18099 pw.print(feat.name); 18100 if (feat.version > 0) { 18101 pw.print(" version="); 18102 pw.print(feat.version); 18103 } 18104 pw.println(); 18105 } 18106 } 18107 } 18108 18109 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18110 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18111 : "Activity Resolver Table:", " ", packageName, 18112 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18113 dumpState.setTitlePrinted(true); 18114 } 18115 } 18116 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18117 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18118 : "Receiver Resolver Table:", " ", packageName, 18119 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18120 dumpState.setTitlePrinted(true); 18121 } 18122 } 18123 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18124 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18125 : "Service Resolver Table:", " ", packageName, 18126 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18127 dumpState.setTitlePrinted(true); 18128 } 18129 } 18130 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18131 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18132 : "Provider Resolver Table:", " ", packageName, 18133 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18134 dumpState.setTitlePrinted(true); 18135 } 18136 } 18137 18138 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18139 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18140 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18141 int user = mSettings.mPreferredActivities.keyAt(i); 18142 if (pir.dump(pw, 18143 dumpState.getTitlePrinted() 18144 ? "\nPreferred Activities User " + user + ":" 18145 : "Preferred Activities User " + user + ":", " ", 18146 packageName, true, false)) { 18147 dumpState.setTitlePrinted(true); 18148 } 18149 } 18150 } 18151 18152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18153 pw.flush(); 18154 FileOutputStream fout = new FileOutputStream(fd); 18155 BufferedOutputStream str = new BufferedOutputStream(fout); 18156 XmlSerializer serializer = new FastXmlSerializer(); 18157 try { 18158 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18159 serializer.startDocument(null, true); 18160 serializer.setFeature( 18161 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18162 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18163 serializer.endDocument(); 18164 serializer.flush(); 18165 } catch (IllegalArgumentException e) { 18166 pw.println("Failed writing: " + e); 18167 } catch (IllegalStateException e) { 18168 pw.println("Failed writing: " + e); 18169 } catch (IOException e) { 18170 pw.println("Failed writing: " + e); 18171 } 18172 } 18173 18174 if (!checkin 18175 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18176 && packageName == null) { 18177 pw.println(); 18178 int count = mSettings.mPackages.size(); 18179 if (count == 0) { 18180 pw.println("No applications!"); 18181 pw.println(); 18182 } else { 18183 final String prefix = " "; 18184 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18185 if (allPackageSettings.size() == 0) { 18186 pw.println("No domain preferred apps!"); 18187 pw.println(); 18188 } else { 18189 pw.println("App verification status:"); 18190 pw.println(); 18191 count = 0; 18192 for (PackageSetting ps : allPackageSettings) { 18193 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18194 if (ivi == null || ivi.getPackageName() == null) continue; 18195 pw.println(prefix + "Package: " + ivi.getPackageName()); 18196 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18197 pw.println(prefix + "Status: " + ivi.getStatusString()); 18198 pw.println(); 18199 count++; 18200 } 18201 if (count == 0) { 18202 pw.println(prefix + "No app verification established."); 18203 pw.println(); 18204 } 18205 for (int userId : sUserManager.getUserIds()) { 18206 pw.println("App linkages for user " + userId + ":"); 18207 pw.println(); 18208 count = 0; 18209 for (PackageSetting ps : allPackageSettings) { 18210 final long status = ps.getDomainVerificationStatusForUser(userId); 18211 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18212 continue; 18213 } 18214 pw.println(prefix + "Package: " + ps.name); 18215 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18216 String statusStr = IntentFilterVerificationInfo. 18217 getStatusStringFromValue(status); 18218 pw.println(prefix + "Status: " + statusStr); 18219 pw.println(); 18220 count++; 18221 } 18222 if (count == 0) { 18223 pw.println(prefix + "No configured app linkages."); 18224 pw.println(); 18225 } 18226 } 18227 } 18228 } 18229 } 18230 18231 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18232 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18233 if (packageName == null && permissionNames == null) { 18234 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18235 if (iperm == 0) { 18236 if (dumpState.onTitlePrinted()) 18237 pw.println(); 18238 pw.println("AppOp Permissions:"); 18239 } 18240 pw.print(" AppOp Permission "); 18241 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18242 pw.println(":"); 18243 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18244 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18245 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18246 } 18247 } 18248 } 18249 } 18250 18251 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18252 boolean printedSomething = false; 18253 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18254 if (packageName != null && !packageName.equals(p.info.packageName)) { 18255 continue; 18256 } 18257 if (!printedSomething) { 18258 if (dumpState.onTitlePrinted()) 18259 pw.println(); 18260 pw.println("Registered ContentProviders:"); 18261 printedSomething = true; 18262 } 18263 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18264 pw.print(" "); pw.println(p.toString()); 18265 } 18266 printedSomething = false; 18267 for (Map.Entry<String, PackageParser.Provider> entry : 18268 mProvidersByAuthority.entrySet()) { 18269 PackageParser.Provider p = entry.getValue(); 18270 if (packageName != null && !packageName.equals(p.info.packageName)) { 18271 continue; 18272 } 18273 if (!printedSomething) { 18274 if (dumpState.onTitlePrinted()) 18275 pw.println(); 18276 pw.println("ContentProvider Authorities:"); 18277 printedSomething = true; 18278 } 18279 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18280 pw.print(" "); pw.println(p.toString()); 18281 if (p.info != null && p.info.applicationInfo != null) { 18282 final String appInfo = p.info.applicationInfo.toString(); 18283 pw.print(" applicationInfo="); pw.println(appInfo); 18284 } 18285 } 18286 } 18287 18288 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18289 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18290 } 18291 18292 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18293 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18294 } 18295 18296 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18297 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18298 } 18299 18300 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18301 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18302 } 18303 18304 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18305 // XXX should handle packageName != null by dumping only install data that 18306 // the given package is involved with. 18307 if (dumpState.onTitlePrinted()) pw.println(); 18308 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18309 } 18310 18311 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18312 // XXX should handle packageName != null by dumping only install data that 18313 // the given package is involved with. 18314 if (dumpState.onTitlePrinted()) pw.println(); 18315 18316 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18317 ipw.println(); 18318 ipw.println("Frozen packages:"); 18319 ipw.increaseIndent(); 18320 if (mFrozenPackages.size() == 0) { 18321 ipw.println("(none)"); 18322 } else { 18323 for (int i = 0; i < mFrozenPackages.size(); i++) { 18324 ipw.println(mFrozenPackages.valueAt(i)); 18325 } 18326 } 18327 ipw.decreaseIndent(); 18328 } 18329 18330 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18331 if (dumpState.onTitlePrinted()) pw.println(); 18332 mSettings.dumpReadMessagesLPr(pw, dumpState); 18333 18334 pw.println(); 18335 pw.println("Package warning messages:"); 18336 BufferedReader in = null; 18337 String line = null; 18338 try { 18339 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18340 while ((line = in.readLine()) != null) { 18341 if (line.contains("ignored: updated version")) continue; 18342 pw.println(line); 18343 } 18344 } catch (IOException ignored) { 18345 } finally { 18346 IoUtils.closeQuietly(in); 18347 } 18348 } 18349 18350 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18351 BufferedReader in = null; 18352 String line = null; 18353 try { 18354 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18355 while ((line = in.readLine()) != null) { 18356 if (line.contains("ignored: updated version")) continue; 18357 pw.print("msg,"); 18358 pw.println(line); 18359 } 18360 } catch (IOException ignored) { 18361 } finally { 18362 IoUtils.closeQuietly(in); 18363 } 18364 } 18365 } 18366 } 18367 18368 private String dumpDomainString(String packageName) { 18369 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18370 .getList(); 18371 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18372 18373 ArraySet<String> result = new ArraySet<>(); 18374 if (iviList.size() > 0) { 18375 for (IntentFilterVerificationInfo ivi : iviList) { 18376 for (String host : ivi.getDomains()) { 18377 result.add(host); 18378 } 18379 } 18380 } 18381 if (filters != null && filters.size() > 0) { 18382 for (IntentFilter filter : filters) { 18383 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18384 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18385 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18386 result.addAll(filter.getHostsList()); 18387 } 18388 } 18389 } 18390 18391 StringBuilder sb = new StringBuilder(result.size() * 16); 18392 for (String domain : result) { 18393 if (sb.length() > 0) sb.append(" "); 18394 sb.append(domain); 18395 } 18396 return sb.toString(); 18397 } 18398 18399 // ------- apps on sdcard specific code ------- 18400 static final boolean DEBUG_SD_INSTALL = false; 18401 18402 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18403 18404 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18405 18406 private boolean mMediaMounted = false; 18407 18408 static String getEncryptKey() { 18409 try { 18410 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18411 SD_ENCRYPTION_KEYSTORE_NAME); 18412 if (sdEncKey == null) { 18413 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18414 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18415 if (sdEncKey == null) { 18416 Slog.e(TAG, "Failed to create encryption keys"); 18417 return null; 18418 } 18419 } 18420 return sdEncKey; 18421 } catch (NoSuchAlgorithmException nsae) { 18422 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18423 return null; 18424 } catch (IOException ioe) { 18425 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18426 return null; 18427 } 18428 } 18429 18430 /* 18431 * Update media status on PackageManager. 18432 */ 18433 @Override 18434 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18435 int callingUid = Binder.getCallingUid(); 18436 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18437 throw new SecurityException("Media status can only be updated by the system"); 18438 } 18439 // reader; this apparently protects mMediaMounted, but should probably 18440 // be a different lock in that case. 18441 synchronized (mPackages) { 18442 Log.i(TAG, "Updating external media status from " 18443 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18444 + (mediaStatus ? "mounted" : "unmounted")); 18445 if (DEBUG_SD_INSTALL) 18446 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18447 + ", mMediaMounted=" + mMediaMounted); 18448 if (mediaStatus == mMediaMounted) { 18449 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18450 : 0, -1); 18451 mHandler.sendMessage(msg); 18452 return; 18453 } 18454 mMediaMounted = mediaStatus; 18455 } 18456 // Queue up an async operation since the package installation may take a 18457 // little while. 18458 mHandler.post(new Runnable() { 18459 public void run() { 18460 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18461 } 18462 }); 18463 } 18464 18465 /** 18466 * Called by MountService when the initial ASECs to scan are available. 18467 * Should block until all the ASEC containers are finished being scanned. 18468 */ 18469 public void scanAvailableAsecs() { 18470 updateExternalMediaStatusInner(true, false, false); 18471 } 18472 18473 /* 18474 * Collect information of applications on external media, map them against 18475 * existing containers and update information based on current mount status. 18476 * Please note that we always have to report status if reportStatus has been 18477 * set to true especially when unloading packages. 18478 */ 18479 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18480 boolean externalStorage) { 18481 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18482 int[] uidArr = EmptyArray.INT; 18483 18484 final String[] list = PackageHelper.getSecureContainerList(); 18485 if (ArrayUtils.isEmpty(list)) { 18486 Log.i(TAG, "No secure containers found"); 18487 } else { 18488 // Process list of secure containers and categorize them 18489 // as active or stale based on their package internal state. 18490 18491 // reader 18492 synchronized (mPackages) { 18493 for (String cid : list) { 18494 // Leave stages untouched for now; installer service owns them 18495 if (PackageInstallerService.isStageName(cid)) continue; 18496 18497 if (DEBUG_SD_INSTALL) 18498 Log.i(TAG, "Processing container " + cid); 18499 String pkgName = getAsecPackageName(cid); 18500 if (pkgName == null) { 18501 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18502 continue; 18503 } 18504 if (DEBUG_SD_INSTALL) 18505 Log.i(TAG, "Looking for pkg : " + pkgName); 18506 18507 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18508 if (ps == null) { 18509 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18510 continue; 18511 } 18512 18513 /* 18514 * Skip packages that are not external if we're unmounting 18515 * external storage. 18516 */ 18517 if (externalStorage && !isMounted && !isExternal(ps)) { 18518 continue; 18519 } 18520 18521 final AsecInstallArgs args = new AsecInstallArgs(cid, 18522 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18523 // The package status is changed only if the code path 18524 // matches between settings and the container id. 18525 if (ps.codePathString != null 18526 && ps.codePathString.startsWith(args.getCodePath())) { 18527 if (DEBUG_SD_INSTALL) { 18528 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18529 + " at code path: " + ps.codePathString); 18530 } 18531 18532 // We do have a valid package installed on sdcard 18533 processCids.put(args, ps.codePathString); 18534 final int uid = ps.appId; 18535 if (uid != -1) { 18536 uidArr = ArrayUtils.appendInt(uidArr, uid); 18537 } 18538 } else { 18539 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18540 + ps.codePathString); 18541 } 18542 } 18543 } 18544 18545 Arrays.sort(uidArr); 18546 } 18547 18548 // Process packages with valid entries. 18549 if (isMounted) { 18550 if (DEBUG_SD_INSTALL) 18551 Log.i(TAG, "Loading packages"); 18552 loadMediaPackages(processCids, uidArr, externalStorage); 18553 startCleaningPackages(); 18554 mInstallerService.onSecureContainersAvailable(); 18555 } else { 18556 if (DEBUG_SD_INSTALL) 18557 Log.i(TAG, "Unloading packages"); 18558 unloadMediaPackages(processCids, uidArr, reportStatus); 18559 } 18560 } 18561 18562 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18563 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18564 final int size = infos.size(); 18565 final String[] packageNames = new String[size]; 18566 final int[] packageUids = new int[size]; 18567 for (int i = 0; i < size; i++) { 18568 final ApplicationInfo info = infos.get(i); 18569 packageNames[i] = info.packageName; 18570 packageUids[i] = info.uid; 18571 } 18572 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18573 finishedReceiver); 18574 } 18575 18576 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18577 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18578 sendResourcesChangedBroadcast(mediaStatus, replacing, 18579 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18580 } 18581 18582 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18583 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18584 int size = pkgList.length; 18585 if (size > 0) { 18586 // Send broadcasts here 18587 Bundle extras = new Bundle(); 18588 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18589 if (uidArr != null) { 18590 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18591 } 18592 if (replacing) { 18593 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18594 } 18595 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18596 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18597 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18598 } 18599 } 18600 18601 /* 18602 * Look at potentially valid container ids from processCids If package 18603 * information doesn't match the one on record or package scanning fails, 18604 * the cid is added to list of removeCids. We currently don't delete stale 18605 * containers. 18606 */ 18607 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18608 boolean externalStorage) { 18609 ArrayList<String> pkgList = new ArrayList<String>(); 18610 Set<AsecInstallArgs> keys = processCids.keySet(); 18611 18612 for (AsecInstallArgs args : keys) { 18613 String codePath = processCids.get(args); 18614 if (DEBUG_SD_INSTALL) 18615 Log.i(TAG, "Loading container : " + args.cid); 18616 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18617 try { 18618 // Make sure there are no container errors first. 18619 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18620 Slog.e(TAG, "Failed to mount cid : " + args.cid 18621 + " when installing from sdcard"); 18622 continue; 18623 } 18624 // Check code path here. 18625 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18626 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18627 + " does not match one in settings " + codePath); 18628 continue; 18629 } 18630 // Parse package 18631 int parseFlags = mDefParseFlags; 18632 if (args.isExternalAsec()) { 18633 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18634 } 18635 if (args.isFwdLocked()) { 18636 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18637 } 18638 18639 synchronized (mInstallLock) { 18640 PackageParser.Package pkg = null; 18641 try { 18642 // Sadly we don't know the package name yet to freeze it 18643 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18644 SCAN_IGNORE_FROZEN, 0, null); 18645 } catch (PackageManagerException e) { 18646 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18647 } 18648 // Scan the package 18649 if (pkg != null) { 18650 /* 18651 * TODO why is the lock being held? doPostInstall is 18652 * called in other places without the lock. This needs 18653 * to be straightened out. 18654 */ 18655 // writer 18656 synchronized (mPackages) { 18657 retCode = PackageManager.INSTALL_SUCCEEDED; 18658 pkgList.add(pkg.packageName); 18659 // Post process args 18660 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18661 pkg.applicationInfo.uid); 18662 } 18663 } else { 18664 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18665 } 18666 } 18667 18668 } finally { 18669 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18670 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18671 } 18672 } 18673 } 18674 // writer 18675 synchronized (mPackages) { 18676 // If the platform SDK has changed since the last time we booted, 18677 // we need to re-grant app permission to catch any new ones that 18678 // appear. This is really a hack, and means that apps can in some 18679 // cases get permissions that the user didn't initially explicitly 18680 // allow... it would be nice to have some better way to handle 18681 // this situation. 18682 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18683 : mSettings.getInternalVersion(); 18684 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18685 : StorageManager.UUID_PRIVATE_INTERNAL; 18686 18687 int updateFlags = UPDATE_PERMISSIONS_ALL; 18688 if (ver.sdkVersion != mSdkVersion) { 18689 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18690 + mSdkVersion + "; regranting permissions for external"); 18691 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18692 } 18693 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18694 18695 // Yay, everything is now upgraded 18696 ver.forceCurrent(); 18697 18698 // can downgrade to reader 18699 // Persist settings 18700 mSettings.writeLPr(); 18701 } 18702 // Send a broadcast to let everyone know we are done processing 18703 if (pkgList.size() > 0) { 18704 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18705 } 18706 } 18707 18708 /* 18709 * Utility method to unload a list of specified containers 18710 */ 18711 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18712 // Just unmount all valid containers. 18713 for (AsecInstallArgs arg : cidArgs) { 18714 synchronized (mInstallLock) { 18715 arg.doPostDeleteLI(false); 18716 } 18717 } 18718 } 18719 18720 /* 18721 * Unload packages mounted on external media. This involves deleting package 18722 * data from internal structures, sending broadcasts about disabled packages, 18723 * gc'ing to free up references, unmounting all secure containers 18724 * corresponding to packages on external media, and posting a 18725 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18726 * that we always have to post this message if status has been requested no 18727 * matter what. 18728 */ 18729 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18730 final boolean reportStatus) { 18731 if (DEBUG_SD_INSTALL) 18732 Log.i(TAG, "unloading media packages"); 18733 ArrayList<String> pkgList = new ArrayList<String>(); 18734 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18735 final Set<AsecInstallArgs> keys = processCids.keySet(); 18736 for (AsecInstallArgs args : keys) { 18737 String pkgName = args.getPackageName(); 18738 if (DEBUG_SD_INSTALL) 18739 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18740 // Delete package internally 18741 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18742 synchronized (mInstallLock) { 18743 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18744 final boolean res; 18745 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18746 "unloadMediaPackages")) { 18747 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18748 null); 18749 } 18750 if (res) { 18751 pkgList.add(pkgName); 18752 } else { 18753 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18754 failedList.add(args); 18755 } 18756 } 18757 } 18758 18759 // reader 18760 synchronized (mPackages) { 18761 // We didn't update the settings after removing each package; 18762 // write them now for all packages. 18763 mSettings.writeLPr(); 18764 } 18765 18766 // We have to absolutely send UPDATED_MEDIA_STATUS only 18767 // after confirming that all the receivers processed the ordered 18768 // broadcast when packages get disabled, force a gc to clean things up. 18769 // and unload all the containers. 18770 if (pkgList.size() > 0) { 18771 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18772 new IIntentReceiver.Stub() { 18773 public void performReceive(Intent intent, int resultCode, String data, 18774 Bundle extras, boolean ordered, boolean sticky, 18775 int sendingUser) throws RemoteException { 18776 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18777 reportStatus ? 1 : 0, 1, keys); 18778 mHandler.sendMessage(msg); 18779 } 18780 }); 18781 } else { 18782 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18783 keys); 18784 mHandler.sendMessage(msg); 18785 } 18786 } 18787 18788 private void loadPrivatePackages(final VolumeInfo vol) { 18789 mHandler.post(new Runnable() { 18790 @Override 18791 public void run() { 18792 loadPrivatePackagesInner(vol); 18793 } 18794 }); 18795 } 18796 18797 private void loadPrivatePackagesInner(VolumeInfo vol) { 18798 final String volumeUuid = vol.fsUuid; 18799 if (TextUtils.isEmpty(volumeUuid)) { 18800 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18801 return; 18802 } 18803 18804 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18805 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18806 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18807 18808 final VersionInfo ver; 18809 final List<PackageSetting> packages; 18810 synchronized (mPackages) { 18811 ver = mSettings.findOrCreateVersion(volumeUuid); 18812 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18813 } 18814 18815 for (PackageSetting ps : packages) { 18816 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18817 synchronized (mInstallLock) { 18818 final PackageParser.Package pkg; 18819 try { 18820 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18821 loaded.add(pkg.applicationInfo); 18822 18823 } catch (PackageManagerException e) { 18824 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18825 } 18826 18827 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18828 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18829 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18830 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18831 } 18832 } 18833 } 18834 18835 // Reconcile app data for all started/unlocked users 18836 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18837 final UserManager um = mContext.getSystemService(UserManager.class); 18838 for (UserInfo user : um.getUsers()) { 18839 final int flags; 18840 if (um.isUserUnlockingOrUnlocked(user.id)) { 18841 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18842 } else if (um.isUserRunning(user.id)) { 18843 flags = StorageManager.FLAG_STORAGE_DE; 18844 } else { 18845 continue; 18846 } 18847 18848 try { 18849 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18850 synchronized (mInstallLock) { 18851 reconcileAppsDataLI(volumeUuid, user.id, flags); 18852 } 18853 } catch (IllegalStateException e) { 18854 // Device was probably ejected, and we'll process that event momentarily 18855 Slog.w(TAG, "Failed to prepare storage: " + e); 18856 } 18857 } 18858 18859 synchronized (mPackages) { 18860 int updateFlags = UPDATE_PERMISSIONS_ALL; 18861 if (ver.sdkVersion != mSdkVersion) { 18862 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18863 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18864 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18865 } 18866 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18867 18868 // Yay, everything is now upgraded 18869 ver.forceCurrent(); 18870 18871 mSettings.writeLPr(); 18872 } 18873 18874 for (PackageFreezer freezer : freezers) { 18875 freezer.close(); 18876 } 18877 18878 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18879 sendResourcesChangedBroadcast(true, false, loaded, null); 18880 } 18881 18882 private void unloadPrivatePackages(final VolumeInfo vol) { 18883 mHandler.post(new Runnable() { 18884 @Override 18885 public void run() { 18886 unloadPrivatePackagesInner(vol); 18887 } 18888 }); 18889 } 18890 18891 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18892 final String volumeUuid = vol.fsUuid; 18893 if (TextUtils.isEmpty(volumeUuid)) { 18894 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18895 return; 18896 } 18897 18898 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18899 synchronized (mInstallLock) { 18900 synchronized (mPackages) { 18901 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18902 for (PackageSetting ps : packages) { 18903 if (ps.pkg == null) continue; 18904 18905 final ApplicationInfo info = ps.pkg.applicationInfo; 18906 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18907 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18908 18909 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18910 "unloadPrivatePackagesInner")) { 18911 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18912 false, null)) { 18913 unloaded.add(info); 18914 } else { 18915 Slog.w(TAG, "Failed to unload " + ps.codePath); 18916 } 18917 } 18918 } 18919 18920 mSettings.writeLPr(); 18921 } 18922 } 18923 18924 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18925 sendResourcesChangedBroadcast(false, false, unloaded, null); 18926 } 18927 18928 /** 18929 * Prepare storage areas for given user on all mounted devices. 18930 */ 18931 void prepareUserData(int userId, int userSerial, int flags) { 18932 synchronized (mInstallLock) { 18933 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18934 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18935 final String volumeUuid = vol.getFsUuid(); 18936 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18937 } 18938 } 18939 } 18940 18941 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18942 boolean allowRecover) { 18943 // Prepare storage and verify that serial numbers are consistent; if 18944 // there's a mismatch we need to destroy to avoid leaking data 18945 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18946 try { 18947 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18948 18949 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18950 UserManagerService.enforceSerialNumber( 18951 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18952 } 18953 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18954 UserManagerService.enforceSerialNumber( 18955 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18956 } 18957 18958 synchronized (mInstallLock) { 18959 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18960 } 18961 } catch (Exception e) { 18962 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18963 + " because we failed to prepare: " + e); 18964 destroyUserDataLI(volumeUuid, userId, 18965 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18966 18967 if (allowRecover) { 18968 // Try one last time; if we fail again we're really in trouble 18969 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18970 } 18971 } 18972 } 18973 18974 /** 18975 * Destroy storage areas for given user on all mounted devices. 18976 */ 18977 void destroyUserData(int userId, int flags) { 18978 synchronized (mInstallLock) { 18979 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18980 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18981 final String volumeUuid = vol.getFsUuid(); 18982 destroyUserDataLI(volumeUuid, userId, flags); 18983 } 18984 } 18985 } 18986 18987 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18988 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18989 try { 18990 // Clean up app data, profile data, and media data 18991 mInstaller.destroyUserData(volumeUuid, userId, flags); 18992 18993 // Clean up system data 18994 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18995 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18996 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18997 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18998 } 18999 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19000 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19001 } 19002 } 19003 19004 // Data with special labels is now gone, so finish the job 19005 storage.destroyUserStorage(volumeUuid, userId, flags); 19006 19007 } catch (Exception e) { 19008 logCriticalInfo(Log.WARN, 19009 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19010 } 19011 } 19012 19013 /** 19014 * Examine all users present on given mounted volume, and destroy data 19015 * belonging to users that are no longer valid, or whose user ID has been 19016 * recycled. 19017 */ 19018 private void reconcileUsers(String volumeUuid) { 19019 final List<File> files = new ArrayList<>(); 19020 Collections.addAll(files, FileUtils 19021 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19022 Collections.addAll(files, FileUtils 19023 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19024 for (File file : files) { 19025 if (!file.isDirectory()) continue; 19026 19027 final int userId; 19028 final UserInfo info; 19029 try { 19030 userId = Integer.parseInt(file.getName()); 19031 info = sUserManager.getUserInfo(userId); 19032 } catch (NumberFormatException e) { 19033 Slog.w(TAG, "Invalid user directory " + file); 19034 continue; 19035 } 19036 19037 boolean destroyUser = false; 19038 if (info == null) { 19039 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19040 + " because no matching user was found"); 19041 destroyUser = true; 19042 } else if (!mOnlyCore) { 19043 try { 19044 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19045 } catch (IOException e) { 19046 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19047 + " because we failed to enforce serial number: " + e); 19048 destroyUser = true; 19049 } 19050 } 19051 19052 if (destroyUser) { 19053 synchronized (mInstallLock) { 19054 destroyUserDataLI(volumeUuid, userId, 19055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19056 } 19057 } 19058 } 19059 } 19060 19061 private void assertPackageKnown(String volumeUuid, String packageName) 19062 throws PackageManagerException { 19063 synchronized (mPackages) { 19064 final PackageSetting ps = mSettings.mPackages.get(packageName); 19065 if (ps == null) { 19066 throw new PackageManagerException("Package " + packageName + " is unknown"); 19067 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19068 throw new PackageManagerException( 19069 "Package " + packageName + " found on unknown volume " + volumeUuid 19070 + "; expected volume " + ps.volumeUuid); 19071 } 19072 } 19073 } 19074 19075 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19076 throws PackageManagerException { 19077 synchronized (mPackages) { 19078 final PackageSetting ps = mSettings.mPackages.get(packageName); 19079 if (ps == null) { 19080 throw new PackageManagerException("Package " + packageName + " is unknown"); 19081 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19082 throw new PackageManagerException( 19083 "Package " + packageName + " found on unknown volume " + volumeUuid 19084 + "; expected volume " + ps.volumeUuid); 19085 } else if (!ps.getInstalled(userId)) { 19086 throw new PackageManagerException( 19087 "Package " + packageName + " not installed for user " + userId); 19088 } 19089 } 19090 } 19091 19092 /** 19093 * Examine all apps present on given mounted volume, and destroy apps that 19094 * aren't expected, either due to uninstallation or reinstallation on 19095 * another volume. 19096 */ 19097 private void reconcileApps(String volumeUuid) { 19098 final File[] files = FileUtils 19099 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19100 for (File file : files) { 19101 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19102 && !PackageInstallerService.isStageName(file.getName()); 19103 if (!isPackage) { 19104 // Ignore entries which are not packages 19105 continue; 19106 } 19107 19108 try { 19109 final PackageLite pkg = PackageParser.parsePackageLite(file, 19110 PackageParser.PARSE_MUST_BE_APK); 19111 assertPackageKnown(volumeUuid, pkg.packageName); 19112 19113 } catch (PackageParserException | PackageManagerException e) { 19114 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19115 synchronized (mInstallLock) { 19116 removeCodePathLI(file); 19117 } 19118 } 19119 } 19120 } 19121 19122 /** 19123 * Reconcile all app data for the given user. 19124 * <p> 19125 * Verifies that directories exist and that ownership and labeling is 19126 * correct for all installed apps on all mounted volumes. 19127 */ 19128 void reconcileAppsData(int userId, int flags) { 19129 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19130 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19131 final String volumeUuid = vol.getFsUuid(); 19132 synchronized (mInstallLock) { 19133 reconcileAppsDataLI(volumeUuid, userId, flags); 19134 } 19135 } 19136 } 19137 19138 /** 19139 * Reconcile all app data on given mounted volume. 19140 * <p> 19141 * Destroys app data that isn't expected, either due to uninstallation or 19142 * reinstallation on another volume. 19143 * <p> 19144 * Verifies that directories exist and that ownership and labeling is 19145 * correct for all installed apps. 19146 */ 19147 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19148 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19149 + Integer.toHexString(flags)); 19150 19151 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19152 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19153 19154 boolean restoreconNeeded = false; 19155 19156 // First look for stale data that doesn't belong, and check if things 19157 // have changed since we did our last restorecon 19158 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19159 if (StorageManager.isFileEncryptedNativeOrEmulated() 19160 && !StorageManager.isUserKeyUnlocked(userId)) { 19161 throw new RuntimeException( 19162 "Yikes, someone asked us to reconcile CE storage while " + userId 19163 + " was still locked; this would have caused massive data loss!"); 19164 } 19165 19166 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19167 19168 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19169 for (File file : files) { 19170 final String packageName = file.getName(); 19171 try { 19172 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19173 } catch (PackageManagerException e) { 19174 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19175 try { 19176 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19177 StorageManager.FLAG_STORAGE_CE, 0); 19178 } catch (InstallerException e2) { 19179 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19180 } 19181 } 19182 } 19183 } 19184 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19185 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19186 19187 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19188 for (File file : files) { 19189 final String packageName = file.getName(); 19190 try { 19191 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19192 } catch (PackageManagerException e) { 19193 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19194 try { 19195 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19196 StorageManager.FLAG_STORAGE_DE, 0); 19197 } catch (InstallerException e2) { 19198 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19199 } 19200 } 19201 } 19202 } 19203 19204 // Ensure that data directories are ready to roll for all packages 19205 // installed for this volume and user 19206 final List<PackageSetting> packages; 19207 synchronized (mPackages) { 19208 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19209 } 19210 int preparedCount = 0; 19211 for (PackageSetting ps : packages) { 19212 final String packageName = ps.name; 19213 if (ps.pkg == null) { 19214 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19215 // TODO: might be due to legacy ASEC apps; we should circle back 19216 // and reconcile again once they're scanned 19217 continue; 19218 } 19219 19220 if (ps.getInstalled(userId)) { 19221 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19222 19223 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19224 // We may have just shuffled around app data directories, so 19225 // prepare them one more time 19226 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19227 } 19228 19229 preparedCount++; 19230 } 19231 } 19232 19233 if (restoreconNeeded) { 19234 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19235 SELinuxMMAC.setRestoreconDone(ceDir); 19236 } 19237 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19238 SELinuxMMAC.setRestoreconDone(deDir); 19239 } 19240 } 19241 19242 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19243 + " packages; restoreconNeeded was " + restoreconNeeded); 19244 } 19245 19246 /** 19247 * Prepare app data for the given app just after it was installed or 19248 * upgraded. This method carefully only touches users that it's installed 19249 * for, and it forces a restorecon to handle any seinfo changes. 19250 * <p> 19251 * Verifies that directories exist and that ownership and labeling is 19252 * correct for all installed apps. If there is an ownership mismatch, it 19253 * will try recovering system apps by wiping data; third-party app data is 19254 * left intact. 19255 * <p> 19256 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19257 */ 19258 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19259 final PackageSetting ps; 19260 synchronized (mPackages) { 19261 ps = mSettings.mPackages.get(pkg.packageName); 19262 mSettings.writeKernelMappingLPr(ps); 19263 } 19264 19265 final UserManager um = mContext.getSystemService(UserManager.class); 19266 for (UserInfo user : um.getUsers()) { 19267 final int flags; 19268 if (um.isUserUnlockingOrUnlocked(user.id)) { 19269 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19270 } else if (um.isUserRunning(user.id)) { 19271 flags = StorageManager.FLAG_STORAGE_DE; 19272 } else { 19273 continue; 19274 } 19275 19276 if (ps.getInstalled(user.id)) { 19277 // Whenever an app changes, force a restorecon of its data 19278 // TODO: when user data is locked, mark that we're still dirty 19279 prepareAppDataLIF(pkg, user.id, flags, true); 19280 } 19281 } 19282 } 19283 19284 /** 19285 * Prepare app data for the given app. 19286 * <p> 19287 * Verifies that directories exist and that ownership and labeling is 19288 * correct for all installed apps. If there is an ownership mismatch, this 19289 * will try recovering system apps by wiping data; third-party app data is 19290 * left intact. 19291 */ 19292 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19293 boolean restoreconNeeded) { 19294 if (pkg == null) { 19295 Slog.wtf(TAG, "Package was null!", new Throwable()); 19296 return; 19297 } 19298 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19299 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19300 for (int i = 0; i < childCount; i++) { 19301 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19302 } 19303 } 19304 19305 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19306 boolean restoreconNeeded) { 19307 if (DEBUG_APP_DATA) { 19308 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19309 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19310 } 19311 19312 final String volumeUuid = pkg.volumeUuid; 19313 final String packageName = pkg.packageName; 19314 final ApplicationInfo app = pkg.applicationInfo; 19315 final int appId = UserHandle.getAppId(app.uid); 19316 19317 Preconditions.checkNotNull(app.seinfo); 19318 19319 try { 19320 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19321 appId, app.seinfo, app.targetSdkVersion); 19322 } catch (InstallerException e) { 19323 if (app.isSystemApp()) { 19324 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19325 + ", but trying to recover: " + e); 19326 destroyAppDataLeafLIF(pkg, userId, flags); 19327 try { 19328 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19329 appId, app.seinfo, app.targetSdkVersion); 19330 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19331 } catch (InstallerException e2) { 19332 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19333 } 19334 } else { 19335 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19336 } 19337 } 19338 19339 if (restoreconNeeded) { 19340 try { 19341 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19342 app.seinfo); 19343 } catch (InstallerException e) { 19344 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19345 } 19346 } 19347 19348 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19349 try { 19350 // CE storage is unlocked right now, so read out the inode and 19351 // remember for use later when it's locked 19352 // TODO: mark this structure as dirty so we persist it! 19353 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19354 StorageManager.FLAG_STORAGE_CE); 19355 synchronized (mPackages) { 19356 final PackageSetting ps = mSettings.mPackages.get(packageName); 19357 if (ps != null) { 19358 ps.setCeDataInode(ceDataInode, userId); 19359 } 19360 } 19361 } catch (InstallerException e) { 19362 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19363 } 19364 } 19365 19366 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19367 } 19368 19369 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19370 if (pkg == null) { 19371 Slog.wtf(TAG, "Package was null!", new Throwable()); 19372 return; 19373 } 19374 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19375 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19376 for (int i = 0; i < childCount; i++) { 19377 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19378 } 19379 } 19380 19381 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19382 final String volumeUuid = pkg.volumeUuid; 19383 final String packageName = pkg.packageName; 19384 final ApplicationInfo app = pkg.applicationInfo; 19385 19386 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19387 // Create a native library symlink only if we have native libraries 19388 // and if the native libraries are 32 bit libraries. We do not provide 19389 // this symlink for 64 bit libraries. 19390 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19391 final String nativeLibPath = app.nativeLibraryDir; 19392 try { 19393 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19394 nativeLibPath, userId); 19395 } catch (InstallerException e) { 19396 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19397 } 19398 } 19399 } 19400 } 19401 19402 /** 19403 * For system apps on non-FBE devices, this method migrates any existing 19404 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19405 * requested by the app. 19406 */ 19407 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19408 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19409 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19410 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19411 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19412 try { 19413 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19414 storageTarget); 19415 } catch (InstallerException e) { 19416 logCriticalInfo(Log.WARN, 19417 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19418 } 19419 return true; 19420 } else { 19421 return false; 19422 } 19423 } 19424 19425 public PackageFreezer freezePackage(String packageName, String killReason) { 19426 return new PackageFreezer(packageName, killReason); 19427 } 19428 19429 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19430 String killReason) { 19431 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19432 return new PackageFreezer(); 19433 } else { 19434 return freezePackage(packageName, killReason); 19435 } 19436 } 19437 19438 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19439 String killReason) { 19440 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19441 return new PackageFreezer(); 19442 } else { 19443 return freezePackage(packageName, killReason); 19444 } 19445 } 19446 19447 /** 19448 * Class that freezes and kills the given package upon creation, and 19449 * unfreezes it upon closing. This is typically used when doing surgery on 19450 * app code/data to prevent the app from running while you're working. 19451 */ 19452 private class PackageFreezer implements AutoCloseable { 19453 private final String mPackageName; 19454 private final PackageFreezer[] mChildren; 19455 19456 private final boolean mWeFroze; 19457 19458 private final AtomicBoolean mClosed = new AtomicBoolean(); 19459 private final CloseGuard mCloseGuard = CloseGuard.get(); 19460 19461 /** 19462 * Create and return a stub freezer that doesn't actually do anything, 19463 * typically used when someone requested 19464 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19465 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19466 */ 19467 public PackageFreezer() { 19468 mPackageName = null; 19469 mChildren = null; 19470 mWeFroze = false; 19471 mCloseGuard.open("close"); 19472 } 19473 19474 public PackageFreezer(String packageName, String killReason) { 19475 synchronized (mPackages) { 19476 mPackageName = packageName; 19477 mWeFroze = mFrozenPackages.add(mPackageName); 19478 19479 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19480 if (ps != null) { 19481 killApplication(ps.name, ps.appId, killReason); 19482 } 19483 19484 final PackageParser.Package p = mPackages.get(packageName); 19485 if (p != null && p.childPackages != null) { 19486 final int N = p.childPackages.size(); 19487 mChildren = new PackageFreezer[N]; 19488 for (int i = 0; i < N; i++) { 19489 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19490 killReason); 19491 } 19492 } else { 19493 mChildren = null; 19494 } 19495 } 19496 mCloseGuard.open("close"); 19497 } 19498 19499 @Override 19500 protected void finalize() throws Throwable { 19501 try { 19502 mCloseGuard.warnIfOpen(); 19503 close(); 19504 } finally { 19505 super.finalize(); 19506 } 19507 } 19508 19509 @Override 19510 public void close() { 19511 mCloseGuard.close(); 19512 if (mClosed.compareAndSet(false, true)) { 19513 synchronized (mPackages) { 19514 if (mWeFroze) { 19515 mFrozenPackages.remove(mPackageName); 19516 } 19517 19518 if (mChildren != null) { 19519 for (PackageFreezer freezer : mChildren) { 19520 freezer.close(); 19521 } 19522 } 19523 } 19524 } 19525 } 19526 } 19527 19528 /** 19529 * Verify that given package is currently frozen. 19530 */ 19531 private void checkPackageFrozen(String packageName) { 19532 synchronized (mPackages) { 19533 if (!mFrozenPackages.contains(packageName)) { 19534 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19535 } 19536 } 19537 } 19538 19539 @Override 19540 public int movePackage(final String packageName, final String volumeUuid) { 19541 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19542 19543 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19544 final int moveId = mNextMoveId.getAndIncrement(); 19545 mHandler.post(new Runnable() { 19546 @Override 19547 public void run() { 19548 try { 19549 movePackageInternal(packageName, volumeUuid, moveId, user); 19550 } catch (PackageManagerException e) { 19551 Slog.w(TAG, "Failed to move " + packageName, e); 19552 mMoveCallbacks.notifyStatusChanged(moveId, 19553 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19554 } 19555 } 19556 }); 19557 return moveId; 19558 } 19559 19560 private void movePackageInternal(final String packageName, final String volumeUuid, 19561 final int moveId, UserHandle user) throws PackageManagerException { 19562 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19563 final PackageManager pm = mContext.getPackageManager(); 19564 19565 final boolean currentAsec; 19566 final String currentVolumeUuid; 19567 final File codeFile; 19568 final String installerPackageName; 19569 final String packageAbiOverride; 19570 final int appId; 19571 final String seinfo; 19572 final String label; 19573 final int targetSdkVersion; 19574 final PackageFreezer freezer; 19575 19576 // reader 19577 synchronized (mPackages) { 19578 final PackageParser.Package pkg = mPackages.get(packageName); 19579 final PackageSetting ps = mSettings.mPackages.get(packageName); 19580 if (pkg == null || ps == null) { 19581 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19582 } 19583 19584 if (pkg.applicationInfo.isSystemApp()) { 19585 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19586 "Cannot move system application"); 19587 } 19588 19589 if (pkg.applicationInfo.isExternalAsec()) { 19590 currentAsec = true; 19591 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19592 } else if (pkg.applicationInfo.isForwardLocked()) { 19593 currentAsec = true; 19594 currentVolumeUuid = "forward_locked"; 19595 } else { 19596 currentAsec = false; 19597 currentVolumeUuid = ps.volumeUuid; 19598 19599 final File probe = new File(pkg.codePath); 19600 final File probeOat = new File(probe, "oat"); 19601 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19602 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19603 "Move only supported for modern cluster style installs"); 19604 } 19605 } 19606 19607 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19608 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19609 "Package already moved to " + volumeUuid); 19610 } 19611 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19612 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19613 "Device admin cannot be moved"); 19614 } 19615 19616 if (mFrozenPackages.contains(packageName)) { 19617 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19618 "Failed to move already frozen package"); 19619 } 19620 19621 codeFile = new File(pkg.codePath); 19622 installerPackageName = ps.installerPackageName; 19623 packageAbiOverride = ps.cpuAbiOverrideString; 19624 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19625 seinfo = pkg.applicationInfo.seinfo; 19626 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19627 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19628 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19629 } 19630 19631 final Bundle extras = new Bundle(); 19632 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19633 extras.putString(Intent.EXTRA_TITLE, label); 19634 mMoveCallbacks.notifyCreated(moveId, extras); 19635 19636 int installFlags; 19637 final boolean moveCompleteApp; 19638 final File measurePath; 19639 19640 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19641 installFlags = INSTALL_INTERNAL; 19642 moveCompleteApp = !currentAsec; 19643 measurePath = Environment.getDataAppDirectory(volumeUuid); 19644 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19645 installFlags = INSTALL_EXTERNAL; 19646 moveCompleteApp = false; 19647 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19648 } else { 19649 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19650 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19651 || !volume.isMountedWritable()) { 19652 freezer.close(); 19653 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19654 "Move location not mounted private volume"); 19655 } 19656 19657 Preconditions.checkState(!currentAsec); 19658 19659 installFlags = INSTALL_INTERNAL; 19660 moveCompleteApp = true; 19661 measurePath = Environment.getDataAppDirectory(volumeUuid); 19662 } 19663 19664 final PackageStats stats = new PackageStats(null, -1); 19665 synchronized (mInstaller) { 19666 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19667 freezer.close(); 19668 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19669 "Failed to measure package size"); 19670 } 19671 } 19672 19673 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19674 + stats.dataSize); 19675 19676 final long startFreeBytes = measurePath.getFreeSpace(); 19677 final long sizeBytes; 19678 if (moveCompleteApp) { 19679 sizeBytes = stats.codeSize + stats.dataSize; 19680 } else { 19681 sizeBytes = stats.codeSize; 19682 } 19683 19684 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19685 freezer.close(); 19686 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19687 "Not enough free space to move"); 19688 } 19689 19690 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19691 19692 final CountDownLatch installedLatch = new CountDownLatch(1); 19693 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19694 @Override 19695 public void onUserActionRequired(Intent intent) throws RemoteException { 19696 throw new IllegalStateException(); 19697 } 19698 19699 @Override 19700 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19701 Bundle extras) throws RemoteException { 19702 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19703 + PackageManager.installStatusToString(returnCode, msg)); 19704 19705 installedLatch.countDown(); 19706 freezer.close(); 19707 19708 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19709 switch (status) { 19710 case PackageInstaller.STATUS_SUCCESS: 19711 mMoveCallbacks.notifyStatusChanged(moveId, 19712 PackageManager.MOVE_SUCCEEDED); 19713 break; 19714 case PackageInstaller.STATUS_FAILURE_STORAGE: 19715 mMoveCallbacks.notifyStatusChanged(moveId, 19716 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19717 break; 19718 default: 19719 mMoveCallbacks.notifyStatusChanged(moveId, 19720 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19721 break; 19722 } 19723 } 19724 }; 19725 19726 final MoveInfo move; 19727 if (moveCompleteApp) { 19728 // Kick off a thread to report progress estimates 19729 new Thread() { 19730 @Override 19731 public void run() { 19732 while (true) { 19733 try { 19734 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19735 break; 19736 } 19737 } catch (InterruptedException ignored) { 19738 } 19739 19740 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19741 final int progress = 10 + (int) MathUtils.constrain( 19742 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19743 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19744 } 19745 } 19746 }.start(); 19747 19748 final String dataAppName = codeFile.getName(); 19749 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19750 dataAppName, appId, seinfo, targetSdkVersion); 19751 } else { 19752 move = null; 19753 } 19754 19755 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19756 19757 final Message msg = mHandler.obtainMessage(INIT_COPY); 19758 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19759 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19760 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19761 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19762 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19763 msg.obj = params; 19764 19765 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19766 System.identityHashCode(msg.obj)); 19767 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19768 System.identityHashCode(msg.obj)); 19769 19770 mHandler.sendMessage(msg); 19771 } 19772 19773 @Override 19774 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19775 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19776 19777 final int realMoveId = mNextMoveId.getAndIncrement(); 19778 final Bundle extras = new Bundle(); 19779 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19780 mMoveCallbacks.notifyCreated(realMoveId, extras); 19781 19782 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19783 @Override 19784 public void onCreated(int moveId, Bundle extras) { 19785 // Ignored 19786 } 19787 19788 @Override 19789 public void onStatusChanged(int moveId, int status, long estMillis) { 19790 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19791 } 19792 }; 19793 19794 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19795 storage.setPrimaryStorageUuid(volumeUuid, callback); 19796 return realMoveId; 19797 } 19798 19799 @Override 19800 public int getMoveStatus(int moveId) { 19801 mContext.enforceCallingOrSelfPermission( 19802 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19803 return mMoveCallbacks.mLastStatus.get(moveId); 19804 } 19805 19806 @Override 19807 public void registerMoveCallback(IPackageMoveObserver callback) { 19808 mContext.enforceCallingOrSelfPermission( 19809 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19810 mMoveCallbacks.register(callback); 19811 } 19812 19813 @Override 19814 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19815 mContext.enforceCallingOrSelfPermission( 19816 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19817 mMoveCallbacks.unregister(callback); 19818 } 19819 19820 @Override 19821 public boolean setInstallLocation(int loc) { 19822 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19823 null); 19824 if (getInstallLocation() == loc) { 19825 return true; 19826 } 19827 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19828 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19829 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19830 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19831 return true; 19832 } 19833 return false; 19834 } 19835 19836 @Override 19837 public int getInstallLocation() { 19838 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19839 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19840 PackageHelper.APP_INSTALL_AUTO); 19841 } 19842 19843 /** Called by UserManagerService */ 19844 void cleanUpUser(UserManagerService userManager, int userHandle) { 19845 synchronized (mPackages) { 19846 mDirtyUsers.remove(userHandle); 19847 mUserNeedsBadging.delete(userHandle); 19848 mSettings.removeUserLPw(userHandle); 19849 mPendingBroadcasts.remove(userHandle); 19850 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19851 removeUnusedPackagesLPw(userManager, userHandle); 19852 } 19853 } 19854 19855 /** 19856 * We're removing userHandle and would like to remove any downloaded packages 19857 * that are no longer in use by any other user. 19858 * @param userHandle the user being removed 19859 */ 19860 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19861 final boolean DEBUG_CLEAN_APKS = false; 19862 int [] users = userManager.getUserIds(); 19863 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19864 while (psit.hasNext()) { 19865 PackageSetting ps = psit.next(); 19866 if (ps.pkg == null) { 19867 continue; 19868 } 19869 final String packageName = ps.pkg.packageName; 19870 // Skip over if system app 19871 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19872 continue; 19873 } 19874 if (DEBUG_CLEAN_APKS) { 19875 Slog.i(TAG, "Checking package " + packageName); 19876 } 19877 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19878 if (keep) { 19879 if (DEBUG_CLEAN_APKS) { 19880 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19881 } 19882 } else { 19883 for (int i = 0; i < users.length; i++) { 19884 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19885 keep = true; 19886 if (DEBUG_CLEAN_APKS) { 19887 Slog.i(TAG, " Keeping package " + packageName + " for user " 19888 + users[i]); 19889 } 19890 break; 19891 } 19892 } 19893 } 19894 if (!keep) { 19895 if (DEBUG_CLEAN_APKS) { 19896 Slog.i(TAG, " Removing package " + packageName); 19897 } 19898 mHandler.post(new Runnable() { 19899 public void run() { 19900 deletePackageX(packageName, userHandle, 0); 19901 } //end run 19902 }); 19903 } 19904 } 19905 } 19906 19907 /** Called by UserManagerService */ 19908 void createNewUser(int userHandle) { 19909 synchronized (mInstallLock) { 19910 mSettings.createNewUserLI(this, mInstaller, userHandle); 19911 } 19912 synchronized (mPackages) { 19913 applyFactoryDefaultBrowserLPw(userHandle); 19914 primeDomainVerificationsLPw(userHandle); 19915 } 19916 } 19917 19918 void newUserCreated(final int userHandle) { 19919 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19920 // If permission review for legacy apps is required, we represent 19921 // dagerous permissions for such apps as always granted runtime 19922 // permissions to keep per user flag state whether review is needed. 19923 // Hence, if a new user is added we have to propagate dangerous 19924 // permission grants for these legacy apps. 19925 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19926 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19927 | UPDATE_PERMISSIONS_REPLACE_ALL); 19928 } 19929 } 19930 19931 @Override 19932 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19933 mContext.enforceCallingOrSelfPermission( 19934 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19935 "Only package verification agents can read the verifier device identity"); 19936 19937 synchronized (mPackages) { 19938 return mSettings.getVerifierDeviceIdentityLPw(); 19939 } 19940 } 19941 19942 @Override 19943 public void setPermissionEnforced(String permission, boolean enforced) { 19944 // TODO: Now that we no longer change GID for storage, this should to away. 19945 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19946 "setPermissionEnforced"); 19947 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19948 synchronized (mPackages) { 19949 if (mSettings.mReadExternalStorageEnforced == null 19950 || mSettings.mReadExternalStorageEnforced != enforced) { 19951 mSettings.mReadExternalStorageEnforced = enforced; 19952 mSettings.writeLPr(); 19953 } 19954 } 19955 // kill any non-foreground processes so we restart them and 19956 // grant/revoke the GID. 19957 final IActivityManager am = ActivityManagerNative.getDefault(); 19958 if (am != null) { 19959 final long token = Binder.clearCallingIdentity(); 19960 try { 19961 am.killProcessesBelowForeground("setPermissionEnforcement"); 19962 } catch (RemoteException e) { 19963 } finally { 19964 Binder.restoreCallingIdentity(token); 19965 } 19966 } 19967 } else { 19968 throw new IllegalArgumentException("No selective enforcement for " + permission); 19969 } 19970 } 19971 19972 @Override 19973 @Deprecated 19974 public boolean isPermissionEnforced(String permission) { 19975 return true; 19976 } 19977 19978 @Override 19979 public boolean isStorageLow() { 19980 final long token = Binder.clearCallingIdentity(); 19981 try { 19982 final DeviceStorageMonitorInternal 19983 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19984 if (dsm != null) { 19985 return dsm.isMemoryLow(); 19986 } else { 19987 return false; 19988 } 19989 } finally { 19990 Binder.restoreCallingIdentity(token); 19991 } 19992 } 19993 19994 @Override 19995 public IPackageInstaller getPackageInstaller() { 19996 return mInstallerService; 19997 } 19998 19999 private boolean userNeedsBadging(int userId) { 20000 int index = mUserNeedsBadging.indexOfKey(userId); 20001 if (index < 0) { 20002 final UserInfo userInfo; 20003 final long token = Binder.clearCallingIdentity(); 20004 try { 20005 userInfo = sUserManager.getUserInfo(userId); 20006 } finally { 20007 Binder.restoreCallingIdentity(token); 20008 } 20009 final boolean b; 20010 if (userInfo != null && userInfo.isManagedProfile()) { 20011 b = true; 20012 } else { 20013 b = false; 20014 } 20015 mUserNeedsBadging.put(userId, b); 20016 return b; 20017 } 20018 return mUserNeedsBadging.valueAt(index); 20019 } 20020 20021 @Override 20022 public KeySet getKeySetByAlias(String packageName, String alias) { 20023 if (packageName == null || alias == null) { 20024 return null; 20025 } 20026 synchronized(mPackages) { 20027 final PackageParser.Package pkg = mPackages.get(packageName); 20028 if (pkg == null) { 20029 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20030 throw new IllegalArgumentException("Unknown package: " + packageName); 20031 } 20032 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20033 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20034 } 20035 } 20036 20037 @Override 20038 public KeySet getSigningKeySet(String packageName) { 20039 if (packageName == null) { 20040 return null; 20041 } 20042 synchronized(mPackages) { 20043 final PackageParser.Package pkg = mPackages.get(packageName); 20044 if (pkg == null) { 20045 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20046 throw new IllegalArgumentException("Unknown package: " + packageName); 20047 } 20048 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20049 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20050 throw new SecurityException("May not access signing KeySet of other apps."); 20051 } 20052 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20053 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20054 } 20055 } 20056 20057 @Override 20058 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20059 if (packageName == null || ks == null) { 20060 return false; 20061 } 20062 synchronized(mPackages) { 20063 final PackageParser.Package pkg = mPackages.get(packageName); 20064 if (pkg == null) { 20065 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20066 throw new IllegalArgumentException("Unknown package: " + packageName); 20067 } 20068 IBinder ksh = ks.getToken(); 20069 if (ksh instanceof KeySetHandle) { 20070 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20071 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20072 } 20073 return false; 20074 } 20075 } 20076 20077 @Override 20078 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20079 if (packageName == null || ks == null) { 20080 return false; 20081 } 20082 synchronized(mPackages) { 20083 final PackageParser.Package pkg = mPackages.get(packageName); 20084 if (pkg == null) { 20085 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20086 throw new IllegalArgumentException("Unknown package: " + packageName); 20087 } 20088 IBinder ksh = ks.getToken(); 20089 if (ksh instanceof KeySetHandle) { 20090 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20091 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20092 } 20093 return false; 20094 } 20095 } 20096 20097 private void deletePackageIfUnusedLPr(final String packageName) { 20098 PackageSetting ps = mSettings.mPackages.get(packageName); 20099 if (ps == null) { 20100 return; 20101 } 20102 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20103 // TODO Implement atomic delete if package is unused 20104 // It is currently possible that the package will be deleted even if it is installed 20105 // after this method returns. 20106 mHandler.post(new Runnable() { 20107 public void run() { 20108 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20109 } 20110 }); 20111 } 20112 } 20113 20114 /** 20115 * Check and throw if the given before/after packages would be considered a 20116 * downgrade. 20117 */ 20118 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20119 throws PackageManagerException { 20120 if (after.versionCode < before.mVersionCode) { 20121 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20122 "Update version code " + after.versionCode + " is older than current " 20123 + before.mVersionCode); 20124 } else if (after.versionCode == before.mVersionCode) { 20125 if (after.baseRevisionCode < before.baseRevisionCode) { 20126 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20127 "Update base revision code " + after.baseRevisionCode 20128 + " is older than current " + before.baseRevisionCode); 20129 } 20130 20131 if (!ArrayUtils.isEmpty(after.splitNames)) { 20132 for (int i = 0; i < after.splitNames.length; i++) { 20133 final String splitName = after.splitNames[i]; 20134 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20135 if (j != -1) { 20136 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20137 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20138 "Update split " + splitName + " revision code " 20139 + after.splitRevisionCodes[i] + " is older than current " 20140 + before.splitRevisionCodes[j]); 20141 } 20142 } 20143 } 20144 } 20145 } 20146 } 20147 20148 private static class MoveCallbacks extends Handler { 20149 private static final int MSG_CREATED = 1; 20150 private static final int MSG_STATUS_CHANGED = 2; 20151 20152 private final RemoteCallbackList<IPackageMoveObserver> 20153 mCallbacks = new RemoteCallbackList<>(); 20154 20155 private final SparseIntArray mLastStatus = new SparseIntArray(); 20156 20157 public MoveCallbacks(Looper looper) { 20158 super(looper); 20159 } 20160 20161 public void register(IPackageMoveObserver callback) { 20162 mCallbacks.register(callback); 20163 } 20164 20165 public void unregister(IPackageMoveObserver callback) { 20166 mCallbacks.unregister(callback); 20167 } 20168 20169 @Override 20170 public void handleMessage(Message msg) { 20171 final SomeArgs args = (SomeArgs) msg.obj; 20172 final int n = mCallbacks.beginBroadcast(); 20173 for (int i = 0; i < n; i++) { 20174 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20175 try { 20176 invokeCallback(callback, msg.what, args); 20177 } catch (RemoteException ignored) { 20178 } 20179 } 20180 mCallbacks.finishBroadcast(); 20181 args.recycle(); 20182 } 20183 20184 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20185 throws RemoteException { 20186 switch (what) { 20187 case MSG_CREATED: { 20188 callback.onCreated(args.argi1, (Bundle) args.arg2); 20189 break; 20190 } 20191 case MSG_STATUS_CHANGED: { 20192 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20193 break; 20194 } 20195 } 20196 } 20197 20198 private void notifyCreated(int moveId, Bundle extras) { 20199 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20200 20201 final SomeArgs args = SomeArgs.obtain(); 20202 args.argi1 = moveId; 20203 args.arg2 = extras; 20204 obtainMessage(MSG_CREATED, args).sendToTarget(); 20205 } 20206 20207 private void notifyStatusChanged(int moveId, int status) { 20208 notifyStatusChanged(moveId, status, -1); 20209 } 20210 20211 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20212 Slog.v(TAG, "Move " + moveId + " status " + status); 20213 20214 final SomeArgs args = SomeArgs.obtain(); 20215 args.argi1 = moveId; 20216 args.argi2 = status; 20217 args.arg3 = estMillis; 20218 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20219 20220 synchronized (mLastStatus) { 20221 mLastStatus.put(moveId, status); 20222 } 20223 } 20224 } 20225 20226 private final static class OnPermissionChangeListeners extends Handler { 20227 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20228 20229 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20230 new RemoteCallbackList<>(); 20231 20232 public OnPermissionChangeListeners(Looper looper) { 20233 super(looper); 20234 } 20235 20236 @Override 20237 public void handleMessage(Message msg) { 20238 switch (msg.what) { 20239 case MSG_ON_PERMISSIONS_CHANGED: { 20240 final int uid = msg.arg1; 20241 handleOnPermissionsChanged(uid); 20242 } break; 20243 } 20244 } 20245 20246 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20247 mPermissionListeners.register(listener); 20248 20249 } 20250 20251 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20252 mPermissionListeners.unregister(listener); 20253 } 20254 20255 public void onPermissionsChanged(int uid) { 20256 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20257 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20258 } 20259 } 20260 20261 private void handleOnPermissionsChanged(int uid) { 20262 final int count = mPermissionListeners.beginBroadcast(); 20263 try { 20264 for (int i = 0; i < count; i++) { 20265 IOnPermissionsChangeListener callback = mPermissionListeners 20266 .getBroadcastItem(i); 20267 try { 20268 callback.onPermissionsChanged(uid); 20269 } catch (RemoteException e) { 20270 Log.e(TAG, "Permission listener is dead", e); 20271 } 20272 } 20273 } finally { 20274 mPermissionListeners.finishBroadcast(); 20275 } 20276 } 20277 } 20278 20279 private class PackageManagerInternalImpl extends PackageManagerInternal { 20280 @Override 20281 public void setLocationPackagesProvider(PackagesProvider provider) { 20282 synchronized (mPackages) { 20283 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20284 } 20285 } 20286 20287 @Override 20288 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20289 synchronized (mPackages) { 20290 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20291 } 20292 } 20293 20294 @Override 20295 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20296 synchronized (mPackages) { 20297 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20298 } 20299 } 20300 20301 @Override 20302 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20303 synchronized (mPackages) { 20304 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20305 } 20306 } 20307 20308 @Override 20309 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20310 synchronized (mPackages) { 20311 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20312 } 20313 } 20314 20315 @Override 20316 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20317 synchronized (mPackages) { 20318 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20319 } 20320 } 20321 20322 @Override 20323 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20324 synchronized (mPackages) { 20325 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20326 packageName, userId); 20327 } 20328 } 20329 20330 @Override 20331 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20332 synchronized (mPackages) { 20333 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20334 packageName, userId); 20335 } 20336 } 20337 20338 @Override 20339 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20340 synchronized (mPackages) { 20341 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20342 packageName, userId); 20343 } 20344 } 20345 20346 @Override 20347 public void setKeepUninstalledPackages(final List<String> packageList) { 20348 Preconditions.checkNotNull(packageList); 20349 List<String> removedFromList = null; 20350 synchronized (mPackages) { 20351 if (mKeepUninstalledPackages != null) { 20352 final int packagesCount = mKeepUninstalledPackages.size(); 20353 for (int i = 0; i < packagesCount; i++) { 20354 String oldPackage = mKeepUninstalledPackages.get(i); 20355 if (packageList != null && packageList.contains(oldPackage)) { 20356 continue; 20357 } 20358 if (removedFromList == null) { 20359 removedFromList = new ArrayList<>(); 20360 } 20361 removedFromList.add(oldPackage); 20362 } 20363 } 20364 mKeepUninstalledPackages = new ArrayList<>(packageList); 20365 if (removedFromList != null) { 20366 final int removedCount = removedFromList.size(); 20367 for (int i = 0; i < removedCount; i++) { 20368 deletePackageIfUnusedLPr(removedFromList.get(i)); 20369 } 20370 } 20371 } 20372 } 20373 20374 @Override 20375 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20376 synchronized (mPackages) { 20377 // If we do not support permission review, done. 20378 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20379 return false; 20380 } 20381 20382 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20383 if (packageSetting == null) { 20384 return false; 20385 } 20386 20387 // Permission review applies only to apps not supporting the new permission model. 20388 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20389 return false; 20390 } 20391 20392 // Legacy apps have the permission and get user consent on launch. 20393 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20394 return permissionsState.isPermissionReviewRequired(userId); 20395 } 20396 } 20397 20398 @Override 20399 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20400 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20401 } 20402 20403 @Override 20404 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20405 int userId) { 20406 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20407 } 20408 } 20409 20410 @Override 20411 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20412 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20413 synchronized (mPackages) { 20414 final long identity = Binder.clearCallingIdentity(); 20415 try { 20416 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20417 packageNames, userId); 20418 } finally { 20419 Binder.restoreCallingIdentity(identity); 20420 } 20421 } 20422 } 20423 20424 private static void enforceSystemOrPhoneCaller(String tag) { 20425 int callingUid = Binder.getCallingUid(); 20426 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20427 throw new SecurityException( 20428 "Cannot call " + tag + " from UID " + callingUid); 20429 } 20430 } 20431 20432 boolean isHistoricalPackageUsageAvailable() { 20433 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20434 } 20435 20436 /** 20437 * Return a <b>copy</b> of the collection of packages known to the package manager. 20438 * @return A copy of the values of mPackages. 20439 */ 20440 Collection<PackageParser.Package> getPackages() { 20441 synchronized (mPackages) { 20442 return new ArrayList<>(mPackages.values()); 20443 } 20444 } 20445 20446 /** 20447 * Logs process start information (including base APK hash) to the security log. 20448 * @hide 20449 */ 20450 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20451 String apkFile, int pid) { 20452 if (!SecurityLog.isLoggingEnabled()) { 20453 return; 20454 } 20455 Bundle data = new Bundle(); 20456 data.putLong("startTimestamp", System.currentTimeMillis()); 20457 data.putString("processName", processName); 20458 data.putInt("uid", uid); 20459 data.putString("seinfo", seinfo); 20460 data.putString("apkFile", apkFile); 20461 data.putInt("pid", pid); 20462 Message msg = mProcessLoggingHandler.obtainMessage( 20463 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20464 msg.setData(data); 20465 mProcessLoggingHandler.sendMessage(msg); 20466 } 20467} 20468