PackageManagerService.java revision 7c5bcfc21ac87c56c57b1929ce04481fa0e116c7
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.ResourcesManager; 109import android.app.admin.DevicePolicyManagerInternal; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedInputStream; 268import java.io.BufferedOutputStream; 269import java.io.BufferedReader; 270import java.io.ByteArrayInputStream; 271import java.io.ByteArrayOutputStream; 272import java.io.File; 273import java.io.FileDescriptor; 274import java.io.FileInputStream; 275import java.io.FileNotFoundException; 276import java.io.FileOutputStream; 277import java.io.FileReader; 278import java.io.FilenameFilter; 279import java.io.IOException; 280import java.io.InputStream; 281import java.io.PrintWriter; 282import java.nio.charset.StandardCharsets; 283import java.security.DigestInputStream; 284import java.security.MessageDigest; 285import java.security.NoSuchAlgorithmException; 286import java.security.PublicKey; 287import java.security.cert.Certificate; 288import java.security.cert.CertificateEncodingException; 289import java.security.cert.CertificateException; 290import java.text.SimpleDateFormat; 291import java.util.ArrayList; 292import java.util.Arrays; 293import java.util.Collection; 294import java.util.Collections; 295import java.util.Comparator; 296import java.util.Date; 297import java.util.HashSet; 298import java.util.Iterator; 299import java.util.List; 300import java.util.Map; 301import java.util.Objects; 302import java.util.Set; 303import java.util.concurrent.CountDownLatch; 304import java.util.concurrent.TimeUnit; 305import java.util.concurrent.atomic.AtomicBoolean; 306import java.util.concurrent.atomic.AtomicInteger; 307import java.util.concurrent.atomic.AtomicLong; 308 309/** 310 * Keep track of all those APKs everywhere. 311 * <p> 312 * Internally there are two important locks: 313 * <ul> 314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 315 * and other related state. It is a fine-grained lock that should only be held 316 * momentarily, as it's one of the most contended locks in the system. 317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 318 * operations typically involve heavy lifting of application data on disk. Since 319 * {@code installd} is single-threaded, and it's operations can often be slow, 320 * this lock should never be acquired while already holding {@link #mPackages}. 321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 322 * holding {@link #mInstallLock}. 323 * </ul> 324 * Many internal methods rely on the caller to hold the appropriate locks, and 325 * this contract is expressed through method name suffixes: 326 * <ul> 327 * <li>fooLI(): the caller must hold {@link #mInstallLock} 328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 329 * being modified must be frozen 330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 332 * </ul> 333 * <p> 334 * Because this class is very central to the platform's security; please run all 335 * CTS and unit tests whenever making modifications: 336 * 337 * <pre> 338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 340 * </pre> 341 */ 342public class PackageManagerService extends IPackageManager.Stub { 343 static final String TAG = "PackageManager"; 344 static final boolean DEBUG_SETTINGS = false; 345 static final boolean DEBUG_PREFERRED = false; 346 static final boolean DEBUG_UPGRADE = false; 347 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 348 private static final boolean DEBUG_BACKUP = false; 349 private static final boolean DEBUG_INSTALL = false; 350 private static final boolean DEBUG_REMOVE = false; 351 private static final boolean DEBUG_BROADCASTS = false; 352 private static final boolean DEBUG_SHOW_INFO = false; 353 private static final boolean DEBUG_PACKAGE_INFO = false; 354 private static final boolean DEBUG_INTENT_MATCHING = false; 355 private static final boolean DEBUG_PACKAGE_SCANNING = false; 356 private static final boolean DEBUG_VERIFY = false; 357 private static final boolean DEBUG_FILTERS = false; 358 359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 361 // user, but by default initialize to this. 362 static final boolean DEBUG_DEXOPT = false; 363 364 private static final boolean DEBUG_ABI_SELECTION = false; 365 private static final boolean DEBUG_EPHEMERAL = false; 366 private static final boolean DEBUG_TRIAGED_MISSING = false; 367 private static final boolean DEBUG_APP_DATA = false; 368 369 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 370 371 private static final boolean DISABLE_EPHEMERAL_APPS = true; 372 373 private static final int RADIO_UID = Process.PHONE_UID; 374 private static final int LOG_UID = Process.LOG_UID; 375 private static final int NFC_UID = Process.NFC_UID; 376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 377 private static final int SHELL_UID = Process.SHELL_UID; 378 379 // Cap the size of permission trees that 3rd party apps can define 380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 381 382 // Suffix used during package installation when copying/moving 383 // package apks to install directory. 384 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 385 386 static final int SCAN_NO_DEX = 1<<1; 387 static final int SCAN_FORCE_DEX = 1<<2; 388 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 389 static final int SCAN_NEW_INSTALL = 1<<4; 390 static final int SCAN_NO_PATHS = 1<<5; 391 static final int SCAN_UPDATE_TIME = 1<<6; 392 static final int SCAN_DEFER_DEX = 1<<7; 393 static final int SCAN_BOOTING = 1<<8; 394 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 396 static final int SCAN_REPLACING = 1<<11; 397 static final int SCAN_REQUIRE_KNOWN = 1<<12; 398 static final int SCAN_MOVE = 1<<13; 399 static final int SCAN_INITIAL = 1<<14; 400 static final int SCAN_CHECK_ONLY = 1<<15; 401 static final int SCAN_DONT_KILL_APP = 1<<17; 402 static final int SCAN_IGNORE_FROZEN = 1<<18; 403 404 static final int REMOVE_CHATTY = 1<<16; 405 406 private static final int[] EMPTY_INT_ARRAY = new int[0]; 407 408 /** 409 * Timeout (in milliseconds) after which the watchdog should declare that 410 * our handler thread is wedged. The usual default for such things is one 411 * minute but we sometimes do very lengthy I/O operations on this thread, 412 * such as installing multi-gigabyte applications, so ours needs to be longer. 413 */ 414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 415 416 /** 417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 419 * settings entry if available, otherwise we use the hardcoded default. If it's been 420 * more than this long since the last fstrim, we force one during the boot sequence. 421 * 422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 423 * one gets run at the next available charging+idle time. This final mandatory 424 * no-fstrim check kicks in only of the other scheduling criteria is never met. 425 */ 426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 427 428 /** 429 * Whether verification is enabled by default. 430 */ 431 private static final boolean DEFAULT_VERIFY_ENABLE = true; 432 433 /** 434 * The default maximum time to wait for the verification agent to return in 435 * milliseconds. 436 */ 437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 438 439 /** 440 * The default response for package verification timeout. 441 * 442 * This can be either PackageManager.VERIFICATION_ALLOW or 443 * PackageManager.VERIFICATION_REJECT. 444 */ 445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 446 447 static final String PLATFORM_PACKAGE_NAME = "android"; 448 449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 450 451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 452 DEFAULT_CONTAINER_PACKAGE, 453 "com.android.defcontainer.DefaultContainerService"); 454 455 private static final String KILL_APP_REASON_GIDS_CHANGED = 456 "permission grant or revoke changed gids"; 457 458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 459 "permissions revoked"; 460 461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 462 463 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 464 465 /** Permission grant: not grant the permission. */ 466 private static final int GRANT_DENIED = 1; 467 468 /** Permission grant: grant the permission as an install permission. */ 469 private static final int GRANT_INSTALL = 2; 470 471 /** Permission grant: grant the permission as a runtime one. */ 472 private static final int GRANT_RUNTIME = 3; 473 474 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 475 private static final int GRANT_UPGRADE = 4; 476 477 /** Canonical intent used to identify what counts as a "web browser" app */ 478 private static final Intent sBrowserIntent; 479 static { 480 sBrowserIntent = new Intent(); 481 sBrowserIntent.setAction(Intent.ACTION_VIEW); 482 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 483 sBrowserIntent.setData(Uri.parse("http:")); 484 } 485 486 /** 487 * The set of all protected actions [i.e. those actions for which a high priority 488 * intent filter is disallowed]. 489 */ 490 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 491 static { 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 495 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 496 } 497 498 // Compilation reasons. 499 public static final int REASON_FIRST_BOOT = 0; 500 public static final int REASON_BOOT = 1; 501 public static final int REASON_INSTALL = 2; 502 public static final int REASON_BACKGROUND_DEXOPT = 3; 503 public static final int REASON_AB_OTA = 4; 504 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 505 public static final int REASON_SHARED_APK = 6; 506 public static final int REASON_FORCED_DEXOPT = 7; 507 508 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 509 510 /** Special library name that skips shared libraries check during compilation. */ 511 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 512 513 final ServiceThread mHandlerThread; 514 515 final PackageHandler mHandler; 516 517 private final ProcessLoggingHandler mProcessLoggingHandler; 518 519 /** 520 * Messages for {@link #mHandler} that need to wait for system ready before 521 * being dispatched. 522 */ 523 private ArrayList<Message> mPostSystemReadyMessages; 524 525 final int mSdkVersion = Build.VERSION.SDK_INT; 526 527 final Context mContext; 528 final boolean mFactoryTest; 529 final boolean mOnlyCore; 530 final DisplayMetrics mMetrics; 531 final int mDefParseFlags; 532 final String[] mSeparateProcesses; 533 final boolean mIsUpgrade; 534 final boolean mIsPreNUpgrade; 535 536 /** The location for ASEC container files on internal storage. */ 537 final String mAsecInternalPath; 538 539 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 540 // LOCK HELD. Can be called with mInstallLock held. 541 @GuardedBy("mInstallLock") 542 final Installer mInstaller; 543 544 /** Directory where installed third-party apps stored */ 545 final File mAppInstallDir; 546 final File mEphemeralInstallDir; 547 548 /** 549 * Directory to which applications installed internally have their 550 * 32 bit native libraries copied. 551 */ 552 private File mAppLib32InstallDir; 553 554 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 555 // apps. 556 final File mDrmAppPrivateInstallDir; 557 558 // ---------------------------------------------------------------- 559 560 // Lock for state used when installing and doing other long running 561 // operations. Methods that must be called with this lock held have 562 // the suffix "LI". 563 final Object mInstallLock = new Object(); 564 565 // ---------------------------------------------------------------- 566 567 // Keys are String (package name), values are Package. This also serves 568 // as the lock for the global state. Methods that must be called with 569 // this lock held have the prefix "LP". 570 @GuardedBy("mPackages") 571 final ArrayMap<String, PackageParser.Package> mPackages = 572 new ArrayMap<String, PackageParser.Package>(); 573 574 final ArrayMap<String, Set<String>> mKnownCodebase = 575 new ArrayMap<String, Set<String>>(); 576 577 // Tracks available target package names -> overlay package paths. 578 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 579 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 580 581 /** 582 * Tracks new system packages [received in an OTA] that we expect to 583 * find updated user-installed versions. Keys are package name, values 584 * are package location. 585 */ 586 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 587 /** 588 * Tracks high priority intent filters for protected actions. During boot, certain 589 * filter actions are protected and should never be allowed to have a high priority 590 * intent filter for them. However, there is one, and only one exception -- the 591 * setup wizard. It must be able to define a high priority intent filter for these 592 * actions to ensure there are no escapes from the wizard. We need to delay processing 593 * of these during boot as we need to look at all of the system packages in order 594 * to know which component is the setup wizard. 595 */ 596 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 597 /** 598 * Whether or not processing protected filters should be deferred. 599 */ 600 private boolean mDeferProtectedFilters = true; 601 602 /** 603 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 604 */ 605 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 606 /** 607 * Whether or not system app permissions should be promoted from install to runtime. 608 */ 609 boolean mPromoteSystemApps; 610 611 @GuardedBy("mPackages") 612 final Settings mSettings; 613 614 /** 615 * Set of package names that are currently "frozen", which means active 616 * surgery is being done on the code/data for that package. The platform 617 * will refuse to launch frozen packages to avoid race conditions. 618 * 619 * @see PackageFreezer 620 */ 621 @GuardedBy("mPackages") 622 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 623 624 boolean mRestoredSettings; 625 626 // System configuration read by SystemConfig. 627 final int[] mGlobalGids; 628 final SparseArray<ArraySet<String>> mSystemPermissions; 629 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 630 631 // If mac_permissions.xml was found for seinfo labeling. 632 boolean mFoundPolicyFile; 633 634 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 635 636 public static final class SharedLibraryEntry { 637 public final String path; 638 public final String apk; 639 640 SharedLibraryEntry(String _path, String _apk) { 641 path = _path; 642 apk = _apk; 643 } 644 } 645 646 // Currently known shared libraries. 647 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 648 new ArrayMap<String, SharedLibraryEntry>(); 649 650 // All available activities, for your resolving pleasure. 651 final ActivityIntentResolver mActivities = 652 new ActivityIntentResolver(); 653 654 // All available receivers, for your resolving pleasure. 655 final ActivityIntentResolver mReceivers = 656 new ActivityIntentResolver(); 657 658 // All available services, for your resolving pleasure. 659 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 660 661 // All available providers, for your resolving pleasure. 662 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 663 664 // Mapping from provider base names (first directory in content URI codePath) 665 // to the provider information. 666 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 667 new ArrayMap<String, PackageParser.Provider>(); 668 669 // Mapping from instrumentation class names to info about them. 670 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 671 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 672 673 // Mapping from permission names to info about them. 674 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 675 new ArrayMap<String, PackageParser.PermissionGroup>(); 676 677 // Packages whose data we have transfered into another package, thus 678 // should no longer exist. 679 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 680 681 // Broadcast actions that are only available to the system. 682 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 683 684 /** List of packages waiting for verification. */ 685 final SparseArray<PackageVerificationState> mPendingVerification 686 = new SparseArray<PackageVerificationState>(); 687 688 /** Set of packages associated with each app op permission. */ 689 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 690 691 final PackageInstallerService mInstallerService; 692 693 private final PackageDexOptimizer mPackageDexOptimizer; 694 695 private AtomicInteger mNextMoveId = new AtomicInteger(); 696 private final MoveCallbacks mMoveCallbacks; 697 698 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 699 700 // Cache of users who need badging. 701 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 702 703 /** Token for keys in mPendingVerification. */ 704 private int mPendingVerificationToken = 0; 705 706 volatile boolean mSystemReady; 707 volatile boolean mSafeMode; 708 volatile boolean mHasSystemUidErrors; 709 710 ApplicationInfo mAndroidApplication; 711 final ActivityInfo mResolveActivity = new ActivityInfo(); 712 final ResolveInfo mResolveInfo = new ResolveInfo(); 713 ComponentName mResolveComponentName; 714 PackageParser.Package mPlatformPackage; 715 ComponentName mCustomResolverComponentName; 716 717 boolean mResolverReplaced = false; 718 719 private final @Nullable ComponentName mIntentFilterVerifierComponent; 720 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 721 722 private int mIntentFilterVerificationToken = 0; 723 724 /** Component that knows whether or not an ephemeral application exists */ 725 final ComponentName mEphemeralResolverComponent; 726 /** The service connection to the ephemeral resolver */ 727 final EphemeralResolverConnection mEphemeralResolverConnection; 728 729 /** Component used to install ephemeral applications */ 730 final ComponentName mEphemeralInstallerComponent; 731 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 732 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 733 734 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 735 = new SparseArray<IntentFilterVerificationState>(); 736 737 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 738 new DefaultPermissionGrantPolicy(this); 739 740 // List of packages names to keep cached, even if they are uninstalled for all users 741 private List<String> mKeepUninstalledPackages; 742 743 private UserManagerInternal mUserManagerInternal; 744 745 private static class IFVerificationParams { 746 PackageParser.Package pkg; 747 boolean replacing; 748 int userId; 749 int verifierUid; 750 751 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 752 int _userId, int _verifierUid) { 753 pkg = _pkg; 754 replacing = _replacing; 755 userId = _userId; 756 replacing = _replacing; 757 verifierUid = _verifierUid; 758 } 759 } 760 761 private interface IntentFilterVerifier<T extends IntentFilter> { 762 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 763 T filter, String packageName); 764 void startVerifications(int userId); 765 void receiveVerificationResponse(int verificationId); 766 } 767 768 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 769 private Context mContext; 770 private ComponentName mIntentFilterVerifierComponent; 771 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 772 773 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 774 mContext = context; 775 mIntentFilterVerifierComponent = verifierComponent; 776 } 777 778 private String getDefaultScheme() { 779 return IntentFilter.SCHEME_HTTPS; 780 } 781 782 @Override 783 public void startVerifications(int userId) { 784 // Launch verifications requests 785 int count = mCurrentIntentFilterVerifications.size(); 786 for (int n=0; n<count; n++) { 787 int verificationId = mCurrentIntentFilterVerifications.get(n); 788 final IntentFilterVerificationState ivs = 789 mIntentFilterVerificationStates.get(verificationId); 790 791 String packageName = ivs.getPackageName(); 792 793 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 794 final int filterCount = filters.size(); 795 ArraySet<String> domainsSet = new ArraySet<>(); 796 for (int m=0; m<filterCount; m++) { 797 PackageParser.ActivityIntentInfo filter = filters.get(m); 798 domainsSet.addAll(filter.getHostsList()); 799 } 800 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 801 synchronized (mPackages) { 802 if (mSettings.createIntentFilterVerificationIfNeededLPw( 803 packageName, domainsList) != null) { 804 scheduleWriteSettingsLocked(); 805 } 806 } 807 sendVerificationRequest(userId, verificationId, ivs); 808 } 809 mCurrentIntentFilterVerifications.clear(); 810 } 811 812 private void sendVerificationRequest(int userId, int verificationId, 813 IntentFilterVerificationState ivs) { 814 815 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 816 verificationIntent.putExtra( 817 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 818 verificationId); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 821 getDefaultScheme()); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 824 ivs.getHostsString()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 827 ivs.getPackageName()); 828 verificationIntent.setComponent(mIntentFilterVerifierComponent); 829 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 830 831 UserHandle user = new UserHandle(userId); 832 mContext.sendBroadcastAsUser(verificationIntent, user); 833 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 834 "Sending IntentFilter verification broadcast"); 835 } 836 837 public void receiveVerificationResponse(int verificationId) { 838 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 839 840 final boolean verified = ivs.isVerified(); 841 842 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 843 final int count = filters.size(); 844 if (DEBUG_DOMAIN_VERIFICATION) { 845 Slog.i(TAG, "Received verification response " + verificationId 846 + " for " + count + " filters, verified=" + verified); 847 } 848 for (int n=0; n<count; n++) { 849 PackageParser.ActivityIntentInfo filter = filters.get(n); 850 filter.setVerified(verified); 851 852 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 853 + " verified with result:" + verified + " and hosts:" 854 + ivs.getHostsString()); 855 } 856 857 mIntentFilterVerificationStates.remove(verificationId); 858 859 final String packageName = ivs.getPackageName(); 860 IntentFilterVerificationInfo ivi = null; 861 862 synchronized (mPackages) { 863 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 864 } 865 if (ivi == null) { 866 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 867 + verificationId + " packageName:" + packageName); 868 return; 869 } 870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 871 "Updating IntentFilterVerificationInfo for package " + packageName 872 +" verificationId:" + verificationId); 873 874 synchronized (mPackages) { 875 if (verified) { 876 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 877 } else { 878 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 879 } 880 scheduleWriteSettingsLocked(); 881 882 final int userId = ivs.getUserId(); 883 if (userId != UserHandle.USER_ALL) { 884 final int userStatus = 885 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 886 887 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 888 boolean needUpdate = false; 889 890 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 891 // already been set by the User thru the Disambiguation dialog 892 switch (userStatus) { 893 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 894 if (verified) { 895 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 896 } else { 897 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 898 } 899 needUpdate = true; 900 break; 901 902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 903 if (verified) { 904 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 905 needUpdate = true; 906 } 907 break; 908 909 default: 910 // Nothing to do 911 } 912 913 if (needUpdate) { 914 mSettings.updateIntentFilterVerificationStatusLPw( 915 packageName, updatedStatus, userId); 916 scheduleWritePackageRestrictionsLocked(userId); 917 } 918 } 919 } 920 } 921 922 @Override 923 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 924 ActivityIntentInfo filter, String packageName) { 925 if (!hasValidDomains(filter)) { 926 return false; 927 } 928 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 929 if (ivs == null) { 930 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 931 packageName); 932 } 933 if (DEBUG_DOMAIN_VERIFICATION) { 934 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 935 } 936 ivs.addFilter(filter); 937 return true; 938 } 939 940 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 941 int userId, int verificationId, String packageName) { 942 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 943 verifierUid, userId, packageName); 944 ivs.setPendingState(); 945 synchronized (mPackages) { 946 mIntentFilterVerificationStates.append(verificationId, ivs); 947 mCurrentIntentFilterVerifications.add(verificationId); 948 } 949 return ivs; 950 } 951 } 952 953 private static boolean hasValidDomains(ActivityIntentInfo filter) { 954 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 955 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 956 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 957 } 958 959 // Set of pending broadcasts for aggregating enable/disable of components. 960 static class PendingPackageBroadcasts { 961 // for each user id, a map of <package name -> components within that package> 962 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 963 964 public PendingPackageBroadcasts() { 965 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 966 } 967 968 public ArrayList<String> get(int userId, String packageName) { 969 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 970 return packages.get(packageName); 971 } 972 973 public void put(int userId, String packageName, ArrayList<String> components) { 974 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 975 packages.put(packageName, components); 976 } 977 978 public void remove(int userId, String packageName) { 979 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 980 if (packages != null) { 981 packages.remove(packageName); 982 } 983 } 984 985 public void remove(int userId) { 986 mUidMap.remove(userId); 987 } 988 989 public int userIdCount() { 990 return mUidMap.size(); 991 } 992 993 public int userIdAt(int n) { 994 return mUidMap.keyAt(n); 995 } 996 997 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 998 return mUidMap.get(userId); 999 } 1000 1001 public int size() { 1002 // total number of pending broadcast entries across all userIds 1003 int num = 0; 1004 for (int i = 0; i< mUidMap.size(); i++) { 1005 num += mUidMap.valueAt(i).size(); 1006 } 1007 return num; 1008 } 1009 1010 public void clear() { 1011 mUidMap.clear(); 1012 } 1013 1014 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1015 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1016 if (map == null) { 1017 map = new ArrayMap<String, ArrayList<String>>(); 1018 mUidMap.put(userId, map); 1019 } 1020 return map; 1021 } 1022 } 1023 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1024 1025 // Service Connection to remote media container service to copy 1026 // package uri's from external media onto secure containers 1027 // or internal storage. 1028 private IMediaContainerService mContainerService = null; 1029 1030 static final int SEND_PENDING_BROADCAST = 1; 1031 static final int MCS_BOUND = 3; 1032 static final int END_COPY = 4; 1033 static final int INIT_COPY = 5; 1034 static final int MCS_UNBIND = 6; 1035 static final int START_CLEANING_PACKAGE = 7; 1036 static final int FIND_INSTALL_LOC = 8; 1037 static final int POST_INSTALL = 9; 1038 static final int MCS_RECONNECT = 10; 1039 static final int MCS_GIVE_UP = 11; 1040 static final int UPDATED_MEDIA_STATUS = 12; 1041 static final int WRITE_SETTINGS = 13; 1042 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1043 static final int PACKAGE_VERIFIED = 15; 1044 static final int CHECK_PENDING_VERIFICATION = 16; 1045 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1046 static final int INTENT_FILTER_VERIFIED = 18; 1047 static final int WRITE_PACKAGE_LIST = 19; 1048 1049 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1050 1051 // Delay time in millisecs 1052 static final int BROADCAST_DELAY = 10 * 1000; 1053 1054 static UserManagerService sUserManager; 1055 1056 // Stores a list of users whose package restrictions file needs to be updated 1057 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1058 1059 final private DefaultContainerConnection mDefContainerConn = 1060 new DefaultContainerConnection(); 1061 class DefaultContainerConnection implements ServiceConnection { 1062 public void onServiceConnected(ComponentName name, IBinder service) { 1063 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1064 IMediaContainerService imcs = 1065 IMediaContainerService.Stub.asInterface(service); 1066 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1067 } 1068 1069 public void onServiceDisconnected(ComponentName name) { 1070 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1071 } 1072 } 1073 1074 // Recordkeeping of restore-after-install operations that are currently in flight 1075 // between the Package Manager and the Backup Manager 1076 static class PostInstallData { 1077 public InstallArgs args; 1078 public PackageInstalledInfo res; 1079 1080 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1081 args = _a; 1082 res = _r; 1083 } 1084 } 1085 1086 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1087 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1088 1089 // XML tags for backup/restore of various bits of state 1090 private static final String TAG_PREFERRED_BACKUP = "pa"; 1091 private static final String TAG_DEFAULT_APPS = "da"; 1092 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1093 1094 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1095 private static final String TAG_ALL_GRANTS = "rt-grants"; 1096 private static final String TAG_GRANT = "grant"; 1097 private static final String ATTR_PACKAGE_NAME = "pkg"; 1098 1099 private static final String TAG_PERMISSION = "perm"; 1100 private static final String ATTR_PERMISSION_NAME = "name"; 1101 private static final String ATTR_IS_GRANTED = "g"; 1102 private static final String ATTR_USER_SET = "set"; 1103 private static final String ATTR_USER_FIXED = "fixed"; 1104 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1105 1106 // System/policy permission grants are not backed up 1107 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1108 FLAG_PERMISSION_POLICY_FIXED 1109 | FLAG_PERMISSION_SYSTEM_FIXED 1110 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1111 1112 // And we back up these user-adjusted states 1113 private static final int USER_RUNTIME_GRANT_MASK = 1114 FLAG_PERMISSION_USER_SET 1115 | FLAG_PERMISSION_USER_FIXED 1116 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1117 1118 final @Nullable String mRequiredVerifierPackage; 1119 final @NonNull String mRequiredInstallerPackage; 1120 final @Nullable String mSetupWizardPackage; 1121 final @NonNull String mServicesSystemSharedLibraryPackageName; 1122 final @NonNull String mSharedSystemSharedLibraryPackageName; 1123 1124 private final PackageUsage mPackageUsage = new PackageUsage(); 1125 1126 private class PackageUsage { 1127 private static final int WRITE_INTERVAL 1128 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1129 1130 private final Object mFileLock = new Object(); 1131 private final AtomicLong mLastWritten = new AtomicLong(0); 1132 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1133 1134 private boolean mIsHistoricalPackageUsageAvailable = true; 1135 1136 boolean isHistoricalPackageUsageAvailable() { 1137 return mIsHistoricalPackageUsageAvailable; 1138 } 1139 1140 void write(boolean force) { 1141 if (force) { 1142 writeInternal(); 1143 return; 1144 } 1145 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1146 && !DEBUG_DEXOPT) { 1147 return; 1148 } 1149 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1150 new Thread("PackageUsage_DiskWriter") { 1151 @Override 1152 public void run() { 1153 try { 1154 writeInternal(); 1155 } finally { 1156 mBackgroundWriteRunning.set(false); 1157 } 1158 } 1159 }.start(); 1160 } 1161 } 1162 1163 private void writeInternal() { 1164 synchronized (mPackages) { 1165 synchronized (mFileLock) { 1166 AtomicFile file = getFile(); 1167 FileOutputStream f = null; 1168 try { 1169 f = file.startWrite(); 1170 BufferedOutputStream out = new BufferedOutputStream(f); 1171 FileUtils.setPermissions(file.getBaseFile().getPath(), 1172 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1173 StringBuilder sb = new StringBuilder(); 1174 1175 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1176 sb.append('\n'); 1177 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1178 1179 for (PackageParser.Package pkg : mPackages.values()) { 1180 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1181 continue; 1182 } 1183 sb.setLength(0); 1184 sb.append(pkg.packageName); 1185 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1186 sb.append(' '); 1187 sb.append(usageTimeInMillis); 1188 } 1189 sb.append('\n'); 1190 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1191 } 1192 out.flush(); 1193 file.finishWrite(f); 1194 } catch (IOException e) { 1195 if (f != null) { 1196 file.failWrite(f); 1197 } 1198 Log.e(TAG, "Failed to write package usage times", e); 1199 } 1200 } 1201 } 1202 mLastWritten.set(SystemClock.elapsedRealtime()); 1203 } 1204 1205 void readLP() { 1206 synchronized (mFileLock) { 1207 AtomicFile file = getFile(); 1208 BufferedInputStream in = null; 1209 try { 1210 in = new BufferedInputStream(file.openRead()); 1211 StringBuffer sb = new StringBuffer(); 1212 1213 String firstLine = readLine(in, sb); 1214 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1215 readVersion1LP(in, sb); 1216 } else { 1217 readVersion0LP(in, sb, firstLine); 1218 } 1219 } catch (FileNotFoundException expected) { 1220 mIsHistoricalPackageUsageAvailable = false; 1221 } catch (IOException e) { 1222 Log.w(TAG, "Failed to read package usage times", e); 1223 } finally { 1224 IoUtils.closeQuietly(in); 1225 } 1226 } 1227 mLastWritten.set(SystemClock.elapsedRealtime()); 1228 } 1229 1230 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1231 throws IOException { 1232 // Initial version of the file had no version number and stored one 1233 // package-timestamp pair per line. 1234 // Note that the first line has already been read from the InputStream. 1235 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1236 String[] tokens = line.split(" "); 1237 if (tokens.length != 2) { 1238 throw new IOException("Failed to parse " + line + 1239 " as package-timestamp pair."); 1240 } 1241 1242 String packageName = tokens[0]; 1243 PackageParser.Package pkg = mPackages.get(packageName); 1244 if (pkg == null) { 1245 continue; 1246 } 1247 1248 long timestamp = parseAsLong(tokens[1]); 1249 for (int reason = 0; 1250 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1251 reason++) { 1252 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1253 } 1254 } 1255 } 1256 1257 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1258 // Version 1 of the file started with the corresponding version 1259 // number and then stored a package name and eight timestamps per line. 1260 String line; 1261 while ((line = readLine(in, sb)) != null) { 1262 String[] tokens = line.split(" "); 1263 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1264 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1265 } 1266 1267 String packageName = tokens[0]; 1268 PackageParser.Package pkg = mPackages.get(packageName); 1269 if (pkg == null) { 1270 continue; 1271 } 1272 1273 for (int reason = 0; 1274 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1275 reason++) { 1276 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1277 } 1278 } 1279 } 1280 1281 private long parseAsLong(String token) throws IOException { 1282 try { 1283 return Long.parseLong(token); 1284 } catch (NumberFormatException e) { 1285 throw new IOException("Failed to parse " + token + " as a long.", e); 1286 } 1287 } 1288 1289 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1290 return readToken(in, sb, '\n'); 1291 } 1292 1293 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1294 throws IOException { 1295 sb.setLength(0); 1296 while (true) { 1297 int ch = in.read(); 1298 if (ch == -1) { 1299 if (sb.length() == 0) { 1300 return null; 1301 } 1302 throw new IOException("Unexpected EOF"); 1303 } 1304 if (ch == endOfToken) { 1305 return sb.toString(); 1306 } 1307 sb.append((char)ch); 1308 } 1309 } 1310 1311 private AtomicFile getFile() { 1312 File dataDir = Environment.getDataDirectory(); 1313 File systemDir = new File(dataDir, "system"); 1314 File fname = new File(systemDir, "package-usage.list"); 1315 return new AtomicFile(fname); 1316 } 1317 1318 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1319 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1320 } 1321 1322 class PackageHandler extends Handler { 1323 private boolean mBound = false; 1324 final ArrayList<HandlerParams> mPendingInstalls = 1325 new ArrayList<HandlerParams>(); 1326 1327 private boolean connectToService() { 1328 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1329 " DefaultContainerService"); 1330 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1331 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1332 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1333 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1334 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1335 mBound = true; 1336 return true; 1337 } 1338 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1339 return false; 1340 } 1341 1342 private void disconnectService() { 1343 mContainerService = null; 1344 mBound = false; 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1346 mContext.unbindService(mDefContainerConn); 1347 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1348 } 1349 1350 PackageHandler(Looper looper) { 1351 super(looper); 1352 } 1353 1354 public void handleMessage(Message msg) { 1355 try { 1356 doHandleMessage(msg); 1357 } finally { 1358 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1359 } 1360 } 1361 1362 void doHandleMessage(Message msg) { 1363 switch (msg.what) { 1364 case INIT_COPY: { 1365 HandlerParams params = (HandlerParams) msg.obj; 1366 int idx = mPendingInstalls.size(); 1367 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1368 // If a bind was already initiated we dont really 1369 // need to do anything. The pending install 1370 // will be processed later on. 1371 if (!mBound) { 1372 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1373 System.identityHashCode(mHandler)); 1374 // If this is the only one pending we might 1375 // have to bind to the service again. 1376 if (!connectToService()) { 1377 Slog.e(TAG, "Failed to bind to media container service"); 1378 params.serviceError(); 1379 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1380 System.identityHashCode(mHandler)); 1381 if (params.traceMethod != null) { 1382 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1383 params.traceCookie); 1384 } 1385 return; 1386 } else { 1387 // Once we bind to the service, the first 1388 // pending request will be processed. 1389 mPendingInstalls.add(idx, params); 1390 } 1391 } else { 1392 mPendingInstalls.add(idx, params); 1393 // Already bound to the service. Just make 1394 // sure we trigger off processing the first request. 1395 if (idx == 0) { 1396 mHandler.sendEmptyMessage(MCS_BOUND); 1397 } 1398 } 1399 break; 1400 } 1401 case MCS_BOUND: { 1402 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1403 if (msg.obj != null) { 1404 mContainerService = (IMediaContainerService) msg.obj; 1405 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1406 System.identityHashCode(mHandler)); 1407 } 1408 if (mContainerService == null) { 1409 if (!mBound) { 1410 // Something seriously wrong since we are not bound and we are not 1411 // waiting for connection. Bail out. 1412 Slog.e(TAG, "Cannot bind to media container service"); 1413 for (HandlerParams params : mPendingInstalls) { 1414 // Indicate service bind error 1415 params.serviceError(); 1416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1417 System.identityHashCode(params)); 1418 if (params.traceMethod != null) { 1419 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1420 params.traceMethod, params.traceCookie); 1421 } 1422 return; 1423 } 1424 mPendingInstalls.clear(); 1425 } else { 1426 Slog.w(TAG, "Waiting to connect to media container service"); 1427 } 1428 } else if (mPendingInstalls.size() > 0) { 1429 HandlerParams params = mPendingInstalls.get(0); 1430 if (params != null) { 1431 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1432 System.identityHashCode(params)); 1433 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1434 if (params.startCopy()) { 1435 // We are done... look for more work or to 1436 // go idle. 1437 if (DEBUG_SD_INSTALL) Log.i(TAG, 1438 "Checking for more work or unbind..."); 1439 // Delete pending install 1440 if (mPendingInstalls.size() > 0) { 1441 mPendingInstalls.remove(0); 1442 } 1443 if (mPendingInstalls.size() == 0) { 1444 if (mBound) { 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, 1446 "Posting delayed MCS_UNBIND"); 1447 removeMessages(MCS_UNBIND); 1448 Message ubmsg = obtainMessage(MCS_UNBIND); 1449 // Unbind after a little delay, to avoid 1450 // continual thrashing. 1451 sendMessageDelayed(ubmsg, 10000); 1452 } 1453 } else { 1454 // There are more pending requests in queue. 1455 // Just post MCS_BOUND message to trigger processing 1456 // of next pending install. 1457 if (DEBUG_SD_INSTALL) Log.i(TAG, 1458 "Posting MCS_BOUND for next work"); 1459 mHandler.sendEmptyMessage(MCS_BOUND); 1460 } 1461 } 1462 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1463 } 1464 } else { 1465 // Should never happen ideally. 1466 Slog.w(TAG, "Empty queue"); 1467 } 1468 break; 1469 } 1470 case MCS_RECONNECT: { 1471 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1472 if (mPendingInstalls.size() > 0) { 1473 if (mBound) { 1474 disconnectService(); 1475 } 1476 if (!connectToService()) { 1477 Slog.e(TAG, "Failed to bind to media container service"); 1478 for (HandlerParams params : mPendingInstalls) { 1479 // Indicate service bind error 1480 params.serviceError(); 1481 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1482 System.identityHashCode(params)); 1483 } 1484 mPendingInstalls.clear(); 1485 } 1486 } 1487 break; 1488 } 1489 case MCS_UNBIND: { 1490 // If there is no actual work left, then time to unbind. 1491 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1492 1493 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1494 if (mBound) { 1495 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1496 1497 disconnectService(); 1498 } 1499 } else if (mPendingInstalls.size() > 0) { 1500 // There are more pending requests in queue. 1501 // Just post MCS_BOUND message to trigger processing 1502 // of next pending install. 1503 mHandler.sendEmptyMessage(MCS_BOUND); 1504 } 1505 1506 break; 1507 } 1508 case MCS_GIVE_UP: { 1509 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1510 HandlerParams params = mPendingInstalls.remove(0); 1511 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1512 System.identityHashCode(params)); 1513 break; 1514 } 1515 case SEND_PENDING_BROADCAST: { 1516 String packages[]; 1517 ArrayList<String> components[]; 1518 int size = 0; 1519 int uids[]; 1520 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1521 synchronized (mPackages) { 1522 if (mPendingBroadcasts == null) { 1523 return; 1524 } 1525 size = mPendingBroadcasts.size(); 1526 if (size <= 0) { 1527 // Nothing to be done. Just return 1528 return; 1529 } 1530 packages = new String[size]; 1531 components = new ArrayList[size]; 1532 uids = new int[size]; 1533 int i = 0; // filling out the above arrays 1534 1535 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1536 int packageUserId = mPendingBroadcasts.userIdAt(n); 1537 Iterator<Map.Entry<String, ArrayList<String>>> it 1538 = mPendingBroadcasts.packagesForUserId(packageUserId) 1539 .entrySet().iterator(); 1540 while (it.hasNext() && i < size) { 1541 Map.Entry<String, ArrayList<String>> ent = it.next(); 1542 packages[i] = ent.getKey(); 1543 components[i] = ent.getValue(); 1544 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1545 uids[i] = (ps != null) 1546 ? UserHandle.getUid(packageUserId, ps.appId) 1547 : -1; 1548 i++; 1549 } 1550 } 1551 size = i; 1552 mPendingBroadcasts.clear(); 1553 } 1554 // Send broadcasts 1555 for (int i = 0; i < size; i++) { 1556 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1557 } 1558 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1559 break; 1560 } 1561 case START_CLEANING_PACKAGE: { 1562 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1563 final String packageName = (String)msg.obj; 1564 final int userId = msg.arg1; 1565 final boolean andCode = msg.arg2 != 0; 1566 synchronized (mPackages) { 1567 if (userId == UserHandle.USER_ALL) { 1568 int[] users = sUserManager.getUserIds(); 1569 for (int user : users) { 1570 mSettings.addPackageToCleanLPw( 1571 new PackageCleanItem(user, packageName, andCode)); 1572 } 1573 } else { 1574 mSettings.addPackageToCleanLPw( 1575 new PackageCleanItem(userId, packageName, andCode)); 1576 } 1577 } 1578 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1579 startCleaningPackages(); 1580 } break; 1581 case POST_INSTALL: { 1582 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1583 1584 PostInstallData data = mRunningInstalls.get(msg.arg1); 1585 final boolean didRestore = (msg.arg2 != 0); 1586 mRunningInstalls.delete(msg.arg1); 1587 1588 if (data != null) { 1589 InstallArgs args = data.args; 1590 PackageInstalledInfo parentRes = data.res; 1591 1592 final boolean grantPermissions = (args.installFlags 1593 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1594 final boolean killApp = (args.installFlags 1595 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1596 final String[] grantedPermissions = args.installGrantPermissions; 1597 1598 // Handle the parent package 1599 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1600 grantedPermissions, didRestore, args.installerPackageName, 1601 args.observer); 1602 1603 // Handle the child packages 1604 final int childCount = (parentRes.addedChildPackages != null) 1605 ? parentRes.addedChildPackages.size() : 0; 1606 for (int i = 0; i < childCount; i++) { 1607 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1608 handlePackagePostInstall(childRes, grantPermissions, killApp, 1609 grantedPermissions, false, args.installerPackageName, 1610 args.observer); 1611 } 1612 1613 // Log tracing if needed 1614 if (args.traceMethod != null) { 1615 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1616 args.traceCookie); 1617 } 1618 } else { 1619 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1620 } 1621 1622 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1623 } break; 1624 case UPDATED_MEDIA_STATUS: { 1625 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1626 boolean reportStatus = msg.arg1 == 1; 1627 boolean doGc = msg.arg2 == 1; 1628 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1629 if (doGc) { 1630 // Force a gc to clear up stale containers. 1631 Runtime.getRuntime().gc(); 1632 } 1633 if (msg.obj != null) { 1634 @SuppressWarnings("unchecked") 1635 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1637 // Unload containers 1638 unloadAllContainers(args); 1639 } 1640 if (reportStatus) { 1641 try { 1642 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1643 PackageHelper.getMountService().finishMediaUpdate(); 1644 } catch (RemoteException e) { 1645 Log.e(TAG, "MountService not running?"); 1646 } 1647 } 1648 } break; 1649 case WRITE_SETTINGS: { 1650 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1651 synchronized (mPackages) { 1652 removeMessages(WRITE_SETTINGS); 1653 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1654 mSettings.writeLPr(); 1655 mDirtyUsers.clear(); 1656 } 1657 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1658 } break; 1659 case WRITE_PACKAGE_RESTRICTIONS: { 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1661 synchronized (mPackages) { 1662 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1663 for (int userId : mDirtyUsers) { 1664 mSettings.writePackageRestrictionsLPr(userId); 1665 } 1666 mDirtyUsers.clear(); 1667 } 1668 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1669 } break; 1670 case WRITE_PACKAGE_LIST: { 1671 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1672 synchronized (mPackages) { 1673 removeMessages(WRITE_PACKAGE_LIST); 1674 mSettings.writePackageListLPr(msg.arg1); 1675 } 1676 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1677 } break; 1678 case CHECK_PENDING_VERIFICATION: { 1679 final int verificationId = msg.arg1; 1680 final PackageVerificationState state = mPendingVerification.get(verificationId); 1681 1682 if ((state != null) && !state.timeoutExtended()) { 1683 final InstallArgs args = state.getInstallArgs(); 1684 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1685 1686 Slog.i(TAG, "Verification timed out for " + originUri); 1687 mPendingVerification.remove(verificationId); 1688 1689 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1690 1691 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1692 Slog.i(TAG, "Continuing with installation of " + originUri); 1693 state.setVerifierResponse(Binder.getCallingUid(), 1694 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1695 broadcastPackageVerified(verificationId, originUri, 1696 PackageManager.VERIFICATION_ALLOW, 1697 state.getInstallArgs().getUser()); 1698 try { 1699 ret = args.copyApk(mContainerService, true); 1700 } catch (RemoteException e) { 1701 Slog.e(TAG, "Could not contact the ContainerService"); 1702 } 1703 } else { 1704 broadcastPackageVerified(verificationId, originUri, 1705 PackageManager.VERIFICATION_REJECT, 1706 state.getInstallArgs().getUser()); 1707 } 1708 1709 Trace.asyncTraceEnd( 1710 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1711 1712 processPendingInstall(args, ret); 1713 mHandler.sendEmptyMessage(MCS_UNBIND); 1714 } 1715 break; 1716 } 1717 case PACKAGE_VERIFIED: { 1718 final int verificationId = msg.arg1; 1719 1720 final PackageVerificationState state = mPendingVerification.get(verificationId); 1721 if (state == null) { 1722 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1723 break; 1724 } 1725 1726 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1727 1728 state.setVerifierResponse(response.callerUid, response.code); 1729 1730 if (state.isVerificationComplete()) { 1731 mPendingVerification.remove(verificationId); 1732 1733 final InstallArgs args = state.getInstallArgs(); 1734 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1735 1736 int ret; 1737 if (state.isInstallAllowed()) { 1738 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1739 broadcastPackageVerified(verificationId, originUri, 1740 response.code, state.getInstallArgs().getUser()); 1741 try { 1742 ret = args.copyApk(mContainerService, true); 1743 } catch (RemoteException e) { 1744 Slog.e(TAG, "Could not contact the ContainerService"); 1745 } 1746 } else { 1747 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1748 } 1749 1750 Trace.asyncTraceEnd( 1751 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1752 1753 processPendingInstall(args, ret); 1754 mHandler.sendEmptyMessage(MCS_UNBIND); 1755 } 1756 1757 break; 1758 } 1759 case START_INTENT_FILTER_VERIFICATIONS: { 1760 IFVerificationParams params = (IFVerificationParams) msg.obj; 1761 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1762 params.replacing, params.pkg); 1763 break; 1764 } 1765 case INTENT_FILTER_VERIFIED: { 1766 final int verificationId = msg.arg1; 1767 1768 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1769 verificationId); 1770 if (state == null) { 1771 Slog.w(TAG, "Invalid IntentFilter verification token " 1772 + verificationId + " received"); 1773 break; 1774 } 1775 1776 final int userId = state.getUserId(); 1777 1778 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1779 "Processing IntentFilter verification with token:" 1780 + verificationId + " and userId:" + userId); 1781 1782 final IntentFilterVerificationResponse response = 1783 (IntentFilterVerificationResponse) msg.obj; 1784 1785 state.setVerifierResponse(response.callerUid, response.code); 1786 1787 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1788 "IntentFilter verification with token:" + verificationId 1789 + " and userId:" + userId 1790 + " is settings verifier response with response code:" 1791 + response.code); 1792 1793 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1794 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1795 + response.getFailedDomainsString()); 1796 } 1797 1798 if (state.isVerificationComplete()) { 1799 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1800 } else { 1801 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1802 "IntentFilter verification with token:" + verificationId 1803 + " was not said to be complete"); 1804 } 1805 1806 break; 1807 } 1808 } 1809 } 1810 } 1811 1812 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1813 boolean killApp, String[] grantedPermissions, 1814 boolean launchedForRestore, String installerPackage, 1815 IPackageInstallObserver2 installObserver) { 1816 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1817 // Send the removed broadcasts 1818 if (res.removedInfo != null) { 1819 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1820 } 1821 1822 // Now that we successfully installed the package, grant runtime 1823 // permissions if requested before broadcasting the install. 1824 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1825 >= Build.VERSION_CODES.M) { 1826 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1827 } 1828 1829 final boolean update = res.removedInfo != null 1830 && res.removedInfo.removedPackage != null; 1831 1832 // If this is the first time we have child packages for a disabled privileged 1833 // app that had no children, we grant requested runtime permissions to the new 1834 // children if the parent on the system image had them already granted. 1835 if (res.pkg.parentPackage != null) { 1836 synchronized (mPackages) { 1837 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1838 } 1839 } 1840 1841 synchronized (mPackages) { 1842 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1843 } 1844 1845 final String packageName = res.pkg.applicationInfo.packageName; 1846 Bundle extras = new Bundle(1); 1847 extras.putInt(Intent.EXTRA_UID, res.uid); 1848 1849 // Determine the set of users who are adding this package for 1850 // the first time vs. those who are seeing an update. 1851 int[] firstUsers = EMPTY_INT_ARRAY; 1852 int[] updateUsers = EMPTY_INT_ARRAY; 1853 if (res.origUsers == null || res.origUsers.length == 0) { 1854 firstUsers = res.newUsers; 1855 } else { 1856 for (int newUser : res.newUsers) { 1857 boolean isNew = true; 1858 for (int origUser : res.origUsers) { 1859 if (origUser == newUser) { 1860 isNew = false; 1861 break; 1862 } 1863 } 1864 if (isNew) { 1865 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1866 } else { 1867 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1868 } 1869 } 1870 } 1871 1872 // Send installed broadcasts if the install/update is not ephemeral 1873 if (!isEphemeral(res.pkg)) { 1874 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1875 1876 // Send added for users that see the package for the first time 1877 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1878 extras, 0 /*flags*/, null /*targetPackage*/, 1879 null /*finishedReceiver*/, firstUsers); 1880 1881 // Send added for users that don't see the package for the first time 1882 if (update) { 1883 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1884 } 1885 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1886 extras, 0 /*flags*/, null /*targetPackage*/, 1887 null /*finishedReceiver*/, updateUsers); 1888 1889 // Send replaced for users that don't see the package for the first time 1890 if (update) { 1891 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1892 packageName, extras, 0 /*flags*/, 1893 null /*targetPackage*/, null /*finishedReceiver*/, 1894 updateUsers); 1895 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1896 null /*package*/, null /*extras*/, 0 /*flags*/, 1897 packageName /*targetPackage*/, 1898 null /*finishedReceiver*/, updateUsers); 1899 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1900 // First-install and we did a restore, so we're responsible for the 1901 // first-launch broadcast. 1902 if (DEBUG_BACKUP) { 1903 Slog.i(TAG, "Post-restore of " + packageName 1904 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1905 } 1906 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1907 } 1908 1909 // Send broadcast package appeared if forward locked/external for all users 1910 // treat asec-hosted packages like removable media on upgrade 1911 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1912 if (DEBUG_INSTALL) { 1913 Slog.i(TAG, "upgrading pkg " + res.pkg 1914 + " is ASEC-hosted -> AVAILABLE"); 1915 } 1916 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1917 ArrayList<String> pkgList = new ArrayList<>(1); 1918 pkgList.add(packageName); 1919 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1920 } 1921 } 1922 1923 // Work that needs to happen on first install within each user 1924 if (firstUsers != null && firstUsers.length > 0) { 1925 synchronized (mPackages) { 1926 for (int userId : firstUsers) { 1927 // If this app is a browser and it's newly-installed for some 1928 // users, clear any default-browser state in those users. The 1929 // app's nature doesn't depend on the user, so we can just check 1930 // its browser nature in any user and generalize. 1931 if (packageIsBrowser(packageName, userId)) { 1932 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1933 } 1934 1935 // We may also need to apply pending (restored) runtime 1936 // permission grants within these users. 1937 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1938 } 1939 } 1940 } 1941 1942 // Log current value of "unknown sources" setting 1943 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1944 getUnknownSourcesSettings()); 1945 1946 // Force a gc to clear up things 1947 Runtime.getRuntime().gc(); 1948 1949 // Remove the replaced package's older resources safely now 1950 // We delete after a gc for applications on sdcard. 1951 if (res.removedInfo != null && res.removedInfo.args != null) { 1952 synchronized (mInstallLock) { 1953 res.removedInfo.args.doPostDeleteLI(true); 1954 } 1955 } 1956 } 1957 1958 // If someone is watching installs - notify them 1959 if (installObserver != null) { 1960 try { 1961 Bundle extras = extrasForInstallResult(res); 1962 installObserver.onPackageInstalled(res.name, res.returnCode, 1963 res.returnMsg, extras); 1964 } catch (RemoteException e) { 1965 Slog.i(TAG, "Observer no longer exists."); 1966 } 1967 } 1968 } 1969 1970 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1971 PackageParser.Package pkg) { 1972 if (pkg.parentPackage == null) { 1973 return; 1974 } 1975 if (pkg.requestedPermissions == null) { 1976 return; 1977 } 1978 final PackageSetting disabledSysParentPs = mSettings 1979 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1980 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1981 || !disabledSysParentPs.isPrivileged() 1982 || (disabledSysParentPs.childPackageNames != null 1983 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1984 return; 1985 } 1986 final int[] allUserIds = sUserManager.getUserIds(); 1987 final int permCount = pkg.requestedPermissions.size(); 1988 for (int i = 0; i < permCount; i++) { 1989 String permission = pkg.requestedPermissions.get(i); 1990 BasePermission bp = mSettings.mPermissions.get(permission); 1991 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1992 continue; 1993 } 1994 for (int userId : allUserIds) { 1995 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1996 permission, userId)) { 1997 grantRuntimePermission(pkg.packageName, permission, userId); 1998 } 1999 } 2000 } 2001 } 2002 2003 private StorageEventListener mStorageListener = new StorageEventListener() { 2004 @Override 2005 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2006 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2007 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2008 final String volumeUuid = vol.getFsUuid(); 2009 2010 // Clean up any users or apps that were removed or recreated 2011 // while this volume was missing 2012 reconcileUsers(volumeUuid); 2013 reconcileApps(volumeUuid); 2014 2015 // Clean up any install sessions that expired or were 2016 // cancelled while this volume was missing 2017 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2018 2019 loadPrivatePackages(vol); 2020 2021 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2022 unloadPrivatePackages(vol); 2023 } 2024 } 2025 2026 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2027 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2028 updateExternalMediaStatus(true, false); 2029 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2030 updateExternalMediaStatus(false, false); 2031 } 2032 } 2033 } 2034 2035 @Override 2036 public void onVolumeForgotten(String fsUuid) { 2037 if (TextUtils.isEmpty(fsUuid)) { 2038 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2039 return; 2040 } 2041 2042 // Remove any apps installed on the forgotten volume 2043 synchronized (mPackages) { 2044 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2045 for (PackageSetting ps : packages) { 2046 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2047 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2048 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2049 } 2050 2051 mSettings.onVolumeForgotten(fsUuid); 2052 mSettings.writeLPr(); 2053 } 2054 } 2055 }; 2056 2057 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2058 String[] grantedPermissions) { 2059 for (int userId : userIds) { 2060 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2061 } 2062 2063 // We could have touched GID membership, so flush out packages.list 2064 synchronized (mPackages) { 2065 mSettings.writePackageListLPr(); 2066 } 2067 } 2068 2069 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2070 String[] grantedPermissions) { 2071 SettingBase sb = (SettingBase) pkg.mExtras; 2072 if (sb == null) { 2073 return; 2074 } 2075 2076 PermissionsState permissionsState = sb.getPermissionsState(); 2077 2078 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2079 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2080 2081 for (String permission : pkg.requestedPermissions) { 2082 final BasePermission bp; 2083 synchronized (mPackages) { 2084 bp = mSettings.mPermissions.get(permission); 2085 } 2086 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2087 && (grantedPermissions == null 2088 || ArrayUtils.contains(grantedPermissions, permission))) { 2089 final int flags = permissionsState.getPermissionFlags(permission, userId); 2090 // Installer cannot change immutable permissions. 2091 if ((flags & immutableFlags) == 0) { 2092 grantRuntimePermission(pkg.packageName, permission, userId); 2093 } 2094 } 2095 } 2096 } 2097 2098 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2099 Bundle extras = null; 2100 switch (res.returnCode) { 2101 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2102 extras = new Bundle(); 2103 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2104 res.origPermission); 2105 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2106 res.origPackage); 2107 break; 2108 } 2109 case PackageManager.INSTALL_SUCCEEDED: { 2110 extras = new Bundle(); 2111 extras.putBoolean(Intent.EXTRA_REPLACING, 2112 res.removedInfo != null && res.removedInfo.removedPackage != null); 2113 break; 2114 } 2115 } 2116 return extras; 2117 } 2118 2119 void scheduleWriteSettingsLocked() { 2120 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2121 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2122 } 2123 } 2124 2125 void scheduleWritePackageListLocked(int userId) { 2126 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2127 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2128 msg.arg1 = userId; 2129 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2130 } 2131 } 2132 2133 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2134 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2135 scheduleWritePackageRestrictionsLocked(userId); 2136 } 2137 2138 void scheduleWritePackageRestrictionsLocked(int userId) { 2139 final int[] userIds = (userId == UserHandle.USER_ALL) 2140 ? sUserManager.getUserIds() : new int[]{userId}; 2141 for (int nextUserId : userIds) { 2142 if (!sUserManager.exists(nextUserId)) return; 2143 mDirtyUsers.add(nextUserId); 2144 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2145 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2146 } 2147 } 2148 } 2149 2150 public static PackageManagerService main(Context context, Installer installer, 2151 boolean factoryTest, boolean onlyCore) { 2152 // Self-check for initial settings. 2153 PackageManagerServiceCompilerMapping.checkProperties(); 2154 2155 PackageManagerService m = new PackageManagerService(context, installer, 2156 factoryTest, onlyCore); 2157 m.enableSystemUserPackages(); 2158 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2159 // disabled after already being started. 2160 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2161 UserHandle.USER_SYSTEM); 2162 ServiceManager.addService("package", m); 2163 return m; 2164 } 2165 2166 private void enableSystemUserPackages() { 2167 if (!UserManager.isSplitSystemUser()) { 2168 return; 2169 } 2170 // For system user, enable apps based on the following conditions: 2171 // - app is whitelisted or belong to one of these groups: 2172 // -- system app which has no launcher icons 2173 // -- system app which has INTERACT_ACROSS_USERS permission 2174 // -- system IME app 2175 // - app is not in the blacklist 2176 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2177 Set<String> enableApps = new ArraySet<>(); 2178 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2179 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2180 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2181 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2182 enableApps.addAll(wlApps); 2183 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2184 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2185 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2186 enableApps.removeAll(blApps); 2187 Log.i(TAG, "Applications installed for system user: " + enableApps); 2188 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2189 UserHandle.SYSTEM); 2190 final int allAppsSize = allAps.size(); 2191 synchronized (mPackages) { 2192 for (int i = 0; i < allAppsSize; i++) { 2193 String pName = allAps.get(i); 2194 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2195 // Should not happen, but we shouldn't be failing if it does 2196 if (pkgSetting == null) { 2197 continue; 2198 } 2199 boolean install = enableApps.contains(pName); 2200 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2201 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2202 + " for system user"); 2203 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2204 } 2205 } 2206 } 2207 } 2208 2209 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2210 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2211 Context.DISPLAY_SERVICE); 2212 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2213 } 2214 2215 public PackageManagerService(Context context, Installer installer, 2216 boolean factoryTest, boolean onlyCore) { 2217 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2218 SystemClock.uptimeMillis()); 2219 2220 if (mSdkVersion <= 0) { 2221 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2222 } 2223 2224 mContext = context; 2225 mFactoryTest = factoryTest; 2226 mOnlyCore = onlyCore; 2227 mMetrics = new DisplayMetrics(); 2228 mSettings = new Settings(mPackages); 2229 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2230 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2231 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2232 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2233 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2234 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2235 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 2242 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2243 if (separateProcesses != null && separateProcesses.length() > 0) { 2244 if ("*".equals(separateProcesses)) { 2245 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2246 mSeparateProcesses = null; 2247 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2248 } else { 2249 mDefParseFlags = 0; 2250 mSeparateProcesses = separateProcesses.split(","); 2251 Slog.w(TAG, "Running with debug.separate_processes: " 2252 + separateProcesses); 2253 } 2254 } else { 2255 mDefParseFlags = 0; 2256 mSeparateProcesses = null; 2257 } 2258 2259 mInstaller = installer; 2260 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2261 "*dexopt*"); 2262 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2263 2264 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2265 FgThread.get().getLooper()); 2266 2267 getDefaultDisplayMetrics(context, mMetrics); 2268 2269 SystemConfig systemConfig = SystemConfig.getInstance(); 2270 mGlobalGids = systemConfig.getGlobalGids(); 2271 mSystemPermissions = systemConfig.getSystemPermissions(); 2272 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2273 2274 synchronized (mInstallLock) { 2275 // writer 2276 synchronized (mPackages) { 2277 mHandlerThread = new ServiceThread(TAG, 2278 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2279 mHandlerThread.start(); 2280 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2281 mProcessLoggingHandler = new ProcessLoggingHandler(); 2282 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2283 2284 File dataDir = Environment.getDataDirectory(); 2285 mAppInstallDir = new File(dataDir, "app"); 2286 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2287 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2288 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2289 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2290 2291 sUserManager = new UserManagerService(context, this, mPackages); 2292 2293 // Propagate permission configuration in to package manager. 2294 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2295 = systemConfig.getPermissions(); 2296 for (int i=0; i<permConfig.size(); i++) { 2297 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2298 BasePermission bp = mSettings.mPermissions.get(perm.name); 2299 if (bp == null) { 2300 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2301 mSettings.mPermissions.put(perm.name, bp); 2302 } 2303 if (perm.gids != null) { 2304 bp.setGids(perm.gids, perm.perUser); 2305 } 2306 } 2307 2308 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2309 for (int i=0; i<libConfig.size(); i++) { 2310 mSharedLibraries.put(libConfig.keyAt(i), 2311 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2312 } 2313 2314 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2315 2316 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2317 2318 String customResolverActivity = Resources.getSystem().getString( 2319 R.string.config_customResolverActivity); 2320 if (TextUtils.isEmpty(customResolverActivity)) { 2321 customResolverActivity = null; 2322 } else { 2323 mCustomResolverComponentName = ComponentName.unflattenFromString( 2324 customResolverActivity); 2325 } 2326 2327 long startTime = SystemClock.uptimeMillis(); 2328 2329 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2330 startTime); 2331 2332 // Set flag to monitor and not change apk file paths when 2333 // scanning install directories. 2334 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2335 2336 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2337 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2338 2339 if (bootClassPath == null) { 2340 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2341 } 2342 2343 if (systemServerClassPath == null) { 2344 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2345 } 2346 2347 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2348 final String[] dexCodeInstructionSets = 2349 getDexCodeInstructionSets( 2350 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2351 2352 /** 2353 * Ensure all external libraries have had dexopt run on them. 2354 */ 2355 if (mSharedLibraries.size() > 0) { 2356 // NOTE: For now, we're compiling these system "shared libraries" 2357 // (and framework jars) into all available architectures. It's possible 2358 // to compile them only when we come across an app that uses them (there's 2359 // already logic for that in scanPackageLI) but that adds some complexity. 2360 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2361 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2362 final String lib = libEntry.path; 2363 if (lib == null) { 2364 continue; 2365 } 2366 2367 try { 2368 // Shared libraries do not have profiles so we perform a full 2369 // AOT compilation (if needed). 2370 int dexoptNeeded = DexFile.getDexOptNeeded( 2371 lib, dexCodeInstructionSet, 2372 getCompilerFilterForReason(REASON_SHARED_APK), 2373 false /* newProfile */); 2374 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2375 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2376 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2377 getCompilerFilterForReason(REASON_SHARED_APK), 2378 StorageManager.UUID_PRIVATE_INTERNAL, 2379 SKIP_SHARED_LIBRARY_CHECK); 2380 } 2381 } catch (FileNotFoundException e) { 2382 Slog.w(TAG, "Library not found: " + lib); 2383 } catch (IOException | InstallerException e) { 2384 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2385 + e.getMessage()); 2386 } 2387 } 2388 } 2389 } 2390 2391 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2392 2393 final VersionInfo ver = mSettings.getInternalVersion(); 2394 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2395 2396 // when upgrading from pre-M, promote system app permissions from install to runtime 2397 mPromoteSystemApps = 2398 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2399 2400 // When upgrading from pre-N, we need to handle package extraction like first boot, 2401 // as there is no profiling data available. 2402 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2403 2404 // save off the names of pre-existing system packages prior to scanning; we don't 2405 // want to automatically grant runtime permissions for new system apps 2406 if (mPromoteSystemApps) { 2407 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2408 while (pkgSettingIter.hasNext()) { 2409 PackageSetting ps = pkgSettingIter.next(); 2410 if (isSystemApp(ps)) { 2411 mExistingSystemPackages.add(ps.name); 2412 } 2413 } 2414 } 2415 2416 // Collect vendor overlay packages. 2417 // (Do this before scanning any apps.) 2418 // For security and version matching reason, only consider 2419 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2420 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2421 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2422 | PackageParser.PARSE_IS_SYSTEM 2423 | PackageParser.PARSE_IS_SYSTEM_DIR 2424 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2425 2426 // Find base frameworks (resource packages without code). 2427 scanDirTracedLI(frameworkDir, mDefParseFlags 2428 | PackageParser.PARSE_IS_SYSTEM 2429 | PackageParser.PARSE_IS_SYSTEM_DIR 2430 | PackageParser.PARSE_IS_PRIVILEGED, 2431 scanFlags | SCAN_NO_DEX, 0); 2432 2433 // Collected privileged system packages. 2434 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2435 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2436 | PackageParser.PARSE_IS_SYSTEM 2437 | PackageParser.PARSE_IS_SYSTEM_DIR 2438 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2439 2440 // Collect ordinary system packages. 2441 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2442 scanDirTracedLI(systemAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2445 2446 // Collect all vendor packages. 2447 File vendorAppDir = new File("/vendor/app"); 2448 try { 2449 vendorAppDir = vendorAppDir.getCanonicalFile(); 2450 } catch (IOException e) { 2451 // failed to look up canonical path, continue with original one 2452 } 2453 scanDirTracedLI(vendorAppDir, mDefParseFlags 2454 | PackageParser.PARSE_IS_SYSTEM 2455 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2456 2457 // Collect all OEM packages. 2458 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2459 scanDirTracedLI(oemAppDir, mDefParseFlags 2460 | PackageParser.PARSE_IS_SYSTEM 2461 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2462 2463 // Prune any system packages that no longer exist. 2464 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2465 if (!mOnlyCore) { 2466 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2467 while (psit.hasNext()) { 2468 PackageSetting ps = psit.next(); 2469 2470 /* 2471 * If this is not a system app, it can't be a 2472 * disable system app. 2473 */ 2474 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2475 continue; 2476 } 2477 2478 /* 2479 * If the package is scanned, it's not erased. 2480 */ 2481 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2482 if (scannedPkg != null) { 2483 /* 2484 * If the system app is both scanned and in the 2485 * disabled packages list, then it must have been 2486 * added via OTA. Remove it from the currently 2487 * scanned package so the previously user-installed 2488 * application can be scanned. 2489 */ 2490 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2491 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2492 + ps.name + "; removing system app. Last known codePath=" 2493 + ps.codePathString + ", installStatus=" + ps.installStatus 2494 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2495 + scannedPkg.mVersionCode); 2496 removePackageLI(scannedPkg, true); 2497 mExpectingBetter.put(ps.name, ps.codePath); 2498 } 2499 2500 continue; 2501 } 2502 2503 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2504 psit.remove(); 2505 logCriticalInfo(Log.WARN, "System package " + ps.name 2506 + " no longer exists; it's data will be wiped"); 2507 // Actual deletion of code and data will be handled by later 2508 // reconciliation step 2509 } else { 2510 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2511 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2512 possiblyDeletedUpdatedSystemApps.add(ps.name); 2513 } 2514 } 2515 } 2516 } 2517 2518 //look for any incomplete package installations 2519 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2520 for (int i = 0; i < deletePkgsList.size(); i++) { 2521 // Actual deletion of code and data will be handled by later 2522 // reconciliation step 2523 final String packageName = deletePkgsList.get(i).name; 2524 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2525 synchronized (mPackages) { 2526 mSettings.removePackageLPw(packageName); 2527 } 2528 } 2529 2530 //delete tmp files 2531 deleteTempPackageFiles(); 2532 2533 // Remove any shared userIDs that have no associated packages 2534 mSettings.pruneSharedUsersLPw(); 2535 2536 if (!mOnlyCore) { 2537 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2538 SystemClock.uptimeMillis()); 2539 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2540 2541 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2542 | PackageParser.PARSE_FORWARD_LOCK, 2543 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2544 2545 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2546 | PackageParser.PARSE_IS_EPHEMERAL, 2547 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2548 2549 /** 2550 * Remove disable package settings for any updated system 2551 * apps that were removed via an OTA. If they're not a 2552 * previously-updated app, remove them completely. 2553 * Otherwise, just revoke their system-level permissions. 2554 */ 2555 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2556 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2557 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2558 2559 String msg; 2560 if (deletedPkg == null) { 2561 msg = "Updated system package " + deletedAppName 2562 + " no longer exists; it's data will be wiped"; 2563 // Actual deletion of code and data will be handled by later 2564 // reconciliation step 2565 } else { 2566 msg = "Updated system app + " + deletedAppName 2567 + " no longer present; removing system privileges for " 2568 + deletedAppName; 2569 2570 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2571 2572 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2573 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2574 } 2575 logCriticalInfo(Log.WARN, msg); 2576 } 2577 2578 /** 2579 * Make sure all system apps that we expected to appear on 2580 * the userdata partition actually showed up. If they never 2581 * appeared, crawl back and revive the system version. 2582 */ 2583 for (int i = 0; i < mExpectingBetter.size(); i++) { 2584 final String packageName = mExpectingBetter.keyAt(i); 2585 if (!mPackages.containsKey(packageName)) { 2586 final File scanFile = mExpectingBetter.valueAt(i); 2587 2588 logCriticalInfo(Log.WARN, "Expected better " + packageName 2589 + " but never showed up; reverting to system"); 2590 2591 int reparseFlags = mDefParseFlags; 2592 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2593 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2594 | PackageParser.PARSE_IS_SYSTEM_DIR 2595 | PackageParser.PARSE_IS_PRIVILEGED; 2596 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2597 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2598 | PackageParser.PARSE_IS_SYSTEM_DIR; 2599 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2600 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2601 | PackageParser.PARSE_IS_SYSTEM_DIR; 2602 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2603 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR; 2605 } else { 2606 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2607 continue; 2608 } 2609 2610 mSettings.enableSystemPackageLPw(packageName); 2611 2612 try { 2613 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2614 } catch (PackageManagerException e) { 2615 Slog.e(TAG, "Failed to parse original system package: " 2616 + e.getMessage()); 2617 } 2618 } 2619 } 2620 } 2621 mExpectingBetter.clear(); 2622 2623 // Resolve protected action filters. Only the setup wizard is allowed to 2624 // have a high priority filter for these actions. 2625 mSetupWizardPackage = getSetupWizardPackageName(); 2626 if (mProtectedFilters.size() > 0) { 2627 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2628 Slog.i(TAG, "No setup wizard;" 2629 + " All protected intents capped to priority 0"); 2630 } 2631 for (ActivityIntentInfo filter : mProtectedFilters) { 2632 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2633 if (DEBUG_FILTERS) { 2634 Slog.i(TAG, "Found setup wizard;" 2635 + " allow priority " + filter.getPriority() + ";" 2636 + " package: " + filter.activity.info.packageName 2637 + " activity: " + filter.activity.className 2638 + " priority: " + filter.getPriority()); 2639 } 2640 // skip setup wizard; allow it to keep the high priority filter 2641 continue; 2642 } 2643 Slog.w(TAG, "Protected action; cap priority to 0;" 2644 + " package: " + filter.activity.info.packageName 2645 + " activity: " + filter.activity.className 2646 + " origPrio: " + filter.getPriority()); 2647 filter.setPriority(0); 2648 } 2649 } 2650 mDeferProtectedFilters = false; 2651 mProtectedFilters.clear(); 2652 2653 // Now that we know all of the shared libraries, update all clients to have 2654 // the correct library paths. 2655 updateAllSharedLibrariesLPw(); 2656 2657 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2658 // NOTE: We ignore potential failures here during a system scan (like 2659 // the rest of the commands above) because there's precious little we 2660 // can do about it. A settings error is reported, though. 2661 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2662 false /* boot complete */); 2663 } 2664 2665 // Now that we know all the packages we are keeping, 2666 // read and update their last usage times. 2667 mPackageUsage.readLP(); 2668 2669 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2670 SystemClock.uptimeMillis()); 2671 Slog.i(TAG, "Time to scan packages: " 2672 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2673 + " seconds"); 2674 2675 // If the platform SDK has changed since the last time we booted, 2676 // we need to re-grant app permission to catch any new ones that 2677 // appear. This is really a hack, and means that apps can in some 2678 // cases get permissions that the user didn't initially explicitly 2679 // allow... it would be nice to have some better way to handle 2680 // this situation. 2681 int updateFlags = UPDATE_PERMISSIONS_ALL; 2682 if (ver.sdkVersion != mSdkVersion) { 2683 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2684 + mSdkVersion + "; regranting permissions for internal storage"); 2685 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2686 } 2687 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2688 ver.sdkVersion = mSdkVersion; 2689 2690 // If this is the first boot or an update from pre-M, and it is a normal 2691 // boot, then we need to initialize the default preferred apps across 2692 // all defined users. 2693 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2694 for (UserInfo user : sUserManager.getUsers(true)) { 2695 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2696 applyFactoryDefaultBrowserLPw(user.id); 2697 primeDomainVerificationsLPw(user.id); 2698 } 2699 } 2700 2701 // Prepare storage for system user really early during boot, 2702 // since core system apps like SettingsProvider and SystemUI 2703 // can't wait for user to start 2704 final int storageFlags; 2705 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2706 storageFlags = StorageManager.FLAG_STORAGE_DE; 2707 } else { 2708 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2709 } 2710 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2711 storageFlags); 2712 2713 // If this is first boot after an OTA, and a normal boot, then 2714 // we need to clear code cache directories. 2715 // Note that we do *not* clear the application profiles. These remain valid 2716 // across OTAs and are used to drive profile verification (post OTA) and 2717 // profile compilation (without waiting to collect a fresh set of profiles). 2718 if (mIsUpgrade && !onlyCore) { 2719 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2720 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2721 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2722 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2723 // No apps are running this early, so no need to freeze 2724 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2725 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2726 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2727 } 2728 } 2729 ver.fingerprint = Build.FINGERPRINT; 2730 } 2731 2732 checkDefaultBrowser(); 2733 2734 // clear only after permissions and other defaults have been updated 2735 mExistingSystemPackages.clear(); 2736 mPromoteSystemApps = false; 2737 2738 // All the changes are done during package scanning. 2739 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2740 2741 // can downgrade to reader 2742 mSettings.writeLPr(); 2743 2744 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2745 SystemClock.uptimeMillis()); 2746 2747 if (!mOnlyCore) { 2748 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2749 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2750 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2751 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2752 mIntentFilterVerifierComponent); 2753 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2754 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2755 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2756 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2757 } else { 2758 mRequiredVerifierPackage = null; 2759 mRequiredInstallerPackage = null; 2760 mIntentFilterVerifierComponent = null; 2761 mIntentFilterVerifier = null; 2762 mServicesSystemSharedLibraryPackageName = null; 2763 mSharedSystemSharedLibraryPackageName = null; 2764 } 2765 2766 mInstallerService = new PackageInstallerService(context, this); 2767 2768 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2769 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2770 // both the installer and resolver must be present to enable ephemeral 2771 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2772 if (DEBUG_EPHEMERAL) { 2773 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2774 + " installer:" + ephemeralInstallerComponent); 2775 } 2776 mEphemeralResolverComponent = ephemeralResolverComponent; 2777 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2778 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2779 mEphemeralResolverConnection = 2780 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2781 } else { 2782 if (DEBUG_EPHEMERAL) { 2783 final String missingComponent = 2784 (ephemeralResolverComponent == null) 2785 ? (ephemeralInstallerComponent == null) 2786 ? "resolver and installer" 2787 : "resolver" 2788 : "installer"; 2789 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2790 } 2791 mEphemeralResolverComponent = null; 2792 mEphemeralInstallerComponent = null; 2793 mEphemeralResolverConnection = null; 2794 } 2795 2796 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2797 } // synchronized (mPackages) 2798 } // synchronized (mInstallLock) 2799 2800 // Now after opening every single application zip, make sure they 2801 // are all flushed. Not really needed, but keeps things nice and 2802 // tidy. 2803 Runtime.getRuntime().gc(); 2804 2805 // The initial scanning above does many calls into installd while 2806 // holding the mPackages lock, but we're mostly interested in yelling 2807 // once we have a booted system. 2808 mInstaller.setWarnIfHeld(mPackages); 2809 2810 // Expose private service for system components to use. 2811 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2812 } 2813 2814 @Override 2815 public boolean isFirstBoot() { 2816 return !mRestoredSettings; 2817 } 2818 2819 @Override 2820 public boolean isOnlyCoreApps() { 2821 return mOnlyCore; 2822 } 2823 2824 @Override 2825 public boolean isUpgrade() { 2826 return mIsUpgrade; 2827 } 2828 2829 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2830 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2831 2832 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2833 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2834 UserHandle.USER_SYSTEM); 2835 if (matches.size() == 1) { 2836 return matches.get(0).getComponentInfo().packageName; 2837 } else { 2838 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2839 return null; 2840 } 2841 } 2842 2843 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2844 synchronized (mPackages) { 2845 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2846 if (libraryEntry == null) { 2847 throw new IllegalStateException("Missing required shared library:" + libraryName); 2848 } 2849 return libraryEntry.apk; 2850 } 2851 } 2852 2853 private @NonNull String getRequiredInstallerLPr() { 2854 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2855 intent.addCategory(Intent.CATEGORY_DEFAULT); 2856 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2857 2858 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2859 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2860 UserHandle.USER_SYSTEM); 2861 if (matches.size() == 1) { 2862 ResolveInfo resolveInfo = matches.get(0); 2863 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2864 throw new RuntimeException("The installer must be a privileged app"); 2865 } 2866 return matches.get(0).getComponentInfo().packageName; 2867 } else { 2868 throw new RuntimeException("There must be exactly one installer; found " + matches); 2869 } 2870 } 2871 2872 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2873 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2874 2875 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2876 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2877 UserHandle.USER_SYSTEM); 2878 ResolveInfo best = null; 2879 final int N = matches.size(); 2880 for (int i = 0; i < N; i++) { 2881 final ResolveInfo cur = matches.get(i); 2882 final String packageName = cur.getComponentInfo().packageName; 2883 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2884 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2885 continue; 2886 } 2887 2888 if (best == null || cur.priority > best.priority) { 2889 best = cur; 2890 } 2891 } 2892 2893 if (best != null) { 2894 return best.getComponentInfo().getComponentName(); 2895 } else { 2896 throw new RuntimeException("There must be at least one intent filter verifier"); 2897 } 2898 } 2899 2900 private @Nullable ComponentName getEphemeralResolverLPr() { 2901 final String[] packageArray = 2902 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2903 if (packageArray.length == 0) { 2904 if (DEBUG_EPHEMERAL) { 2905 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2906 } 2907 return null; 2908 } 2909 2910 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2911 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 2915 final int N = resolvers.size(); 2916 if (N == 0) { 2917 if (DEBUG_EPHEMERAL) { 2918 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2919 } 2920 return null; 2921 } 2922 2923 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2924 for (int i = 0; i < N; i++) { 2925 final ResolveInfo info = resolvers.get(i); 2926 2927 if (info.serviceInfo == null) { 2928 continue; 2929 } 2930 2931 final String packageName = info.serviceInfo.packageName; 2932 if (!possiblePackages.contains(packageName)) { 2933 if (DEBUG_EPHEMERAL) { 2934 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2935 + " pkg: " + packageName + ", info:" + info); 2936 } 2937 continue; 2938 } 2939 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.v(TAG, "Ephemeral resolver found;" 2942 + " pkg: " + packageName + ", info:" + info); 2943 } 2944 return new ComponentName(packageName, info.serviceInfo.name); 2945 } 2946 if (DEBUG_EPHEMERAL) { 2947 Slog.v(TAG, "Ephemeral resolver NOT found"); 2948 } 2949 return null; 2950 } 2951 2952 private @Nullable ComponentName getEphemeralInstallerLPr() { 2953 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2954 intent.addCategory(Intent.CATEGORY_DEFAULT); 2955 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2956 2957 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2958 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2959 UserHandle.USER_SYSTEM); 2960 if (matches.size() == 0) { 2961 return null; 2962 } else if (matches.size() == 1) { 2963 return matches.get(0).getComponentInfo().getComponentName(); 2964 } else { 2965 throw new RuntimeException( 2966 "There must be at most one ephemeral installer; found " + matches); 2967 } 2968 } 2969 2970 private void primeDomainVerificationsLPw(int userId) { 2971 if (DEBUG_DOMAIN_VERIFICATION) { 2972 Slog.d(TAG, "Priming domain verifications in user " + userId); 2973 } 2974 2975 SystemConfig systemConfig = SystemConfig.getInstance(); 2976 ArraySet<String> packages = systemConfig.getLinkedApps(); 2977 ArraySet<String> domains = new ArraySet<String>(); 2978 2979 for (String packageName : packages) { 2980 PackageParser.Package pkg = mPackages.get(packageName); 2981 if (pkg != null) { 2982 if (!pkg.isSystemApp()) { 2983 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2984 continue; 2985 } 2986 2987 domains.clear(); 2988 for (PackageParser.Activity a : pkg.activities) { 2989 for (ActivityIntentInfo filter : a.intents) { 2990 if (hasValidDomains(filter)) { 2991 domains.addAll(filter.getHostsList()); 2992 } 2993 } 2994 } 2995 2996 if (domains.size() > 0) { 2997 if (DEBUG_DOMAIN_VERIFICATION) { 2998 Slog.v(TAG, " + " + packageName); 2999 } 3000 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3001 // state w.r.t. the formal app-linkage "no verification attempted" state; 3002 // and then 'always' in the per-user state actually used for intent resolution. 3003 final IntentFilterVerificationInfo ivi; 3004 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3005 new ArrayList<String>(domains)); 3006 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3007 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3008 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3009 } else { 3010 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3011 + "' does not handle web links"); 3012 } 3013 } else { 3014 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3015 } 3016 } 3017 3018 scheduleWritePackageRestrictionsLocked(userId); 3019 scheduleWriteSettingsLocked(); 3020 } 3021 3022 private void applyFactoryDefaultBrowserLPw(int userId) { 3023 // The default browser app's package name is stored in a string resource, 3024 // with a product-specific overlay used for vendor customization. 3025 String browserPkg = mContext.getResources().getString( 3026 com.android.internal.R.string.default_browser); 3027 if (!TextUtils.isEmpty(browserPkg)) { 3028 // non-empty string => required to be a known package 3029 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3030 if (ps == null) { 3031 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3032 browserPkg = null; 3033 } else { 3034 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3035 } 3036 } 3037 3038 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3039 // default. If there's more than one, just leave everything alone. 3040 if (browserPkg == null) { 3041 calculateDefaultBrowserLPw(userId); 3042 } 3043 } 3044 3045 private void calculateDefaultBrowserLPw(int userId) { 3046 List<String> allBrowsers = resolveAllBrowserApps(userId); 3047 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3048 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3049 } 3050 3051 private List<String> resolveAllBrowserApps(int userId) { 3052 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3053 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3054 PackageManager.MATCH_ALL, userId); 3055 3056 final int count = list.size(); 3057 List<String> result = new ArrayList<String>(count); 3058 for (int i=0; i<count; i++) { 3059 ResolveInfo info = list.get(i); 3060 if (info.activityInfo == null 3061 || !info.handleAllWebDataURI 3062 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3063 || result.contains(info.activityInfo.packageName)) { 3064 continue; 3065 } 3066 result.add(info.activityInfo.packageName); 3067 } 3068 3069 return result; 3070 } 3071 3072 private boolean packageIsBrowser(String packageName, int userId) { 3073 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3074 PackageManager.MATCH_ALL, userId); 3075 final int N = list.size(); 3076 for (int i = 0; i < N; i++) { 3077 ResolveInfo info = list.get(i); 3078 if (packageName.equals(info.activityInfo.packageName)) { 3079 return true; 3080 } 3081 } 3082 return false; 3083 } 3084 3085 private void checkDefaultBrowser() { 3086 final int myUserId = UserHandle.myUserId(); 3087 final String packageName = getDefaultBrowserPackageName(myUserId); 3088 if (packageName != null) { 3089 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3090 if (info == null) { 3091 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3092 synchronized (mPackages) { 3093 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3094 } 3095 } 3096 } 3097 } 3098 3099 @Override 3100 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3101 throws RemoteException { 3102 try { 3103 return super.onTransact(code, data, reply, flags); 3104 } catch (RuntimeException e) { 3105 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3106 Slog.wtf(TAG, "Package Manager Crash", e); 3107 } 3108 throw e; 3109 } 3110 } 3111 3112 static int[] appendInts(int[] cur, int[] add) { 3113 if (add == null) return cur; 3114 if (cur == null) return add; 3115 final int N = add.length; 3116 for (int i=0; i<N; i++) { 3117 cur = appendInt(cur, add[i]); 3118 } 3119 return cur; 3120 } 3121 3122 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3123 if (!sUserManager.exists(userId)) return null; 3124 if (ps == null) { 3125 return null; 3126 } 3127 final PackageParser.Package p = ps.pkg; 3128 if (p == null) { 3129 return null; 3130 } 3131 3132 final PermissionsState permissionsState = ps.getPermissionsState(); 3133 3134 final int[] gids = permissionsState.computeGids(userId); 3135 final Set<String> permissions = permissionsState.getPermissions(userId); 3136 final PackageUserState state = ps.readUserState(userId); 3137 3138 return PackageParser.generatePackageInfo(p, gids, flags, 3139 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3140 } 3141 3142 @Override 3143 public void checkPackageStartable(String packageName, int userId) { 3144 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3145 3146 synchronized (mPackages) { 3147 final PackageSetting ps = mSettings.mPackages.get(packageName); 3148 if (ps == null) { 3149 throw new SecurityException("Package " + packageName + " was not found!"); 3150 } 3151 3152 if (!ps.getInstalled(userId)) { 3153 throw new SecurityException( 3154 "Package " + packageName + " was not installed for user " + userId + "!"); 3155 } 3156 3157 if (mSafeMode && !ps.isSystem()) { 3158 throw new SecurityException("Package " + packageName + " not a system app!"); 3159 } 3160 3161 if (mFrozenPackages.contains(packageName)) { 3162 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3163 } 3164 3165 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3166 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3167 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3168 } 3169 } 3170 } 3171 3172 @Override 3173 public boolean isPackageAvailable(String packageName, int userId) { 3174 if (!sUserManager.exists(userId)) return false; 3175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3176 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3177 synchronized (mPackages) { 3178 PackageParser.Package p = mPackages.get(packageName); 3179 if (p != null) { 3180 final PackageSetting ps = (PackageSetting) p.mExtras; 3181 if (ps != null) { 3182 final PackageUserState state = ps.readUserState(userId); 3183 if (state != null) { 3184 return PackageParser.isAvailable(state); 3185 } 3186 } 3187 } 3188 } 3189 return false; 3190 } 3191 3192 @Override 3193 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3194 if (!sUserManager.exists(userId)) return null; 3195 flags = updateFlagsForPackage(flags, userId, packageName); 3196 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3197 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3198 // reader 3199 synchronized (mPackages) { 3200 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3201 PackageParser.Package p = null; 3202 if (matchFactoryOnly) { 3203 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3204 if (ps != null) { 3205 return generatePackageInfo(ps, flags, userId); 3206 } 3207 } 3208 if (p == null) { 3209 p = mPackages.get(packageName); 3210 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3211 return null; 3212 } 3213 } 3214 if (DEBUG_PACKAGE_INFO) 3215 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3216 if (p != null) { 3217 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3218 } 3219 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3220 final PackageSetting ps = mSettings.mPackages.get(packageName); 3221 return generatePackageInfo(ps, flags, userId); 3222 } 3223 } 3224 return null; 3225 } 3226 3227 @Override 3228 public String[] currentToCanonicalPackageNames(String[] names) { 3229 String[] out = new String[names.length]; 3230 // reader 3231 synchronized (mPackages) { 3232 for (int i=names.length-1; i>=0; i--) { 3233 PackageSetting ps = mSettings.mPackages.get(names[i]); 3234 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3235 } 3236 } 3237 return out; 3238 } 3239 3240 @Override 3241 public String[] canonicalToCurrentPackageNames(String[] names) { 3242 String[] out = new String[names.length]; 3243 // reader 3244 synchronized (mPackages) { 3245 for (int i=names.length-1; i>=0; i--) { 3246 String cur = mSettings.mRenamedPackages.get(names[i]); 3247 out[i] = cur != null ? cur : names[i]; 3248 } 3249 } 3250 return out; 3251 } 3252 3253 @Override 3254 public int getPackageUid(String packageName, int flags, int userId) { 3255 if (!sUserManager.exists(userId)) return -1; 3256 flags = updateFlagsForPackage(flags, userId, packageName); 3257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3258 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3259 3260 // reader 3261 synchronized (mPackages) { 3262 final PackageParser.Package p = mPackages.get(packageName); 3263 if (p != null && p.isMatch(flags)) { 3264 return UserHandle.getUid(userId, p.applicationInfo.uid); 3265 } 3266 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3267 final PackageSetting ps = mSettings.mPackages.get(packageName); 3268 if (ps != null && ps.isMatch(flags)) { 3269 return UserHandle.getUid(userId, ps.appId); 3270 } 3271 } 3272 } 3273 3274 return -1; 3275 } 3276 3277 @Override 3278 public int[] getPackageGids(String packageName, int flags, int userId) { 3279 if (!sUserManager.exists(userId)) return null; 3280 flags = updateFlagsForPackage(flags, userId, packageName); 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3282 false /* requireFullPermission */, false /* checkShell */, 3283 "getPackageGids"); 3284 3285 // reader 3286 synchronized (mPackages) { 3287 final PackageParser.Package p = mPackages.get(packageName); 3288 if (p != null && p.isMatch(flags)) { 3289 PackageSetting ps = (PackageSetting) p.mExtras; 3290 return ps.getPermissionsState().computeGids(userId); 3291 } 3292 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3293 final PackageSetting ps = mSettings.mPackages.get(packageName); 3294 if (ps != null && ps.isMatch(flags)) { 3295 return ps.getPermissionsState().computeGids(userId); 3296 } 3297 } 3298 } 3299 3300 return null; 3301 } 3302 3303 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3304 if (bp.perm != null) { 3305 return PackageParser.generatePermissionInfo(bp.perm, flags); 3306 } 3307 PermissionInfo pi = new PermissionInfo(); 3308 pi.name = bp.name; 3309 pi.packageName = bp.sourcePackage; 3310 pi.nonLocalizedLabel = bp.name; 3311 pi.protectionLevel = bp.protectionLevel; 3312 return pi; 3313 } 3314 3315 @Override 3316 public PermissionInfo getPermissionInfo(String name, int flags) { 3317 // reader 3318 synchronized (mPackages) { 3319 final BasePermission p = mSettings.mPermissions.get(name); 3320 if (p != null) { 3321 return generatePermissionInfo(p, flags); 3322 } 3323 return null; 3324 } 3325 } 3326 3327 @Override 3328 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3329 int flags) { 3330 // reader 3331 synchronized (mPackages) { 3332 if (group != null && !mPermissionGroups.containsKey(group)) { 3333 // This is thrown as NameNotFoundException 3334 return null; 3335 } 3336 3337 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3338 for (BasePermission p : mSettings.mPermissions.values()) { 3339 if (group == null) { 3340 if (p.perm == null || p.perm.info.group == null) { 3341 out.add(generatePermissionInfo(p, flags)); 3342 } 3343 } else { 3344 if (p.perm != null && group.equals(p.perm.info.group)) { 3345 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3346 } 3347 } 3348 } 3349 return new ParceledListSlice<>(out); 3350 } 3351 } 3352 3353 @Override 3354 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3355 // reader 3356 synchronized (mPackages) { 3357 return PackageParser.generatePermissionGroupInfo( 3358 mPermissionGroups.get(name), flags); 3359 } 3360 } 3361 3362 @Override 3363 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3364 // reader 3365 synchronized (mPackages) { 3366 final int N = mPermissionGroups.size(); 3367 ArrayList<PermissionGroupInfo> out 3368 = new ArrayList<PermissionGroupInfo>(N); 3369 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3370 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3371 } 3372 return new ParceledListSlice<>(out); 3373 } 3374 } 3375 3376 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3377 int userId) { 3378 if (!sUserManager.exists(userId)) return null; 3379 PackageSetting ps = mSettings.mPackages.get(packageName); 3380 if (ps != null) { 3381 if (ps.pkg == null) { 3382 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3383 if (pInfo != null) { 3384 return pInfo.applicationInfo; 3385 } 3386 return null; 3387 } 3388 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3389 ps.readUserState(userId), userId); 3390 } 3391 return null; 3392 } 3393 3394 @Override 3395 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3396 if (!sUserManager.exists(userId)) return null; 3397 flags = updateFlagsForApplication(flags, userId, packageName); 3398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3399 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3400 // writer 3401 synchronized (mPackages) { 3402 PackageParser.Package p = mPackages.get(packageName); 3403 if (DEBUG_PACKAGE_INFO) Log.v( 3404 TAG, "getApplicationInfo " + packageName 3405 + ": " + p); 3406 if (p != null) { 3407 PackageSetting ps = mSettings.mPackages.get(packageName); 3408 if (ps == null) return null; 3409 // Note: isEnabledLP() does not apply here - always return info 3410 return PackageParser.generateApplicationInfo( 3411 p, flags, ps.readUserState(userId), userId); 3412 } 3413 if ("android".equals(packageName)||"system".equals(packageName)) { 3414 return mAndroidApplication; 3415 } 3416 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3417 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3418 } 3419 } 3420 return null; 3421 } 3422 3423 @Override 3424 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3425 final IPackageDataObserver observer) { 3426 mContext.enforceCallingOrSelfPermission( 3427 android.Manifest.permission.CLEAR_APP_CACHE, null); 3428 // Queue up an async operation since clearing cache may take a little while. 3429 mHandler.post(new Runnable() { 3430 public void run() { 3431 mHandler.removeCallbacks(this); 3432 boolean success = true; 3433 synchronized (mInstallLock) { 3434 try { 3435 mInstaller.freeCache(volumeUuid, freeStorageSize); 3436 } catch (InstallerException e) { 3437 Slog.w(TAG, "Couldn't clear application caches: " + e); 3438 success = false; 3439 } 3440 } 3441 if (observer != null) { 3442 try { 3443 observer.onRemoveCompleted(null, success); 3444 } catch (RemoteException e) { 3445 Slog.w(TAG, "RemoveException when invoking call back"); 3446 } 3447 } 3448 } 3449 }); 3450 } 3451 3452 @Override 3453 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3454 final IntentSender pi) { 3455 mContext.enforceCallingOrSelfPermission( 3456 android.Manifest.permission.CLEAR_APP_CACHE, null); 3457 // Queue up an async operation since clearing cache may take a little while. 3458 mHandler.post(new Runnable() { 3459 public void run() { 3460 mHandler.removeCallbacks(this); 3461 boolean success = true; 3462 synchronized (mInstallLock) { 3463 try { 3464 mInstaller.freeCache(volumeUuid, freeStorageSize); 3465 } catch (InstallerException e) { 3466 Slog.w(TAG, "Couldn't clear application caches: " + e); 3467 success = false; 3468 } 3469 } 3470 if(pi != null) { 3471 try { 3472 // Callback via pending intent 3473 int code = success ? 1 : 0; 3474 pi.sendIntent(null, code, null, 3475 null, null); 3476 } catch (SendIntentException e1) { 3477 Slog.i(TAG, "Failed to send pending intent"); 3478 } 3479 } 3480 } 3481 }); 3482 } 3483 3484 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3485 synchronized (mInstallLock) { 3486 try { 3487 mInstaller.freeCache(volumeUuid, freeStorageSize); 3488 } catch (InstallerException e) { 3489 throw new IOException("Failed to free enough space", e); 3490 } 3491 } 3492 } 3493 3494 /** 3495 * Update given flags based on encryption status of current user. 3496 */ 3497 private int updateFlags(int flags, int userId) { 3498 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3499 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3500 // Caller expressed an explicit opinion about what encryption 3501 // aware/unaware components they want to see, so fall through and 3502 // give them what they want 3503 } else { 3504 // Caller expressed no opinion, so match based on user state 3505 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3506 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3507 } else { 3508 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3509 } 3510 } 3511 return flags; 3512 } 3513 3514 private UserManagerInternal getUserManagerInternal() { 3515 if (mUserManagerInternal == null) { 3516 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3517 } 3518 return mUserManagerInternal; 3519 } 3520 3521 /** 3522 * Update given flags when being used to request {@link PackageInfo}. 3523 */ 3524 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3525 boolean triaged = true; 3526 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3527 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3528 // Caller is asking for component details, so they'd better be 3529 // asking for specific encryption matching behavior, or be triaged 3530 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3531 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3532 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3533 triaged = false; 3534 } 3535 } 3536 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3537 | PackageManager.MATCH_SYSTEM_ONLY 3538 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3539 triaged = false; 3540 } 3541 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3542 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3543 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3544 } 3545 return updateFlags(flags, userId); 3546 } 3547 3548 /** 3549 * Update given flags when being used to request {@link ApplicationInfo}. 3550 */ 3551 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3552 return updateFlagsForPackage(flags, userId, cookie); 3553 } 3554 3555 /** 3556 * Update given flags when being used to request {@link ComponentInfo}. 3557 */ 3558 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3559 if (cookie instanceof Intent) { 3560 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3561 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3562 } 3563 } 3564 3565 boolean triaged = true; 3566 // Caller is asking for component details, so they'd better be 3567 // asking for specific encryption matching behavior, or be triaged 3568 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3569 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3570 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3571 triaged = false; 3572 } 3573 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3574 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3575 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3576 } 3577 3578 return updateFlags(flags, userId); 3579 } 3580 3581 /** 3582 * Update given flags when being used to request {@link ResolveInfo}. 3583 */ 3584 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3585 // Safe mode means we shouldn't match any third-party components 3586 if (mSafeMode) { 3587 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3588 } 3589 3590 return updateFlagsForComponent(flags, userId, cookie); 3591 } 3592 3593 @Override 3594 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3595 if (!sUserManager.exists(userId)) return null; 3596 flags = updateFlagsForComponent(flags, userId, component); 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3598 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3599 synchronized (mPackages) { 3600 PackageParser.Activity a = mActivities.mActivities.get(component); 3601 3602 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3603 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3604 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3605 if (ps == null) return null; 3606 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3607 userId); 3608 } 3609 if (mResolveComponentName.equals(component)) { 3610 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3611 new PackageUserState(), userId); 3612 } 3613 } 3614 return null; 3615 } 3616 3617 @Override 3618 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3619 String resolvedType) { 3620 synchronized (mPackages) { 3621 if (component.equals(mResolveComponentName)) { 3622 // The resolver supports EVERYTHING! 3623 return true; 3624 } 3625 PackageParser.Activity a = mActivities.mActivities.get(component); 3626 if (a == null) { 3627 return false; 3628 } 3629 for (int i=0; i<a.intents.size(); i++) { 3630 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3631 intent.getData(), intent.getCategories(), TAG) >= 0) { 3632 return true; 3633 } 3634 } 3635 return false; 3636 } 3637 } 3638 3639 @Override 3640 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3641 if (!sUserManager.exists(userId)) return null; 3642 flags = updateFlagsForComponent(flags, userId, component); 3643 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3644 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3645 synchronized (mPackages) { 3646 PackageParser.Activity a = mReceivers.mActivities.get(component); 3647 if (DEBUG_PACKAGE_INFO) Log.v( 3648 TAG, "getReceiverInfo " + component + ": " + a); 3649 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3650 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3651 if (ps == null) return null; 3652 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3653 userId); 3654 } 3655 } 3656 return null; 3657 } 3658 3659 @Override 3660 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3661 if (!sUserManager.exists(userId)) return null; 3662 flags = updateFlagsForComponent(flags, userId, component); 3663 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3664 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3665 synchronized (mPackages) { 3666 PackageParser.Service s = mServices.mServices.get(component); 3667 if (DEBUG_PACKAGE_INFO) Log.v( 3668 TAG, "getServiceInfo " + component + ": " + s); 3669 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3670 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3671 if (ps == null) return null; 3672 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3673 userId); 3674 } 3675 } 3676 return null; 3677 } 3678 3679 @Override 3680 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3681 if (!sUserManager.exists(userId)) return null; 3682 flags = updateFlagsForComponent(flags, userId, component); 3683 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3684 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3685 synchronized (mPackages) { 3686 PackageParser.Provider p = mProviders.mProviders.get(component); 3687 if (DEBUG_PACKAGE_INFO) Log.v( 3688 TAG, "getProviderInfo " + component + ": " + p); 3689 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3690 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3691 if (ps == null) return null; 3692 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3693 userId); 3694 } 3695 } 3696 return null; 3697 } 3698 3699 @Override 3700 public String[] getSystemSharedLibraryNames() { 3701 Set<String> libSet; 3702 synchronized (mPackages) { 3703 libSet = mSharedLibraries.keySet(); 3704 int size = libSet.size(); 3705 if (size > 0) { 3706 String[] libs = new String[size]; 3707 libSet.toArray(libs); 3708 return libs; 3709 } 3710 } 3711 return null; 3712 } 3713 3714 @Override 3715 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3716 synchronized (mPackages) { 3717 return mServicesSystemSharedLibraryPackageName; 3718 } 3719 } 3720 3721 @Override 3722 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3723 synchronized (mPackages) { 3724 return mSharedSystemSharedLibraryPackageName; 3725 } 3726 } 3727 3728 @Override 3729 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3730 synchronized (mPackages) { 3731 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3732 3733 final FeatureInfo fi = new FeatureInfo(); 3734 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3735 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3736 res.add(fi); 3737 3738 return new ParceledListSlice<>(res); 3739 } 3740 } 3741 3742 @Override 3743 public boolean hasSystemFeature(String name, int version) { 3744 synchronized (mPackages) { 3745 final FeatureInfo feat = mAvailableFeatures.get(name); 3746 if (feat == null) { 3747 return false; 3748 } else { 3749 return feat.version >= version; 3750 } 3751 } 3752 } 3753 3754 @Override 3755 public int checkPermission(String permName, String pkgName, int userId) { 3756 if (!sUserManager.exists(userId)) { 3757 return PackageManager.PERMISSION_DENIED; 3758 } 3759 3760 synchronized (mPackages) { 3761 final PackageParser.Package p = mPackages.get(pkgName); 3762 if (p != null && p.mExtras != null) { 3763 final PackageSetting ps = (PackageSetting) p.mExtras; 3764 final PermissionsState permissionsState = ps.getPermissionsState(); 3765 if (permissionsState.hasPermission(permName, userId)) { 3766 return PackageManager.PERMISSION_GRANTED; 3767 } 3768 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3769 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3770 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3771 return PackageManager.PERMISSION_GRANTED; 3772 } 3773 } 3774 } 3775 3776 return PackageManager.PERMISSION_DENIED; 3777 } 3778 3779 @Override 3780 public int checkUidPermission(String permName, int uid) { 3781 final int userId = UserHandle.getUserId(uid); 3782 3783 if (!sUserManager.exists(userId)) { 3784 return PackageManager.PERMISSION_DENIED; 3785 } 3786 3787 synchronized (mPackages) { 3788 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3789 if (obj != null) { 3790 final SettingBase ps = (SettingBase) obj; 3791 final PermissionsState permissionsState = ps.getPermissionsState(); 3792 if (permissionsState.hasPermission(permName, userId)) { 3793 return PackageManager.PERMISSION_GRANTED; 3794 } 3795 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3796 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3797 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3798 return PackageManager.PERMISSION_GRANTED; 3799 } 3800 } else { 3801 ArraySet<String> perms = mSystemPermissions.get(uid); 3802 if (perms != null) { 3803 if (perms.contains(permName)) { 3804 return PackageManager.PERMISSION_GRANTED; 3805 } 3806 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3807 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3808 return PackageManager.PERMISSION_GRANTED; 3809 } 3810 } 3811 } 3812 } 3813 3814 return PackageManager.PERMISSION_DENIED; 3815 } 3816 3817 @Override 3818 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3819 if (UserHandle.getCallingUserId() != userId) { 3820 mContext.enforceCallingPermission( 3821 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3822 "isPermissionRevokedByPolicy for user " + userId); 3823 } 3824 3825 if (checkPermission(permission, packageName, userId) 3826 == PackageManager.PERMISSION_GRANTED) { 3827 return false; 3828 } 3829 3830 final long identity = Binder.clearCallingIdentity(); 3831 try { 3832 final int flags = getPermissionFlags(permission, packageName, userId); 3833 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3834 } finally { 3835 Binder.restoreCallingIdentity(identity); 3836 } 3837 } 3838 3839 @Override 3840 public String getPermissionControllerPackageName() { 3841 synchronized (mPackages) { 3842 return mRequiredInstallerPackage; 3843 } 3844 } 3845 3846 /** 3847 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3848 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3849 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3850 * @param message the message to log on security exception 3851 */ 3852 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3853 boolean checkShell, String message) { 3854 if (userId < 0) { 3855 throw new IllegalArgumentException("Invalid userId " + userId); 3856 } 3857 if (checkShell) { 3858 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3859 } 3860 if (userId == UserHandle.getUserId(callingUid)) return; 3861 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3862 if (requireFullPermission) { 3863 mContext.enforceCallingOrSelfPermission( 3864 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3865 } else { 3866 try { 3867 mContext.enforceCallingOrSelfPermission( 3868 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3869 } catch (SecurityException se) { 3870 mContext.enforceCallingOrSelfPermission( 3871 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3872 } 3873 } 3874 } 3875 } 3876 3877 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3878 if (callingUid == Process.SHELL_UID) { 3879 if (userHandle >= 0 3880 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3881 throw new SecurityException("Shell does not have permission to access user " 3882 + userHandle); 3883 } else if (userHandle < 0) { 3884 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3885 + Debug.getCallers(3)); 3886 } 3887 } 3888 } 3889 3890 private BasePermission findPermissionTreeLP(String permName) { 3891 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3892 if (permName.startsWith(bp.name) && 3893 permName.length() > bp.name.length() && 3894 permName.charAt(bp.name.length()) == '.') { 3895 return bp; 3896 } 3897 } 3898 return null; 3899 } 3900 3901 private BasePermission checkPermissionTreeLP(String permName) { 3902 if (permName != null) { 3903 BasePermission bp = findPermissionTreeLP(permName); 3904 if (bp != null) { 3905 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3906 return bp; 3907 } 3908 throw new SecurityException("Calling uid " 3909 + Binder.getCallingUid() 3910 + " is not allowed to add to permission tree " 3911 + bp.name + " owned by uid " + bp.uid); 3912 } 3913 } 3914 throw new SecurityException("No permission tree found for " + permName); 3915 } 3916 3917 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3918 if (s1 == null) { 3919 return s2 == null; 3920 } 3921 if (s2 == null) { 3922 return false; 3923 } 3924 if (s1.getClass() != s2.getClass()) { 3925 return false; 3926 } 3927 return s1.equals(s2); 3928 } 3929 3930 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3931 if (pi1.icon != pi2.icon) return false; 3932 if (pi1.logo != pi2.logo) return false; 3933 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3934 if (!compareStrings(pi1.name, pi2.name)) return false; 3935 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3936 // We'll take care of setting this one. 3937 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3938 // These are not currently stored in settings. 3939 //if (!compareStrings(pi1.group, pi2.group)) return false; 3940 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3941 //if (pi1.labelRes != pi2.labelRes) return false; 3942 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3943 return true; 3944 } 3945 3946 int permissionInfoFootprint(PermissionInfo info) { 3947 int size = info.name.length(); 3948 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3949 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3950 return size; 3951 } 3952 3953 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3954 int size = 0; 3955 for (BasePermission perm : mSettings.mPermissions.values()) { 3956 if (perm.uid == tree.uid) { 3957 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3958 } 3959 } 3960 return size; 3961 } 3962 3963 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3964 // We calculate the max size of permissions defined by this uid and throw 3965 // if that plus the size of 'info' would exceed our stated maximum. 3966 if (tree.uid != Process.SYSTEM_UID) { 3967 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3968 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3969 throw new SecurityException("Permission tree size cap exceeded"); 3970 } 3971 } 3972 } 3973 3974 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3975 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3976 throw new SecurityException("Label must be specified in permission"); 3977 } 3978 BasePermission tree = checkPermissionTreeLP(info.name); 3979 BasePermission bp = mSettings.mPermissions.get(info.name); 3980 boolean added = bp == null; 3981 boolean changed = true; 3982 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3983 if (added) { 3984 enforcePermissionCapLocked(info, tree); 3985 bp = new BasePermission(info.name, tree.sourcePackage, 3986 BasePermission.TYPE_DYNAMIC); 3987 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3988 throw new SecurityException( 3989 "Not allowed to modify non-dynamic permission " 3990 + info.name); 3991 } else { 3992 if (bp.protectionLevel == fixedLevel 3993 && bp.perm.owner.equals(tree.perm.owner) 3994 && bp.uid == tree.uid 3995 && comparePermissionInfos(bp.perm.info, info)) { 3996 changed = false; 3997 } 3998 } 3999 bp.protectionLevel = fixedLevel; 4000 info = new PermissionInfo(info); 4001 info.protectionLevel = fixedLevel; 4002 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4003 bp.perm.info.packageName = tree.perm.info.packageName; 4004 bp.uid = tree.uid; 4005 if (added) { 4006 mSettings.mPermissions.put(info.name, bp); 4007 } 4008 if (changed) { 4009 if (!async) { 4010 mSettings.writeLPr(); 4011 } else { 4012 scheduleWriteSettingsLocked(); 4013 } 4014 } 4015 return added; 4016 } 4017 4018 @Override 4019 public boolean addPermission(PermissionInfo info) { 4020 synchronized (mPackages) { 4021 return addPermissionLocked(info, false); 4022 } 4023 } 4024 4025 @Override 4026 public boolean addPermissionAsync(PermissionInfo info) { 4027 synchronized (mPackages) { 4028 return addPermissionLocked(info, true); 4029 } 4030 } 4031 4032 @Override 4033 public void removePermission(String name) { 4034 synchronized (mPackages) { 4035 checkPermissionTreeLP(name); 4036 BasePermission bp = mSettings.mPermissions.get(name); 4037 if (bp != null) { 4038 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4039 throw new SecurityException( 4040 "Not allowed to modify non-dynamic permission " 4041 + name); 4042 } 4043 mSettings.mPermissions.remove(name); 4044 mSettings.writeLPr(); 4045 } 4046 } 4047 } 4048 4049 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4050 BasePermission bp) { 4051 int index = pkg.requestedPermissions.indexOf(bp.name); 4052 if (index == -1) { 4053 throw new SecurityException("Package " + pkg.packageName 4054 + " has not requested permission " + bp.name); 4055 } 4056 if (!bp.isRuntime() && !bp.isDevelopment()) { 4057 throw new SecurityException("Permission " + bp.name 4058 + " is not a changeable permission type"); 4059 } 4060 } 4061 4062 @Override 4063 public void grantRuntimePermission(String packageName, String name, final int userId) { 4064 if (!sUserManager.exists(userId)) { 4065 Log.e(TAG, "No such user:" + userId); 4066 return; 4067 } 4068 4069 mContext.enforceCallingOrSelfPermission( 4070 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4071 "grantRuntimePermission"); 4072 4073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4074 true /* requireFullPermission */, true /* checkShell */, 4075 "grantRuntimePermission"); 4076 4077 final int uid; 4078 final SettingBase sb; 4079 4080 synchronized (mPackages) { 4081 final PackageParser.Package pkg = mPackages.get(packageName); 4082 if (pkg == null) { 4083 throw new IllegalArgumentException("Unknown package: " + packageName); 4084 } 4085 4086 final BasePermission bp = mSettings.mPermissions.get(name); 4087 if (bp == null) { 4088 throw new IllegalArgumentException("Unknown permission: " + name); 4089 } 4090 4091 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4092 4093 // If a permission review is required for legacy apps we represent 4094 // their permissions as always granted runtime ones since we need 4095 // to keep the review required permission flag per user while an 4096 // install permission's state is shared across all users. 4097 if (Build.PERMISSIONS_REVIEW_REQUIRED 4098 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4099 && bp.isRuntime()) { 4100 return; 4101 } 4102 4103 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4104 sb = (SettingBase) pkg.mExtras; 4105 if (sb == null) { 4106 throw new IllegalArgumentException("Unknown package: " + packageName); 4107 } 4108 4109 final PermissionsState permissionsState = sb.getPermissionsState(); 4110 4111 final int flags = permissionsState.getPermissionFlags(name, userId); 4112 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4113 throw new SecurityException("Cannot grant system fixed permission " 4114 + name + " for package " + packageName); 4115 } 4116 4117 if (bp.isDevelopment()) { 4118 // Development permissions must be handled specially, since they are not 4119 // normal runtime permissions. For now they apply to all users. 4120 if (permissionsState.grantInstallPermission(bp) != 4121 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4122 scheduleWriteSettingsLocked(); 4123 } 4124 return; 4125 } 4126 4127 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4128 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4129 return; 4130 } 4131 4132 final int result = permissionsState.grantRuntimePermission(bp, userId); 4133 switch (result) { 4134 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4135 return; 4136 } 4137 4138 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4139 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4140 mHandler.post(new Runnable() { 4141 @Override 4142 public void run() { 4143 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4144 } 4145 }); 4146 } 4147 break; 4148 } 4149 4150 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4151 4152 // Not critical if that is lost - app has to request again. 4153 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4154 } 4155 4156 // Only need to do this if user is initialized. Otherwise it's a new user 4157 // and there are no processes running as the user yet and there's no need 4158 // to make an expensive call to remount processes for the changed permissions. 4159 if (READ_EXTERNAL_STORAGE.equals(name) 4160 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4161 final long token = Binder.clearCallingIdentity(); 4162 try { 4163 if (sUserManager.isInitialized(userId)) { 4164 MountServiceInternal mountServiceInternal = LocalServices.getService( 4165 MountServiceInternal.class); 4166 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4167 } 4168 } finally { 4169 Binder.restoreCallingIdentity(token); 4170 } 4171 } 4172 } 4173 4174 @Override 4175 public void revokeRuntimePermission(String packageName, String name, int userId) { 4176 if (!sUserManager.exists(userId)) { 4177 Log.e(TAG, "No such user:" + userId); 4178 return; 4179 } 4180 4181 mContext.enforceCallingOrSelfPermission( 4182 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4183 "revokeRuntimePermission"); 4184 4185 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4186 true /* requireFullPermission */, true /* checkShell */, 4187 "revokeRuntimePermission"); 4188 4189 final int appId; 4190 4191 synchronized (mPackages) { 4192 final PackageParser.Package pkg = mPackages.get(packageName); 4193 if (pkg == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final BasePermission bp = mSettings.mPermissions.get(name); 4198 if (bp == null) { 4199 throw new IllegalArgumentException("Unknown permission: " + name); 4200 } 4201 4202 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4203 4204 // If a permission review is required for legacy apps we represent 4205 // their permissions as always granted runtime ones since we need 4206 // to keep the review required permission flag per user while an 4207 // install permission's state is shared across all users. 4208 if (Build.PERMISSIONS_REVIEW_REQUIRED 4209 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4210 && bp.isRuntime()) { 4211 return; 4212 } 4213 4214 SettingBase sb = (SettingBase) pkg.mExtras; 4215 if (sb == null) { 4216 throw new IllegalArgumentException("Unknown package: " + packageName); 4217 } 4218 4219 final PermissionsState permissionsState = sb.getPermissionsState(); 4220 4221 final int flags = permissionsState.getPermissionFlags(name, userId); 4222 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4223 throw new SecurityException("Cannot revoke system fixed permission " 4224 + name + " for package " + packageName); 4225 } 4226 4227 if (bp.isDevelopment()) { 4228 // Development permissions must be handled specially, since they are not 4229 // normal runtime permissions. For now they apply to all users. 4230 if (permissionsState.revokeInstallPermission(bp) != 4231 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4232 scheduleWriteSettingsLocked(); 4233 } 4234 return; 4235 } 4236 4237 if (permissionsState.revokeRuntimePermission(bp, userId) == 4238 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4239 return; 4240 } 4241 4242 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4243 4244 // Critical, after this call app should never have the permission. 4245 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4246 4247 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4248 } 4249 4250 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4251 } 4252 4253 @Override 4254 public void resetRuntimePermissions() { 4255 mContext.enforceCallingOrSelfPermission( 4256 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4257 "revokeRuntimePermission"); 4258 4259 int callingUid = Binder.getCallingUid(); 4260 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4261 mContext.enforceCallingOrSelfPermission( 4262 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4263 "resetRuntimePermissions"); 4264 } 4265 4266 synchronized (mPackages) { 4267 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4268 for (int userId : UserManagerService.getInstance().getUserIds()) { 4269 final int packageCount = mPackages.size(); 4270 for (int i = 0; i < packageCount; i++) { 4271 PackageParser.Package pkg = mPackages.valueAt(i); 4272 if (!(pkg.mExtras instanceof PackageSetting)) { 4273 continue; 4274 } 4275 PackageSetting ps = (PackageSetting) pkg.mExtras; 4276 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4277 } 4278 } 4279 } 4280 } 4281 4282 @Override 4283 public int getPermissionFlags(String name, String packageName, int userId) { 4284 if (!sUserManager.exists(userId)) { 4285 return 0; 4286 } 4287 4288 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4289 4290 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4291 true /* requireFullPermission */, false /* checkShell */, 4292 "getPermissionFlags"); 4293 4294 synchronized (mPackages) { 4295 final PackageParser.Package pkg = mPackages.get(packageName); 4296 if (pkg == null) { 4297 return 0; 4298 } 4299 4300 final BasePermission bp = mSettings.mPermissions.get(name); 4301 if (bp == null) { 4302 return 0; 4303 } 4304 4305 SettingBase sb = (SettingBase) pkg.mExtras; 4306 if (sb == null) { 4307 return 0; 4308 } 4309 4310 PermissionsState permissionsState = sb.getPermissionsState(); 4311 return permissionsState.getPermissionFlags(name, userId); 4312 } 4313 } 4314 4315 @Override 4316 public void updatePermissionFlags(String name, String packageName, int flagMask, 4317 int flagValues, int userId) { 4318 if (!sUserManager.exists(userId)) { 4319 return; 4320 } 4321 4322 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4323 4324 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4325 true /* requireFullPermission */, true /* checkShell */, 4326 "updatePermissionFlags"); 4327 4328 // Only the system can change these flags and nothing else. 4329 if (getCallingUid() != Process.SYSTEM_UID) { 4330 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4331 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4332 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4333 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4334 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4335 } 4336 4337 synchronized (mPackages) { 4338 final PackageParser.Package pkg = mPackages.get(packageName); 4339 if (pkg == null) { 4340 throw new IllegalArgumentException("Unknown package: " + packageName); 4341 } 4342 4343 final BasePermission bp = mSettings.mPermissions.get(name); 4344 if (bp == null) { 4345 throw new IllegalArgumentException("Unknown permission: " + name); 4346 } 4347 4348 SettingBase sb = (SettingBase) pkg.mExtras; 4349 if (sb == null) { 4350 throw new IllegalArgumentException("Unknown package: " + packageName); 4351 } 4352 4353 PermissionsState permissionsState = sb.getPermissionsState(); 4354 4355 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4356 4357 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4358 // Install and runtime permissions are stored in different places, 4359 // so figure out what permission changed and persist the change. 4360 if (permissionsState.getInstallPermissionState(name) != null) { 4361 scheduleWriteSettingsLocked(); 4362 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4363 || hadState) { 4364 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4365 } 4366 } 4367 } 4368 } 4369 4370 /** 4371 * Update the permission flags for all packages and runtime permissions of a user in order 4372 * to allow device or profile owner to remove POLICY_FIXED. 4373 */ 4374 @Override 4375 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4376 if (!sUserManager.exists(userId)) { 4377 return; 4378 } 4379 4380 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4381 4382 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4383 true /* requireFullPermission */, true /* checkShell */, 4384 "updatePermissionFlagsForAllApps"); 4385 4386 // Only the system can change system fixed flags. 4387 if (getCallingUid() != Process.SYSTEM_UID) { 4388 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4389 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4390 } 4391 4392 synchronized (mPackages) { 4393 boolean changed = false; 4394 final int packageCount = mPackages.size(); 4395 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4396 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4397 SettingBase sb = (SettingBase) pkg.mExtras; 4398 if (sb == null) { 4399 continue; 4400 } 4401 PermissionsState permissionsState = sb.getPermissionsState(); 4402 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4403 userId, flagMask, flagValues); 4404 } 4405 if (changed) { 4406 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4407 } 4408 } 4409 } 4410 4411 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4412 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4413 != PackageManager.PERMISSION_GRANTED 4414 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4415 != PackageManager.PERMISSION_GRANTED) { 4416 throw new SecurityException(message + " requires " 4417 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4418 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4419 } 4420 } 4421 4422 @Override 4423 public boolean shouldShowRequestPermissionRationale(String permissionName, 4424 String packageName, int userId) { 4425 if (UserHandle.getCallingUserId() != userId) { 4426 mContext.enforceCallingPermission( 4427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4428 "canShowRequestPermissionRationale for user " + userId); 4429 } 4430 4431 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4432 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4433 return false; 4434 } 4435 4436 if (checkPermission(permissionName, packageName, userId) 4437 == PackageManager.PERMISSION_GRANTED) { 4438 return false; 4439 } 4440 4441 final int flags; 4442 4443 final long identity = Binder.clearCallingIdentity(); 4444 try { 4445 flags = getPermissionFlags(permissionName, 4446 packageName, userId); 4447 } finally { 4448 Binder.restoreCallingIdentity(identity); 4449 } 4450 4451 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4452 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4453 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4454 4455 if ((flags & fixedFlags) != 0) { 4456 return false; 4457 } 4458 4459 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4460 } 4461 4462 @Override 4463 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4464 mContext.enforceCallingOrSelfPermission( 4465 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4466 "addOnPermissionsChangeListener"); 4467 4468 synchronized (mPackages) { 4469 mOnPermissionChangeListeners.addListenerLocked(listener); 4470 } 4471 } 4472 4473 @Override 4474 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4475 synchronized (mPackages) { 4476 mOnPermissionChangeListeners.removeListenerLocked(listener); 4477 } 4478 } 4479 4480 @Override 4481 public boolean isProtectedBroadcast(String actionName) { 4482 synchronized (mPackages) { 4483 if (mProtectedBroadcasts.contains(actionName)) { 4484 return true; 4485 } else if (actionName != null) { 4486 // TODO: remove these terrible hacks 4487 if (actionName.startsWith("android.net.netmon.lingerExpired") 4488 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4489 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4490 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4491 return true; 4492 } 4493 } 4494 } 4495 return false; 4496 } 4497 4498 @Override 4499 public int checkSignatures(String pkg1, String pkg2) { 4500 synchronized (mPackages) { 4501 final PackageParser.Package p1 = mPackages.get(pkg1); 4502 final PackageParser.Package p2 = mPackages.get(pkg2); 4503 if (p1 == null || p1.mExtras == null 4504 || p2 == null || p2.mExtras == null) { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 return compareSignatures(p1.mSignatures, p2.mSignatures); 4508 } 4509 } 4510 4511 @Override 4512 public int checkUidSignatures(int uid1, int uid2) { 4513 // Map to base uids. 4514 uid1 = UserHandle.getAppId(uid1); 4515 uid2 = UserHandle.getAppId(uid2); 4516 // reader 4517 synchronized (mPackages) { 4518 Signature[] s1; 4519 Signature[] s2; 4520 Object obj = mSettings.getUserIdLPr(uid1); 4521 if (obj != null) { 4522 if (obj instanceof SharedUserSetting) { 4523 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4524 } else if (obj instanceof PackageSetting) { 4525 s1 = ((PackageSetting)obj).signatures.mSignatures; 4526 } else { 4527 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4528 } 4529 } else { 4530 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4531 } 4532 obj = mSettings.getUserIdLPr(uid2); 4533 if (obj != null) { 4534 if (obj instanceof SharedUserSetting) { 4535 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4536 } else if (obj instanceof PackageSetting) { 4537 s2 = ((PackageSetting)obj).signatures.mSignatures; 4538 } else { 4539 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4540 } 4541 } else { 4542 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4543 } 4544 return compareSignatures(s1, s2); 4545 } 4546 } 4547 4548 /** 4549 * This method should typically only be used when granting or revoking 4550 * permissions, since the app may immediately restart after this call. 4551 * <p> 4552 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4553 * guard your work against the app being relaunched. 4554 */ 4555 private void killUid(int appId, int userId, String reason) { 4556 final long identity = Binder.clearCallingIdentity(); 4557 try { 4558 IActivityManager am = ActivityManagerNative.getDefault(); 4559 if (am != null) { 4560 try { 4561 am.killUid(appId, userId, reason); 4562 } catch (RemoteException e) { 4563 /* ignore - same process */ 4564 } 4565 } 4566 } finally { 4567 Binder.restoreCallingIdentity(identity); 4568 } 4569 } 4570 4571 /** 4572 * Compares two sets of signatures. Returns: 4573 * <br /> 4574 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4575 * <br /> 4576 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4577 * <br /> 4578 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4579 * <br /> 4580 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4581 * <br /> 4582 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4583 */ 4584 static int compareSignatures(Signature[] s1, Signature[] s2) { 4585 if (s1 == null) { 4586 return s2 == null 4587 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4588 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4589 } 4590 4591 if (s2 == null) { 4592 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4593 } 4594 4595 if (s1.length != s2.length) { 4596 return PackageManager.SIGNATURE_NO_MATCH; 4597 } 4598 4599 // Since both signature sets are of size 1, we can compare without HashSets. 4600 if (s1.length == 1) { 4601 return s1[0].equals(s2[0]) ? 4602 PackageManager.SIGNATURE_MATCH : 4603 PackageManager.SIGNATURE_NO_MATCH; 4604 } 4605 4606 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4607 for (Signature sig : s1) { 4608 set1.add(sig); 4609 } 4610 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4611 for (Signature sig : s2) { 4612 set2.add(sig); 4613 } 4614 // Make sure s2 contains all signatures in s1. 4615 if (set1.equals(set2)) { 4616 return PackageManager.SIGNATURE_MATCH; 4617 } 4618 return PackageManager.SIGNATURE_NO_MATCH; 4619 } 4620 4621 /** 4622 * If the database version for this type of package (internal storage or 4623 * external storage) is less than the version where package signatures 4624 * were updated, return true. 4625 */ 4626 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4627 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4628 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4629 } 4630 4631 /** 4632 * Used for backward compatibility to make sure any packages with 4633 * certificate chains get upgraded to the new style. {@code existingSigs} 4634 * will be in the old format (since they were stored on disk from before the 4635 * system upgrade) and {@code scannedSigs} will be in the newer format. 4636 */ 4637 private int compareSignaturesCompat(PackageSignatures existingSigs, 4638 PackageParser.Package scannedPkg) { 4639 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4640 return PackageManager.SIGNATURE_NO_MATCH; 4641 } 4642 4643 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4644 for (Signature sig : existingSigs.mSignatures) { 4645 existingSet.add(sig); 4646 } 4647 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4648 for (Signature sig : scannedPkg.mSignatures) { 4649 try { 4650 Signature[] chainSignatures = sig.getChainSignatures(); 4651 for (Signature chainSig : chainSignatures) { 4652 scannedCompatSet.add(chainSig); 4653 } 4654 } catch (CertificateEncodingException e) { 4655 scannedCompatSet.add(sig); 4656 } 4657 } 4658 /* 4659 * Make sure the expanded scanned set contains all signatures in the 4660 * existing one. 4661 */ 4662 if (scannedCompatSet.equals(existingSet)) { 4663 // Migrate the old signatures to the new scheme. 4664 existingSigs.assignSignatures(scannedPkg.mSignatures); 4665 // The new KeySets will be re-added later in the scanning process. 4666 synchronized (mPackages) { 4667 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4668 } 4669 return PackageManager.SIGNATURE_MATCH; 4670 } 4671 return PackageManager.SIGNATURE_NO_MATCH; 4672 } 4673 4674 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4675 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4676 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4677 } 4678 4679 private int compareSignaturesRecover(PackageSignatures existingSigs, 4680 PackageParser.Package scannedPkg) { 4681 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4682 return PackageManager.SIGNATURE_NO_MATCH; 4683 } 4684 4685 String msg = null; 4686 try { 4687 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4688 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4689 + scannedPkg.packageName); 4690 return PackageManager.SIGNATURE_MATCH; 4691 } 4692 } catch (CertificateException e) { 4693 msg = e.getMessage(); 4694 } 4695 4696 logCriticalInfo(Log.INFO, 4697 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4698 return PackageManager.SIGNATURE_NO_MATCH; 4699 } 4700 4701 @Override 4702 public List<String> getAllPackages() { 4703 synchronized (mPackages) { 4704 return new ArrayList<String>(mPackages.keySet()); 4705 } 4706 } 4707 4708 @Override 4709 public String[] getPackagesForUid(int uid) { 4710 uid = UserHandle.getAppId(uid); 4711 // reader 4712 synchronized (mPackages) { 4713 Object obj = mSettings.getUserIdLPr(uid); 4714 if (obj instanceof SharedUserSetting) { 4715 final SharedUserSetting sus = (SharedUserSetting) obj; 4716 final int N = sus.packages.size(); 4717 final String[] res = new String[N]; 4718 final Iterator<PackageSetting> it = sus.packages.iterator(); 4719 int i = 0; 4720 while (it.hasNext()) { 4721 res[i++] = it.next().name; 4722 } 4723 return res; 4724 } else if (obj instanceof PackageSetting) { 4725 final PackageSetting ps = (PackageSetting) obj; 4726 return new String[] { ps.name }; 4727 } 4728 } 4729 return null; 4730 } 4731 4732 @Override 4733 public String getNameForUid(int uid) { 4734 // reader 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.name + ":" + sus.userId; 4740 } else if (obj instanceof PackageSetting) { 4741 final PackageSetting ps = (PackageSetting) obj; 4742 return ps.name; 4743 } 4744 } 4745 return null; 4746 } 4747 4748 @Override 4749 public int getUidForSharedUser(String sharedUserName) { 4750 if(sharedUserName == null) { 4751 return -1; 4752 } 4753 // reader 4754 synchronized (mPackages) { 4755 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4756 if (suid == null) { 4757 return -1; 4758 } 4759 return suid.userId; 4760 } 4761 } 4762 4763 @Override 4764 public int getFlagsForUid(int uid) { 4765 synchronized (mPackages) { 4766 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4767 if (obj instanceof SharedUserSetting) { 4768 final SharedUserSetting sus = (SharedUserSetting) obj; 4769 return sus.pkgFlags; 4770 } else if (obj instanceof PackageSetting) { 4771 final PackageSetting ps = (PackageSetting) obj; 4772 return ps.pkgFlags; 4773 } 4774 } 4775 return 0; 4776 } 4777 4778 @Override 4779 public int getPrivateFlagsForUid(int uid) { 4780 synchronized (mPackages) { 4781 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4782 if (obj instanceof SharedUserSetting) { 4783 final SharedUserSetting sus = (SharedUserSetting) obj; 4784 return sus.pkgPrivateFlags; 4785 } else if (obj instanceof PackageSetting) { 4786 final PackageSetting ps = (PackageSetting) obj; 4787 return ps.pkgPrivateFlags; 4788 } 4789 } 4790 return 0; 4791 } 4792 4793 @Override 4794 public boolean isUidPrivileged(int uid) { 4795 uid = UserHandle.getAppId(uid); 4796 // reader 4797 synchronized (mPackages) { 4798 Object obj = mSettings.getUserIdLPr(uid); 4799 if (obj instanceof SharedUserSetting) { 4800 final SharedUserSetting sus = (SharedUserSetting) obj; 4801 final Iterator<PackageSetting> it = sus.packages.iterator(); 4802 while (it.hasNext()) { 4803 if (it.next().isPrivileged()) { 4804 return true; 4805 } 4806 } 4807 } else if (obj instanceof PackageSetting) { 4808 final PackageSetting ps = (PackageSetting) obj; 4809 return ps.isPrivileged(); 4810 } 4811 } 4812 return false; 4813 } 4814 4815 @Override 4816 public String[] getAppOpPermissionPackages(String permissionName) { 4817 synchronized (mPackages) { 4818 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4819 if (pkgs == null) { 4820 return null; 4821 } 4822 return pkgs.toArray(new String[pkgs.size()]); 4823 } 4824 } 4825 4826 @Override 4827 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4828 int flags, int userId) { 4829 try { 4830 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4831 4832 if (!sUserManager.exists(userId)) return null; 4833 flags = updateFlagsForResolve(flags, userId, intent); 4834 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4835 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4836 4837 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4838 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4839 flags, userId); 4840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4841 4842 final ResolveInfo bestChoice = 4843 chooseBestActivity(intent, resolvedType, flags, query, userId); 4844 4845 if (isEphemeralAllowed(intent, query, userId)) { 4846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4847 final EphemeralResolveInfo ai = 4848 getEphemeralResolveInfo(intent, resolvedType, userId); 4849 if (ai != null) { 4850 if (DEBUG_EPHEMERAL) { 4851 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4852 } 4853 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4854 bestChoice.ephemeralResolveInfo = ai; 4855 } 4856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4857 } 4858 return bestChoice; 4859 } finally { 4860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4861 } 4862 } 4863 4864 @Override 4865 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4866 IntentFilter filter, int match, ComponentName activity) { 4867 final int userId = UserHandle.getCallingUserId(); 4868 if (DEBUG_PREFERRED) { 4869 Log.v(TAG, "setLastChosenActivity intent=" + intent 4870 + " resolvedType=" + resolvedType 4871 + " flags=" + flags 4872 + " filter=" + filter 4873 + " match=" + match 4874 + " activity=" + activity); 4875 filter.dump(new PrintStreamPrinter(System.out), " "); 4876 } 4877 intent.setComponent(null); 4878 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4879 userId); 4880 // Find any earlier preferred or last chosen entries and nuke them 4881 findPreferredActivity(intent, resolvedType, 4882 flags, query, 0, false, true, false, userId); 4883 // Add the new activity as the last chosen for this filter 4884 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4885 "Setting last chosen"); 4886 } 4887 4888 @Override 4889 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4890 final int userId = UserHandle.getCallingUserId(); 4891 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4892 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4893 userId); 4894 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4895 false, false, false, userId); 4896 } 4897 4898 4899 private boolean isEphemeralAllowed( 4900 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4901 // Short circuit and return early if possible. 4902 if (DISABLE_EPHEMERAL_APPS) { 4903 return false; 4904 } 4905 final int callingUser = UserHandle.getCallingUserId(); 4906 if (callingUser != UserHandle.USER_SYSTEM) { 4907 return false; 4908 } 4909 if (mEphemeralResolverConnection == null) { 4910 return false; 4911 } 4912 if (intent.getComponent() != null) { 4913 return false; 4914 } 4915 if (intent.getPackage() != null) { 4916 return false; 4917 } 4918 final boolean isWebUri = hasWebURI(intent); 4919 if (!isWebUri) { 4920 return false; 4921 } 4922 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4923 synchronized (mPackages) { 4924 final int count = resolvedActivites.size(); 4925 for (int n = 0; n < count; n++) { 4926 ResolveInfo info = resolvedActivites.get(n); 4927 String packageName = info.activityInfo.packageName; 4928 PackageSetting ps = mSettings.mPackages.get(packageName); 4929 if (ps != null) { 4930 // Try to get the status from User settings first 4931 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4932 int status = (int) (packedStatus >> 32); 4933 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4934 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4935 if (DEBUG_EPHEMERAL) { 4936 Slog.v(TAG, "DENY ephemeral apps;" 4937 + " pkg: " + packageName + ", status: " + status); 4938 } 4939 return false; 4940 } 4941 } 4942 } 4943 } 4944 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4945 return true; 4946 } 4947 4948 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4949 int userId) { 4950 MessageDigest digest = null; 4951 try { 4952 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4953 } catch (NoSuchAlgorithmException e) { 4954 // If we can't create a digest, ignore ephemeral apps. 4955 return null; 4956 } 4957 4958 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4959 final byte[] digestBytes = digest.digest(hostBytes); 4960 int shaPrefix = 4961 digestBytes[0] << 24 4962 | digestBytes[1] << 16 4963 | digestBytes[2] << 8 4964 | digestBytes[3] << 0; 4965 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4966 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4967 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4968 // No hash prefix match; there are no ephemeral apps for this domain. 4969 return null; 4970 } 4971 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4972 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4973 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4974 continue; 4975 } 4976 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4977 // No filters; this should never happen. 4978 if (filters.isEmpty()) { 4979 continue; 4980 } 4981 // We have a domain match; resolve the filters to see if anything matches. 4982 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4983 for (int j = filters.size() - 1; j >= 0; --j) { 4984 final EphemeralResolveIntentInfo intentInfo = 4985 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4986 ephemeralResolver.addFilter(intentInfo); 4987 } 4988 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4989 intent, resolvedType, false /*defaultOnly*/, userId); 4990 if (!matchedResolveInfoList.isEmpty()) { 4991 return matchedResolveInfoList.get(0); 4992 } 4993 } 4994 // Hash or filter mis-match; no ephemeral apps for this domain. 4995 return null; 4996 } 4997 4998 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4999 int flags, List<ResolveInfo> query, int userId) { 5000 if (query != null) { 5001 final int N = query.size(); 5002 if (N == 1) { 5003 return query.get(0); 5004 } else if (N > 1) { 5005 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5006 // If there is more than one activity with the same priority, 5007 // then let the user decide between them. 5008 ResolveInfo r0 = query.get(0); 5009 ResolveInfo r1 = query.get(1); 5010 if (DEBUG_INTENT_MATCHING || debug) { 5011 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5012 + r1.activityInfo.name + "=" + r1.priority); 5013 } 5014 // If the first activity has a higher priority, or a different 5015 // default, then it is always desirable to pick it. 5016 if (r0.priority != r1.priority 5017 || r0.preferredOrder != r1.preferredOrder 5018 || r0.isDefault != r1.isDefault) { 5019 return query.get(0); 5020 } 5021 // If we have saved a preference for a preferred activity for 5022 // this Intent, use that. 5023 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5024 flags, query, r0.priority, true, false, debug, userId); 5025 if (ri != null) { 5026 return ri; 5027 } 5028 ri = new ResolveInfo(mResolveInfo); 5029 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5030 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5031 // If all of the options come from the same package, show the application's 5032 // label and icon instead of the generic resolver's. 5033 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5034 // and then throw away the ResolveInfo itself, meaning that the caller loses 5035 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5036 // a fallback for this case; we only set the target package's resources on 5037 // the ResolveInfo, not the ActivityInfo. 5038 final String intentPackage = intent.getPackage(); 5039 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5040 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5041 ri.resolvePackageName = intentPackage; 5042 if (userNeedsBadging(userId)) { 5043 ri.noResourceId = true; 5044 } else { 5045 ri.icon = appi.icon; 5046 } 5047 ri.iconResourceId = appi.icon; 5048 ri.labelRes = appi.labelRes; 5049 } 5050 ri.activityInfo.applicationInfo = new ApplicationInfo( 5051 ri.activityInfo.applicationInfo); 5052 if (userId != 0) { 5053 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5054 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5055 } 5056 // Make sure that the resolver is displayable in car mode 5057 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5058 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5059 return ri; 5060 } 5061 } 5062 return null; 5063 } 5064 5065 /** 5066 * Return true if the given list is not empty and all of its contents have 5067 * an activityInfo with the given package name. 5068 */ 5069 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5070 if (ArrayUtils.isEmpty(list)) { 5071 return false; 5072 } 5073 for (int i = 0, N = list.size(); i < N; i++) { 5074 final ResolveInfo ri = list.get(i); 5075 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5076 if (ai == null || !packageName.equals(ai.packageName)) { 5077 return false; 5078 } 5079 } 5080 return true; 5081 } 5082 5083 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5084 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5085 final int N = query.size(); 5086 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5087 .get(userId); 5088 // Get the list of persistent preferred activities that handle the intent 5089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5090 List<PersistentPreferredActivity> pprefs = ppir != null 5091 ? ppir.queryIntent(intent, resolvedType, 5092 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5093 : null; 5094 if (pprefs != null && pprefs.size() > 0) { 5095 final int M = pprefs.size(); 5096 for (int i=0; i<M; i++) { 5097 final PersistentPreferredActivity ppa = pprefs.get(i); 5098 if (DEBUG_PREFERRED || debug) { 5099 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5100 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5101 + "\n component=" + ppa.mComponent); 5102 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5103 } 5104 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5105 flags | MATCH_DISABLED_COMPONENTS, userId); 5106 if (DEBUG_PREFERRED || debug) { 5107 Slog.v(TAG, "Found persistent preferred activity:"); 5108 if (ai != null) { 5109 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5110 } else { 5111 Slog.v(TAG, " null"); 5112 } 5113 } 5114 if (ai == null) { 5115 // This previously registered persistent preferred activity 5116 // component is no longer known. Ignore it and do NOT remove it. 5117 continue; 5118 } 5119 for (int j=0; j<N; j++) { 5120 final ResolveInfo ri = query.get(j); 5121 if (!ri.activityInfo.applicationInfo.packageName 5122 .equals(ai.applicationInfo.packageName)) { 5123 continue; 5124 } 5125 if (!ri.activityInfo.name.equals(ai.name)) { 5126 continue; 5127 } 5128 // Found a persistent preference that can handle the intent. 5129 if (DEBUG_PREFERRED || debug) { 5130 Slog.v(TAG, "Returning persistent preferred activity: " + 5131 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5132 } 5133 return ri; 5134 } 5135 } 5136 } 5137 return null; 5138 } 5139 5140 // TODO: handle preferred activities missing while user has amnesia 5141 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5142 List<ResolveInfo> query, int priority, boolean always, 5143 boolean removeMatches, boolean debug, int userId) { 5144 if (!sUserManager.exists(userId)) return null; 5145 flags = updateFlagsForResolve(flags, userId, intent); 5146 // writer 5147 synchronized (mPackages) { 5148 if (intent.getSelector() != null) { 5149 intent = intent.getSelector(); 5150 } 5151 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5152 5153 // Try to find a matching persistent preferred activity. 5154 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5155 debug, userId); 5156 5157 // If a persistent preferred activity matched, use it. 5158 if (pri != null) { 5159 return pri; 5160 } 5161 5162 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5163 // Get the list of preferred activities that handle the intent 5164 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5165 List<PreferredActivity> prefs = pir != null 5166 ? pir.queryIntent(intent, resolvedType, 5167 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5168 : null; 5169 if (prefs != null && prefs.size() > 0) { 5170 boolean changed = false; 5171 try { 5172 // First figure out how good the original match set is. 5173 // We will only allow preferred activities that came 5174 // from the same match quality. 5175 int match = 0; 5176 5177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5178 5179 final int N = query.size(); 5180 for (int j=0; j<N; j++) { 5181 final ResolveInfo ri = query.get(j); 5182 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5183 + ": 0x" + Integer.toHexString(match)); 5184 if (ri.match > match) { 5185 match = ri.match; 5186 } 5187 } 5188 5189 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5190 + Integer.toHexString(match)); 5191 5192 match &= IntentFilter.MATCH_CATEGORY_MASK; 5193 final int M = prefs.size(); 5194 for (int i=0; i<M; i++) { 5195 final PreferredActivity pa = prefs.get(i); 5196 if (DEBUG_PREFERRED || debug) { 5197 Slog.v(TAG, "Checking PreferredActivity ds=" 5198 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5199 + "\n component=" + pa.mPref.mComponent); 5200 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5201 } 5202 if (pa.mPref.mMatch != match) { 5203 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5204 + Integer.toHexString(pa.mPref.mMatch)); 5205 continue; 5206 } 5207 // If it's not an "always" type preferred activity and that's what we're 5208 // looking for, skip it. 5209 if (always && !pa.mPref.mAlways) { 5210 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5211 continue; 5212 } 5213 final ActivityInfo ai = getActivityInfo( 5214 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5215 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5216 userId); 5217 if (DEBUG_PREFERRED || debug) { 5218 Slog.v(TAG, "Found preferred activity:"); 5219 if (ai != null) { 5220 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5221 } else { 5222 Slog.v(TAG, " null"); 5223 } 5224 } 5225 if (ai == null) { 5226 // This previously registered preferred activity 5227 // component is no longer known. Most likely an update 5228 // to the app was installed and in the new version this 5229 // component no longer exists. Clean it up by removing 5230 // it from the preferred activities list, and skip it. 5231 Slog.w(TAG, "Removing dangling preferred activity: " 5232 + pa.mPref.mComponent); 5233 pir.removeFilter(pa); 5234 changed = true; 5235 continue; 5236 } 5237 for (int j=0; j<N; j++) { 5238 final ResolveInfo ri = query.get(j); 5239 if (!ri.activityInfo.applicationInfo.packageName 5240 .equals(ai.applicationInfo.packageName)) { 5241 continue; 5242 } 5243 if (!ri.activityInfo.name.equals(ai.name)) { 5244 continue; 5245 } 5246 5247 if (removeMatches) { 5248 pir.removeFilter(pa); 5249 changed = true; 5250 if (DEBUG_PREFERRED) { 5251 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5252 } 5253 break; 5254 } 5255 5256 // Okay we found a previously set preferred or last chosen app. 5257 // If the result set is different from when this 5258 // was created, we need to clear it and re-ask the 5259 // user their preference, if we're looking for an "always" type entry. 5260 if (always && !pa.mPref.sameSet(query)) { 5261 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5262 + intent + " type " + resolvedType); 5263 if (DEBUG_PREFERRED) { 5264 Slog.v(TAG, "Removing preferred activity since set changed " 5265 + pa.mPref.mComponent); 5266 } 5267 pir.removeFilter(pa); 5268 // Re-add the filter as a "last chosen" entry (!always) 5269 PreferredActivity lastChosen = new PreferredActivity( 5270 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5271 pir.addFilter(lastChosen); 5272 changed = true; 5273 return null; 5274 } 5275 5276 // Yay! Either the set matched or we're looking for the last chosen 5277 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5278 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5279 return ri; 5280 } 5281 } 5282 } finally { 5283 if (changed) { 5284 if (DEBUG_PREFERRED) { 5285 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5286 } 5287 scheduleWritePackageRestrictionsLocked(userId); 5288 } 5289 } 5290 } 5291 } 5292 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5293 return null; 5294 } 5295 5296 /* 5297 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5298 */ 5299 @Override 5300 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5301 int targetUserId) { 5302 mContext.enforceCallingOrSelfPermission( 5303 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5304 List<CrossProfileIntentFilter> matches = 5305 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5306 if (matches != null) { 5307 int size = matches.size(); 5308 for (int i = 0; i < size; i++) { 5309 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5310 } 5311 } 5312 if (hasWebURI(intent)) { 5313 // cross-profile app linking works only towards the parent. 5314 final UserInfo parent = getProfileParent(sourceUserId); 5315 synchronized(mPackages) { 5316 int flags = updateFlagsForResolve(0, parent.id, intent); 5317 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5318 intent, resolvedType, flags, sourceUserId, parent.id); 5319 return xpDomainInfo != null; 5320 } 5321 } 5322 return false; 5323 } 5324 5325 private UserInfo getProfileParent(int userId) { 5326 final long identity = Binder.clearCallingIdentity(); 5327 try { 5328 return sUserManager.getProfileParent(userId); 5329 } finally { 5330 Binder.restoreCallingIdentity(identity); 5331 } 5332 } 5333 5334 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5335 String resolvedType, int userId) { 5336 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5337 if (resolver != null) { 5338 return resolver.queryIntent(intent, resolvedType, false, userId); 5339 } 5340 return null; 5341 } 5342 5343 @Override 5344 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5345 String resolvedType, int flags, int userId) { 5346 try { 5347 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5348 5349 return new ParceledListSlice<>( 5350 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5351 } finally { 5352 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5353 } 5354 } 5355 5356 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5357 String resolvedType, int flags, int userId) { 5358 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5359 flags = updateFlagsForResolve(flags, userId, intent); 5360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5361 false /* requireFullPermission */, false /* checkShell */, 5362 "query intent activities"); 5363 ComponentName comp = intent.getComponent(); 5364 if (comp == null) { 5365 if (intent.getSelector() != null) { 5366 intent = intent.getSelector(); 5367 comp = intent.getComponent(); 5368 } 5369 } 5370 5371 if (comp != null) { 5372 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5373 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5374 if (ai != null) { 5375 final ResolveInfo ri = new ResolveInfo(); 5376 ri.activityInfo = ai; 5377 list.add(ri); 5378 } 5379 return list; 5380 } 5381 5382 // reader 5383 synchronized (mPackages) { 5384 final String pkgName = intent.getPackage(); 5385 if (pkgName == null) { 5386 List<CrossProfileIntentFilter> matchingFilters = 5387 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5388 // Check for results that need to skip the current profile. 5389 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5390 resolvedType, flags, userId); 5391 if (xpResolveInfo != null) { 5392 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5393 result.add(xpResolveInfo); 5394 return filterIfNotSystemUser(result, userId); 5395 } 5396 5397 // Check for results in the current profile. 5398 List<ResolveInfo> result = mActivities.queryIntent( 5399 intent, resolvedType, flags, userId); 5400 result = filterIfNotSystemUser(result, userId); 5401 5402 // Check for cross profile results. 5403 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5404 xpResolveInfo = queryCrossProfileIntents( 5405 matchingFilters, intent, resolvedType, flags, userId, 5406 hasNonNegativePriorityResult); 5407 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5408 boolean isVisibleToUser = filterIfNotSystemUser( 5409 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5410 if (isVisibleToUser) { 5411 result.add(xpResolveInfo); 5412 Collections.sort(result, mResolvePrioritySorter); 5413 } 5414 } 5415 if (hasWebURI(intent)) { 5416 CrossProfileDomainInfo xpDomainInfo = null; 5417 final UserInfo parent = getProfileParent(userId); 5418 if (parent != null) { 5419 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5420 flags, userId, parent.id); 5421 } 5422 if (xpDomainInfo != null) { 5423 if (xpResolveInfo != null) { 5424 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5425 // in the result. 5426 result.remove(xpResolveInfo); 5427 } 5428 if (result.size() == 0) { 5429 result.add(xpDomainInfo.resolveInfo); 5430 return result; 5431 } 5432 } else if (result.size() <= 1) { 5433 return result; 5434 } 5435 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5436 xpDomainInfo, userId); 5437 Collections.sort(result, mResolvePrioritySorter); 5438 } 5439 return result; 5440 } 5441 final PackageParser.Package pkg = mPackages.get(pkgName); 5442 if (pkg != null) { 5443 return filterIfNotSystemUser( 5444 mActivities.queryIntentForPackage( 5445 intent, resolvedType, flags, pkg.activities, userId), 5446 userId); 5447 } 5448 return new ArrayList<ResolveInfo>(); 5449 } 5450 } 5451 5452 private static class CrossProfileDomainInfo { 5453 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5454 ResolveInfo resolveInfo; 5455 /* Best domain verification status of the activities found in the other profile */ 5456 int bestDomainVerificationStatus; 5457 } 5458 5459 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5460 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5461 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5462 sourceUserId)) { 5463 return null; 5464 } 5465 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5466 resolvedType, flags, parentUserId); 5467 5468 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5469 return null; 5470 } 5471 CrossProfileDomainInfo result = null; 5472 int size = resultTargetUser.size(); 5473 for (int i = 0; i < size; i++) { 5474 ResolveInfo riTargetUser = resultTargetUser.get(i); 5475 // Intent filter verification is only for filters that specify a host. So don't return 5476 // those that handle all web uris. 5477 if (riTargetUser.handleAllWebDataURI) { 5478 continue; 5479 } 5480 String packageName = riTargetUser.activityInfo.packageName; 5481 PackageSetting ps = mSettings.mPackages.get(packageName); 5482 if (ps == null) { 5483 continue; 5484 } 5485 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5486 int status = (int)(verificationState >> 32); 5487 if (result == null) { 5488 result = new CrossProfileDomainInfo(); 5489 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5490 sourceUserId, parentUserId); 5491 result.bestDomainVerificationStatus = status; 5492 } else { 5493 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5494 result.bestDomainVerificationStatus); 5495 } 5496 } 5497 // Don't consider matches with status NEVER across profiles. 5498 if (result != null && result.bestDomainVerificationStatus 5499 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5500 return null; 5501 } 5502 return result; 5503 } 5504 5505 /** 5506 * Verification statuses are ordered from the worse to the best, except for 5507 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5508 */ 5509 private int bestDomainVerificationStatus(int status1, int status2) { 5510 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5511 return status2; 5512 } 5513 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5514 return status1; 5515 } 5516 return (int) MathUtils.max(status1, status2); 5517 } 5518 5519 private boolean isUserEnabled(int userId) { 5520 long callingId = Binder.clearCallingIdentity(); 5521 try { 5522 UserInfo userInfo = sUserManager.getUserInfo(userId); 5523 return userInfo != null && userInfo.isEnabled(); 5524 } finally { 5525 Binder.restoreCallingIdentity(callingId); 5526 } 5527 } 5528 5529 /** 5530 * Filter out activities with systemUserOnly flag set, when current user is not System. 5531 * 5532 * @return filtered list 5533 */ 5534 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5535 if (userId == UserHandle.USER_SYSTEM) { 5536 return resolveInfos; 5537 } 5538 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5539 ResolveInfo info = resolveInfos.get(i); 5540 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5541 resolveInfos.remove(i); 5542 } 5543 } 5544 return resolveInfos; 5545 } 5546 5547 /** 5548 * @param resolveInfos list of resolve infos in descending priority order 5549 * @return if the list contains a resolve info with non-negative priority 5550 */ 5551 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5552 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5553 } 5554 5555 private static boolean hasWebURI(Intent intent) { 5556 if (intent.getData() == null) { 5557 return false; 5558 } 5559 final String scheme = intent.getScheme(); 5560 if (TextUtils.isEmpty(scheme)) { 5561 return false; 5562 } 5563 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5564 } 5565 5566 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5567 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5568 int userId) { 5569 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5570 5571 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5572 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5573 candidates.size()); 5574 } 5575 5576 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5577 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5578 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5579 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5580 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5581 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5582 5583 synchronized (mPackages) { 5584 final int count = candidates.size(); 5585 // First, try to use linked apps. Partition the candidates into four lists: 5586 // one for the final results, one for the "do not use ever", one for "undefined status" 5587 // and finally one for "browser app type". 5588 for (int n=0; n<count; n++) { 5589 ResolveInfo info = candidates.get(n); 5590 String packageName = info.activityInfo.packageName; 5591 PackageSetting ps = mSettings.mPackages.get(packageName); 5592 if (ps != null) { 5593 // Add to the special match all list (Browser use case) 5594 if (info.handleAllWebDataURI) { 5595 matchAllList.add(info); 5596 continue; 5597 } 5598 // Try to get the status from User settings first 5599 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5600 int status = (int)(packedStatus >> 32); 5601 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5602 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5603 if (DEBUG_DOMAIN_VERIFICATION) { 5604 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5605 + " : linkgen=" + linkGeneration); 5606 } 5607 // Use link-enabled generation as preferredOrder, i.e. 5608 // prefer newly-enabled over earlier-enabled. 5609 info.preferredOrder = linkGeneration; 5610 alwaysList.add(info); 5611 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5612 if (DEBUG_DOMAIN_VERIFICATION) { 5613 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5614 } 5615 neverList.add(info); 5616 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5617 if (DEBUG_DOMAIN_VERIFICATION) { 5618 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5619 } 5620 alwaysAskList.add(info); 5621 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5622 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5623 if (DEBUG_DOMAIN_VERIFICATION) { 5624 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5625 } 5626 undefinedList.add(info); 5627 } 5628 } 5629 } 5630 5631 // We'll want to include browser possibilities in a few cases 5632 boolean includeBrowser = false; 5633 5634 // First try to add the "always" resolution(s) for the current user, if any 5635 if (alwaysList.size() > 0) { 5636 result.addAll(alwaysList); 5637 } else { 5638 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5639 result.addAll(undefinedList); 5640 // Maybe add one for the other profile. 5641 if (xpDomainInfo != null && ( 5642 xpDomainInfo.bestDomainVerificationStatus 5643 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5644 result.add(xpDomainInfo.resolveInfo); 5645 } 5646 includeBrowser = true; 5647 } 5648 5649 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5650 // If there were 'always' entries their preferred order has been set, so we also 5651 // back that off to make the alternatives equivalent 5652 if (alwaysAskList.size() > 0) { 5653 for (ResolveInfo i : result) { 5654 i.preferredOrder = 0; 5655 } 5656 result.addAll(alwaysAskList); 5657 includeBrowser = true; 5658 } 5659 5660 if (includeBrowser) { 5661 // Also add browsers (all of them or only the default one) 5662 if (DEBUG_DOMAIN_VERIFICATION) { 5663 Slog.v(TAG, " ...including browsers in candidate set"); 5664 } 5665 if ((matchFlags & MATCH_ALL) != 0) { 5666 result.addAll(matchAllList); 5667 } else { 5668 // Browser/generic handling case. If there's a default browser, go straight 5669 // to that (but only if there is no other higher-priority match). 5670 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5671 int maxMatchPrio = 0; 5672 ResolveInfo defaultBrowserMatch = null; 5673 final int numCandidates = matchAllList.size(); 5674 for (int n = 0; n < numCandidates; n++) { 5675 ResolveInfo info = matchAllList.get(n); 5676 // track the highest overall match priority... 5677 if (info.priority > maxMatchPrio) { 5678 maxMatchPrio = info.priority; 5679 } 5680 // ...and the highest-priority default browser match 5681 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5682 if (defaultBrowserMatch == null 5683 || (defaultBrowserMatch.priority < info.priority)) { 5684 if (debug) { 5685 Slog.v(TAG, "Considering default browser match " + info); 5686 } 5687 defaultBrowserMatch = info; 5688 } 5689 } 5690 } 5691 if (defaultBrowserMatch != null 5692 && defaultBrowserMatch.priority >= maxMatchPrio 5693 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5694 { 5695 if (debug) { 5696 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5697 } 5698 result.add(defaultBrowserMatch); 5699 } else { 5700 result.addAll(matchAllList); 5701 } 5702 } 5703 5704 // If there is nothing selected, add all candidates and remove the ones that the user 5705 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5706 if (result.size() == 0) { 5707 result.addAll(candidates); 5708 result.removeAll(neverList); 5709 } 5710 } 5711 } 5712 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5713 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5714 result.size()); 5715 for (ResolveInfo info : result) { 5716 Slog.v(TAG, " + " + info.activityInfo); 5717 } 5718 } 5719 return result; 5720 } 5721 5722 // Returns a packed value as a long: 5723 // 5724 // high 'int'-sized word: link status: undefined/ask/never/always. 5725 // low 'int'-sized word: relative priority among 'always' results. 5726 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5727 long result = ps.getDomainVerificationStatusForUser(userId); 5728 // if none available, get the master status 5729 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5730 if (ps.getIntentFilterVerificationInfo() != null) { 5731 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5732 } 5733 } 5734 return result; 5735 } 5736 5737 private ResolveInfo querySkipCurrentProfileIntents( 5738 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5739 int flags, int sourceUserId) { 5740 if (matchingFilters != null) { 5741 int size = matchingFilters.size(); 5742 for (int i = 0; i < size; i ++) { 5743 CrossProfileIntentFilter filter = matchingFilters.get(i); 5744 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5745 // Checking if there are activities in the target user that can handle the 5746 // intent. 5747 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5748 resolvedType, flags, sourceUserId); 5749 if (resolveInfo != null) { 5750 return resolveInfo; 5751 } 5752 } 5753 } 5754 } 5755 return null; 5756 } 5757 5758 // Return matching ResolveInfo in target user if any. 5759 private ResolveInfo queryCrossProfileIntents( 5760 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5761 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5762 if (matchingFilters != null) { 5763 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5764 // match the same intent. For performance reasons, it is better not to 5765 // run queryIntent twice for the same userId 5766 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5767 int size = matchingFilters.size(); 5768 for (int i = 0; i < size; i++) { 5769 CrossProfileIntentFilter filter = matchingFilters.get(i); 5770 int targetUserId = filter.getTargetUserId(); 5771 boolean skipCurrentProfile = 5772 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5773 boolean skipCurrentProfileIfNoMatchFound = 5774 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5775 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5776 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5777 // Checking if there are activities in the target user that can handle the 5778 // intent. 5779 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5780 resolvedType, flags, sourceUserId); 5781 if (resolveInfo != null) return resolveInfo; 5782 alreadyTriedUserIds.put(targetUserId, true); 5783 } 5784 } 5785 } 5786 return null; 5787 } 5788 5789 /** 5790 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5791 * will forward the intent to the filter's target user. 5792 * Otherwise, returns null. 5793 */ 5794 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5795 String resolvedType, int flags, int sourceUserId) { 5796 int targetUserId = filter.getTargetUserId(); 5797 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5798 resolvedType, flags, targetUserId); 5799 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5800 // If all the matches in the target profile are suspended, return null. 5801 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5802 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5803 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5804 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5805 targetUserId); 5806 } 5807 } 5808 } 5809 return null; 5810 } 5811 5812 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5813 int sourceUserId, int targetUserId) { 5814 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5815 long ident = Binder.clearCallingIdentity(); 5816 boolean targetIsProfile; 5817 try { 5818 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5819 } finally { 5820 Binder.restoreCallingIdentity(ident); 5821 } 5822 String className; 5823 if (targetIsProfile) { 5824 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5825 } else { 5826 className = FORWARD_INTENT_TO_PARENT; 5827 } 5828 ComponentName forwardingActivityComponentName = new ComponentName( 5829 mAndroidApplication.packageName, className); 5830 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5831 sourceUserId); 5832 if (!targetIsProfile) { 5833 forwardingActivityInfo.showUserIcon = targetUserId; 5834 forwardingResolveInfo.noResourceId = true; 5835 } 5836 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5837 forwardingResolveInfo.priority = 0; 5838 forwardingResolveInfo.preferredOrder = 0; 5839 forwardingResolveInfo.match = 0; 5840 forwardingResolveInfo.isDefault = true; 5841 forwardingResolveInfo.filter = filter; 5842 forwardingResolveInfo.targetUserId = targetUserId; 5843 return forwardingResolveInfo; 5844 } 5845 5846 @Override 5847 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5848 Intent[] specifics, String[] specificTypes, Intent intent, 5849 String resolvedType, int flags, int userId) { 5850 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5851 specificTypes, intent, resolvedType, flags, userId)); 5852 } 5853 5854 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5855 Intent[] specifics, String[] specificTypes, Intent intent, 5856 String resolvedType, int flags, int userId) { 5857 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5858 flags = updateFlagsForResolve(flags, userId, intent); 5859 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5860 false /* requireFullPermission */, false /* checkShell */, 5861 "query intent activity options"); 5862 final String resultsAction = intent.getAction(); 5863 5864 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5865 | PackageManager.GET_RESOLVED_FILTER, userId); 5866 5867 if (DEBUG_INTENT_MATCHING) { 5868 Log.v(TAG, "Query " + intent + ": " + results); 5869 } 5870 5871 int specificsPos = 0; 5872 int N; 5873 5874 // todo: note that the algorithm used here is O(N^2). This 5875 // isn't a problem in our current environment, but if we start running 5876 // into situations where we have more than 5 or 10 matches then this 5877 // should probably be changed to something smarter... 5878 5879 // First we go through and resolve each of the specific items 5880 // that were supplied, taking care of removing any corresponding 5881 // duplicate items in the generic resolve list. 5882 if (specifics != null) { 5883 for (int i=0; i<specifics.length; i++) { 5884 final Intent sintent = specifics[i]; 5885 if (sintent == null) { 5886 continue; 5887 } 5888 5889 if (DEBUG_INTENT_MATCHING) { 5890 Log.v(TAG, "Specific #" + i + ": " + sintent); 5891 } 5892 5893 String action = sintent.getAction(); 5894 if (resultsAction != null && resultsAction.equals(action)) { 5895 // If this action was explicitly requested, then don't 5896 // remove things that have it. 5897 action = null; 5898 } 5899 5900 ResolveInfo ri = null; 5901 ActivityInfo ai = null; 5902 5903 ComponentName comp = sintent.getComponent(); 5904 if (comp == null) { 5905 ri = resolveIntent( 5906 sintent, 5907 specificTypes != null ? specificTypes[i] : null, 5908 flags, userId); 5909 if (ri == null) { 5910 continue; 5911 } 5912 if (ri == mResolveInfo) { 5913 // ACK! Must do something better with this. 5914 } 5915 ai = ri.activityInfo; 5916 comp = new ComponentName(ai.applicationInfo.packageName, 5917 ai.name); 5918 } else { 5919 ai = getActivityInfo(comp, flags, userId); 5920 if (ai == null) { 5921 continue; 5922 } 5923 } 5924 5925 // Look for any generic query activities that are duplicates 5926 // of this specific one, and remove them from the results. 5927 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5928 N = results.size(); 5929 int j; 5930 for (j=specificsPos; j<N; j++) { 5931 ResolveInfo sri = results.get(j); 5932 if ((sri.activityInfo.name.equals(comp.getClassName()) 5933 && sri.activityInfo.applicationInfo.packageName.equals( 5934 comp.getPackageName())) 5935 || (action != null && sri.filter.matchAction(action))) { 5936 results.remove(j); 5937 if (DEBUG_INTENT_MATCHING) Log.v( 5938 TAG, "Removing duplicate item from " + j 5939 + " due to specific " + specificsPos); 5940 if (ri == null) { 5941 ri = sri; 5942 } 5943 j--; 5944 N--; 5945 } 5946 } 5947 5948 // Add this specific item to its proper place. 5949 if (ri == null) { 5950 ri = new ResolveInfo(); 5951 ri.activityInfo = ai; 5952 } 5953 results.add(specificsPos, ri); 5954 ri.specificIndex = i; 5955 specificsPos++; 5956 } 5957 } 5958 5959 // Now we go through the remaining generic results and remove any 5960 // duplicate actions that are found here. 5961 N = results.size(); 5962 for (int i=specificsPos; i<N-1; i++) { 5963 final ResolveInfo rii = results.get(i); 5964 if (rii.filter == null) { 5965 continue; 5966 } 5967 5968 // Iterate over all of the actions of this result's intent 5969 // filter... typically this should be just one. 5970 final Iterator<String> it = rii.filter.actionsIterator(); 5971 if (it == null) { 5972 continue; 5973 } 5974 while (it.hasNext()) { 5975 final String action = it.next(); 5976 if (resultsAction != null && resultsAction.equals(action)) { 5977 // If this action was explicitly requested, then don't 5978 // remove things that have it. 5979 continue; 5980 } 5981 for (int j=i+1; j<N; j++) { 5982 final ResolveInfo rij = results.get(j); 5983 if (rij.filter != null && rij.filter.hasAction(action)) { 5984 results.remove(j); 5985 if (DEBUG_INTENT_MATCHING) Log.v( 5986 TAG, "Removing duplicate item from " + j 5987 + " due to action " + action + " at " + i); 5988 j--; 5989 N--; 5990 } 5991 } 5992 } 5993 5994 // If the caller didn't request filter information, drop it now 5995 // so we don't have to marshall/unmarshall it. 5996 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5997 rii.filter = null; 5998 } 5999 } 6000 6001 // Filter out the caller activity if so requested. 6002 if (caller != null) { 6003 N = results.size(); 6004 for (int i=0; i<N; i++) { 6005 ActivityInfo ainfo = results.get(i).activityInfo; 6006 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6007 && caller.getClassName().equals(ainfo.name)) { 6008 results.remove(i); 6009 break; 6010 } 6011 } 6012 } 6013 6014 // If the caller didn't request filter information, 6015 // drop them now so we don't have to 6016 // marshall/unmarshall it. 6017 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6018 N = results.size(); 6019 for (int i=0; i<N; i++) { 6020 results.get(i).filter = null; 6021 } 6022 } 6023 6024 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6025 return results; 6026 } 6027 6028 @Override 6029 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6030 String resolvedType, int flags, int userId) { 6031 return new ParceledListSlice<>( 6032 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6033 } 6034 6035 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6036 String resolvedType, int flags, int userId) { 6037 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6038 flags = updateFlagsForResolve(flags, userId, intent); 6039 ComponentName comp = intent.getComponent(); 6040 if (comp == null) { 6041 if (intent.getSelector() != null) { 6042 intent = intent.getSelector(); 6043 comp = intent.getComponent(); 6044 } 6045 } 6046 if (comp != null) { 6047 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6048 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6049 if (ai != null) { 6050 ResolveInfo ri = new ResolveInfo(); 6051 ri.activityInfo = ai; 6052 list.add(ri); 6053 } 6054 return list; 6055 } 6056 6057 // reader 6058 synchronized (mPackages) { 6059 String pkgName = intent.getPackage(); 6060 if (pkgName == null) { 6061 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6062 } 6063 final PackageParser.Package pkg = mPackages.get(pkgName); 6064 if (pkg != null) { 6065 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6066 userId); 6067 } 6068 return Collections.emptyList(); 6069 } 6070 } 6071 6072 @Override 6073 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6074 if (!sUserManager.exists(userId)) return null; 6075 flags = updateFlagsForResolve(flags, userId, intent); 6076 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6077 if (query != null) { 6078 if (query.size() >= 1) { 6079 // If there is more than one service with the same priority, 6080 // just arbitrarily pick the first one. 6081 return query.get(0); 6082 } 6083 } 6084 return null; 6085 } 6086 6087 @Override 6088 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6089 String resolvedType, int flags, int userId) { 6090 return new ParceledListSlice<>( 6091 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6092 } 6093 6094 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6095 String resolvedType, int flags, int userId) { 6096 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6097 flags = updateFlagsForResolve(flags, userId, intent); 6098 ComponentName comp = intent.getComponent(); 6099 if (comp == null) { 6100 if (intent.getSelector() != null) { 6101 intent = intent.getSelector(); 6102 comp = intent.getComponent(); 6103 } 6104 } 6105 if (comp != null) { 6106 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6107 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6108 if (si != null) { 6109 final ResolveInfo ri = new ResolveInfo(); 6110 ri.serviceInfo = si; 6111 list.add(ri); 6112 } 6113 return list; 6114 } 6115 6116 // reader 6117 synchronized (mPackages) { 6118 String pkgName = intent.getPackage(); 6119 if (pkgName == null) { 6120 return mServices.queryIntent(intent, resolvedType, flags, userId); 6121 } 6122 final PackageParser.Package pkg = mPackages.get(pkgName); 6123 if (pkg != null) { 6124 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6125 userId); 6126 } 6127 return Collections.emptyList(); 6128 } 6129 } 6130 6131 @Override 6132 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6133 String resolvedType, int flags, int userId) { 6134 return new ParceledListSlice<>( 6135 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6136 } 6137 6138 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6139 Intent intent, String resolvedType, int flags, int userId) { 6140 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6141 flags = updateFlagsForResolve(flags, userId, intent); 6142 ComponentName comp = intent.getComponent(); 6143 if (comp == null) { 6144 if (intent.getSelector() != null) { 6145 intent = intent.getSelector(); 6146 comp = intent.getComponent(); 6147 } 6148 } 6149 if (comp != null) { 6150 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6151 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6152 if (pi != null) { 6153 final ResolveInfo ri = new ResolveInfo(); 6154 ri.providerInfo = pi; 6155 list.add(ri); 6156 } 6157 return list; 6158 } 6159 6160 // reader 6161 synchronized (mPackages) { 6162 String pkgName = intent.getPackage(); 6163 if (pkgName == null) { 6164 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6165 } 6166 final PackageParser.Package pkg = mPackages.get(pkgName); 6167 if (pkg != null) { 6168 return mProviders.queryIntentForPackage( 6169 intent, resolvedType, flags, pkg.providers, userId); 6170 } 6171 return Collections.emptyList(); 6172 } 6173 } 6174 6175 @Override 6176 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6177 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6178 flags = updateFlagsForPackage(flags, userId, null); 6179 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6180 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6181 true /* requireFullPermission */, false /* checkShell */, 6182 "get installed packages"); 6183 6184 // writer 6185 synchronized (mPackages) { 6186 ArrayList<PackageInfo> list; 6187 if (listUninstalled) { 6188 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6189 for (PackageSetting ps : mSettings.mPackages.values()) { 6190 final PackageInfo pi; 6191 if (ps.pkg != null) { 6192 pi = generatePackageInfo(ps, flags, userId); 6193 } else { 6194 pi = generatePackageInfo(ps, flags, userId); 6195 } 6196 if (pi != null) { 6197 list.add(pi); 6198 } 6199 } 6200 } else { 6201 list = new ArrayList<PackageInfo>(mPackages.size()); 6202 for (PackageParser.Package p : mPackages.values()) { 6203 final PackageInfo pi = 6204 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6205 if (pi != null) { 6206 list.add(pi); 6207 } 6208 } 6209 } 6210 6211 return new ParceledListSlice<PackageInfo>(list); 6212 } 6213 } 6214 6215 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6216 String[] permissions, boolean[] tmp, int flags, int userId) { 6217 int numMatch = 0; 6218 final PermissionsState permissionsState = ps.getPermissionsState(); 6219 for (int i=0; i<permissions.length; i++) { 6220 final String permission = permissions[i]; 6221 if (permissionsState.hasPermission(permission, userId)) { 6222 tmp[i] = true; 6223 numMatch++; 6224 } else { 6225 tmp[i] = false; 6226 } 6227 } 6228 if (numMatch == 0) { 6229 return; 6230 } 6231 final PackageInfo pi; 6232 if (ps.pkg != null) { 6233 pi = generatePackageInfo(ps, flags, userId); 6234 } else { 6235 pi = generatePackageInfo(ps, flags, userId); 6236 } 6237 // The above might return null in cases of uninstalled apps or install-state 6238 // skew across users/profiles. 6239 if (pi != null) { 6240 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6241 if (numMatch == permissions.length) { 6242 pi.requestedPermissions = permissions; 6243 } else { 6244 pi.requestedPermissions = new String[numMatch]; 6245 numMatch = 0; 6246 for (int i=0; i<permissions.length; i++) { 6247 if (tmp[i]) { 6248 pi.requestedPermissions[numMatch] = permissions[i]; 6249 numMatch++; 6250 } 6251 } 6252 } 6253 } 6254 list.add(pi); 6255 } 6256 } 6257 6258 @Override 6259 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6260 String[] permissions, int flags, int userId) { 6261 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6262 flags = updateFlagsForPackage(flags, userId, permissions); 6263 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6264 6265 // writer 6266 synchronized (mPackages) { 6267 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6268 boolean[] tmpBools = new boolean[permissions.length]; 6269 if (listUninstalled) { 6270 for (PackageSetting ps : mSettings.mPackages.values()) { 6271 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6272 } 6273 } else { 6274 for (PackageParser.Package pkg : mPackages.values()) { 6275 PackageSetting ps = (PackageSetting)pkg.mExtras; 6276 if (ps != null) { 6277 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6278 userId); 6279 } 6280 } 6281 } 6282 6283 return new ParceledListSlice<PackageInfo>(list); 6284 } 6285 } 6286 6287 @Override 6288 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6289 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6290 flags = updateFlagsForApplication(flags, userId, null); 6291 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6292 6293 // writer 6294 synchronized (mPackages) { 6295 ArrayList<ApplicationInfo> list; 6296 if (listUninstalled) { 6297 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6298 for (PackageSetting ps : mSettings.mPackages.values()) { 6299 ApplicationInfo ai; 6300 if (ps.pkg != null) { 6301 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6302 ps.readUserState(userId), userId); 6303 } else { 6304 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6305 } 6306 if (ai != null) { 6307 list.add(ai); 6308 } 6309 } 6310 } else { 6311 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6312 for (PackageParser.Package p : mPackages.values()) { 6313 if (p.mExtras != null) { 6314 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6315 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6316 if (ai != null) { 6317 list.add(ai); 6318 } 6319 } 6320 } 6321 } 6322 6323 return new ParceledListSlice<ApplicationInfo>(list); 6324 } 6325 } 6326 6327 @Override 6328 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6329 if (DISABLE_EPHEMERAL_APPS) { 6330 return null; 6331 } 6332 6333 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6334 "getEphemeralApplications"); 6335 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6336 true /* requireFullPermission */, false /* checkShell */, 6337 "getEphemeralApplications"); 6338 synchronized (mPackages) { 6339 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6340 .getEphemeralApplicationsLPw(userId); 6341 if (ephemeralApps != null) { 6342 return new ParceledListSlice<>(ephemeralApps); 6343 } 6344 } 6345 return null; 6346 } 6347 6348 @Override 6349 public boolean isEphemeralApplication(String packageName, int userId) { 6350 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6351 true /* requireFullPermission */, false /* checkShell */, 6352 "isEphemeral"); 6353 if (DISABLE_EPHEMERAL_APPS) { 6354 return false; 6355 } 6356 6357 if (!isCallerSameApp(packageName)) { 6358 return false; 6359 } 6360 synchronized (mPackages) { 6361 PackageParser.Package pkg = mPackages.get(packageName); 6362 if (pkg != null) { 6363 return pkg.applicationInfo.isEphemeralApp(); 6364 } 6365 } 6366 return false; 6367 } 6368 6369 @Override 6370 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6371 if (DISABLE_EPHEMERAL_APPS) { 6372 return null; 6373 } 6374 6375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6376 true /* requireFullPermission */, false /* checkShell */, 6377 "getCookie"); 6378 if (!isCallerSameApp(packageName)) { 6379 return null; 6380 } 6381 synchronized (mPackages) { 6382 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6383 packageName, userId); 6384 } 6385 } 6386 6387 @Override 6388 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6389 if (DISABLE_EPHEMERAL_APPS) { 6390 return true; 6391 } 6392 6393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6394 true /* requireFullPermission */, true /* checkShell */, 6395 "setCookie"); 6396 if (!isCallerSameApp(packageName)) { 6397 return false; 6398 } 6399 synchronized (mPackages) { 6400 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6401 packageName, cookie, userId); 6402 } 6403 } 6404 6405 @Override 6406 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6407 if (DISABLE_EPHEMERAL_APPS) { 6408 return null; 6409 } 6410 6411 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6412 "getEphemeralApplicationIcon"); 6413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6414 true /* requireFullPermission */, false /* checkShell */, 6415 "getEphemeralApplicationIcon"); 6416 synchronized (mPackages) { 6417 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6418 packageName, userId); 6419 } 6420 } 6421 6422 private boolean isCallerSameApp(String packageName) { 6423 PackageParser.Package pkg = mPackages.get(packageName); 6424 return pkg != null 6425 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6426 } 6427 6428 @Override 6429 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6430 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6431 } 6432 6433 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6434 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6435 6436 // reader 6437 synchronized (mPackages) { 6438 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6439 final int userId = UserHandle.getCallingUserId(); 6440 while (i.hasNext()) { 6441 final PackageParser.Package p = i.next(); 6442 if (p.applicationInfo == null) continue; 6443 6444 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6445 && !p.applicationInfo.isDirectBootAware(); 6446 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6447 && p.applicationInfo.isDirectBootAware(); 6448 6449 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6450 && (!mSafeMode || isSystemApp(p)) 6451 && (matchesUnaware || matchesAware)) { 6452 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6453 if (ps != null) { 6454 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6455 ps.readUserState(userId), userId); 6456 if (ai != null) { 6457 finalList.add(ai); 6458 } 6459 } 6460 } 6461 } 6462 } 6463 6464 return finalList; 6465 } 6466 6467 @Override 6468 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6469 if (!sUserManager.exists(userId)) return null; 6470 flags = updateFlagsForComponent(flags, userId, name); 6471 // reader 6472 synchronized (mPackages) { 6473 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6474 PackageSetting ps = provider != null 6475 ? mSettings.mPackages.get(provider.owner.packageName) 6476 : null; 6477 return ps != null 6478 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6479 ? PackageParser.generateProviderInfo(provider, flags, 6480 ps.readUserState(userId), userId) 6481 : null; 6482 } 6483 } 6484 6485 /** 6486 * @deprecated 6487 */ 6488 @Deprecated 6489 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6490 // reader 6491 synchronized (mPackages) { 6492 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6493 .entrySet().iterator(); 6494 final int userId = UserHandle.getCallingUserId(); 6495 while (i.hasNext()) { 6496 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6497 PackageParser.Provider p = entry.getValue(); 6498 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6499 6500 if (ps != null && p.syncable 6501 && (!mSafeMode || (p.info.applicationInfo.flags 6502 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6503 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6504 ps.readUserState(userId), userId); 6505 if (info != null) { 6506 outNames.add(entry.getKey()); 6507 outInfo.add(info); 6508 } 6509 } 6510 } 6511 } 6512 } 6513 6514 @Override 6515 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6516 int uid, int flags) { 6517 final int userId = processName != null ? UserHandle.getUserId(uid) 6518 : UserHandle.getCallingUserId(); 6519 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6520 flags = updateFlagsForComponent(flags, userId, processName); 6521 6522 ArrayList<ProviderInfo> finalList = null; 6523 // reader 6524 synchronized (mPackages) { 6525 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6526 while (i.hasNext()) { 6527 final PackageParser.Provider p = i.next(); 6528 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6529 if (ps != null && p.info.authority != null 6530 && (processName == null 6531 || (p.info.processName.equals(processName) 6532 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6533 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6534 if (finalList == null) { 6535 finalList = new ArrayList<ProviderInfo>(3); 6536 } 6537 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6538 ps.readUserState(userId), userId); 6539 if (info != null) { 6540 finalList.add(info); 6541 } 6542 } 6543 } 6544 } 6545 6546 if (finalList != null) { 6547 Collections.sort(finalList, mProviderInitOrderSorter); 6548 return new ParceledListSlice<ProviderInfo>(finalList); 6549 } 6550 6551 return ParceledListSlice.emptyList(); 6552 } 6553 6554 @Override 6555 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6556 // reader 6557 synchronized (mPackages) { 6558 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6559 return PackageParser.generateInstrumentationInfo(i, flags); 6560 } 6561 } 6562 6563 @Override 6564 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6565 String targetPackage, int flags) { 6566 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6567 } 6568 6569 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6570 int flags) { 6571 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6572 6573 // reader 6574 synchronized (mPackages) { 6575 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6576 while (i.hasNext()) { 6577 final PackageParser.Instrumentation p = i.next(); 6578 if (targetPackage == null 6579 || targetPackage.equals(p.info.targetPackage)) { 6580 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6581 flags); 6582 if (ii != null) { 6583 finalList.add(ii); 6584 } 6585 } 6586 } 6587 } 6588 6589 return finalList; 6590 } 6591 6592 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6593 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6594 if (overlays == null) { 6595 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6596 return; 6597 } 6598 for (PackageParser.Package opkg : overlays.values()) { 6599 // Not much to do if idmap fails: we already logged the error 6600 // and we certainly don't want to abort installation of pkg simply 6601 // because an overlay didn't fit properly. For these reasons, 6602 // ignore the return value of createIdmapForPackagePairLI. 6603 createIdmapForPackagePairLI(pkg, opkg); 6604 } 6605 } 6606 6607 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6608 PackageParser.Package opkg) { 6609 if (!opkg.mTrustedOverlay) { 6610 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6611 opkg.baseCodePath + ": overlay not trusted"); 6612 return false; 6613 } 6614 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6615 if (overlaySet == null) { 6616 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6617 opkg.baseCodePath + " but target package has no known overlays"); 6618 return false; 6619 } 6620 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6621 // TODO: generate idmap for split APKs 6622 try { 6623 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6624 } catch (InstallerException e) { 6625 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6626 + opkg.baseCodePath); 6627 return false; 6628 } 6629 PackageParser.Package[] overlayArray = 6630 overlaySet.values().toArray(new PackageParser.Package[0]); 6631 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6632 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6633 return p1.mOverlayPriority - p2.mOverlayPriority; 6634 } 6635 }; 6636 Arrays.sort(overlayArray, cmp); 6637 6638 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6639 int i = 0; 6640 for (PackageParser.Package p : overlayArray) { 6641 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6642 } 6643 return true; 6644 } 6645 6646 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6648 try { 6649 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6650 } finally { 6651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6652 } 6653 } 6654 6655 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6656 final File[] files = dir.listFiles(); 6657 if (ArrayUtils.isEmpty(files)) { 6658 Log.d(TAG, "No files in app dir " + dir); 6659 return; 6660 } 6661 6662 if (DEBUG_PACKAGE_SCANNING) { 6663 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6664 + " flags=0x" + Integer.toHexString(parseFlags)); 6665 } 6666 6667 for (File file : files) { 6668 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6669 && !PackageInstallerService.isStageName(file.getName()); 6670 if (!isPackage) { 6671 // Ignore entries which are not packages 6672 continue; 6673 } 6674 try { 6675 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6676 scanFlags, currentTime, null); 6677 } catch (PackageManagerException e) { 6678 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6679 6680 // Delete invalid userdata apps 6681 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6682 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6683 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6684 removeCodePathLI(file); 6685 } 6686 } 6687 } 6688 } 6689 6690 private static File getSettingsProblemFile() { 6691 File dataDir = Environment.getDataDirectory(); 6692 File systemDir = new File(dataDir, "system"); 6693 File fname = new File(systemDir, "uiderrors.txt"); 6694 return fname; 6695 } 6696 6697 static void reportSettingsProblem(int priority, String msg) { 6698 logCriticalInfo(priority, msg); 6699 } 6700 6701 static void logCriticalInfo(int priority, String msg) { 6702 Slog.println(priority, TAG, msg); 6703 EventLogTags.writePmCriticalInfo(msg); 6704 try { 6705 File fname = getSettingsProblemFile(); 6706 FileOutputStream out = new FileOutputStream(fname, true); 6707 PrintWriter pw = new FastPrintWriter(out); 6708 SimpleDateFormat formatter = new SimpleDateFormat(); 6709 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6710 pw.println(dateString + ": " + msg); 6711 pw.close(); 6712 FileUtils.setPermissions( 6713 fname.toString(), 6714 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6715 -1, -1); 6716 } catch (java.io.IOException e) { 6717 } 6718 } 6719 6720 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6721 final int policyFlags) throws PackageManagerException { 6722 if (ps != null 6723 && ps.codePath.equals(srcFile) 6724 && ps.timeStamp == srcFile.lastModified() 6725 && !isCompatSignatureUpdateNeeded(pkg) 6726 && !isRecoverSignatureUpdateNeeded(pkg)) { 6727 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6728 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6729 ArraySet<PublicKey> signingKs; 6730 synchronized (mPackages) { 6731 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6732 } 6733 if (ps.signatures.mSignatures != null 6734 && ps.signatures.mSignatures.length != 0 6735 && signingKs != null) { 6736 // Optimization: reuse the existing cached certificates 6737 // if the package appears to be unchanged. 6738 pkg.mSignatures = ps.signatures.mSignatures; 6739 pkg.mSigningKeys = signingKs; 6740 return; 6741 } 6742 6743 Slog.w(TAG, "PackageSetting for " + ps.name 6744 + " is missing signatures. Collecting certs again to recover them."); 6745 } else { 6746 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6747 } 6748 6749 try { 6750 PackageParser.collectCertificates(pkg, policyFlags); 6751 } catch (PackageParserException e) { 6752 throw PackageManagerException.from(e); 6753 } 6754 } 6755 6756 /** 6757 * Traces a package scan. 6758 * @see #scanPackageLI(File, int, int, long, UserHandle) 6759 */ 6760 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6761 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6762 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6763 try { 6764 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6765 } finally { 6766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6767 } 6768 } 6769 6770 /** 6771 * Scans a package and returns the newly parsed package. 6772 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6773 */ 6774 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6775 long currentTime, UserHandle user) throws PackageManagerException { 6776 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6777 PackageParser pp = new PackageParser(); 6778 pp.setSeparateProcesses(mSeparateProcesses); 6779 pp.setOnlyCoreApps(mOnlyCore); 6780 pp.setDisplayMetrics(mMetrics); 6781 6782 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6783 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6784 } 6785 6786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6787 final PackageParser.Package pkg; 6788 try { 6789 pkg = pp.parsePackage(scanFile, parseFlags); 6790 } catch (PackageParserException e) { 6791 throw PackageManagerException.from(e); 6792 } finally { 6793 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6794 } 6795 6796 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6797 } 6798 6799 /** 6800 * Scans a package and returns the newly parsed package. 6801 * @throws PackageManagerException on a parse error. 6802 */ 6803 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6804 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6805 throws PackageManagerException { 6806 // If the package has children and this is the first dive in the function 6807 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6808 // packages (parent and children) would be successfully scanned before the 6809 // actual scan since scanning mutates internal state and we want to atomically 6810 // install the package and its children. 6811 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6812 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6813 scanFlags |= SCAN_CHECK_ONLY; 6814 } 6815 } else { 6816 scanFlags &= ~SCAN_CHECK_ONLY; 6817 } 6818 6819 // Scan the parent 6820 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6821 scanFlags, currentTime, user); 6822 6823 // Scan the children 6824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6825 for (int i = 0; i < childCount; i++) { 6826 PackageParser.Package childPackage = pkg.childPackages.get(i); 6827 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6828 currentTime, user); 6829 } 6830 6831 6832 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6833 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6834 } 6835 6836 return scannedPkg; 6837 } 6838 6839 /** 6840 * Scans a package and returns the newly parsed package. 6841 * @throws PackageManagerException on a parse error. 6842 */ 6843 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6844 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6845 throws PackageManagerException { 6846 PackageSetting ps = null; 6847 PackageSetting updatedPkg; 6848 // reader 6849 synchronized (mPackages) { 6850 // Look to see if we already know about this package. 6851 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6852 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6853 // This package has been renamed to its original name. Let's 6854 // use that. 6855 ps = mSettings.peekPackageLPr(oldName); 6856 } 6857 // If there was no original package, see one for the real package name. 6858 if (ps == null) { 6859 ps = mSettings.peekPackageLPr(pkg.packageName); 6860 } 6861 // Check to see if this package could be hiding/updating a system 6862 // package. Must look for it either under the original or real 6863 // package name depending on our state. 6864 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6865 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6866 6867 // If this is a package we don't know about on the system partition, we 6868 // may need to remove disabled child packages on the system partition 6869 // or may need to not add child packages if the parent apk is updated 6870 // on the data partition and no longer defines this child package. 6871 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6872 // If this is a parent package for an updated system app and this system 6873 // app got an OTA update which no longer defines some of the child packages 6874 // we have to prune them from the disabled system packages. 6875 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6876 if (disabledPs != null) { 6877 final int scannedChildCount = (pkg.childPackages != null) 6878 ? pkg.childPackages.size() : 0; 6879 final int disabledChildCount = disabledPs.childPackageNames != null 6880 ? disabledPs.childPackageNames.size() : 0; 6881 for (int i = 0; i < disabledChildCount; i++) { 6882 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6883 boolean disabledPackageAvailable = false; 6884 for (int j = 0; j < scannedChildCount; j++) { 6885 PackageParser.Package childPkg = pkg.childPackages.get(j); 6886 if (childPkg.packageName.equals(disabledChildPackageName)) { 6887 disabledPackageAvailable = true; 6888 break; 6889 } 6890 } 6891 if (!disabledPackageAvailable) { 6892 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6893 } 6894 } 6895 } 6896 } 6897 } 6898 6899 boolean updatedPkgBetter = false; 6900 // First check if this is a system package that may involve an update 6901 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6902 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6903 // it needs to drop FLAG_PRIVILEGED. 6904 if (locationIsPrivileged(scanFile)) { 6905 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6906 } else { 6907 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6908 } 6909 6910 if (ps != null && !ps.codePath.equals(scanFile)) { 6911 // The path has changed from what was last scanned... check the 6912 // version of the new path against what we have stored to determine 6913 // what to do. 6914 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6915 if (pkg.mVersionCode <= ps.versionCode) { 6916 // The system package has been updated and the code path does not match 6917 // Ignore entry. Skip it. 6918 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6919 + " ignored: updated version " + ps.versionCode 6920 + " better than this " + pkg.mVersionCode); 6921 if (!updatedPkg.codePath.equals(scanFile)) { 6922 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6923 + ps.name + " changing from " + updatedPkg.codePathString 6924 + " to " + scanFile); 6925 updatedPkg.codePath = scanFile; 6926 updatedPkg.codePathString = scanFile.toString(); 6927 updatedPkg.resourcePath = scanFile; 6928 updatedPkg.resourcePathString = scanFile.toString(); 6929 } 6930 updatedPkg.pkg = pkg; 6931 updatedPkg.versionCode = pkg.mVersionCode; 6932 6933 // Update the disabled system child packages to point to the package too. 6934 final int childCount = updatedPkg.childPackageNames != null 6935 ? updatedPkg.childPackageNames.size() : 0; 6936 for (int i = 0; i < childCount; i++) { 6937 String childPackageName = updatedPkg.childPackageNames.get(i); 6938 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6939 childPackageName); 6940 if (updatedChildPkg != null) { 6941 updatedChildPkg.pkg = pkg; 6942 updatedChildPkg.versionCode = pkg.mVersionCode; 6943 } 6944 } 6945 6946 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6947 + scanFile + " ignored: updated version " + ps.versionCode 6948 + " better than this " + pkg.mVersionCode); 6949 } else { 6950 // The current app on the system partition is better than 6951 // what we have updated to on the data partition; switch 6952 // back to the system partition version. 6953 // At this point, its safely assumed that package installation for 6954 // apps in system partition will go through. If not there won't be a working 6955 // version of the app 6956 // writer 6957 synchronized (mPackages) { 6958 // Just remove the loaded entries from package lists. 6959 mPackages.remove(ps.name); 6960 } 6961 6962 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6963 + " reverting from " + ps.codePathString 6964 + ": new version " + pkg.mVersionCode 6965 + " better than installed " + ps.versionCode); 6966 6967 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6968 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6969 synchronized (mInstallLock) { 6970 args.cleanUpResourcesLI(); 6971 } 6972 synchronized (mPackages) { 6973 mSettings.enableSystemPackageLPw(ps.name); 6974 } 6975 updatedPkgBetter = true; 6976 } 6977 } 6978 } 6979 6980 if (updatedPkg != null) { 6981 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6982 // initially 6983 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6984 6985 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6986 // flag set initially 6987 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6988 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6989 } 6990 } 6991 6992 // Verify certificates against what was last scanned 6993 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6994 6995 /* 6996 * A new system app appeared, but we already had a non-system one of the 6997 * same name installed earlier. 6998 */ 6999 boolean shouldHideSystemApp = false; 7000 if (updatedPkg == null && ps != null 7001 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7002 /* 7003 * Check to make sure the signatures match first. If they don't, 7004 * wipe the installed application and its data. 7005 */ 7006 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7007 != PackageManager.SIGNATURE_MATCH) { 7008 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7009 + " signatures don't match existing userdata copy; removing"); 7010 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7011 "scanPackageInternalLI")) { 7012 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7013 } 7014 ps = null; 7015 } else { 7016 /* 7017 * If the newly-added system app is an older version than the 7018 * already installed version, hide it. It will be scanned later 7019 * and re-added like an update. 7020 */ 7021 if (pkg.mVersionCode <= ps.versionCode) { 7022 shouldHideSystemApp = true; 7023 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7024 + " but new version " + pkg.mVersionCode + " better than installed " 7025 + ps.versionCode + "; hiding system"); 7026 } else { 7027 /* 7028 * The newly found system app is a newer version that the 7029 * one previously installed. Simply remove the 7030 * already-installed application and replace it with our own 7031 * while keeping the application data. 7032 */ 7033 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7034 + " reverting from " + ps.codePathString + ": new version " 7035 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7036 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7037 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7038 synchronized (mInstallLock) { 7039 args.cleanUpResourcesLI(); 7040 } 7041 } 7042 } 7043 } 7044 7045 // The apk is forward locked (not public) if its code and resources 7046 // are kept in different files. (except for app in either system or 7047 // vendor path). 7048 // TODO grab this value from PackageSettings 7049 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7050 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7051 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7052 } 7053 } 7054 7055 // TODO: extend to support forward-locked splits 7056 String resourcePath = null; 7057 String baseResourcePath = null; 7058 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7059 if (ps != null && ps.resourcePathString != null) { 7060 resourcePath = ps.resourcePathString; 7061 baseResourcePath = ps.resourcePathString; 7062 } else { 7063 // Should not happen at all. Just log an error. 7064 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7065 } 7066 } else { 7067 resourcePath = pkg.codePath; 7068 baseResourcePath = pkg.baseCodePath; 7069 } 7070 7071 // Set application objects path explicitly. 7072 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7073 pkg.setApplicationInfoCodePath(pkg.codePath); 7074 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7075 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7076 pkg.setApplicationInfoResourcePath(resourcePath); 7077 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7078 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7079 7080 // Note that we invoke the following method only if we are about to unpack an application 7081 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7082 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7083 7084 /* 7085 * If the system app should be overridden by a previously installed 7086 * data, hide the system app now and let the /data/app scan pick it up 7087 * again. 7088 */ 7089 if (shouldHideSystemApp) { 7090 synchronized (mPackages) { 7091 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7092 } 7093 } 7094 7095 return scannedPkg; 7096 } 7097 7098 private static String fixProcessName(String defProcessName, 7099 String processName, int uid) { 7100 if (processName == null) { 7101 return defProcessName; 7102 } 7103 return processName; 7104 } 7105 7106 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7107 throws PackageManagerException { 7108 if (pkgSetting.signatures.mSignatures != null) { 7109 // Already existing package. Make sure signatures match 7110 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7111 == PackageManager.SIGNATURE_MATCH; 7112 if (!match) { 7113 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7114 == PackageManager.SIGNATURE_MATCH; 7115 } 7116 if (!match) { 7117 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7118 == PackageManager.SIGNATURE_MATCH; 7119 } 7120 if (!match) { 7121 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7122 + pkg.packageName + " signatures do not match the " 7123 + "previously installed version; ignoring!"); 7124 } 7125 } 7126 7127 // Check for shared user signatures 7128 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7129 // Already existing package. Make sure signatures match 7130 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7131 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7132 if (!match) { 7133 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7134 == PackageManager.SIGNATURE_MATCH; 7135 } 7136 if (!match) { 7137 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7138 == PackageManager.SIGNATURE_MATCH; 7139 } 7140 if (!match) { 7141 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7142 "Package " + pkg.packageName 7143 + " has no signatures that match those in shared user " 7144 + pkgSetting.sharedUser.name + "; ignoring!"); 7145 } 7146 } 7147 } 7148 7149 /** 7150 * Enforces that only the system UID or root's UID can call a method exposed 7151 * via Binder. 7152 * 7153 * @param message used as message if SecurityException is thrown 7154 * @throws SecurityException if the caller is not system or root 7155 */ 7156 private static final void enforceSystemOrRoot(String message) { 7157 final int uid = Binder.getCallingUid(); 7158 if (uid != Process.SYSTEM_UID && uid != 0) { 7159 throw new SecurityException(message); 7160 } 7161 } 7162 7163 @Override 7164 public void performFstrimIfNeeded() { 7165 enforceSystemOrRoot("Only the system can request fstrim"); 7166 7167 // Before everything else, see whether we need to fstrim. 7168 try { 7169 IMountService ms = PackageHelper.getMountService(); 7170 if (ms != null) { 7171 final boolean isUpgrade = isUpgrade(); 7172 boolean doTrim = isUpgrade; 7173 if (doTrim) { 7174 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7175 } else { 7176 final long interval = android.provider.Settings.Global.getLong( 7177 mContext.getContentResolver(), 7178 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7179 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7180 if (interval > 0) { 7181 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7182 if (timeSinceLast > interval) { 7183 doTrim = true; 7184 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7185 + "; running immediately"); 7186 } 7187 } 7188 } 7189 if (doTrim) { 7190 if (!isFirstBoot()) { 7191 try { 7192 ActivityManagerNative.getDefault().showBootMessage( 7193 mContext.getResources().getString( 7194 R.string.android_upgrading_fstrim), true); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 ms.runMaintenance(); 7199 } 7200 } else { 7201 Slog.e(TAG, "Mount service unavailable!"); 7202 } 7203 } catch (RemoteException e) { 7204 // Can't happen; MountService is local 7205 } 7206 } 7207 7208 @Override 7209 public void updatePackagesIfNeeded() { 7210 enforceSystemOrRoot("Only the system can request package update"); 7211 7212 // We need to re-extract after an OTA. 7213 boolean causeUpgrade = isUpgrade(); 7214 7215 // First boot or factory reset. 7216 // Note: we also handle devices that are upgrading to N right now as if it is their 7217 // first boot, as they do not have profile data. 7218 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7219 7220 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7221 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7222 7223 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7224 return; 7225 } 7226 7227 List<PackageParser.Package> pkgs; 7228 synchronized (mPackages) { 7229 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7230 } 7231 7232 int numberOfPackagesVisited = 0; 7233 int numberOfPackagesOptimized = 0; 7234 int numberOfPackagesSkipped = 0; 7235 int numberOfPackagesFailed = 0; 7236 final int numberOfPackagesToDexopt = pkgs.size(); 7237 final long startTime = System.nanoTime(); 7238 7239 for (PackageParser.Package pkg : pkgs) { 7240 numberOfPackagesVisited++; 7241 7242 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7243 if (DEBUG_DEXOPT) { 7244 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7245 } 7246 numberOfPackagesSkipped++; 7247 continue; 7248 } 7249 7250 if (DEBUG_DEXOPT) { 7251 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7252 numberOfPackagesToDexopt + ": " + pkg.packageName); 7253 } 7254 7255 if (mIsPreNUpgrade) { 7256 try { 7257 ActivityManagerNative.getDefault().showBootMessage( 7258 mContext.getResources().getString(R.string.android_upgrading_apk, 7259 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7260 } catch (RemoteException e) { 7261 } 7262 } 7263 7264 // checkProfiles is false to avoid merging profiles during boot which 7265 // might interfere with background compilation (b/28612421). 7266 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7267 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7268 // trade-off worth doing to save boot time work. 7269 int dexOptStatus = performDexOptTraced(pkg.packageName, 7270 false /* checkProfiles */, 7271 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7272 false /* force */); 7273 switch (dexOptStatus) { 7274 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7275 numberOfPackagesOptimized++; 7276 break; 7277 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7278 numberOfPackagesSkipped++; 7279 break; 7280 case PackageDexOptimizer.DEX_OPT_FAILED: 7281 numberOfPackagesFailed++; 7282 break; 7283 default: 7284 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7285 break; 7286 } 7287 } 7288 7289 final int elapsedTimeSeconds = 7290 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7291 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7292 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7293 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7294 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7295 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7296 } 7297 7298 @Override 7299 public void notifyPackageUse(String packageName, int reason) { 7300 synchronized (mPackages) { 7301 PackageParser.Package p = mPackages.get(packageName); 7302 if (p == null) { 7303 return; 7304 } 7305 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7306 } 7307 } 7308 7309 // TODO: this is not used nor needed. Delete it. 7310 @Override 7311 public boolean performDexOptIfNeeded(String packageName) { 7312 int dexOptStatus = performDexOptTraced(packageName, 7313 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7314 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7315 } 7316 7317 @Override 7318 public boolean performDexOpt(String packageName, 7319 boolean checkProfiles, int compileReason, boolean force) { 7320 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7321 getCompilerFilterForReason(compileReason), force); 7322 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7323 } 7324 7325 @Override 7326 public boolean performDexOptMode(String packageName, 7327 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7328 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7329 targetCompilerFilter, force); 7330 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7331 } 7332 7333 private int performDexOptTraced(String packageName, 7334 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7336 try { 7337 return performDexOptInternal(packageName, checkProfiles, 7338 targetCompilerFilter, force); 7339 } finally { 7340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7341 } 7342 } 7343 7344 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7345 // if the package can now be considered up to date for the given filter. 7346 private int performDexOptInternal(String packageName, 7347 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7348 PackageParser.Package p; 7349 synchronized (mPackages) { 7350 p = mPackages.get(packageName); 7351 if (p == null) { 7352 // Package could not be found. Report failure. 7353 return PackageDexOptimizer.DEX_OPT_FAILED; 7354 } 7355 mPackageUsage.write(false); 7356 } 7357 long callingId = Binder.clearCallingIdentity(); 7358 try { 7359 synchronized (mInstallLock) { 7360 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7361 targetCompilerFilter, force); 7362 } 7363 } finally { 7364 Binder.restoreCallingIdentity(callingId); 7365 } 7366 } 7367 7368 public ArraySet<String> getOptimizablePackages() { 7369 ArraySet<String> pkgs = new ArraySet<String>(); 7370 synchronized (mPackages) { 7371 for (PackageParser.Package p : mPackages.values()) { 7372 if (PackageDexOptimizer.canOptimizePackage(p)) { 7373 pkgs.add(p.packageName); 7374 } 7375 } 7376 } 7377 return pkgs; 7378 } 7379 7380 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7381 boolean checkProfiles, String targetCompilerFilter, 7382 boolean force) { 7383 // Select the dex optimizer based on the force parameter. 7384 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7385 // allocate an object here. 7386 PackageDexOptimizer pdo = force 7387 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7388 : mPackageDexOptimizer; 7389 7390 // Optimize all dependencies first. Note: we ignore the return value and march on 7391 // on errors. 7392 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7393 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7394 if (!deps.isEmpty()) { 7395 for (PackageParser.Package depPackage : deps) { 7396 // TODO: Analyze and investigate if we (should) profile libraries. 7397 // Currently this will do a full compilation of the library by default. 7398 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7399 false /* checkProfiles */, 7400 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7401 } 7402 } 7403 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7404 targetCompilerFilter); 7405 } 7406 7407 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7408 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7409 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7410 Set<String> collectedNames = new HashSet<>(); 7411 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7412 7413 retValue.remove(p); 7414 7415 return retValue; 7416 } else { 7417 return Collections.emptyList(); 7418 } 7419 } 7420 7421 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7422 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7423 if (!collectedNames.contains(p.packageName)) { 7424 collectedNames.add(p.packageName); 7425 collected.add(p); 7426 7427 if (p.usesLibraries != null) { 7428 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7429 } 7430 if (p.usesOptionalLibraries != null) { 7431 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7432 collectedNames); 7433 } 7434 } 7435 } 7436 7437 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7438 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7439 for (String libName : libs) { 7440 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7441 if (libPkg != null) { 7442 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7443 } 7444 } 7445 } 7446 7447 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7448 synchronized (mPackages) { 7449 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7450 if (lib != null && lib.apk != null) { 7451 return mPackages.get(lib.apk); 7452 } 7453 } 7454 return null; 7455 } 7456 7457 public void shutdown() { 7458 mPackageUsage.write(true); 7459 } 7460 7461 @Override 7462 public void dumpProfiles(String packageName) { 7463 PackageParser.Package pkg; 7464 synchronized (mPackages) { 7465 pkg = mPackages.get(packageName); 7466 if (pkg == null) { 7467 throw new IllegalArgumentException("Unknown package: " + packageName); 7468 } 7469 } 7470 /* Only the shell or the app user should be able to dump profiles. */ 7471 int callingUid = Binder.getCallingUid(); 7472 if (callingUid != Process.SHELL_UID && callingUid != pkg.applicationInfo.uid) { 7473 throw new SecurityException("dumpProfiles"); 7474 } 7475 7476 synchronized (mInstallLock) { 7477 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7478 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7479 try { 7480 final File codeFile = new File(pkg.applicationInfo.getCodePath()); 7481 List<String> allCodePaths = Collections.EMPTY_LIST; 7482 if (codeFile != null && codeFile.exists()) { 7483 try { 7484 final PackageLite codePkg = PackageParser.parsePackageLite(codeFile, 0); 7485 allCodePaths = codePkg.getAllCodePaths(); 7486 } catch (PackageParserException e) { 7487 // Well, we tried. 7488 } 7489 } 7490 String gid = Integer.toString(sharedGid); 7491 String codePaths = TextUtils.join(";", allCodePaths); 7492 mInstaller.dumpProfiles(gid, packageName, codePaths); 7493 } catch (InstallerException e) { 7494 Slog.w(TAG, "Failed to dump profiles", e); 7495 } 7496 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7497 } 7498 } 7499 7500 @Override 7501 public void forceDexOpt(String packageName) { 7502 enforceSystemOrRoot("forceDexOpt"); 7503 7504 PackageParser.Package pkg; 7505 synchronized (mPackages) { 7506 pkg = mPackages.get(packageName); 7507 if (pkg == null) { 7508 throw new IllegalArgumentException("Unknown package: " + packageName); 7509 } 7510 } 7511 7512 synchronized (mInstallLock) { 7513 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7514 7515 // Whoever is calling forceDexOpt wants a fully compiled package. 7516 // Don't use profiles since that may cause compilation to be skipped. 7517 final int res = performDexOptInternalWithDependenciesLI(pkg, 7518 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7519 true /* force */); 7520 7521 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7522 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7523 throw new IllegalStateException("Failed to dexopt: " + res); 7524 } 7525 } 7526 } 7527 7528 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7529 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7530 Slog.w(TAG, "Unable to update from " + oldPkg.name 7531 + " to " + newPkg.packageName 7532 + ": old package not in system partition"); 7533 return false; 7534 } else if (mPackages.get(oldPkg.name) != null) { 7535 Slog.w(TAG, "Unable to update from " + oldPkg.name 7536 + " to " + newPkg.packageName 7537 + ": old package still exists"); 7538 return false; 7539 } 7540 return true; 7541 } 7542 7543 void removeCodePathLI(File codePath) { 7544 if (codePath.isDirectory()) { 7545 try { 7546 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7547 } catch (InstallerException e) { 7548 Slog.w(TAG, "Failed to remove code path", e); 7549 } 7550 } else { 7551 codePath.delete(); 7552 } 7553 } 7554 7555 private int[] resolveUserIds(int userId) { 7556 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7557 } 7558 7559 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7560 if (pkg == null) { 7561 Slog.wtf(TAG, "Package was null!", new Throwable()); 7562 return; 7563 } 7564 clearAppDataLeafLIF(pkg, userId, flags); 7565 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7566 for (int i = 0; i < childCount; i++) { 7567 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7568 } 7569 } 7570 7571 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7572 final PackageSetting ps; 7573 synchronized (mPackages) { 7574 ps = mSettings.mPackages.get(pkg.packageName); 7575 } 7576 for (int realUserId : resolveUserIds(userId)) { 7577 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7578 try { 7579 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7580 ceDataInode); 7581 } catch (InstallerException e) { 7582 Slog.w(TAG, String.valueOf(e)); 7583 } 7584 } 7585 } 7586 7587 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7588 if (pkg == null) { 7589 Slog.wtf(TAG, "Package was null!", new Throwable()); 7590 return; 7591 } 7592 destroyAppDataLeafLIF(pkg, userId, flags); 7593 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7594 for (int i = 0; i < childCount; i++) { 7595 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7596 } 7597 } 7598 7599 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7600 final PackageSetting ps; 7601 synchronized (mPackages) { 7602 ps = mSettings.mPackages.get(pkg.packageName); 7603 } 7604 for (int realUserId : resolveUserIds(userId)) { 7605 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7606 try { 7607 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7608 ceDataInode); 7609 } catch (InstallerException e) { 7610 Slog.w(TAG, String.valueOf(e)); 7611 } 7612 } 7613 } 7614 7615 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7616 if (pkg == null) { 7617 Slog.wtf(TAG, "Package was null!", new Throwable()); 7618 return; 7619 } 7620 destroyAppProfilesLeafLIF(pkg); 7621 destroyAppReferenceProfileLeafLIF(pkg, userId); 7622 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7623 for (int i = 0; i < childCount; i++) { 7624 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7625 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId); 7626 } 7627 } 7628 7629 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) { 7630 if (pkg.isForwardLocked()) { 7631 return; 7632 } 7633 7634 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7635 try { 7636 path = PackageManagerServiceUtils.realpath(new File(path)); 7637 } catch (IOException e) { 7638 // TODO: Should we return early here ? 7639 Slog.w(TAG, "Failed to get canonical path", e); 7640 continue; 7641 } 7642 7643 final String useMarker = path.replace('/', '@'); 7644 for (int realUserId : resolveUserIds(userId)) { 7645 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7646 File foreignUseMark = new File(profileDir, useMarker); 7647 if (foreignUseMark.exists()) { 7648 if (!foreignUseMark.delete()) { 7649 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7650 + pkg.packageName); 7651 } 7652 } 7653 7654 File[] markers = profileDir.listFiles(); 7655 if (markers != null) { 7656 final String searchString = "@" + pkg.packageName + "@"; 7657 // We also delete all markers that contain the package name we're 7658 // uninstalling. These are associated with secondary dex-files belonging 7659 // to the package. Reconstructing the path of these dex files is messy 7660 // in general. 7661 for (File marker : markers) { 7662 if (marker.getName().indexOf(searchString) > 0) { 7663 if (!marker.delete()) { 7664 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7665 + pkg.packageName); 7666 } 7667 } 7668 } 7669 } 7670 } 7671 } 7672 } 7673 7674 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7675 try { 7676 mInstaller.destroyAppProfiles(pkg.packageName); 7677 } catch (InstallerException e) { 7678 Slog.w(TAG, String.valueOf(e)); 7679 } 7680 } 7681 7682 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7683 if (pkg == null) { 7684 Slog.wtf(TAG, "Package was null!", new Throwable()); 7685 return; 7686 } 7687 clearAppProfilesLeafLIF(pkg); 7688 destroyAppReferenceProfileLeafLIF(pkg, userId); 7689 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7690 for (int i = 0; i < childCount; i++) { 7691 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7692 } 7693 } 7694 7695 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7696 try { 7697 mInstaller.clearAppProfiles(pkg.packageName); 7698 } catch (InstallerException e) { 7699 Slog.w(TAG, String.valueOf(e)); 7700 } 7701 } 7702 7703 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7704 long lastUpdateTime) { 7705 // Set parent install/update time 7706 PackageSetting ps = (PackageSetting) pkg.mExtras; 7707 if (ps != null) { 7708 ps.firstInstallTime = firstInstallTime; 7709 ps.lastUpdateTime = lastUpdateTime; 7710 } 7711 // Set children install/update time 7712 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7713 for (int i = 0; i < childCount; i++) { 7714 PackageParser.Package childPkg = pkg.childPackages.get(i); 7715 ps = (PackageSetting) childPkg.mExtras; 7716 if (ps != null) { 7717 ps.firstInstallTime = firstInstallTime; 7718 ps.lastUpdateTime = lastUpdateTime; 7719 } 7720 } 7721 } 7722 7723 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7724 PackageParser.Package changingLib) { 7725 if (file.path != null) { 7726 usesLibraryFiles.add(file.path); 7727 return; 7728 } 7729 PackageParser.Package p = mPackages.get(file.apk); 7730 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7731 // If we are doing this while in the middle of updating a library apk, 7732 // then we need to make sure to use that new apk for determining the 7733 // dependencies here. (We haven't yet finished committing the new apk 7734 // to the package manager state.) 7735 if (p == null || p.packageName.equals(changingLib.packageName)) { 7736 p = changingLib; 7737 } 7738 } 7739 if (p != null) { 7740 usesLibraryFiles.addAll(p.getAllCodePaths()); 7741 } 7742 } 7743 7744 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7745 PackageParser.Package changingLib) throws PackageManagerException { 7746 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7747 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7748 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7749 for (int i=0; i<N; i++) { 7750 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7751 if (file == null) { 7752 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7753 "Package " + pkg.packageName + " requires unavailable shared library " 7754 + pkg.usesLibraries.get(i) + "; failing!"); 7755 } 7756 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7757 } 7758 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7759 for (int i=0; i<N; i++) { 7760 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7761 if (file == null) { 7762 Slog.w(TAG, "Package " + pkg.packageName 7763 + " desires unavailable shared library " 7764 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7765 } else { 7766 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7767 } 7768 } 7769 N = usesLibraryFiles.size(); 7770 if (N > 0) { 7771 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7772 } else { 7773 pkg.usesLibraryFiles = null; 7774 } 7775 } 7776 } 7777 7778 private static boolean hasString(List<String> list, List<String> which) { 7779 if (list == null) { 7780 return false; 7781 } 7782 for (int i=list.size()-1; i>=0; i--) { 7783 for (int j=which.size()-1; j>=0; j--) { 7784 if (which.get(j).equals(list.get(i))) { 7785 return true; 7786 } 7787 } 7788 } 7789 return false; 7790 } 7791 7792 private void updateAllSharedLibrariesLPw() { 7793 for (PackageParser.Package pkg : mPackages.values()) { 7794 try { 7795 updateSharedLibrariesLPw(pkg, null); 7796 } catch (PackageManagerException e) { 7797 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7798 } 7799 } 7800 } 7801 7802 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7803 PackageParser.Package changingPkg) { 7804 ArrayList<PackageParser.Package> res = null; 7805 for (PackageParser.Package pkg : mPackages.values()) { 7806 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7807 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7808 if (res == null) { 7809 res = new ArrayList<PackageParser.Package>(); 7810 } 7811 res.add(pkg); 7812 try { 7813 updateSharedLibrariesLPw(pkg, changingPkg); 7814 } catch (PackageManagerException e) { 7815 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7816 } 7817 } 7818 } 7819 return res; 7820 } 7821 7822 /** 7823 * Derive the value of the {@code cpuAbiOverride} based on the provided 7824 * value and an optional stored value from the package settings. 7825 */ 7826 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7827 String cpuAbiOverride = null; 7828 7829 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7830 cpuAbiOverride = null; 7831 } else if (abiOverride != null) { 7832 cpuAbiOverride = abiOverride; 7833 } else if (settings != null) { 7834 cpuAbiOverride = settings.cpuAbiOverrideString; 7835 } 7836 7837 return cpuAbiOverride; 7838 } 7839 7840 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7841 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7842 throws PackageManagerException { 7843 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7844 // If the package has children and this is the first dive in the function 7845 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7846 // whether all packages (parent and children) would be successfully scanned 7847 // before the actual scan since scanning mutates internal state and we want 7848 // to atomically install the package and its children. 7849 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7850 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7851 scanFlags |= SCAN_CHECK_ONLY; 7852 } 7853 } else { 7854 scanFlags &= ~SCAN_CHECK_ONLY; 7855 } 7856 7857 final PackageParser.Package scannedPkg; 7858 try { 7859 // Scan the parent 7860 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7861 // Scan the children 7862 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7863 for (int i = 0; i < childCount; i++) { 7864 PackageParser.Package childPkg = pkg.childPackages.get(i); 7865 scanPackageLI(childPkg, policyFlags, 7866 scanFlags, currentTime, user); 7867 } 7868 } finally { 7869 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7870 } 7871 7872 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7873 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7874 } 7875 7876 return scannedPkg; 7877 } 7878 7879 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7880 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7881 boolean success = false; 7882 try { 7883 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7884 currentTime, user); 7885 success = true; 7886 return res; 7887 } finally { 7888 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7889 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7890 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7891 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7892 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7893 } 7894 } 7895 } 7896 7897 /** 7898 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7899 */ 7900 private static boolean apkHasCode(String fileName) { 7901 StrictJarFile jarFile = null; 7902 try { 7903 jarFile = new StrictJarFile(fileName, 7904 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7905 return jarFile.findEntry("classes.dex") != null; 7906 } catch (IOException ignore) { 7907 } finally { 7908 try { 7909 jarFile.close(); 7910 } catch (IOException ignore) {} 7911 } 7912 return false; 7913 } 7914 7915 /** 7916 * Enforces code policy for the package. This ensures that if an APK has 7917 * declared hasCode="true" in its manifest that the APK actually contains 7918 * code. 7919 * 7920 * @throws PackageManagerException If bytecode could not be found when it should exist 7921 */ 7922 private static void enforceCodePolicy(PackageParser.Package pkg) 7923 throws PackageManagerException { 7924 final boolean shouldHaveCode = 7925 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7926 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7927 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7928 "Package " + pkg.baseCodePath + " code is missing"); 7929 } 7930 7931 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7932 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7933 final boolean splitShouldHaveCode = 7934 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7935 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7936 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7937 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7938 } 7939 } 7940 } 7941 } 7942 7943 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7944 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7945 throws PackageManagerException { 7946 final File scanFile = new File(pkg.codePath); 7947 if (pkg.applicationInfo.getCodePath() == null || 7948 pkg.applicationInfo.getResourcePath() == null) { 7949 // Bail out. The resource and code paths haven't been set. 7950 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7951 "Code and resource paths haven't been set correctly"); 7952 } 7953 7954 // Apply policy 7955 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7956 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7957 if (pkg.applicationInfo.isDirectBootAware()) { 7958 // we're direct boot aware; set for all components 7959 for (PackageParser.Service s : pkg.services) { 7960 s.info.encryptionAware = s.info.directBootAware = true; 7961 } 7962 for (PackageParser.Provider p : pkg.providers) { 7963 p.info.encryptionAware = p.info.directBootAware = true; 7964 } 7965 for (PackageParser.Activity a : pkg.activities) { 7966 a.info.encryptionAware = a.info.directBootAware = true; 7967 } 7968 for (PackageParser.Activity r : pkg.receivers) { 7969 r.info.encryptionAware = r.info.directBootAware = true; 7970 } 7971 } 7972 } else { 7973 // Only allow system apps to be flagged as core apps. 7974 pkg.coreApp = false; 7975 // clear flags not applicable to regular apps 7976 pkg.applicationInfo.privateFlags &= 7977 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7978 pkg.applicationInfo.privateFlags &= 7979 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7980 } 7981 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7982 7983 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7984 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7985 } 7986 7987 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7988 enforceCodePolicy(pkg); 7989 } 7990 7991 if (mCustomResolverComponentName != null && 7992 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7993 setUpCustomResolverActivity(pkg); 7994 } 7995 7996 if (pkg.packageName.equals("android")) { 7997 synchronized (mPackages) { 7998 if (mAndroidApplication != null) { 7999 Slog.w(TAG, "*************************************************"); 8000 Slog.w(TAG, "Core android package being redefined. Skipping."); 8001 Slog.w(TAG, " file=" + scanFile); 8002 Slog.w(TAG, "*************************************************"); 8003 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8004 "Core android package being redefined. Skipping."); 8005 } 8006 8007 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8008 // Set up information for our fall-back user intent resolution activity. 8009 mPlatformPackage = pkg; 8010 pkg.mVersionCode = mSdkVersion; 8011 mAndroidApplication = pkg.applicationInfo; 8012 8013 if (!mResolverReplaced) { 8014 mResolveActivity.applicationInfo = mAndroidApplication; 8015 mResolveActivity.name = ResolverActivity.class.getName(); 8016 mResolveActivity.packageName = mAndroidApplication.packageName; 8017 mResolveActivity.processName = "system:ui"; 8018 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8019 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8020 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8021 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8022 mResolveActivity.exported = true; 8023 mResolveActivity.enabled = true; 8024 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8025 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8026 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8027 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8028 | ActivityInfo.CONFIG_ORIENTATION 8029 | ActivityInfo.CONFIG_KEYBOARD 8030 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8031 mResolveInfo.activityInfo = mResolveActivity; 8032 mResolveInfo.priority = 0; 8033 mResolveInfo.preferredOrder = 0; 8034 mResolveInfo.match = 0; 8035 mResolveComponentName = new ComponentName( 8036 mAndroidApplication.packageName, mResolveActivity.name); 8037 } 8038 } 8039 } 8040 } 8041 8042 if (DEBUG_PACKAGE_SCANNING) { 8043 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8044 Log.d(TAG, "Scanning package " + pkg.packageName); 8045 } 8046 8047 synchronized (mPackages) { 8048 if (mPackages.containsKey(pkg.packageName) 8049 || mSharedLibraries.containsKey(pkg.packageName)) { 8050 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8051 "Application package " + pkg.packageName 8052 + " already installed. Skipping duplicate."); 8053 } 8054 8055 // If we're only installing presumed-existing packages, require that the 8056 // scanned APK is both already known and at the path previously established 8057 // for it. Previously unknown packages we pick up normally, but if we have an 8058 // a priori expectation about this package's install presence, enforce it. 8059 // With a singular exception for new system packages. When an OTA contains 8060 // a new system package, we allow the codepath to change from a system location 8061 // to the user-installed location. If we don't allow this change, any newer, 8062 // user-installed version of the application will be ignored. 8063 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8064 if (mExpectingBetter.containsKey(pkg.packageName)) { 8065 logCriticalInfo(Log.WARN, 8066 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8067 } else { 8068 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8069 if (known != null) { 8070 if (DEBUG_PACKAGE_SCANNING) { 8071 Log.d(TAG, "Examining " + pkg.codePath 8072 + " and requiring known paths " + known.codePathString 8073 + " & " + known.resourcePathString); 8074 } 8075 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8076 || !pkg.applicationInfo.getResourcePath().equals( 8077 known.resourcePathString)) { 8078 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8079 "Application package " + pkg.packageName 8080 + " found at " + pkg.applicationInfo.getCodePath() 8081 + " but expected at " + known.codePathString 8082 + "; ignoring."); 8083 } 8084 } 8085 } 8086 } 8087 } 8088 8089 // Initialize package source and resource directories 8090 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8091 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8092 8093 SharedUserSetting suid = null; 8094 PackageSetting pkgSetting = null; 8095 8096 if (!isSystemApp(pkg)) { 8097 // Only system apps can use these features. 8098 pkg.mOriginalPackages = null; 8099 pkg.mRealPackage = null; 8100 pkg.mAdoptPermissions = null; 8101 } 8102 8103 // Getting the package setting may have a side-effect, so if we 8104 // are only checking if scan would succeed, stash a copy of the 8105 // old setting to restore at the end. 8106 PackageSetting nonMutatedPs = null; 8107 8108 // writer 8109 synchronized (mPackages) { 8110 if (pkg.mSharedUserId != null) { 8111 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8112 if (suid == null) { 8113 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8114 "Creating application package " + pkg.packageName 8115 + " for shared user failed"); 8116 } 8117 if (DEBUG_PACKAGE_SCANNING) { 8118 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8119 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8120 + "): packages=" + suid.packages); 8121 } 8122 } 8123 8124 // Check if we are renaming from an original package name. 8125 PackageSetting origPackage = null; 8126 String realName = null; 8127 if (pkg.mOriginalPackages != null) { 8128 // This package may need to be renamed to a previously 8129 // installed name. Let's check on that... 8130 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8131 if (pkg.mOriginalPackages.contains(renamed)) { 8132 // This package had originally been installed as the 8133 // original name, and we have already taken care of 8134 // transitioning to the new one. Just update the new 8135 // one to continue using the old name. 8136 realName = pkg.mRealPackage; 8137 if (!pkg.packageName.equals(renamed)) { 8138 // Callers into this function may have already taken 8139 // care of renaming the package; only do it here if 8140 // it is not already done. 8141 pkg.setPackageName(renamed); 8142 } 8143 8144 } else { 8145 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8146 if ((origPackage = mSettings.peekPackageLPr( 8147 pkg.mOriginalPackages.get(i))) != null) { 8148 // We do have the package already installed under its 8149 // original name... should we use it? 8150 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8151 // New package is not compatible with original. 8152 origPackage = null; 8153 continue; 8154 } else if (origPackage.sharedUser != null) { 8155 // Make sure uid is compatible between packages. 8156 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8157 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8158 + " to " + pkg.packageName + ": old uid " 8159 + origPackage.sharedUser.name 8160 + " differs from " + pkg.mSharedUserId); 8161 origPackage = null; 8162 continue; 8163 } 8164 // TODO: Add case when shared user id is added [b/28144775] 8165 } else { 8166 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8167 + pkg.packageName + " to old name " + origPackage.name); 8168 } 8169 break; 8170 } 8171 } 8172 } 8173 } 8174 8175 if (mTransferedPackages.contains(pkg.packageName)) { 8176 Slog.w(TAG, "Package " + pkg.packageName 8177 + " was transferred to another, but its .apk remains"); 8178 } 8179 8180 // See comments in nonMutatedPs declaration 8181 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8182 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8183 if (foundPs != null) { 8184 nonMutatedPs = new PackageSetting(foundPs); 8185 } 8186 } 8187 8188 // Just create the setting, don't add it yet. For already existing packages 8189 // the PkgSetting exists already and doesn't have to be created. 8190 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8191 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8192 pkg.applicationInfo.primaryCpuAbi, 8193 pkg.applicationInfo.secondaryCpuAbi, 8194 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8195 user, false); 8196 if (pkgSetting == null) { 8197 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8198 "Creating application package " + pkg.packageName + " failed"); 8199 } 8200 8201 if (pkgSetting.origPackage != null) { 8202 // If we are first transitioning from an original package, 8203 // fix up the new package's name now. We need to do this after 8204 // looking up the package under its new name, so getPackageLP 8205 // can take care of fiddling things correctly. 8206 pkg.setPackageName(origPackage.name); 8207 8208 // File a report about this. 8209 String msg = "New package " + pkgSetting.realName 8210 + " renamed to replace old package " + pkgSetting.name; 8211 reportSettingsProblem(Log.WARN, msg); 8212 8213 // Make a note of it. 8214 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8215 mTransferedPackages.add(origPackage.name); 8216 } 8217 8218 // No longer need to retain this. 8219 pkgSetting.origPackage = null; 8220 } 8221 8222 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8223 // Make a note of it. 8224 mTransferedPackages.add(pkg.packageName); 8225 } 8226 8227 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8228 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8229 } 8230 8231 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8232 // Check all shared libraries and map to their actual file path. 8233 // We only do this here for apps not on a system dir, because those 8234 // are the only ones that can fail an install due to this. We 8235 // will take care of the system apps by updating all of their 8236 // library paths after the scan is done. 8237 updateSharedLibrariesLPw(pkg, null); 8238 } 8239 8240 if (mFoundPolicyFile) { 8241 SELinuxMMAC.assignSeinfoValue(pkg); 8242 } 8243 8244 pkg.applicationInfo.uid = pkgSetting.appId; 8245 pkg.mExtras = pkgSetting; 8246 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8247 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8248 // We just determined the app is signed correctly, so bring 8249 // over the latest parsed certs. 8250 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8251 } else { 8252 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8253 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8254 "Package " + pkg.packageName + " upgrade keys do not match the " 8255 + "previously installed version"); 8256 } else { 8257 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8258 String msg = "System package " + pkg.packageName 8259 + " signature changed; retaining data."; 8260 reportSettingsProblem(Log.WARN, msg); 8261 } 8262 } 8263 } else { 8264 try { 8265 verifySignaturesLP(pkgSetting, pkg); 8266 // We just determined the app is signed correctly, so bring 8267 // over the latest parsed certs. 8268 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8269 } catch (PackageManagerException e) { 8270 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8271 throw e; 8272 } 8273 // The signature has changed, but this package is in the system 8274 // image... let's recover! 8275 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8276 // However... if this package is part of a shared user, but it 8277 // doesn't match the signature of the shared user, let's fail. 8278 // What this means is that you can't change the signatures 8279 // associated with an overall shared user, which doesn't seem all 8280 // that unreasonable. 8281 if (pkgSetting.sharedUser != null) { 8282 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8283 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8284 throw new PackageManagerException( 8285 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8286 "Signature mismatch for shared user: " 8287 + pkgSetting.sharedUser); 8288 } 8289 } 8290 // File a report about this. 8291 String msg = "System package " + pkg.packageName 8292 + " signature changed; retaining data."; 8293 reportSettingsProblem(Log.WARN, msg); 8294 } 8295 } 8296 // Verify that this new package doesn't have any content providers 8297 // that conflict with existing packages. Only do this if the 8298 // package isn't already installed, since we don't want to break 8299 // things that are installed. 8300 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8301 final int N = pkg.providers.size(); 8302 int i; 8303 for (i=0; i<N; i++) { 8304 PackageParser.Provider p = pkg.providers.get(i); 8305 if (p.info.authority != null) { 8306 String names[] = p.info.authority.split(";"); 8307 for (int j = 0; j < names.length; j++) { 8308 if (mProvidersByAuthority.containsKey(names[j])) { 8309 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8310 final String otherPackageName = 8311 ((other != null && other.getComponentName() != null) ? 8312 other.getComponentName().getPackageName() : "?"); 8313 throw new PackageManagerException( 8314 INSTALL_FAILED_CONFLICTING_PROVIDER, 8315 "Can't install because provider name " + names[j] 8316 + " (in package " + pkg.applicationInfo.packageName 8317 + ") is already used by " + otherPackageName); 8318 } 8319 } 8320 } 8321 } 8322 } 8323 8324 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8325 // This package wants to adopt ownership of permissions from 8326 // another package. 8327 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8328 final String origName = pkg.mAdoptPermissions.get(i); 8329 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8330 if (orig != null) { 8331 if (verifyPackageUpdateLPr(orig, pkg)) { 8332 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8333 + pkg.packageName); 8334 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8335 } 8336 } 8337 } 8338 } 8339 } 8340 8341 final String pkgName = pkg.packageName; 8342 8343 final long scanFileTime = scanFile.lastModified(); 8344 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8345 pkg.applicationInfo.processName = fixProcessName( 8346 pkg.applicationInfo.packageName, 8347 pkg.applicationInfo.processName, 8348 pkg.applicationInfo.uid); 8349 8350 if (pkg != mPlatformPackage) { 8351 // Get all of our default paths setup 8352 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8353 } 8354 8355 final String path = scanFile.getPath(); 8356 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8357 8358 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8359 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8360 8361 // Some system apps still use directory structure for native libraries 8362 // in which case we might end up not detecting abi solely based on apk 8363 // structure. Try to detect abi based on directory structure. 8364 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8365 pkg.applicationInfo.primaryCpuAbi == null) { 8366 setBundledAppAbisAndRoots(pkg, pkgSetting); 8367 setNativeLibraryPaths(pkg); 8368 } 8369 8370 } else { 8371 if ((scanFlags & SCAN_MOVE) != 0) { 8372 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8373 // but we already have this packages package info in the PackageSetting. We just 8374 // use that and derive the native library path based on the new codepath. 8375 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8376 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8377 } 8378 8379 // Set native library paths again. For moves, the path will be updated based on the 8380 // ABIs we've determined above. For non-moves, the path will be updated based on the 8381 // ABIs we determined during compilation, but the path will depend on the final 8382 // package path (after the rename away from the stage path). 8383 setNativeLibraryPaths(pkg); 8384 } 8385 8386 // This is a special case for the "system" package, where the ABI is 8387 // dictated by the zygote configuration (and init.rc). We should keep track 8388 // of this ABI so that we can deal with "normal" applications that run under 8389 // the same UID correctly. 8390 if (mPlatformPackage == pkg) { 8391 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8392 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8393 } 8394 8395 // If there's a mismatch between the abi-override in the package setting 8396 // and the abiOverride specified for the install. Warn about this because we 8397 // would've already compiled the app without taking the package setting into 8398 // account. 8399 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8400 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8401 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8402 " for package " + pkg.packageName); 8403 } 8404 } 8405 8406 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8407 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8408 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8409 8410 // Copy the derived override back to the parsed package, so that we can 8411 // update the package settings accordingly. 8412 pkg.cpuAbiOverride = cpuAbiOverride; 8413 8414 if (DEBUG_ABI_SELECTION) { 8415 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8416 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8417 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8418 } 8419 8420 // Push the derived path down into PackageSettings so we know what to 8421 // clean up at uninstall time. 8422 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8423 8424 if (DEBUG_ABI_SELECTION) { 8425 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8426 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8427 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8428 } 8429 8430 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8431 // We don't do this here during boot because we can do it all 8432 // at once after scanning all existing packages. 8433 // 8434 // We also do this *before* we perform dexopt on this package, so that 8435 // we can avoid redundant dexopts, and also to make sure we've got the 8436 // code and package path correct. 8437 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8438 pkg, true /* boot complete */); 8439 } 8440 8441 if (mFactoryTest && pkg.requestedPermissions.contains( 8442 android.Manifest.permission.FACTORY_TEST)) { 8443 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8444 } 8445 8446 ArrayList<PackageParser.Package> clientLibPkgs = null; 8447 8448 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8449 if (nonMutatedPs != null) { 8450 synchronized (mPackages) { 8451 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8452 } 8453 } 8454 return pkg; 8455 } 8456 8457 // Only privileged apps and updated privileged apps can add child packages. 8458 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8459 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8460 throw new PackageManagerException("Only privileged apps and updated " 8461 + "privileged apps can add child packages. Ignoring package " 8462 + pkg.packageName); 8463 } 8464 final int childCount = pkg.childPackages.size(); 8465 for (int i = 0; i < childCount; i++) { 8466 PackageParser.Package childPkg = pkg.childPackages.get(i); 8467 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8468 childPkg.packageName)) { 8469 throw new PackageManagerException("Cannot override a child package of " 8470 + "another disabled system app. Ignoring package " + pkg.packageName); 8471 } 8472 } 8473 } 8474 8475 // writer 8476 synchronized (mPackages) { 8477 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8478 // Only system apps can add new shared libraries. 8479 if (pkg.libraryNames != null) { 8480 for (int i=0; i<pkg.libraryNames.size(); i++) { 8481 String name = pkg.libraryNames.get(i); 8482 boolean allowed = false; 8483 if (pkg.isUpdatedSystemApp()) { 8484 // New library entries can only be added through the 8485 // system image. This is important to get rid of a lot 8486 // of nasty edge cases: for example if we allowed a non- 8487 // system update of the app to add a library, then uninstalling 8488 // the update would make the library go away, and assumptions 8489 // we made such as through app install filtering would now 8490 // have allowed apps on the device which aren't compatible 8491 // with it. Better to just have the restriction here, be 8492 // conservative, and create many fewer cases that can negatively 8493 // impact the user experience. 8494 final PackageSetting sysPs = mSettings 8495 .getDisabledSystemPkgLPr(pkg.packageName); 8496 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8497 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8498 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8499 allowed = true; 8500 break; 8501 } 8502 } 8503 } 8504 } else { 8505 allowed = true; 8506 } 8507 if (allowed) { 8508 if (!mSharedLibraries.containsKey(name)) { 8509 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8510 } else if (!name.equals(pkg.packageName)) { 8511 Slog.w(TAG, "Package " + pkg.packageName + " library " 8512 + name + " already exists; skipping"); 8513 } 8514 } else { 8515 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8516 + name + " that is not declared on system image; skipping"); 8517 } 8518 } 8519 if ((scanFlags & SCAN_BOOTING) == 0) { 8520 // If we are not booting, we need to update any applications 8521 // that are clients of our shared library. If we are booting, 8522 // this will all be done once the scan is complete. 8523 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8524 } 8525 } 8526 } 8527 } 8528 8529 if ((scanFlags & SCAN_BOOTING) != 0) { 8530 // No apps can run during boot scan, so they don't need to be frozen 8531 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8532 // Caller asked to not kill app, so it's probably not frozen 8533 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8534 // Caller asked us to ignore frozen check for some reason; they 8535 // probably didn't know the package name 8536 } else { 8537 // We're doing major surgery on this package, so it better be frozen 8538 // right now to keep it from launching 8539 checkPackageFrozen(pkgName); 8540 } 8541 8542 // Also need to kill any apps that are dependent on the library. 8543 if (clientLibPkgs != null) { 8544 for (int i=0; i<clientLibPkgs.size(); i++) { 8545 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8546 killApplication(clientPkg.applicationInfo.packageName, 8547 clientPkg.applicationInfo.uid, "update lib"); 8548 } 8549 } 8550 8551 // Make sure we're not adding any bogus keyset info 8552 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8553 ksms.assertScannedPackageValid(pkg); 8554 8555 // writer 8556 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8557 8558 boolean createIdmapFailed = false; 8559 synchronized (mPackages) { 8560 // We don't expect installation to fail beyond this point 8561 8562 // Add the new setting to mSettings 8563 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8564 // Add the new setting to mPackages 8565 mPackages.put(pkg.applicationInfo.packageName, pkg); 8566 // Make sure we don't accidentally delete its data. 8567 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8568 while (iter.hasNext()) { 8569 PackageCleanItem item = iter.next(); 8570 if (pkgName.equals(item.packageName)) { 8571 iter.remove(); 8572 } 8573 } 8574 8575 // Take care of first install / last update times. 8576 if (currentTime != 0) { 8577 if (pkgSetting.firstInstallTime == 0) { 8578 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8579 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8580 pkgSetting.lastUpdateTime = currentTime; 8581 } 8582 } else if (pkgSetting.firstInstallTime == 0) { 8583 // We need *something*. Take time time stamp of the file. 8584 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8585 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8586 if (scanFileTime != pkgSetting.timeStamp) { 8587 // A package on the system image has changed; consider this 8588 // to be an update. 8589 pkgSetting.lastUpdateTime = scanFileTime; 8590 } 8591 } 8592 8593 // Add the package's KeySets to the global KeySetManagerService 8594 ksms.addScannedPackageLPw(pkg); 8595 8596 int N = pkg.providers.size(); 8597 StringBuilder r = null; 8598 int i; 8599 for (i=0; i<N; i++) { 8600 PackageParser.Provider p = pkg.providers.get(i); 8601 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8602 p.info.processName, pkg.applicationInfo.uid); 8603 mProviders.addProvider(p); 8604 p.syncable = p.info.isSyncable; 8605 if (p.info.authority != null) { 8606 String names[] = p.info.authority.split(";"); 8607 p.info.authority = null; 8608 for (int j = 0; j < names.length; j++) { 8609 if (j == 1 && p.syncable) { 8610 // We only want the first authority for a provider to possibly be 8611 // syncable, so if we already added this provider using a different 8612 // authority clear the syncable flag. We copy the provider before 8613 // changing it because the mProviders object contains a reference 8614 // to a provider that we don't want to change. 8615 // Only do this for the second authority since the resulting provider 8616 // object can be the same for all future authorities for this provider. 8617 p = new PackageParser.Provider(p); 8618 p.syncable = false; 8619 } 8620 if (!mProvidersByAuthority.containsKey(names[j])) { 8621 mProvidersByAuthority.put(names[j], p); 8622 if (p.info.authority == null) { 8623 p.info.authority = names[j]; 8624 } else { 8625 p.info.authority = p.info.authority + ";" + names[j]; 8626 } 8627 if (DEBUG_PACKAGE_SCANNING) { 8628 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8629 Log.d(TAG, "Registered content provider: " + names[j] 8630 + ", className = " + p.info.name + ", isSyncable = " 8631 + p.info.isSyncable); 8632 } 8633 } else { 8634 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8635 Slog.w(TAG, "Skipping provider name " + names[j] + 8636 " (in package " + pkg.applicationInfo.packageName + 8637 "): name already used by " 8638 + ((other != null && other.getComponentName() != null) 8639 ? other.getComponentName().getPackageName() : "?")); 8640 } 8641 } 8642 } 8643 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8644 if (r == null) { 8645 r = new StringBuilder(256); 8646 } else { 8647 r.append(' '); 8648 } 8649 r.append(p.info.name); 8650 } 8651 } 8652 if (r != null) { 8653 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8654 } 8655 8656 N = pkg.services.size(); 8657 r = null; 8658 for (i=0; i<N; i++) { 8659 PackageParser.Service s = pkg.services.get(i); 8660 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8661 s.info.processName, pkg.applicationInfo.uid); 8662 mServices.addService(s); 8663 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8664 if (r == null) { 8665 r = new StringBuilder(256); 8666 } else { 8667 r.append(' '); 8668 } 8669 r.append(s.info.name); 8670 } 8671 } 8672 if (r != null) { 8673 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8674 } 8675 8676 N = pkg.receivers.size(); 8677 r = null; 8678 for (i=0; i<N; i++) { 8679 PackageParser.Activity a = pkg.receivers.get(i); 8680 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8681 a.info.processName, pkg.applicationInfo.uid); 8682 mReceivers.addActivity(a, "receiver"); 8683 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8684 if (r == null) { 8685 r = new StringBuilder(256); 8686 } else { 8687 r.append(' '); 8688 } 8689 r.append(a.info.name); 8690 } 8691 } 8692 if (r != null) { 8693 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8694 } 8695 8696 N = pkg.activities.size(); 8697 r = null; 8698 for (i=0; i<N; i++) { 8699 PackageParser.Activity a = pkg.activities.get(i); 8700 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8701 a.info.processName, pkg.applicationInfo.uid); 8702 mActivities.addActivity(a, "activity"); 8703 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8704 if (r == null) { 8705 r = new StringBuilder(256); 8706 } else { 8707 r.append(' '); 8708 } 8709 r.append(a.info.name); 8710 } 8711 } 8712 if (r != null) { 8713 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8714 } 8715 8716 N = pkg.permissionGroups.size(); 8717 r = null; 8718 for (i=0; i<N; i++) { 8719 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8720 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8721 if (cur == null) { 8722 mPermissionGroups.put(pg.info.name, pg); 8723 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8724 if (r == null) { 8725 r = new StringBuilder(256); 8726 } else { 8727 r.append(' '); 8728 } 8729 r.append(pg.info.name); 8730 } 8731 } else { 8732 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8733 + pg.info.packageName + " ignored: original from " 8734 + cur.info.packageName); 8735 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8736 if (r == null) { 8737 r = new StringBuilder(256); 8738 } else { 8739 r.append(' '); 8740 } 8741 r.append("DUP:"); 8742 r.append(pg.info.name); 8743 } 8744 } 8745 } 8746 if (r != null) { 8747 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8748 } 8749 8750 N = pkg.permissions.size(); 8751 r = null; 8752 for (i=0; i<N; i++) { 8753 PackageParser.Permission p = pkg.permissions.get(i); 8754 8755 // Assume by default that we did not install this permission into the system. 8756 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8757 8758 // Now that permission groups have a special meaning, we ignore permission 8759 // groups for legacy apps to prevent unexpected behavior. In particular, 8760 // permissions for one app being granted to someone just becase they happen 8761 // to be in a group defined by another app (before this had no implications). 8762 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8763 p.group = mPermissionGroups.get(p.info.group); 8764 // Warn for a permission in an unknown group. 8765 if (p.info.group != null && p.group == null) { 8766 Slog.w(TAG, "Permission " + p.info.name + " from package " 8767 + p.info.packageName + " in an unknown group " + p.info.group); 8768 } 8769 } 8770 8771 ArrayMap<String, BasePermission> permissionMap = 8772 p.tree ? mSettings.mPermissionTrees 8773 : mSettings.mPermissions; 8774 BasePermission bp = permissionMap.get(p.info.name); 8775 8776 // Allow system apps to redefine non-system permissions 8777 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8778 final boolean currentOwnerIsSystem = (bp.perm != null 8779 && isSystemApp(bp.perm.owner)); 8780 if (isSystemApp(p.owner)) { 8781 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8782 // It's a built-in permission and no owner, take ownership now 8783 bp.packageSetting = pkgSetting; 8784 bp.perm = p; 8785 bp.uid = pkg.applicationInfo.uid; 8786 bp.sourcePackage = p.info.packageName; 8787 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8788 } else if (!currentOwnerIsSystem) { 8789 String msg = "New decl " + p.owner + " of permission " 8790 + p.info.name + " is system; overriding " + bp.sourcePackage; 8791 reportSettingsProblem(Log.WARN, msg); 8792 bp = null; 8793 } 8794 } 8795 } 8796 8797 if (bp == null) { 8798 bp = new BasePermission(p.info.name, p.info.packageName, 8799 BasePermission.TYPE_NORMAL); 8800 permissionMap.put(p.info.name, bp); 8801 } 8802 8803 if (bp.perm == null) { 8804 if (bp.sourcePackage == null 8805 || bp.sourcePackage.equals(p.info.packageName)) { 8806 BasePermission tree = findPermissionTreeLP(p.info.name); 8807 if (tree == null 8808 || tree.sourcePackage.equals(p.info.packageName)) { 8809 bp.packageSetting = pkgSetting; 8810 bp.perm = p; 8811 bp.uid = pkg.applicationInfo.uid; 8812 bp.sourcePackage = p.info.packageName; 8813 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8814 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8815 if (r == null) { 8816 r = new StringBuilder(256); 8817 } else { 8818 r.append(' '); 8819 } 8820 r.append(p.info.name); 8821 } 8822 } else { 8823 Slog.w(TAG, "Permission " + p.info.name + " from package " 8824 + p.info.packageName + " ignored: base tree " 8825 + tree.name + " is from package " 8826 + tree.sourcePackage); 8827 } 8828 } else { 8829 Slog.w(TAG, "Permission " + p.info.name + " from package " 8830 + p.info.packageName + " ignored: original from " 8831 + bp.sourcePackage); 8832 } 8833 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8834 if (r == null) { 8835 r = new StringBuilder(256); 8836 } else { 8837 r.append(' '); 8838 } 8839 r.append("DUP:"); 8840 r.append(p.info.name); 8841 } 8842 if (bp.perm == p) { 8843 bp.protectionLevel = p.info.protectionLevel; 8844 } 8845 } 8846 8847 if (r != null) { 8848 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8849 } 8850 8851 N = pkg.instrumentation.size(); 8852 r = null; 8853 for (i=0; i<N; i++) { 8854 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8855 a.info.packageName = pkg.applicationInfo.packageName; 8856 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8857 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8858 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8859 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8860 a.info.dataDir = pkg.applicationInfo.dataDir; 8861 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8862 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8863 8864 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8865 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8866 mInstrumentation.put(a.getComponentName(), a); 8867 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8868 if (r == null) { 8869 r = new StringBuilder(256); 8870 } else { 8871 r.append(' '); 8872 } 8873 r.append(a.info.name); 8874 } 8875 } 8876 if (r != null) { 8877 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8878 } 8879 8880 if (pkg.protectedBroadcasts != null) { 8881 N = pkg.protectedBroadcasts.size(); 8882 for (i=0; i<N; i++) { 8883 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8884 } 8885 } 8886 8887 pkgSetting.setTimeStamp(scanFileTime); 8888 8889 // Create idmap files for pairs of (packages, overlay packages). 8890 // Note: "android", ie framework-res.apk, is handled by native layers. 8891 if (pkg.mOverlayTarget != null) { 8892 // This is an overlay package. 8893 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8894 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8895 mOverlays.put(pkg.mOverlayTarget, 8896 new ArrayMap<String, PackageParser.Package>()); 8897 } 8898 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8899 map.put(pkg.packageName, pkg); 8900 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8901 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8902 createIdmapFailed = true; 8903 } 8904 } 8905 } else if (mOverlays.containsKey(pkg.packageName) && 8906 !pkg.packageName.equals("android")) { 8907 // This is a regular package, with one or more known overlay packages. 8908 createIdmapsForPackageLI(pkg); 8909 } 8910 } 8911 8912 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8913 8914 if (createIdmapFailed) { 8915 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8916 "scanPackageLI failed to createIdmap"); 8917 } 8918 return pkg; 8919 } 8920 8921 /** 8922 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8923 * is derived purely on the basis of the contents of {@code scanFile} and 8924 * {@code cpuAbiOverride}. 8925 * 8926 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8927 */ 8928 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8929 String cpuAbiOverride, boolean extractLibs) 8930 throws PackageManagerException { 8931 // TODO: We can probably be smarter about this stuff. For installed apps, 8932 // we can calculate this information at install time once and for all. For 8933 // system apps, we can probably assume that this information doesn't change 8934 // after the first boot scan. As things stand, we do lots of unnecessary work. 8935 8936 // Give ourselves some initial paths; we'll come back for another 8937 // pass once we've determined ABI below. 8938 setNativeLibraryPaths(pkg); 8939 8940 // We would never need to extract libs for forward-locked and external packages, 8941 // since the container service will do it for us. We shouldn't attempt to 8942 // extract libs from system app when it was not updated. 8943 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8944 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8945 extractLibs = false; 8946 } 8947 8948 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8949 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8950 8951 NativeLibraryHelper.Handle handle = null; 8952 try { 8953 handle = NativeLibraryHelper.Handle.create(pkg); 8954 // TODO(multiArch): This can be null for apps that didn't go through the 8955 // usual installation process. We can calculate it again, like we 8956 // do during install time. 8957 // 8958 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8959 // unnecessary. 8960 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8961 8962 // Null out the abis so that they can be recalculated. 8963 pkg.applicationInfo.primaryCpuAbi = null; 8964 pkg.applicationInfo.secondaryCpuAbi = null; 8965 if (isMultiArch(pkg.applicationInfo)) { 8966 // Warn if we've set an abiOverride for multi-lib packages.. 8967 // By definition, we need to copy both 32 and 64 bit libraries for 8968 // such packages. 8969 if (pkg.cpuAbiOverride != null 8970 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8971 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8972 } 8973 8974 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8975 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8976 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8977 if (extractLibs) { 8978 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8979 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8980 useIsaSpecificSubdirs); 8981 } else { 8982 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8983 } 8984 } 8985 8986 maybeThrowExceptionForMultiArchCopy( 8987 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8988 8989 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8990 if (extractLibs) { 8991 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8992 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8993 useIsaSpecificSubdirs); 8994 } else { 8995 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8996 } 8997 } 8998 8999 maybeThrowExceptionForMultiArchCopy( 9000 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9001 9002 if (abi64 >= 0) { 9003 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9004 } 9005 9006 if (abi32 >= 0) { 9007 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9008 if (abi64 >= 0) { 9009 if (pkg.use32bitAbi) { 9010 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9011 pkg.applicationInfo.primaryCpuAbi = abi; 9012 } else { 9013 pkg.applicationInfo.secondaryCpuAbi = abi; 9014 } 9015 } else { 9016 pkg.applicationInfo.primaryCpuAbi = abi; 9017 } 9018 } 9019 9020 } else { 9021 String[] abiList = (cpuAbiOverride != null) ? 9022 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9023 9024 // Enable gross and lame hacks for apps that are built with old 9025 // SDK tools. We must scan their APKs for renderscript bitcode and 9026 // not launch them if it's present. Don't bother checking on devices 9027 // that don't have 64 bit support. 9028 boolean needsRenderScriptOverride = false; 9029 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9030 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9031 abiList = Build.SUPPORTED_32_BIT_ABIS; 9032 needsRenderScriptOverride = true; 9033 } 9034 9035 final int copyRet; 9036 if (extractLibs) { 9037 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9038 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9039 } else { 9040 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9041 } 9042 9043 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9044 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9045 "Error unpackaging native libs for app, errorCode=" + copyRet); 9046 } 9047 9048 if (copyRet >= 0) { 9049 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9050 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9051 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9052 } else if (needsRenderScriptOverride) { 9053 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9054 } 9055 } 9056 } catch (IOException ioe) { 9057 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9058 } finally { 9059 IoUtils.closeQuietly(handle); 9060 } 9061 9062 // Now that we've calculated the ABIs and determined if it's an internal app, 9063 // we will go ahead and populate the nativeLibraryPath. 9064 setNativeLibraryPaths(pkg); 9065 } 9066 9067 /** 9068 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9069 * i.e, so that all packages can be run inside a single process if required. 9070 * 9071 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9072 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9073 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9074 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9075 * updating a package that belongs to a shared user. 9076 * 9077 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9078 * adds unnecessary complexity. 9079 */ 9080 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9081 PackageParser.Package scannedPackage, boolean bootComplete) { 9082 String requiredInstructionSet = null; 9083 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9084 requiredInstructionSet = VMRuntime.getInstructionSet( 9085 scannedPackage.applicationInfo.primaryCpuAbi); 9086 } 9087 9088 PackageSetting requirer = null; 9089 for (PackageSetting ps : packagesForUser) { 9090 // If packagesForUser contains scannedPackage, we skip it. This will happen 9091 // when scannedPackage is an update of an existing package. Without this check, 9092 // we will never be able to change the ABI of any package belonging to a shared 9093 // user, even if it's compatible with other packages. 9094 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9095 if (ps.primaryCpuAbiString == null) { 9096 continue; 9097 } 9098 9099 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9100 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9101 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9102 // this but there's not much we can do. 9103 String errorMessage = "Instruction set mismatch, " 9104 + ((requirer == null) ? "[caller]" : requirer) 9105 + " requires " + requiredInstructionSet + " whereas " + ps 9106 + " requires " + instructionSet; 9107 Slog.w(TAG, errorMessage); 9108 } 9109 9110 if (requiredInstructionSet == null) { 9111 requiredInstructionSet = instructionSet; 9112 requirer = ps; 9113 } 9114 } 9115 } 9116 9117 if (requiredInstructionSet != null) { 9118 String adjustedAbi; 9119 if (requirer != null) { 9120 // requirer != null implies that either scannedPackage was null or that scannedPackage 9121 // did not require an ABI, in which case we have to adjust scannedPackage to match 9122 // the ABI of the set (which is the same as requirer's ABI) 9123 adjustedAbi = requirer.primaryCpuAbiString; 9124 if (scannedPackage != null) { 9125 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9126 } 9127 } else { 9128 // requirer == null implies that we're updating all ABIs in the set to 9129 // match scannedPackage. 9130 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9131 } 9132 9133 for (PackageSetting ps : packagesForUser) { 9134 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9135 if (ps.primaryCpuAbiString != null) { 9136 continue; 9137 } 9138 9139 ps.primaryCpuAbiString = adjustedAbi; 9140 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9141 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9142 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9143 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9144 + " (requirer=" 9145 + (requirer == null ? "null" : requirer.pkg.packageName) 9146 + ", scannedPackage=" 9147 + (scannedPackage != null ? scannedPackage.packageName : "null") 9148 + ")"); 9149 try { 9150 mInstaller.rmdex(ps.codePathString, 9151 getDexCodeInstructionSet(getPreferredInstructionSet())); 9152 } catch (InstallerException ignored) { 9153 } 9154 } 9155 } 9156 } 9157 } 9158 } 9159 9160 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9161 synchronized (mPackages) { 9162 mResolverReplaced = true; 9163 // Set up information for custom user intent resolution activity. 9164 mResolveActivity.applicationInfo = pkg.applicationInfo; 9165 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9166 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9167 mResolveActivity.processName = pkg.applicationInfo.packageName; 9168 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9169 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9170 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9171 mResolveActivity.theme = 0; 9172 mResolveActivity.exported = true; 9173 mResolveActivity.enabled = true; 9174 mResolveInfo.activityInfo = mResolveActivity; 9175 mResolveInfo.priority = 0; 9176 mResolveInfo.preferredOrder = 0; 9177 mResolveInfo.match = 0; 9178 mResolveComponentName = mCustomResolverComponentName; 9179 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9180 mResolveComponentName); 9181 } 9182 } 9183 9184 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9185 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9186 9187 // Set up information for ephemeral installer activity 9188 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9189 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9190 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9191 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9192 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9193 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9194 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9195 mEphemeralInstallerActivity.theme = 0; 9196 mEphemeralInstallerActivity.exported = true; 9197 mEphemeralInstallerActivity.enabled = true; 9198 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9199 mEphemeralInstallerInfo.priority = 0; 9200 mEphemeralInstallerInfo.preferredOrder = 0; 9201 mEphemeralInstallerInfo.match = 0; 9202 9203 if (DEBUG_EPHEMERAL) { 9204 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9205 } 9206 } 9207 9208 private static String calculateBundledApkRoot(final String codePathString) { 9209 final File codePath = new File(codePathString); 9210 final File codeRoot; 9211 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9212 codeRoot = Environment.getRootDirectory(); 9213 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9214 codeRoot = Environment.getOemDirectory(); 9215 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9216 codeRoot = Environment.getVendorDirectory(); 9217 } else { 9218 // Unrecognized code path; take its top real segment as the apk root: 9219 // e.g. /something/app/blah.apk => /something 9220 try { 9221 File f = codePath.getCanonicalFile(); 9222 File parent = f.getParentFile(); // non-null because codePath is a file 9223 File tmp; 9224 while ((tmp = parent.getParentFile()) != null) { 9225 f = parent; 9226 parent = tmp; 9227 } 9228 codeRoot = f; 9229 Slog.w(TAG, "Unrecognized code path " 9230 + codePath + " - using " + codeRoot); 9231 } catch (IOException e) { 9232 // Can't canonicalize the code path -- shenanigans? 9233 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9234 return Environment.getRootDirectory().getPath(); 9235 } 9236 } 9237 return codeRoot.getPath(); 9238 } 9239 9240 /** 9241 * Derive and set the location of native libraries for the given package, 9242 * which varies depending on where and how the package was installed. 9243 */ 9244 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9245 final ApplicationInfo info = pkg.applicationInfo; 9246 final String codePath = pkg.codePath; 9247 final File codeFile = new File(codePath); 9248 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9249 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9250 9251 info.nativeLibraryRootDir = null; 9252 info.nativeLibraryRootRequiresIsa = false; 9253 info.nativeLibraryDir = null; 9254 info.secondaryNativeLibraryDir = null; 9255 9256 if (isApkFile(codeFile)) { 9257 // Monolithic install 9258 if (bundledApp) { 9259 // If "/system/lib64/apkname" exists, assume that is the per-package 9260 // native library directory to use; otherwise use "/system/lib/apkname". 9261 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9262 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9263 getPrimaryInstructionSet(info)); 9264 9265 // This is a bundled system app so choose the path based on the ABI. 9266 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9267 // is just the default path. 9268 final String apkName = deriveCodePathName(codePath); 9269 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9270 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9271 apkName).getAbsolutePath(); 9272 9273 if (info.secondaryCpuAbi != null) { 9274 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9275 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9276 secondaryLibDir, apkName).getAbsolutePath(); 9277 } 9278 } else if (asecApp) { 9279 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9280 .getAbsolutePath(); 9281 } else { 9282 final String apkName = deriveCodePathName(codePath); 9283 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9284 .getAbsolutePath(); 9285 } 9286 9287 info.nativeLibraryRootRequiresIsa = false; 9288 info.nativeLibraryDir = info.nativeLibraryRootDir; 9289 } else { 9290 // Cluster install 9291 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9292 info.nativeLibraryRootRequiresIsa = true; 9293 9294 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9295 getPrimaryInstructionSet(info)).getAbsolutePath(); 9296 9297 if (info.secondaryCpuAbi != null) { 9298 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9299 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9300 } 9301 } 9302 } 9303 9304 /** 9305 * Calculate the abis and roots for a bundled app. These can uniquely 9306 * be determined from the contents of the system partition, i.e whether 9307 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9308 * of this information, and instead assume that the system was built 9309 * sensibly. 9310 */ 9311 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9312 PackageSetting pkgSetting) { 9313 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9314 9315 // If "/system/lib64/apkname" exists, assume that is the per-package 9316 // native library directory to use; otherwise use "/system/lib/apkname". 9317 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9318 setBundledAppAbi(pkg, apkRoot, apkName); 9319 // pkgSetting might be null during rescan following uninstall of updates 9320 // to a bundled app, so accommodate that possibility. The settings in 9321 // that case will be established later from the parsed package. 9322 // 9323 // If the settings aren't null, sync them up with what we've just derived. 9324 // note that apkRoot isn't stored in the package settings. 9325 if (pkgSetting != null) { 9326 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9327 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9328 } 9329 } 9330 9331 /** 9332 * Deduces the ABI of a bundled app and sets the relevant fields on the 9333 * parsed pkg object. 9334 * 9335 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9336 * under which system libraries are installed. 9337 * @param apkName the name of the installed package. 9338 */ 9339 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9340 final File codeFile = new File(pkg.codePath); 9341 9342 final boolean has64BitLibs; 9343 final boolean has32BitLibs; 9344 if (isApkFile(codeFile)) { 9345 // Monolithic install 9346 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9347 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9348 } else { 9349 // Cluster install 9350 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9351 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9352 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9353 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9354 has64BitLibs = (new File(rootDir, isa)).exists(); 9355 } else { 9356 has64BitLibs = false; 9357 } 9358 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9359 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9360 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9361 has32BitLibs = (new File(rootDir, isa)).exists(); 9362 } else { 9363 has32BitLibs = false; 9364 } 9365 } 9366 9367 if (has64BitLibs && !has32BitLibs) { 9368 // The package has 64 bit libs, but not 32 bit libs. Its primary 9369 // ABI should be 64 bit. We can safely assume here that the bundled 9370 // native libraries correspond to the most preferred ABI in the list. 9371 9372 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9373 pkg.applicationInfo.secondaryCpuAbi = null; 9374 } else if (has32BitLibs && !has64BitLibs) { 9375 // The package has 32 bit libs but not 64 bit libs. Its primary 9376 // ABI should be 32 bit. 9377 9378 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9379 pkg.applicationInfo.secondaryCpuAbi = null; 9380 } else if (has32BitLibs && has64BitLibs) { 9381 // The application has both 64 and 32 bit bundled libraries. We check 9382 // here that the app declares multiArch support, and warn if it doesn't. 9383 // 9384 // We will be lenient here and record both ABIs. The primary will be the 9385 // ABI that's higher on the list, i.e, a device that's configured to prefer 9386 // 64 bit apps will see a 64 bit primary ABI, 9387 9388 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9389 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9390 } 9391 9392 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9393 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9394 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9395 } else { 9396 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9397 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9398 } 9399 } else { 9400 pkg.applicationInfo.primaryCpuAbi = null; 9401 pkg.applicationInfo.secondaryCpuAbi = null; 9402 } 9403 } 9404 9405 private void killApplication(String pkgName, int appId, String reason) { 9406 // Request the ActivityManager to kill the process(only for existing packages) 9407 // so that we do not end up in a confused state while the user is still using the older 9408 // version of the application while the new one gets installed. 9409 final long token = Binder.clearCallingIdentity(); 9410 try { 9411 IActivityManager am = ActivityManagerNative.getDefault(); 9412 if (am != null) { 9413 try { 9414 am.killApplicationWithAppId(pkgName, appId, reason); 9415 } catch (RemoteException e) { 9416 } 9417 } 9418 } finally { 9419 Binder.restoreCallingIdentity(token); 9420 } 9421 } 9422 9423 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9424 // Remove the parent package setting 9425 PackageSetting ps = (PackageSetting) pkg.mExtras; 9426 if (ps != null) { 9427 removePackageLI(ps, chatty); 9428 } 9429 // Remove the child package setting 9430 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9431 for (int i = 0; i < childCount; i++) { 9432 PackageParser.Package childPkg = pkg.childPackages.get(i); 9433 ps = (PackageSetting) childPkg.mExtras; 9434 if (ps != null) { 9435 removePackageLI(ps, chatty); 9436 } 9437 } 9438 } 9439 9440 void removePackageLI(PackageSetting ps, boolean chatty) { 9441 if (DEBUG_INSTALL) { 9442 if (chatty) 9443 Log.d(TAG, "Removing package " + ps.name); 9444 } 9445 9446 // writer 9447 synchronized (mPackages) { 9448 mPackages.remove(ps.name); 9449 final PackageParser.Package pkg = ps.pkg; 9450 if (pkg != null) { 9451 cleanPackageDataStructuresLILPw(pkg, chatty); 9452 } 9453 } 9454 } 9455 9456 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9457 if (DEBUG_INSTALL) { 9458 if (chatty) 9459 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9460 } 9461 9462 // writer 9463 synchronized (mPackages) { 9464 // Remove the parent package 9465 mPackages.remove(pkg.applicationInfo.packageName); 9466 cleanPackageDataStructuresLILPw(pkg, chatty); 9467 9468 // Remove the child packages 9469 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9470 for (int i = 0; i < childCount; i++) { 9471 PackageParser.Package childPkg = pkg.childPackages.get(i); 9472 mPackages.remove(childPkg.applicationInfo.packageName); 9473 cleanPackageDataStructuresLILPw(childPkg, chatty); 9474 } 9475 } 9476 } 9477 9478 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9479 int N = pkg.providers.size(); 9480 StringBuilder r = null; 9481 int i; 9482 for (i=0; i<N; i++) { 9483 PackageParser.Provider p = pkg.providers.get(i); 9484 mProviders.removeProvider(p); 9485 if (p.info.authority == null) { 9486 9487 /* There was another ContentProvider with this authority when 9488 * this app was installed so this authority is null, 9489 * Ignore it as we don't have to unregister the provider. 9490 */ 9491 continue; 9492 } 9493 String names[] = p.info.authority.split(";"); 9494 for (int j = 0; j < names.length; j++) { 9495 if (mProvidersByAuthority.get(names[j]) == p) { 9496 mProvidersByAuthority.remove(names[j]); 9497 if (DEBUG_REMOVE) { 9498 if (chatty) 9499 Log.d(TAG, "Unregistered content provider: " + names[j] 9500 + ", className = " + p.info.name + ", isSyncable = " 9501 + p.info.isSyncable); 9502 } 9503 } 9504 } 9505 if (DEBUG_REMOVE && chatty) { 9506 if (r == null) { 9507 r = new StringBuilder(256); 9508 } else { 9509 r.append(' '); 9510 } 9511 r.append(p.info.name); 9512 } 9513 } 9514 if (r != null) { 9515 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9516 } 9517 9518 N = pkg.services.size(); 9519 r = null; 9520 for (i=0; i<N; i++) { 9521 PackageParser.Service s = pkg.services.get(i); 9522 mServices.removeService(s); 9523 if (chatty) { 9524 if (r == null) { 9525 r = new StringBuilder(256); 9526 } else { 9527 r.append(' '); 9528 } 9529 r.append(s.info.name); 9530 } 9531 } 9532 if (r != null) { 9533 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9534 } 9535 9536 N = pkg.receivers.size(); 9537 r = null; 9538 for (i=0; i<N; i++) { 9539 PackageParser.Activity a = pkg.receivers.get(i); 9540 mReceivers.removeActivity(a, "receiver"); 9541 if (DEBUG_REMOVE && chatty) { 9542 if (r == null) { 9543 r = new StringBuilder(256); 9544 } else { 9545 r.append(' '); 9546 } 9547 r.append(a.info.name); 9548 } 9549 } 9550 if (r != null) { 9551 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9552 } 9553 9554 N = pkg.activities.size(); 9555 r = null; 9556 for (i=0; i<N; i++) { 9557 PackageParser.Activity a = pkg.activities.get(i); 9558 mActivities.removeActivity(a, "activity"); 9559 if (DEBUG_REMOVE && chatty) { 9560 if (r == null) { 9561 r = new StringBuilder(256); 9562 } else { 9563 r.append(' '); 9564 } 9565 r.append(a.info.name); 9566 } 9567 } 9568 if (r != null) { 9569 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9570 } 9571 9572 N = pkg.permissions.size(); 9573 r = null; 9574 for (i=0; i<N; i++) { 9575 PackageParser.Permission p = pkg.permissions.get(i); 9576 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9577 if (bp == null) { 9578 bp = mSettings.mPermissionTrees.get(p.info.name); 9579 } 9580 if (bp != null && bp.perm == p) { 9581 bp.perm = null; 9582 if (DEBUG_REMOVE && chatty) { 9583 if (r == null) { 9584 r = new StringBuilder(256); 9585 } else { 9586 r.append(' '); 9587 } 9588 r.append(p.info.name); 9589 } 9590 } 9591 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9592 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9593 if (appOpPkgs != null) { 9594 appOpPkgs.remove(pkg.packageName); 9595 } 9596 } 9597 } 9598 if (r != null) { 9599 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9600 } 9601 9602 N = pkg.requestedPermissions.size(); 9603 r = null; 9604 for (i=0; i<N; i++) { 9605 String perm = pkg.requestedPermissions.get(i); 9606 BasePermission bp = mSettings.mPermissions.get(perm); 9607 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9608 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9609 if (appOpPkgs != null) { 9610 appOpPkgs.remove(pkg.packageName); 9611 if (appOpPkgs.isEmpty()) { 9612 mAppOpPermissionPackages.remove(perm); 9613 } 9614 } 9615 } 9616 } 9617 if (r != null) { 9618 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9619 } 9620 9621 N = pkg.instrumentation.size(); 9622 r = null; 9623 for (i=0; i<N; i++) { 9624 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9625 mInstrumentation.remove(a.getComponentName()); 9626 if (DEBUG_REMOVE && chatty) { 9627 if (r == null) { 9628 r = new StringBuilder(256); 9629 } else { 9630 r.append(' '); 9631 } 9632 r.append(a.info.name); 9633 } 9634 } 9635 if (r != null) { 9636 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9637 } 9638 9639 r = null; 9640 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9641 // Only system apps can hold shared libraries. 9642 if (pkg.libraryNames != null) { 9643 for (i=0; i<pkg.libraryNames.size(); i++) { 9644 String name = pkg.libraryNames.get(i); 9645 SharedLibraryEntry cur = mSharedLibraries.get(name); 9646 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9647 mSharedLibraries.remove(name); 9648 if (DEBUG_REMOVE && chatty) { 9649 if (r == null) { 9650 r = new StringBuilder(256); 9651 } else { 9652 r.append(' '); 9653 } 9654 r.append(name); 9655 } 9656 } 9657 } 9658 } 9659 } 9660 if (r != null) { 9661 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9662 } 9663 } 9664 9665 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9666 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9667 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9668 return true; 9669 } 9670 } 9671 return false; 9672 } 9673 9674 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9675 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9676 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9677 9678 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9679 // Update the parent permissions 9680 updatePermissionsLPw(pkg.packageName, pkg, flags); 9681 // Update the child permissions 9682 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9683 for (int i = 0; i < childCount; i++) { 9684 PackageParser.Package childPkg = pkg.childPackages.get(i); 9685 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9686 } 9687 } 9688 9689 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9690 int flags) { 9691 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9692 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9693 } 9694 9695 private void updatePermissionsLPw(String changingPkg, 9696 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9697 // Make sure there are no dangling permission trees. 9698 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9699 while (it.hasNext()) { 9700 final BasePermission bp = it.next(); 9701 if (bp.packageSetting == null) { 9702 // We may not yet have parsed the package, so just see if 9703 // we still know about its settings. 9704 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9705 } 9706 if (bp.packageSetting == null) { 9707 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9708 + " from package " + bp.sourcePackage); 9709 it.remove(); 9710 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9711 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9712 Slog.i(TAG, "Removing old permission tree: " + bp.name 9713 + " from package " + bp.sourcePackage); 9714 flags |= UPDATE_PERMISSIONS_ALL; 9715 it.remove(); 9716 } 9717 } 9718 } 9719 9720 // Make sure all dynamic permissions have been assigned to a package, 9721 // and make sure there are no dangling permissions. 9722 it = mSettings.mPermissions.values().iterator(); 9723 while (it.hasNext()) { 9724 final BasePermission bp = it.next(); 9725 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9726 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9727 + bp.name + " pkg=" + bp.sourcePackage 9728 + " info=" + bp.pendingInfo); 9729 if (bp.packageSetting == null && bp.pendingInfo != null) { 9730 final BasePermission tree = findPermissionTreeLP(bp.name); 9731 if (tree != null && tree.perm != null) { 9732 bp.packageSetting = tree.packageSetting; 9733 bp.perm = new PackageParser.Permission(tree.perm.owner, 9734 new PermissionInfo(bp.pendingInfo)); 9735 bp.perm.info.packageName = tree.perm.info.packageName; 9736 bp.perm.info.name = bp.name; 9737 bp.uid = tree.uid; 9738 } 9739 } 9740 } 9741 if (bp.packageSetting == null) { 9742 // We may not yet have parsed the package, so just see if 9743 // we still know about its settings. 9744 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9745 } 9746 if (bp.packageSetting == null) { 9747 Slog.w(TAG, "Removing dangling permission: " + bp.name 9748 + " from package " + bp.sourcePackage); 9749 it.remove(); 9750 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9751 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9752 Slog.i(TAG, "Removing old permission: " + bp.name 9753 + " from package " + bp.sourcePackage); 9754 flags |= UPDATE_PERMISSIONS_ALL; 9755 it.remove(); 9756 } 9757 } 9758 } 9759 9760 // Now update the permissions for all packages, in particular 9761 // replace the granted permissions of the system packages. 9762 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9763 for (PackageParser.Package pkg : mPackages.values()) { 9764 if (pkg != pkgInfo) { 9765 // Only replace for packages on requested volume 9766 final String volumeUuid = getVolumeUuidForPackage(pkg); 9767 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9768 && Objects.equals(replaceVolumeUuid, volumeUuid); 9769 grantPermissionsLPw(pkg, replace, changingPkg); 9770 } 9771 } 9772 } 9773 9774 if (pkgInfo != null) { 9775 // Only replace for packages on requested volume 9776 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9777 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9778 && Objects.equals(replaceVolumeUuid, volumeUuid); 9779 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9780 } 9781 } 9782 9783 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9784 String packageOfInterest) { 9785 // IMPORTANT: There are two types of permissions: install and runtime. 9786 // Install time permissions are granted when the app is installed to 9787 // all device users and users added in the future. Runtime permissions 9788 // are granted at runtime explicitly to specific users. Normal and signature 9789 // protected permissions are install time permissions. Dangerous permissions 9790 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9791 // otherwise they are runtime permissions. This function does not manage 9792 // runtime permissions except for the case an app targeting Lollipop MR1 9793 // being upgraded to target a newer SDK, in which case dangerous permissions 9794 // are transformed from install time to runtime ones. 9795 9796 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9797 if (ps == null) { 9798 return; 9799 } 9800 9801 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9802 9803 PermissionsState permissionsState = ps.getPermissionsState(); 9804 PermissionsState origPermissions = permissionsState; 9805 9806 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9807 9808 boolean runtimePermissionsRevoked = false; 9809 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9810 9811 boolean changedInstallPermission = false; 9812 9813 if (replace) { 9814 ps.installPermissionsFixed = false; 9815 if (!ps.isSharedUser()) { 9816 origPermissions = new PermissionsState(permissionsState); 9817 permissionsState.reset(); 9818 } else { 9819 // We need to know only about runtime permission changes since the 9820 // calling code always writes the install permissions state but 9821 // the runtime ones are written only if changed. The only cases of 9822 // changed runtime permissions here are promotion of an install to 9823 // runtime and revocation of a runtime from a shared user. 9824 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9825 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9826 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9827 runtimePermissionsRevoked = true; 9828 } 9829 } 9830 } 9831 9832 permissionsState.setGlobalGids(mGlobalGids); 9833 9834 final int N = pkg.requestedPermissions.size(); 9835 for (int i=0; i<N; i++) { 9836 final String name = pkg.requestedPermissions.get(i); 9837 final BasePermission bp = mSettings.mPermissions.get(name); 9838 9839 if (DEBUG_INSTALL) { 9840 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9841 } 9842 9843 if (bp == null || bp.packageSetting == null) { 9844 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9845 Slog.w(TAG, "Unknown permission " + name 9846 + " in package " + pkg.packageName); 9847 } 9848 continue; 9849 } 9850 9851 final String perm = bp.name; 9852 boolean allowedSig = false; 9853 int grant = GRANT_DENIED; 9854 9855 // Keep track of app op permissions. 9856 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9857 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9858 if (pkgs == null) { 9859 pkgs = new ArraySet<>(); 9860 mAppOpPermissionPackages.put(bp.name, pkgs); 9861 } 9862 pkgs.add(pkg.packageName); 9863 } 9864 9865 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9866 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9867 >= Build.VERSION_CODES.M; 9868 switch (level) { 9869 case PermissionInfo.PROTECTION_NORMAL: { 9870 // For all apps normal permissions are install time ones. 9871 grant = GRANT_INSTALL; 9872 } break; 9873 9874 case PermissionInfo.PROTECTION_DANGEROUS: { 9875 // If a permission review is required for legacy apps we represent 9876 // their permissions as always granted runtime ones since we need 9877 // to keep the review required permission flag per user while an 9878 // install permission's state is shared across all users. 9879 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9880 // For legacy apps dangerous permissions are install time ones. 9881 grant = GRANT_INSTALL; 9882 } else if (origPermissions.hasInstallPermission(bp.name)) { 9883 // For legacy apps that became modern, install becomes runtime. 9884 grant = GRANT_UPGRADE; 9885 } else if (mPromoteSystemApps 9886 && isSystemApp(ps) 9887 && mExistingSystemPackages.contains(ps.name)) { 9888 // For legacy system apps, install becomes runtime. 9889 // We cannot check hasInstallPermission() for system apps since those 9890 // permissions were granted implicitly and not persisted pre-M. 9891 grant = GRANT_UPGRADE; 9892 } else { 9893 // For modern apps keep runtime permissions unchanged. 9894 grant = GRANT_RUNTIME; 9895 } 9896 } break; 9897 9898 case PermissionInfo.PROTECTION_SIGNATURE: { 9899 // For all apps signature permissions are install time ones. 9900 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9901 if (allowedSig) { 9902 grant = GRANT_INSTALL; 9903 } 9904 } break; 9905 } 9906 9907 if (DEBUG_INSTALL) { 9908 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9909 } 9910 9911 if (grant != GRANT_DENIED) { 9912 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9913 // If this is an existing, non-system package, then 9914 // we can't add any new permissions to it. 9915 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9916 // Except... if this is a permission that was added 9917 // to the platform (note: need to only do this when 9918 // updating the platform). 9919 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9920 grant = GRANT_DENIED; 9921 } 9922 } 9923 } 9924 9925 switch (grant) { 9926 case GRANT_INSTALL: { 9927 // Revoke this as runtime permission to handle the case of 9928 // a runtime permission being downgraded to an install one. 9929 // Also in permission review mode we keep dangerous permissions 9930 // for legacy apps 9931 for (int userId : UserManagerService.getInstance().getUserIds()) { 9932 if (origPermissions.getRuntimePermissionState( 9933 bp.name, userId) != null) { 9934 // Revoke the runtime permission and clear the flags. 9935 origPermissions.revokeRuntimePermission(bp, userId); 9936 origPermissions.updatePermissionFlags(bp, userId, 9937 PackageManager.MASK_PERMISSION_FLAGS, 0); 9938 // If we revoked a permission permission, we have to write. 9939 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9940 changedRuntimePermissionUserIds, userId); 9941 } 9942 } 9943 // Grant an install permission. 9944 if (permissionsState.grantInstallPermission(bp) != 9945 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9946 changedInstallPermission = true; 9947 } 9948 } break; 9949 9950 case GRANT_RUNTIME: { 9951 // Grant previously granted runtime permissions. 9952 for (int userId : UserManagerService.getInstance().getUserIds()) { 9953 PermissionState permissionState = origPermissions 9954 .getRuntimePermissionState(bp.name, userId); 9955 int flags = permissionState != null 9956 ? permissionState.getFlags() : 0; 9957 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9958 if (permissionsState.grantRuntimePermission(bp, userId) == 9959 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9960 // If we cannot put the permission as it was, we have to write. 9961 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9962 changedRuntimePermissionUserIds, userId); 9963 } 9964 // If the app supports runtime permissions no need for a review. 9965 if (Build.PERMISSIONS_REVIEW_REQUIRED 9966 && appSupportsRuntimePermissions 9967 && (flags & PackageManager 9968 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9969 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9970 // Since we changed the flags, we have to write. 9971 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9972 changedRuntimePermissionUserIds, userId); 9973 } 9974 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9975 && !appSupportsRuntimePermissions) { 9976 // For legacy apps that need a permission review, every new 9977 // runtime permission is granted but it is pending a review. 9978 // We also need to review only platform defined runtime 9979 // permissions as these are the only ones the platform knows 9980 // how to disable the API to simulate revocation as legacy 9981 // apps don't expect to run with revoked permissions. 9982 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9983 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9984 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9985 // We changed the flags, hence have to write. 9986 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9987 changedRuntimePermissionUserIds, userId); 9988 } 9989 } 9990 if (permissionsState.grantRuntimePermission(bp, userId) 9991 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9992 // We changed the permission, hence have to write. 9993 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9994 changedRuntimePermissionUserIds, userId); 9995 } 9996 } 9997 // Propagate the permission flags. 9998 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9999 } 10000 } break; 10001 10002 case GRANT_UPGRADE: { 10003 // Grant runtime permissions for a previously held install permission. 10004 PermissionState permissionState = origPermissions 10005 .getInstallPermissionState(bp.name); 10006 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10007 10008 if (origPermissions.revokeInstallPermission(bp) 10009 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10010 // We will be transferring the permission flags, so clear them. 10011 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10012 PackageManager.MASK_PERMISSION_FLAGS, 0); 10013 changedInstallPermission = true; 10014 } 10015 10016 // If the permission is not to be promoted to runtime we ignore it and 10017 // also its other flags as they are not applicable to install permissions. 10018 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10019 for (int userId : currentUserIds) { 10020 if (permissionsState.grantRuntimePermission(bp, userId) != 10021 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10022 // Transfer the permission flags. 10023 permissionsState.updatePermissionFlags(bp, userId, 10024 flags, flags); 10025 // If we granted the permission, we have to write. 10026 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10027 changedRuntimePermissionUserIds, userId); 10028 } 10029 } 10030 } 10031 } break; 10032 10033 default: { 10034 if (packageOfInterest == null 10035 || packageOfInterest.equals(pkg.packageName)) { 10036 Slog.w(TAG, "Not granting permission " + perm 10037 + " to package " + pkg.packageName 10038 + " because it was previously installed without"); 10039 } 10040 } break; 10041 } 10042 } else { 10043 if (permissionsState.revokeInstallPermission(bp) != 10044 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10045 // Also drop the permission flags. 10046 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10047 PackageManager.MASK_PERMISSION_FLAGS, 0); 10048 changedInstallPermission = true; 10049 Slog.i(TAG, "Un-granting permission " + perm 10050 + " from package " + pkg.packageName 10051 + " (protectionLevel=" + bp.protectionLevel 10052 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10053 + ")"); 10054 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10055 // Don't print warning for app op permissions, since it is fine for them 10056 // not to be granted, there is a UI for the user to decide. 10057 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10058 Slog.w(TAG, "Not granting permission " + perm 10059 + " to package " + pkg.packageName 10060 + " (protectionLevel=" + bp.protectionLevel 10061 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10062 + ")"); 10063 } 10064 } 10065 } 10066 } 10067 10068 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10069 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10070 // This is the first that we have heard about this package, so the 10071 // permissions we have now selected are fixed until explicitly 10072 // changed. 10073 ps.installPermissionsFixed = true; 10074 } 10075 10076 // Persist the runtime permissions state for users with changes. If permissions 10077 // were revoked because no app in the shared user declares them we have to 10078 // write synchronously to avoid losing runtime permissions state. 10079 for (int userId : changedRuntimePermissionUserIds) { 10080 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10081 } 10082 10083 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10084 } 10085 10086 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10087 boolean allowed = false; 10088 final int NP = PackageParser.NEW_PERMISSIONS.length; 10089 for (int ip=0; ip<NP; ip++) { 10090 final PackageParser.NewPermissionInfo npi 10091 = PackageParser.NEW_PERMISSIONS[ip]; 10092 if (npi.name.equals(perm) 10093 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10094 allowed = true; 10095 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10096 + pkg.packageName); 10097 break; 10098 } 10099 } 10100 return allowed; 10101 } 10102 10103 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10104 BasePermission bp, PermissionsState origPermissions) { 10105 boolean allowed; 10106 allowed = (compareSignatures( 10107 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10108 == PackageManager.SIGNATURE_MATCH) 10109 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10110 == PackageManager.SIGNATURE_MATCH); 10111 if (!allowed && (bp.protectionLevel 10112 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10113 if (isSystemApp(pkg)) { 10114 // For updated system applications, a system permission 10115 // is granted only if it had been defined by the original application. 10116 if (pkg.isUpdatedSystemApp()) { 10117 final PackageSetting sysPs = mSettings 10118 .getDisabledSystemPkgLPr(pkg.packageName); 10119 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10120 // If the original was granted this permission, we take 10121 // that grant decision as read and propagate it to the 10122 // update. 10123 if (sysPs.isPrivileged()) { 10124 allowed = true; 10125 } 10126 } else { 10127 // The system apk may have been updated with an older 10128 // version of the one on the data partition, but which 10129 // granted a new system permission that it didn't have 10130 // before. In this case we do want to allow the app to 10131 // now get the new permission if the ancestral apk is 10132 // privileged to get it. 10133 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10134 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10135 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10136 allowed = true; 10137 break; 10138 } 10139 } 10140 } 10141 // Also if a privileged parent package on the system image or any of 10142 // its children requested a privileged permission, the updated child 10143 // packages can also get the permission. 10144 if (pkg.parentPackage != null) { 10145 final PackageSetting disabledSysParentPs = mSettings 10146 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10147 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10148 && disabledSysParentPs.isPrivileged()) { 10149 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10150 allowed = true; 10151 } else if (disabledSysParentPs.pkg.childPackages != null) { 10152 final int count = disabledSysParentPs.pkg.childPackages.size(); 10153 for (int i = 0; i < count; i++) { 10154 PackageParser.Package disabledSysChildPkg = 10155 disabledSysParentPs.pkg.childPackages.get(i); 10156 if (isPackageRequestingPermission(disabledSysChildPkg, 10157 perm)) { 10158 allowed = true; 10159 break; 10160 } 10161 } 10162 } 10163 } 10164 } 10165 } 10166 } else { 10167 allowed = isPrivilegedApp(pkg); 10168 } 10169 } 10170 } 10171 if (!allowed) { 10172 if (!allowed && (bp.protectionLevel 10173 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10174 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10175 // If this was a previously normal/dangerous permission that got moved 10176 // to a system permission as part of the runtime permission redesign, then 10177 // we still want to blindly grant it to old apps. 10178 allowed = true; 10179 } 10180 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10181 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10182 // If this permission is to be granted to the system installer and 10183 // this app is an installer, then it gets the permission. 10184 allowed = true; 10185 } 10186 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10187 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10188 // If this permission is to be granted to the system verifier and 10189 // this app is a verifier, then it gets the permission. 10190 allowed = true; 10191 } 10192 if (!allowed && (bp.protectionLevel 10193 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10194 && isSystemApp(pkg)) { 10195 // Any pre-installed system app is allowed to get this permission. 10196 allowed = true; 10197 } 10198 if (!allowed && (bp.protectionLevel 10199 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10200 // For development permissions, a development permission 10201 // is granted only if it was already granted. 10202 allowed = origPermissions.hasInstallPermission(perm); 10203 } 10204 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10205 && pkg.packageName.equals(mSetupWizardPackage)) { 10206 // If this permission is to be granted to the system setup wizard and 10207 // this app is a setup wizard, then it gets the permission. 10208 allowed = true; 10209 } 10210 } 10211 return allowed; 10212 } 10213 10214 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10215 final int permCount = pkg.requestedPermissions.size(); 10216 for (int j = 0; j < permCount; j++) { 10217 String requestedPermission = pkg.requestedPermissions.get(j); 10218 if (permission.equals(requestedPermission)) { 10219 return true; 10220 } 10221 } 10222 return false; 10223 } 10224 10225 final class ActivityIntentResolver 10226 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10227 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10228 boolean defaultOnly, int userId) { 10229 if (!sUserManager.exists(userId)) return null; 10230 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10231 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10232 } 10233 10234 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10235 int userId) { 10236 if (!sUserManager.exists(userId)) return null; 10237 mFlags = flags; 10238 return super.queryIntent(intent, resolvedType, 10239 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10240 } 10241 10242 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10243 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10244 if (!sUserManager.exists(userId)) return null; 10245 if (packageActivities == null) { 10246 return null; 10247 } 10248 mFlags = flags; 10249 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10250 final int N = packageActivities.size(); 10251 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10252 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10253 10254 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10255 for (int i = 0; i < N; ++i) { 10256 intentFilters = packageActivities.get(i).intents; 10257 if (intentFilters != null && intentFilters.size() > 0) { 10258 PackageParser.ActivityIntentInfo[] array = 10259 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10260 intentFilters.toArray(array); 10261 listCut.add(array); 10262 } 10263 } 10264 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10265 } 10266 10267 /** 10268 * Finds a privileged activity that matches the specified activity names. 10269 */ 10270 private PackageParser.Activity findMatchingActivity( 10271 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10272 for (PackageParser.Activity sysActivity : activityList) { 10273 if (sysActivity.info.name.equals(activityInfo.name)) { 10274 return sysActivity; 10275 } 10276 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10277 return sysActivity; 10278 } 10279 if (sysActivity.info.targetActivity != null) { 10280 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10281 return sysActivity; 10282 } 10283 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10284 return sysActivity; 10285 } 10286 } 10287 } 10288 return null; 10289 } 10290 10291 public class IterGenerator<E> { 10292 public Iterator<E> generate(ActivityIntentInfo info) { 10293 return null; 10294 } 10295 } 10296 10297 public class ActionIterGenerator extends IterGenerator<String> { 10298 @Override 10299 public Iterator<String> generate(ActivityIntentInfo info) { 10300 return info.actionsIterator(); 10301 } 10302 } 10303 10304 public class CategoriesIterGenerator extends IterGenerator<String> { 10305 @Override 10306 public Iterator<String> generate(ActivityIntentInfo info) { 10307 return info.categoriesIterator(); 10308 } 10309 } 10310 10311 public class SchemesIterGenerator extends IterGenerator<String> { 10312 @Override 10313 public Iterator<String> generate(ActivityIntentInfo info) { 10314 return info.schemesIterator(); 10315 } 10316 } 10317 10318 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10319 @Override 10320 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10321 return info.authoritiesIterator(); 10322 } 10323 } 10324 10325 /** 10326 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10327 * MODIFIED. Do not pass in a list that should not be changed. 10328 */ 10329 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10330 IterGenerator<T> generator, Iterator<T> searchIterator) { 10331 // loop through the set of actions; every one must be found in the intent filter 10332 while (searchIterator.hasNext()) { 10333 // we must have at least one filter in the list to consider a match 10334 if (intentList.size() == 0) { 10335 break; 10336 } 10337 10338 final T searchAction = searchIterator.next(); 10339 10340 // loop through the set of intent filters 10341 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10342 while (intentIter.hasNext()) { 10343 final ActivityIntentInfo intentInfo = intentIter.next(); 10344 boolean selectionFound = false; 10345 10346 // loop through the intent filter's selection criteria; at least one 10347 // of them must match the searched criteria 10348 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10349 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10350 final T intentSelection = intentSelectionIter.next(); 10351 if (intentSelection != null && intentSelection.equals(searchAction)) { 10352 selectionFound = true; 10353 break; 10354 } 10355 } 10356 10357 // the selection criteria wasn't found in this filter's set; this filter 10358 // is not a potential match 10359 if (!selectionFound) { 10360 intentIter.remove(); 10361 } 10362 } 10363 } 10364 } 10365 10366 private boolean isProtectedAction(ActivityIntentInfo filter) { 10367 final Iterator<String> actionsIter = filter.actionsIterator(); 10368 while (actionsIter != null && actionsIter.hasNext()) { 10369 final String filterAction = actionsIter.next(); 10370 if (PROTECTED_ACTIONS.contains(filterAction)) { 10371 return true; 10372 } 10373 } 10374 return false; 10375 } 10376 10377 /** 10378 * Adjusts the priority of the given intent filter according to policy. 10379 * <p> 10380 * <ul> 10381 * <li>The priority for non privileged applications is capped to '0'</li> 10382 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10383 * <li>The priority for unbundled updates to privileged applications is capped to the 10384 * priority defined on the system partition</li> 10385 * </ul> 10386 * <p> 10387 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10388 * allowed to obtain any priority on any action. 10389 */ 10390 private void adjustPriority( 10391 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10392 // nothing to do; priority is fine as-is 10393 if (intent.getPriority() <= 0) { 10394 return; 10395 } 10396 10397 final ActivityInfo activityInfo = intent.activity.info; 10398 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10399 10400 final boolean privilegedApp = 10401 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10402 if (!privilegedApp) { 10403 // non-privileged applications can never define a priority >0 10404 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10405 + " package: " + applicationInfo.packageName 10406 + " activity: " + intent.activity.className 10407 + " origPrio: " + intent.getPriority()); 10408 intent.setPriority(0); 10409 return; 10410 } 10411 10412 if (systemActivities == null) { 10413 // the system package is not disabled; we're parsing the system partition 10414 if (isProtectedAction(intent)) { 10415 if (mDeferProtectedFilters) { 10416 // We can't deal with these just yet. No component should ever obtain a 10417 // >0 priority for a protected actions, with ONE exception -- the setup 10418 // wizard. The setup wizard, however, cannot be known until we're able to 10419 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10420 // until all intent filters have been processed. Chicken, meet egg. 10421 // Let the filter temporarily have a high priority and rectify the 10422 // priorities after all system packages have been scanned. 10423 mProtectedFilters.add(intent); 10424 if (DEBUG_FILTERS) { 10425 Slog.i(TAG, "Protected action; save for later;" 10426 + " package: " + applicationInfo.packageName 10427 + " activity: " + intent.activity.className 10428 + " origPrio: " + intent.getPriority()); 10429 } 10430 return; 10431 } else { 10432 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10433 Slog.i(TAG, "No setup wizard;" 10434 + " All protected intents capped to priority 0"); 10435 } 10436 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10437 if (DEBUG_FILTERS) { 10438 Slog.i(TAG, "Found setup wizard;" 10439 + " allow priority " + intent.getPriority() + ";" 10440 + " package: " + intent.activity.info.packageName 10441 + " activity: " + intent.activity.className 10442 + " priority: " + intent.getPriority()); 10443 } 10444 // setup wizard gets whatever it wants 10445 return; 10446 } 10447 Slog.w(TAG, "Protected action; cap priority to 0;" 10448 + " package: " + intent.activity.info.packageName 10449 + " activity: " + intent.activity.className 10450 + " origPrio: " + intent.getPriority()); 10451 intent.setPriority(0); 10452 return; 10453 } 10454 } 10455 // privileged apps on the system image get whatever priority they request 10456 return; 10457 } 10458 10459 // privileged app unbundled update ... try to find the same activity 10460 final PackageParser.Activity foundActivity = 10461 findMatchingActivity(systemActivities, activityInfo); 10462 if (foundActivity == null) { 10463 // this is a new activity; it cannot obtain >0 priority 10464 if (DEBUG_FILTERS) { 10465 Slog.i(TAG, "New activity; cap priority to 0;" 10466 + " package: " + applicationInfo.packageName 10467 + " activity: " + intent.activity.className 10468 + " origPrio: " + intent.getPriority()); 10469 } 10470 intent.setPriority(0); 10471 return; 10472 } 10473 10474 // found activity, now check for filter equivalence 10475 10476 // a shallow copy is enough; we modify the list, not its contents 10477 final List<ActivityIntentInfo> intentListCopy = 10478 new ArrayList<>(foundActivity.intents); 10479 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10480 10481 // find matching action subsets 10482 final Iterator<String> actionsIterator = intent.actionsIterator(); 10483 if (actionsIterator != null) { 10484 getIntentListSubset( 10485 intentListCopy, new ActionIterGenerator(), actionsIterator); 10486 if (intentListCopy.size() == 0) { 10487 // no more intents to match; we're not equivalent 10488 if (DEBUG_FILTERS) { 10489 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10490 + " package: " + applicationInfo.packageName 10491 + " activity: " + intent.activity.className 10492 + " origPrio: " + intent.getPriority()); 10493 } 10494 intent.setPriority(0); 10495 return; 10496 } 10497 } 10498 10499 // find matching category subsets 10500 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10501 if (categoriesIterator != null) { 10502 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10503 categoriesIterator); 10504 if (intentListCopy.size() == 0) { 10505 // no more intents to match; we're not equivalent 10506 if (DEBUG_FILTERS) { 10507 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10508 + " package: " + applicationInfo.packageName 10509 + " activity: " + intent.activity.className 10510 + " origPrio: " + intent.getPriority()); 10511 } 10512 intent.setPriority(0); 10513 return; 10514 } 10515 } 10516 10517 // find matching schemes subsets 10518 final Iterator<String> schemesIterator = intent.schemesIterator(); 10519 if (schemesIterator != null) { 10520 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10521 schemesIterator); 10522 if (intentListCopy.size() == 0) { 10523 // no more intents to match; we're not equivalent 10524 if (DEBUG_FILTERS) { 10525 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10526 + " package: " + applicationInfo.packageName 10527 + " activity: " + intent.activity.className 10528 + " origPrio: " + intent.getPriority()); 10529 } 10530 intent.setPriority(0); 10531 return; 10532 } 10533 } 10534 10535 // find matching authorities subsets 10536 final Iterator<IntentFilter.AuthorityEntry> 10537 authoritiesIterator = intent.authoritiesIterator(); 10538 if (authoritiesIterator != null) { 10539 getIntentListSubset(intentListCopy, 10540 new AuthoritiesIterGenerator(), 10541 authoritiesIterator); 10542 if (intentListCopy.size() == 0) { 10543 // no more intents to match; we're not equivalent 10544 if (DEBUG_FILTERS) { 10545 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10546 + " package: " + applicationInfo.packageName 10547 + " activity: " + intent.activity.className 10548 + " origPrio: " + intent.getPriority()); 10549 } 10550 intent.setPriority(0); 10551 return; 10552 } 10553 } 10554 10555 // we found matching filter(s); app gets the max priority of all intents 10556 int cappedPriority = 0; 10557 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10558 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10559 } 10560 if (intent.getPriority() > cappedPriority) { 10561 if (DEBUG_FILTERS) { 10562 Slog.i(TAG, "Found matching filter(s);" 10563 + " cap priority to " + cappedPriority + ";" 10564 + " package: " + applicationInfo.packageName 10565 + " activity: " + intent.activity.className 10566 + " origPrio: " + intent.getPriority()); 10567 } 10568 intent.setPriority(cappedPriority); 10569 return; 10570 } 10571 // all this for nothing; the requested priority was <= what was on the system 10572 } 10573 10574 public final void addActivity(PackageParser.Activity a, String type) { 10575 mActivities.put(a.getComponentName(), a); 10576 if (DEBUG_SHOW_INFO) 10577 Log.v( 10578 TAG, " " + type + " " + 10579 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10580 if (DEBUG_SHOW_INFO) 10581 Log.v(TAG, " Class=" + a.info.name); 10582 final int NI = a.intents.size(); 10583 for (int j=0; j<NI; j++) { 10584 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10585 if ("activity".equals(type)) { 10586 final PackageSetting ps = 10587 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10588 final List<PackageParser.Activity> systemActivities = 10589 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10590 adjustPriority(systemActivities, intent); 10591 } 10592 if (DEBUG_SHOW_INFO) { 10593 Log.v(TAG, " IntentFilter:"); 10594 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10595 } 10596 if (!intent.debugCheck()) { 10597 Log.w(TAG, "==> For Activity " + a.info.name); 10598 } 10599 addFilter(intent); 10600 } 10601 } 10602 10603 public final void removeActivity(PackageParser.Activity a, String type) { 10604 mActivities.remove(a.getComponentName()); 10605 if (DEBUG_SHOW_INFO) { 10606 Log.v(TAG, " " + type + " " 10607 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10608 : a.info.name) + ":"); 10609 Log.v(TAG, " Class=" + a.info.name); 10610 } 10611 final int NI = a.intents.size(); 10612 for (int j=0; j<NI; j++) { 10613 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10614 if (DEBUG_SHOW_INFO) { 10615 Log.v(TAG, " IntentFilter:"); 10616 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10617 } 10618 removeFilter(intent); 10619 } 10620 } 10621 10622 @Override 10623 protected boolean allowFilterResult( 10624 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10625 ActivityInfo filterAi = filter.activity.info; 10626 for (int i=dest.size()-1; i>=0; i--) { 10627 ActivityInfo destAi = dest.get(i).activityInfo; 10628 if (destAi.name == filterAi.name 10629 && destAi.packageName == filterAi.packageName) { 10630 return false; 10631 } 10632 } 10633 return true; 10634 } 10635 10636 @Override 10637 protected ActivityIntentInfo[] newArray(int size) { 10638 return new ActivityIntentInfo[size]; 10639 } 10640 10641 @Override 10642 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10643 if (!sUserManager.exists(userId)) return true; 10644 PackageParser.Package p = filter.activity.owner; 10645 if (p != null) { 10646 PackageSetting ps = (PackageSetting)p.mExtras; 10647 if (ps != null) { 10648 // System apps are never considered stopped for purposes of 10649 // filtering, because there may be no way for the user to 10650 // actually re-launch them. 10651 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10652 && ps.getStopped(userId); 10653 } 10654 } 10655 return false; 10656 } 10657 10658 @Override 10659 protected boolean isPackageForFilter(String packageName, 10660 PackageParser.ActivityIntentInfo info) { 10661 return packageName.equals(info.activity.owner.packageName); 10662 } 10663 10664 @Override 10665 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10666 int match, int userId) { 10667 if (!sUserManager.exists(userId)) return null; 10668 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10669 return null; 10670 } 10671 final PackageParser.Activity activity = info.activity; 10672 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10673 if (ps == null) { 10674 return null; 10675 } 10676 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10677 ps.readUserState(userId), userId); 10678 if (ai == null) { 10679 return null; 10680 } 10681 final ResolveInfo res = new ResolveInfo(); 10682 res.activityInfo = ai; 10683 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10684 res.filter = info; 10685 } 10686 if (info != null) { 10687 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10688 } 10689 res.priority = info.getPriority(); 10690 res.preferredOrder = activity.owner.mPreferredOrder; 10691 //System.out.println("Result: " + res.activityInfo.className + 10692 // " = " + res.priority); 10693 res.match = match; 10694 res.isDefault = info.hasDefault; 10695 res.labelRes = info.labelRes; 10696 res.nonLocalizedLabel = info.nonLocalizedLabel; 10697 if (userNeedsBadging(userId)) { 10698 res.noResourceId = true; 10699 } else { 10700 res.icon = info.icon; 10701 } 10702 res.iconResourceId = info.icon; 10703 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10704 return res; 10705 } 10706 10707 @Override 10708 protected void sortResults(List<ResolveInfo> results) { 10709 Collections.sort(results, mResolvePrioritySorter); 10710 } 10711 10712 @Override 10713 protected void dumpFilter(PrintWriter out, String prefix, 10714 PackageParser.ActivityIntentInfo filter) { 10715 out.print(prefix); out.print( 10716 Integer.toHexString(System.identityHashCode(filter.activity))); 10717 out.print(' '); 10718 filter.activity.printComponentShortName(out); 10719 out.print(" filter "); 10720 out.println(Integer.toHexString(System.identityHashCode(filter))); 10721 } 10722 10723 @Override 10724 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10725 return filter.activity; 10726 } 10727 10728 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10729 PackageParser.Activity activity = (PackageParser.Activity)label; 10730 out.print(prefix); out.print( 10731 Integer.toHexString(System.identityHashCode(activity))); 10732 out.print(' '); 10733 activity.printComponentShortName(out); 10734 if (count > 1) { 10735 out.print(" ("); out.print(count); out.print(" filters)"); 10736 } 10737 out.println(); 10738 } 10739 10740 // Keys are String (activity class name), values are Activity. 10741 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10742 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10743 private int mFlags; 10744 } 10745 10746 private final class ServiceIntentResolver 10747 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10748 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10749 boolean defaultOnly, int userId) { 10750 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10751 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10752 } 10753 10754 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10755 int userId) { 10756 if (!sUserManager.exists(userId)) return null; 10757 mFlags = flags; 10758 return super.queryIntent(intent, resolvedType, 10759 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10760 } 10761 10762 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10763 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10764 if (!sUserManager.exists(userId)) return null; 10765 if (packageServices == null) { 10766 return null; 10767 } 10768 mFlags = flags; 10769 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10770 final int N = packageServices.size(); 10771 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10772 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10773 10774 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10775 for (int i = 0; i < N; ++i) { 10776 intentFilters = packageServices.get(i).intents; 10777 if (intentFilters != null && intentFilters.size() > 0) { 10778 PackageParser.ServiceIntentInfo[] array = 10779 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10780 intentFilters.toArray(array); 10781 listCut.add(array); 10782 } 10783 } 10784 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10785 } 10786 10787 public final void addService(PackageParser.Service s) { 10788 mServices.put(s.getComponentName(), s); 10789 if (DEBUG_SHOW_INFO) { 10790 Log.v(TAG, " " 10791 + (s.info.nonLocalizedLabel != null 10792 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10793 Log.v(TAG, " Class=" + s.info.name); 10794 } 10795 final int NI = s.intents.size(); 10796 int j; 10797 for (j=0; j<NI; j++) { 10798 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10799 if (DEBUG_SHOW_INFO) { 10800 Log.v(TAG, " IntentFilter:"); 10801 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10802 } 10803 if (!intent.debugCheck()) { 10804 Log.w(TAG, "==> For Service " + s.info.name); 10805 } 10806 addFilter(intent); 10807 } 10808 } 10809 10810 public final void removeService(PackageParser.Service s) { 10811 mServices.remove(s.getComponentName()); 10812 if (DEBUG_SHOW_INFO) { 10813 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10814 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10815 Log.v(TAG, " Class=" + s.info.name); 10816 } 10817 final int NI = s.intents.size(); 10818 int j; 10819 for (j=0; j<NI; j++) { 10820 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10821 if (DEBUG_SHOW_INFO) { 10822 Log.v(TAG, " IntentFilter:"); 10823 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10824 } 10825 removeFilter(intent); 10826 } 10827 } 10828 10829 @Override 10830 protected boolean allowFilterResult( 10831 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10832 ServiceInfo filterSi = filter.service.info; 10833 for (int i=dest.size()-1; i>=0; i--) { 10834 ServiceInfo destAi = dest.get(i).serviceInfo; 10835 if (destAi.name == filterSi.name 10836 && destAi.packageName == filterSi.packageName) { 10837 return false; 10838 } 10839 } 10840 return true; 10841 } 10842 10843 @Override 10844 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10845 return new PackageParser.ServiceIntentInfo[size]; 10846 } 10847 10848 @Override 10849 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10850 if (!sUserManager.exists(userId)) return true; 10851 PackageParser.Package p = filter.service.owner; 10852 if (p != null) { 10853 PackageSetting ps = (PackageSetting)p.mExtras; 10854 if (ps != null) { 10855 // System apps are never considered stopped for purposes of 10856 // filtering, because there may be no way for the user to 10857 // actually re-launch them. 10858 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10859 && ps.getStopped(userId); 10860 } 10861 } 10862 return false; 10863 } 10864 10865 @Override 10866 protected boolean isPackageForFilter(String packageName, 10867 PackageParser.ServiceIntentInfo info) { 10868 return packageName.equals(info.service.owner.packageName); 10869 } 10870 10871 @Override 10872 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10873 int match, int userId) { 10874 if (!sUserManager.exists(userId)) return null; 10875 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10876 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10877 return null; 10878 } 10879 final PackageParser.Service service = info.service; 10880 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10881 if (ps == null) { 10882 return null; 10883 } 10884 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10885 ps.readUserState(userId), userId); 10886 if (si == null) { 10887 return null; 10888 } 10889 final ResolveInfo res = new ResolveInfo(); 10890 res.serviceInfo = si; 10891 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10892 res.filter = filter; 10893 } 10894 res.priority = info.getPriority(); 10895 res.preferredOrder = service.owner.mPreferredOrder; 10896 res.match = match; 10897 res.isDefault = info.hasDefault; 10898 res.labelRes = info.labelRes; 10899 res.nonLocalizedLabel = info.nonLocalizedLabel; 10900 res.icon = info.icon; 10901 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10902 return res; 10903 } 10904 10905 @Override 10906 protected void sortResults(List<ResolveInfo> results) { 10907 Collections.sort(results, mResolvePrioritySorter); 10908 } 10909 10910 @Override 10911 protected void dumpFilter(PrintWriter out, String prefix, 10912 PackageParser.ServiceIntentInfo filter) { 10913 out.print(prefix); out.print( 10914 Integer.toHexString(System.identityHashCode(filter.service))); 10915 out.print(' '); 10916 filter.service.printComponentShortName(out); 10917 out.print(" filter "); 10918 out.println(Integer.toHexString(System.identityHashCode(filter))); 10919 } 10920 10921 @Override 10922 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10923 return filter.service; 10924 } 10925 10926 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10927 PackageParser.Service service = (PackageParser.Service)label; 10928 out.print(prefix); out.print( 10929 Integer.toHexString(System.identityHashCode(service))); 10930 out.print(' '); 10931 service.printComponentShortName(out); 10932 if (count > 1) { 10933 out.print(" ("); out.print(count); out.print(" filters)"); 10934 } 10935 out.println(); 10936 } 10937 10938// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10939// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10940// final List<ResolveInfo> retList = Lists.newArrayList(); 10941// while (i.hasNext()) { 10942// final ResolveInfo resolveInfo = (ResolveInfo) i; 10943// if (isEnabledLP(resolveInfo.serviceInfo)) { 10944// retList.add(resolveInfo); 10945// } 10946// } 10947// return retList; 10948// } 10949 10950 // Keys are String (activity class name), values are Activity. 10951 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10952 = new ArrayMap<ComponentName, PackageParser.Service>(); 10953 private int mFlags; 10954 }; 10955 10956 private final class ProviderIntentResolver 10957 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10958 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10959 boolean defaultOnly, int userId) { 10960 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10961 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10962 } 10963 10964 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10965 int userId) { 10966 if (!sUserManager.exists(userId)) 10967 return null; 10968 mFlags = flags; 10969 return super.queryIntent(intent, resolvedType, 10970 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10971 } 10972 10973 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10974 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10975 if (!sUserManager.exists(userId)) 10976 return null; 10977 if (packageProviders == null) { 10978 return null; 10979 } 10980 mFlags = flags; 10981 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10982 final int N = packageProviders.size(); 10983 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10984 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10985 10986 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10987 for (int i = 0; i < N; ++i) { 10988 intentFilters = packageProviders.get(i).intents; 10989 if (intentFilters != null && intentFilters.size() > 0) { 10990 PackageParser.ProviderIntentInfo[] array = 10991 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10992 intentFilters.toArray(array); 10993 listCut.add(array); 10994 } 10995 } 10996 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10997 } 10998 10999 public final void addProvider(PackageParser.Provider p) { 11000 if (mProviders.containsKey(p.getComponentName())) { 11001 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11002 return; 11003 } 11004 11005 mProviders.put(p.getComponentName(), p); 11006 if (DEBUG_SHOW_INFO) { 11007 Log.v(TAG, " " 11008 + (p.info.nonLocalizedLabel != null 11009 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11010 Log.v(TAG, " Class=" + p.info.name); 11011 } 11012 final int NI = p.intents.size(); 11013 int j; 11014 for (j = 0; j < NI; j++) { 11015 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11016 if (DEBUG_SHOW_INFO) { 11017 Log.v(TAG, " IntentFilter:"); 11018 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11019 } 11020 if (!intent.debugCheck()) { 11021 Log.w(TAG, "==> For Provider " + p.info.name); 11022 } 11023 addFilter(intent); 11024 } 11025 } 11026 11027 public final void removeProvider(PackageParser.Provider p) { 11028 mProviders.remove(p.getComponentName()); 11029 if (DEBUG_SHOW_INFO) { 11030 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11031 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11032 Log.v(TAG, " Class=" + p.info.name); 11033 } 11034 final int NI = p.intents.size(); 11035 int j; 11036 for (j = 0; j < NI; j++) { 11037 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11038 if (DEBUG_SHOW_INFO) { 11039 Log.v(TAG, " IntentFilter:"); 11040 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11041 } 11042 removeFilter(intent); 11043 } 11044 } 11045 11046 @Override 11047 protected boolean allowFilterResult( 11048 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11049 ProviderInfo filterPi = filter.provider.info; 11050 for (int i = dest.size() - 1; i >= 0; i--) { 11051 ProviderInfo destPi = dest.get(i).providerInfo; 11052 if (destPi.name == filterPi.name 11053 && destPi.packageName == filterPi.packageName) { 11054 return false; 11055 } 11056 } 11057 return true; 11058 } 11059 11060 @Override 11061 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11062 return new PackageParser.ProviderIntentInfo[size]; 11063 } 11064 11065 @Override 11066 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11067 if (!sUserManager.exists(userId)) 11068 return true; 11069 PackageParser.Package p = filter.provider.owner; 11070 if (p != null) { 11071 PackageSetting ps = (PackageSetting) p.mExtras; 11072 if (ps != null) { 11073 // System apps are never considered stopped for purposes of 11074 // filtering, because there may be no way for the user to 11075 // actually re-launch them. 11076 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11077 && ps.getStopped(userId); 11078 } 11079 } 11080 return false; 11081 } 11082 11083 @Override 11084 protected boolean isPackageForFilter(String packageName, 11085 PackageParser.ProviderIntentInfo info) { 11086 return packageName.equals(info.provider.owner.packageName); 11087 } 11088 11089 @Override 11090 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11091 int match, int userId) { 11092 if (!sUserManager.exists(userId)) 11093 return null; 11094 final PackageParser.ProviderIntentInfo info = filter; 11095 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11096 return null; 11097 } 11098 final PackageParser.Provider provider = info.provider; 11099 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11100 if (ps == null) { 11101 return null; 11102 } 11103 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11104 ps.readUserState(userId), userId); 11105 if (pi == null) { 11106 return null; 11107 } 11108 final ResolveInfo res = new ResolveInfo(); 11109 res.providerInfo = pi; 11110 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11111 res.filter = filter; 11112 } 11113 res.priority = info.getPriority(); 11114 res.preferredOrder = provider.owner.mPreferredOrder; 11115 res.match = match; 11116 res.isDefault = info.hasDefault; 11117 res.labelRes = info.labelRes; 11118 res.nonLocalizedLabel = info.nonLocalizedLabel; 11119 res.icon = info.icon; 11120 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11121 return res; 11122 } 11123 11124 @Override 11125 protected void sortResults(List<ResolveInfo> results) { 11126 Collections.sort(results, mResolvePrioritySorter); 11127 } 11128 11129 @Override 11130 protected void dumpFilter(PrintWriter out, String prefix, 11131 PackageParser.ProviderIntentInfo filter) { 11132 out.print(prefix); 11133 out.print( 11134 Integer.toHexString(System.identityHashCode(filter.provider))); 11135 out.print(' '); 11136 filter.provider.printComponentShortName(out); 11137 out.print(" filter "); 11138 out.println(Integer.toHexString(System.identityHashCode(filter))); 11139 } 11140 11141 @Override 11142 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11143 return filter.provider; 11144 } 11145 11146 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11147 PackageParser.Provider provider = (PackageParser.Provider)label; 11148 out.print(prefix); out.print( 11149 Integer.toHexString(System.identityHashCode(provider))); 11150 out.print(' '); 11151 provider.printComponentShortName(out); 11152 if (count > 1) { 11153 out.print(" ("); out.print(count); out.print(" filters)"); 11154 } 11155 out.println(); 11156 } 11157 11158 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11159 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11160 private int mFlags; 11161 } 11162 11163 private static final class EphemeralIntentResolver 11164 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11165 @Override 11166 protected EphemeralResolveIntentInfo[] newArray(int size) { 11167 return new EphemeralResolveIntentInfo[size]; 11168 } 11169 11170 @Override 11171 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11172 return true; 11173 } 11174 11175 @Override 11176 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11177 int userId) { 11178 if (!sUserManager.exists(userId)) { 11179 return null; 11180 } 11181 return info.getEphemeralResolveInfo(); 11182 } 11183 } 11184 11185 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11186 new Comparator<ResolveInfo>() { 11187 public int compare(ResolveInfo r1, ResolveInfo r2) { 11188 int v1 = r1.priority; 11189 int v2 = r2.priority; 11190 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11191 if (v1 != v2) { 11192 return (v1 > v2) ? -1 : 1; 11193 } 11194 v1 = r1.preferredOrder; 11195 v2 = r2.preferredOrder; 11196 if (v1 != v2) { 11197 return (v1 > v2) ? -1 : 1; 11198 } 11199 if (r1.isDefault != r2.isDefault) { 11200 return r1.isDefault ? -1 : 1; 11201 } 11202 v1 = r1.match; 11203 v2 = r2.match; 11204 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11205 if (v1 != v2) { 11206 return (v1 > v2) ? -1 : 1; 11207 } 11208 if (r1.system != r2.system) { 11209 return r1.system ? -1 : 1; 11210 } 11211 if (r1.activityInfo != null) { 11212 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11213 } 11214 if (r1.serviceInfo != null) { 11215 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11216 } 11217 if (r1.providerInfo != null) { 11218 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11219 } 11220 return 0; 11221 } 11222 }; 11223 11224 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11225 new Comparator<ProviderInfo>() { 11226 public int compare(ProviderInfo p1, ProviderInfo p2) { 11227 final int v1 = p1.initOrder; 11228 final int v2 = p2.initOrder; 11229 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11230 } 11231 }; 11232 11233 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11234 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11235 final int[] userIds) { 11236 mHandler.post(new Runnable() { 11237 @Override 11238 public void run() { 11239 try { 11240 final IActivityManager am = ActivityManagerNative.getDefault(); 11241 if (am == null) return; 11242 final int[] resolvedUserIds; 11243 if (userIds == null) { 11244 resolvedUserIds = am.getRunningUserIds(); 11245 } else { 11246 resolvedUserIds = userIds; 11247 } 11248 for (int id : resolvedUserIds) { 11249 final Intent intent = new Intent(action, 11250 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11251 if (extras != null) { 11252 intent.putExtras(extras); 11253 } 11254 if (targetPkg != null) { 11255 intent.setPackage(targetPkg); 11256 } 11257 // Modify the UID when posting to other users 11258 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11259 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11260 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11261 intent.putExtra(Intent.EXTRA_UID, uid); 11262 } 11263 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11264 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11265 if (DEBUG_BROADCASTS) { 11266 RuntimeException here = new RuntimeException("here"); 11267 here.fillInStackTrace(); 11268 Slog.d(TAG, "Sending to user " + id + ": " 11269 + intent.toShortString(false, true, false, false) 11270 + " " + intent.getExtras(), here); 11271 } 11272 am.broadcastIntent(null, intent, null, finishedReceiver, 11273 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11274 null, finishedReceiver != null, false, id); 11275 } 11276 } catch (RemoteException ex) { 11277 } 11278 } 11279 }); 11280 } 11281 11282 /** 11283 * Check if the external storage media is available. This is true if there 11284 * is a mounted external storage medium or if the external storage is 11285 * emulated. 11286 */ 11287 private boolean isExternalMediaAvailable() { 11288 return mMediaMounted || Environment.isExternalStorageEmulated(); 11289 } 11290 11291 @Override 11292 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11293 // writer 11294 synchronized (mPackages) { 11295 if (!isExternalMediaAvailable()) { 11296 // If the external storage is no longer mounted at this point, 11297 // the caller may not have been able to delete all of this 11298 // packages files and can not delete any more. Bail. 11299 return null; 11300 } 11301 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11302 if (lastPackage != null) { 11303 pkgs.remove(lastPackage); 11304 } 11305 if (pkgs.size() > 0) { 11306 return pkgs.get(0); 11307 } 11308 } 11309 return null; 11310 } 11311 11312 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11313 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11314 userId, andCode ? 1 : 0, packageName); 11315 if (mSystemReady) { 11316 msg.sendToTarget(); 11317 } else { 11318 if (mPostSystemReadyMessages == null) { 11319 mPostSystemReadyMessages = new ArrayList<>(); 11320 } 11321 mPostSystemReadyMessages.add(msg); 11322 } 11323 } 11324 11325 void startCleaningPackages() { 11326 // reader 11327 if (!isExternalMediaAvailable()) { 11328 return; 11329 } 11330 synchronized (mPackages) { 11331 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11332 return; 11333 } 11334 } 11335 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11336 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11337 IActivityManager am = ActivityManagerNative.getDefault(); 11338 if (am != null) { 11339 try { 11340 am.startService(null, intent, null, mContext.getOpPackageName(), 11341 UserHandle.USER_SYSTEM); 11342 } catch (RemoteException e) { 11343 } 11344 } 11345 } 11346 11347 @Override 11348 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11349 int installFlags, String installerPackageName, int userId) { 11350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11351 11352 final int callingUid = Binder.getCallingUid(); 11353 enforceCrossUserPermission(callingUid, userId, 11354 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11355 11356 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11357 try { 11358 if (observer != null) { 11359 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11360 } 11361 } catch (RemoteException re) { 11362 } 11363 return; 11364 } 11365 11366 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11367 installFlags |= PackageManager.INSTALL_FROM_ADB; 11368 11369 } else { 11370 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11371 // about installerPackageName. 11372 11373 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11374 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11375 } 11376 11377 UserHandle user; 11378 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11379 user = UserHandle.ALL; 11380 } else { 11381 user = new UserHandle(userId); 11382 } 11383 11384 // Only system components can circumvent runtime permissions when installing. 11385 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11386 && mContext.checkCallingOrSelfPermission(Manifest.permission 11387 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11388 throw new SecurityException("You need the " 11389 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11390 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11391 } 11392 11393 final File originFile = new File(originPath); 11394 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11395 11396 final Message msg = mHandler.obtainMessage(INIT_COPY); 11397 final VerificationInfo verificationInfo = new VerificationInfo( 11398 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11399 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11400 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11401 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11402 null /*certificates*/); 11403 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11404 msg.obj = params; 11405 11406 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11407 System.identityHashCode(msg.obj)); 11408 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11409 System.identityHashCode(msg.obj)); 11410 11411 mHandler.sendMessage(msg); 11412 } 11413 11414 void installStage(String packageName, File stagedDir, String stagedCid, 11415 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11416 String installerPackageName, int installerUid, UserHandle user, 11417 Certificate[][] certificates) { 11418 if (DEBUG_EPHEMERAL) { 11419 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11420 Slog.d(TAG, "Ephemeral install of " + packageName); 11421 } 11422 } 11423 final VerificationInfo verificationInfo = new VerificationInfo( 11424 sessionParams.originatingUri, sessionParams.referrerUri, 11425 sessionParams.originatingUid, installerUid); 11426 11427 final OriginInfo origin; 11428 if (stagedDir != null) { 11429 origin = OriginInfo.fromStagedFile(stagedDir); 11430 } else { 11431 origin = OriginInfo.fromStagedContainer(stagedCid); 11432 } 11433 11434 final Message msg = mHandler.obtainMessage(INIT_COPY); 11435 final InstallParams params = new InstallParams(origin, null, observer, 11436 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11437 verificationInfo, user, sessionParams.abiOverride, 11438 sessionParams.grantedRuntimePermissions, certificates); 11439 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11440 msg.obj = params; 11441 11442 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11443 System.identityHashCode(msg.obj)); 11444 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11445 System.identityHashCode(msg.obj)); 11446 11447 mHandler.sendMessage(msg); 11448 } 11449 11450 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11451 int userId) { 11452 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11453 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11454 } 11455 11456 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11457 int appId, int userId) { 11458 Bundle extras = new Bundle(1); 11459 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11460 11461 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11462 packageName, extras, 0, null, null, new int[] {userId}); 11463 try { 11464 IActivityManager am = ActivityManagerNative.getDefault(); 11465 if (isSystem && am.isUserRunning(userId, 0)) { 11466 // The just-installed/enabled app is bundled on the system, so presumed 11467 // to be able to run automatically without needing an explicit launch. 11468 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11469 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11470 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11471 .setPackage(packageName); 11472 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11473 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11474 } 11475 } catch (RemoteException e) { 11476 // shouldn't happen 11477 Slog.w(TAG, "Unable to bootstrap installed package", e); 11478 } 11479 } 11480 11481 @Override 11482 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11483 int userId) { 11484 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11485 PackageSetting pkgSetting; 11486 final int uid = Binder.getCallingUid(); 11487 enforceCrossUserPermission(uid, userId, 11488 true /* requireFullPermission */, true /* checkShell */, 11489 "setApplicationHiddenSetting for user " + userId); 11490 11491 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11492 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11493 return false; 11494 } 11495 11496 long callingId = Binder.clearCallingIdentity(); 11497 try { 11498 boolean sendAdded = false; 11499 boolean sendRemoved = false; 11500 // writer 11501 synchronized (mPackages) { 11502 pkgSetting = mSettings.mPackages.get(packageName); 11503 if (pkgSetting == null) { 11504 return false; 11505 } 11506 if (pkgSetting.getHidden(userId) != hidden) { 11507 pkgSetting.setHidden(hidden, userId); 11508 mSettings.writePackageRestrictionsLPr(userId); 11509 if (hidden) { 11510 sendRemoved = true; 11511 } else { 11512 sendAdded = true; 11513 } 11514 } 11515 } 11516 if (sendAdded) { 11517 sendPackageAddedForUser(packageName, pkgSetting, userId); 11518 return true; 11519 } 11520 if (sendRemoved) { 11521 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11522 "hiding pkg"); 11523 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11524 return true; 11525 } 11526 } finally { 11527 Binder.restoreCallingIdentity(callingId); 11528 } 11529 return false; 11530 } 11531 11532 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11533 int userId) { 11534 final PackageRemovedInfo info = new PackageRemovedInfo(); 11535 info.removedPackage = packageName; 11536 info.removedUsers = new int[] {userId}; 11537 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11538 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11539 } 11540 11541 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11542 if (pkgList.length > 0) { 11543 Bundle extras = new Bundle(1); 11544 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11545 11546 sendPackageBroadcast( 11547 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11548 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11549 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11550 new int[] {userId}); 11551 } 11552 } 11553 11554 /** 11555 * Returns true if application is not found or there was an error. Otherwise it returns 11556 * the hidden state of the package for the given user. 11557 */ 11558 @Override 11559 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11560 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11561 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11562 true /* requireFullPermission */, false /* checkShell */, 11563 "getApplicationHidden for user " + userId); 11564 PackageSetting pkgSetting; 11565 long callingId = Binder.clearCallingIdentity(); 11566 try { 11567 // writer 11568 synchronized (mPackages) { 11569 pkgSetting = mSettings.mPackages.get(packageName); 11570 if (pkgSetting == null) { 11571 return true; 11572 } 11573 return pkgSetting.getHidden(userId); 11574 } 11575 } finally { 11576 Binder.restoreCallingIdentity(callingId); 11577 } 11578 } 11579 11580 /** 11581 * @hide 11582 */ 11583 @Override 11584 public int installExistingPackageAsUser(String packageName, int userId) { 11585 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11586 null); 11587 PackageSetting pkgSetting; 11588 final int uid = Binder.getCallingUid(); 11589 enforceCrossUserPermission(uid, userId, 11590 true /* requireFullPermission */, true /* checkShell */, 11591 "installExistingPackage for user " + userId); 11592 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11593 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11594 } 11595 11596 long callingId = Binder.clearCallingIdentity(); 11597 try { 11598 boolean installed = false; 11599 11600 // writer 11601 synchronized (mPackages) { 11602 pkgSetting = mSettings.mPackages.get(packageName); 11603 if (pkgSetting == null) { 11604 return PackageManager.INSTALL_FAILED_INVALID_URI; 11605 } 11606 if (!pkgSetting.getInstalled(userId)) { 11607 pkgSetting.setInstalled(true, userId); 11608 pkgSetting.setHidden(false, userId); 11609 mSettings.writePackageRestrictionsLPr(userId); 11610 installed = true; 11611 } 11612 } 11613 11614 if (installed) { 11615 if (pkgSetting.pkg != null) { 11616 synchronized (mInstallLock) { 11617 // We don't need to freeze for a brand new install 11618 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11619 } 11620 } 11621 sendPackageAddedForUser(packageName, pkgSetting, userId); 11622 } 11623 } finally { 11624 Binder.restoreCallingIdentity(callingId); 11625 } 11626 11627 return PackageManager.INSTALL_SUCCEEDED; 11628 } 11629 11630 boolean isUserRestricted(int userId, String restrictionKey) { 11631 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11632 if (restrictions.getBoolean(restrictionKey, false)) { 11633 Log.w(TAG, "User is restricted: " + restrictionKey); 11634 return true; 11635 } 11636 return false; 11637 } 11638 11639 @Override 11640 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11641 int userId) { 11642 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11643 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11644 true /* requireFullPermission */, true /* checkShell */, 11645 "setPackagesSuspended for user " + userId); 11646 11647 if (ArrayUtils.isEmpty(packageNames)) { 11648 return packageNames; 11649 } 11650 11651 // List of package names for whom the suspended state has changed. 11652 List<String> changedPackages = new ArrayList<>(packageNames.length); 11653 // List of package names for whom the suspended state is not set as requested in this 11654 // method. 11655 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11656 long callingId = Binder.clearCallingIdentity(); 11657 try { 11658 for (int i = 0; i < packageNames.length; i++) { 11659 String packageName = packageNames[i]; 11660 boolean changed = false; 11661 final int appId; 11662 synchronized (mPackages) { 11663 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11664 if (pkgSetting == null) { 11665 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11666 + "\". Skipping suspending/un-suspending."); 11667 unactionedPackages.add(packageName); 11668 continue; 11669 } 11670 appId = pkgSetting.appId; 11671 if (pkgSetting.getSuspended(userId) != suspended) { 11672 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11673 unactionedPackages.add(packageName); 11674 continue; 11675 } 11676 pkgSetting.setSuspended(suspended, userId); 11677 mSettings.writePackageRestrictionsLPr(userId); 11678 changed = true; 11679 changedPackages.add(packageName); 11680 } 11681 } 11682 11683 if (changed && suspended) { 11684 killApplication(packageName, UserHandle.getUid(userId, appId), 11685 "suspending package"); 11686 } 11687 } 11688 } finally { 11689 Binder.restoreCallingIdentity(callingId); 11690 } 11691 11692 if (!changedPackages.isEmpty()) { 11693 sendPackagesSuspendedForUser(changedPackages.toArray( 11694 new String[changedPackages.size()]), userId, suspended); 11695 } 11696 11697 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11698 } 11699 11700 @Override 11701 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11702 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11703 true /* requireFullPermission */, false /* checkShell */, 11704 "isPackageSuspendedForUser for user " + userId); 11705 synchronized (mPackages) { 11706 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11707 if (pkgSetting == null) { 11708 throw new IllegalArgumentException("Unknown target package: " + packageName); 11709 } 11710 return pkgSetting.getSuspended(userId); 11711 } 11712 } 11713 11714 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11715 if (isPackageDeviceAdmin(packageName, userId)) { 11716 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11717 + "\": has an active device admin"); 11718 return false; 11719 } 11720 11721 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11722 if (packageName.equals(activeLauncherPackageName)) { 11723 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11724 + "\": contains the active launcher"); 11725 return false; 11726 } 11727 11728 if (packageName.equals(mRequiredInstallerPackage)) { 11729 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11730 + "\": required for package installation"); 11731 return false; 11732 } 11733 11734 if (packageName.equals(mRequiredVerifierPackage)) { 11735 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11736 + "\": required for package verification"); 11737 return false; 11738 } 11739 11740 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11741 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11742 + "\": is the default dialer"); 11743 return false; 11744 } 11745 11746 return true; 11747 } 11748 11749 private String getActiveLauncherPackageName(int userId) { 11750 Intent intent = new Intent(Intent.ACTION_MAIN); 11751 intent.addCategory(Intent.CATEGORY_HOME); 11752 ResolveInfo resolveInfo = resolveIntent( 11753 intent, 11754 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11755 PackageManager.MATCH_DEFAULT_ONLY, 11756 userId); 11757 11758 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11759 } 11760 11761 private String getDefaultDialerPackageName(int userId) { 11762 synchronized (mPackages) { 11763 return mSettings.getDefaultDialerPackageNameLPw(userId); 11764 } 11765 } 11766 11767 @Override 11768 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11769 mContext.enforceCallingOrSelfPermission( 11770 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11771 "Only package verification agents can verify applications"); 11772 11773 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11774 final PackageVerificationResponse response = new PackageVerificationResponse( 11775 verificationCode, Binder.getCallingUid()); 11776 msg.arg1 = id; 11777 msg.obj = response; 11778 mHandler.sendMessage(msg); 11779 } 11780 11781 @Override 11782 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11783 long millisecondsToDelay) { 11784 mContext.enforceCallingOrSelfPermission( 11785 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11786 "Only package verification agents can extend verification timeouts"); 11787 11788 final PackageVerificationState state = mPendingVerification.get(id); 11789 final PackageVerificationResponse response = new PackageVerificationResponse( 11790 verificationCodeAtTimeout, Binder.getCallingUid()); 11791 11792 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11793 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11794 } 11795 if (millisecondsToDelay < 0) { 11796 millisecondsToDelay = 0; 11797 } 11798 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11799 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11800 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11801 } 11802 11803 if ((state != null) && !state.timeoutExtended()) { 11804 state.extendTimeout(); 11805 11806 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11807 msg.arg1 = id; 11808 msg.obj = response; 11809 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11810 } 11811 } 11812 11813 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11814 int verificationCode, UserHandle user) { 11815 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11816 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11817 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11818 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11819 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11820 11821 mContext.sendBroadcastAsUser(intent, user, 11822 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11823 } 11824 11825 private ComponentName matchComponentForVerifier(String packageName, 11826 List<ResolveInfo> receivers) { 11827 ActivityInfo targetReceiver = null; 11828 11829 final int NR = receivers.size(); 11830 for (int i = 0; i < NR; i++) { 11831 final ResolveInfo info = receivers.get(i); 11832 if (info.activityInfo == null) { 11833 continue; 11834 } 11835 11836 if (packageName.equals(info.activityInfo.packageName)) { 11837 targetReceiver = info.activityInfo; 11838 break; 11839 } 11840 } 11841 11842 if (targetReceiver == null) { 11843 return null; 11844 } 11845 11846 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11847 } 11848 11849 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11850 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11851 if (pkgInfo.verifiers.length == 0) { 11852 return null; 11853 } 11854 11855 final int N = pkgInfo.verifiers.length; 11856 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11857 for (int i = 0; i < N; i++) { 11858 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11859 11860 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11861 receivers); 11862 if (comp == null) { 11863 continue; 11864 } 11865 11866 final int verifierUid = getUidForVerifier(verifierInfo); 11867 if (verifierUid == -1) { 11868 continue; 11869 } 11870 11871 if (DEBUG_VERIFY) { 11872 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11873 + " with the correct signature"); 11874 } 11875 sufficientVerifiers.add(comp); 11876 verificationState.addSufficientVerifier(verifierUid); 11877 } 11878 11879 return sufficientVerifiers; 11880 } 11881 11882 private int getUidForVerifier(VerifierInfo verifierInfo) { 11883 synchronized (mPackages) { 11884 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11885 if (pkg == null) { 11886 return -1; 11887 } else if (pkg.mSignatures.length != 1) { 11888 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11889 + " has more than one signature; ignoring"); 11890 return -1; 11891 } 11892 11893 /* 11894 * If the public key of the package's signature does not match 11895 * our expected public key, then this is a different package and 11896 * we should skip. 11897 */ 11898 11899 final byte[] expectedPublicKey; 11900 try { 11901 final Signature verifierSig = pkg.mSignatures[0]; 11902 final PublicKey publicKey = verifierSig.getPublicKey(); 11903 expectedPublicKey = publicKey.getEncoded(); 11904 } catch (CertificateException e) { 11905 return -1; 11906 } 11907 11908 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11909 11910 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11911 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11912 + " does not have the expected public key; ignoring"); 11913 return -1; 11914 } 11915 11916 return pkg.applicationInfo.uid; 11917 } 11918 } 11919 11920 @Override 11921 public void finishPackageInstall(int token, boolean didLaunch) { 11922 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11923 11924 if (DEBUG_INSTALL) { 11925 Slog.v(TAG, "BM finishing package install for " + token); 11926 } 11927 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11928 11929 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11930 mHandler.sendMessage(msg); 11931 } 11932 11933 /** 11934 * Get the verification agent timeout. 11935 * 11936 * @return verification timeout in milliseconds 11937 */ 11938 private long getVerificationTimeout() { 11939 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11940 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11941 DEFAULT_VERIFICATION_TIMEOUT); 11942 } 11943 11944 /** 11945 * Get the default verification agent response code. 11946 * 11947 * @return default verification response code 11948 */ 11949 private int getDefaultVerificationResponse() { 11950 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11951 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11952 DEFAULT_VERIFICATION_RESPONSE); 11953 } 11954 11955 /** 11956 * Check whether or not package verification has been enabled. 11957 * 11958 * @return true if verification should be performed 11959 */ 11960 private boolean isVerificationEnabled(int userId, int installFlags) { 11961 if (!DEFAULT_VERIFY_ENABLE) { 11962 return false; 11963 } 11964 // Ephemeral apps don't get the full verification treatment 11965 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11966 if (DEBUG_EPHEMERAL) { 11967 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11968 } 11969 return false; 11970 } 11971 11972 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11973 11974 // Check if installing from ADB 11975 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11976 // Do not run verification in a test harness environment 11977 if (ActivityManager.isRunningInTestHarness()) { 11978 return false; 11979 } 11980 if (ensureVerifyAppsEnabled) { 11981 return true; 11982 } 11983 // Check if the developer does not want package verification for ADB installs 11984 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11985 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11986 return false; 11987 } 11988 } 11989 11990 if (ensureVerifyAppsEnabled) { 11991 return true; 11992 } 11993 11994 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11995 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11996 } 11997 11998 @Override 11999 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12000 throws RemoteException { 12001 mContext.enforceCallingOrSelfPermission( 12002 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12003 "Only intentfilter verification agents can verify applications"); 12004 12005 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12006 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12007 Binder.getCallingUid(), verificationCode, failedDomains); 12008 msg.arg1 = id; 12009 msg.obj = response; 12010 mHandler.sendMessage(msg); 12011 } 12012 12013 @Override 12014 public int getIntentVerificationStatus(String packageName, int userId) { 12015 synchronized (mPackages) { 12016 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12017 } 12018 } 12019 12020 @Override 12021 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12022 mContext.enforceCallingOrSelfPermission( 12023 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12024 12025 boolean result = false; 12026 synchronized (mPackages) { 12027 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12028 } 12029 if (result) { 12030 scheduleWritePackageRestrictionsLocked(userId); 12031 } 12032 return result; 12033 } 12034 12035 @Override 12036 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12037 String packageName) { 12038 synchronized (mPackages) { 12039 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12040 } 12041 } 12042 12043 @Override 12044 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12045 if (TextUtils.isEmpty(packageName)) { 12046 return ParceledListSlice.emptyList(); 12047 } 12048 synchronized (mPackages) { 12049 PackageParser.Package pkg = mPackages.get(packageName); 12050 if (pkg == null || pkg.activities == null) { 12051 return ParceledListSlice.emptyList(); 12052 } 12053 final int count = pkg.activities.size(); 12054 ArrayList<IntentFilter> result = new ArrayList<>(); 12055 for (int n=0; n<count; n++) { 12056 PackageParser.Activity activity = pkg.activities.get(n); 12057 if (activity.intents != null && activity.intents.size() > 0) { 12058 result.addAll(activity.intents); 12059 } 12060 } 12061 return new ParceledListSlice<>(result); 12062 } 12063 } 12064 12065 @Override 12066 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12067 mContext.enforceCallingOrSelfPermission( 12068 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12069 12070 synchronized (mPackages) { 12071 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12072 if (packageName != null) { 12073 result |= updateIntentVerificationStatus(packageName, 12074 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12075 userId); 12076 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12077 packageName, userId); 12078 } 12079 return result; 12080 } 12081 } 12082 12083 @Override 12084 public String getDefaultBrowserPackageName(int userId) { 12085 synchronized (mPackages) { 12086 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12087 } 12088 } 12089 12090 /** 12091 * Get the "allow unknown sources" setting. 12092 * 12093 * @return the current "allow unknown sources" setting 12094 */ 12095 private int getUnknownSourcesSettings() { 12096 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12097 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12098 -1); 12099 } 12100 12101 @Override 12102 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12103 final int uid = Binder.getCallingUid(); 12104 // writer 12105 synchronized (mPackages) { 12106 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12107 if (targetPackageSetting == null) { 12108 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12109 } 12110 12111 PackageSetting installerPackageSetting; 12112 if (installerPackageName != null) { 12113 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12114 if (installerPackageSetting == null) { 12115 throw new IllegalArgumentException("Unknown installer package: " 12116 + installerPackageName); 12117 } 12118 } else { 12119 installerPackageSetting = null; 12120 } 12121 12122 Signature[] callerSignature; 12123 Object obj = mSettings.getUserIdLPr(uid); 12124 if (obj != null) { 12125 if (obj instanceof SharedUserSetting) { 12126 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12127 } else if (obj instanceof PackageSetting) { 12128 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12129 } else { 12130 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12131 } 12132 } else { 12133 throw new SecurityException("Unknown calling UID: " + uid); 12134 } 12135 12136 // Verify: can't set installerPackageName to a package that is 12137 // not signed with the same cert as the caller. 12138 if (installerPackageSetting != null) { 12139 if (compareSignatures(callerSignature, 12140 installerPackageSetting.signatures.mSignatures) 12141 != PackageManager.SIGNATURE_MATCH) { 12142 throw new SecurityException( 12143 "Caller does not have same cert as new installer package " 12144 + installerPackageName); 12145 } 12146 } 12147 12148 // Verify: if target already has an installer package, it must 12149 // be signed with the same cert as the caller. 12150 if (targetPackageSetting.installerPackageName != null) { 12151 PackageSetting setting = mSettings.mPackages.get( 12152 targetPackageSetting.installerPackageName); 12153 // If the currently set package isn't valid, then it's always 12154 // okay to change it. 12155 if (setting != null) { 12156 if (compareSignatures(callerSignature, 12157 setting.signatures.mSignatures) 12158 != PackageManager.SIGNATURE_MATCH) { 12159 throw new SecurityException( 12160 "Caller does not have same cert as old installer package " 12161 + targetPackageSetting.installerPackageName); 12162 } 12163 } 12164 } 12165 12166 // Okay! 12167 targetPackageSetting.installerPackageName = installerPackageName; 12168 if (installerPackageName != null) { 12169 mSettings.mInstallerPackages.add(installerPackageName); 12170 } 12171 scheduleWriteSettingsLocked(); 12172 } 12173 } 12174 12175 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12176 // Queue up an async operation since the package installation may take a little while. 12177 mHandler.post(new Runnable() { 12178 public void run() { 12179 mHandler.removeCallbacks(this); 12180 // Result object to be returned 12181 PackageInstalledInfo res = new PackageInstalledInfo(); 12182 res.setReturnCode(currentStatus); 12183 res.uid = -1; 12184 res.pkg = null; 12185 res.removedInfo = null; 12186 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12187 args.doPreInstall(res.returnCode); 12188 synchronized (mInstallLock) { 12189 installPackageTracedLI(args, res); 12190 } 12191 args.doPostInstall(res.returnCode, res.uid); 12192 } 12193 12194 // A restore should be performed at this point if (a) the install 12195 // succeeded, (b) the operation is not an update, and (c) the new 12196 // package has not opted out of backup participation. 12197 final boolean update = res.removedInfo != null 12198 && res.removedInfo.removedPackage != null; 12199 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12200 boolean doRestore = !update 12201 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12202 12203 // Set up the post-install work request bookkeeping. This will be used 12204 // and cleaned up by the post-install event handling regardless of whether 12205 // there's a restore pass performed. Token values are >= 1. 12206 int token; 12207 if (mNextInstallToken < 0) mNextInstallToken = 1; 12208 token = mNextInstallToken++; 12209 12210 PostInstallData data = new PostInstallData(args, res); 12211 mRunningInstalls.put(token, data); 12212 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12213 12214 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12215 // Pass responsibility to the Backup Manager. It will perform a 12216 // restore if appropriate, then pass responsibility back to the 12217 // Package Manager to run the post-install observer callbacks 12218 // and broadcasts. 12219 IBackupManager bm = IBackupManager.Stub.asInterface( 12220 ServiceManager.getService(Context.BACKUP_SERVICE)); 12221 if (bm != null) { 12222 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12223 + " to BM for possible restore"); 12224 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12225 try { 12226 // TODO: http://b/22388012 12227 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12228 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12229 } else { 12230 doRestore = false; 12231 } 12232 } catch (RemoteException e) { 12233 // can't happen; the backup manager is local 12234 } catch (Exception e) { 12235 Slog.e(TAG, "Exception trying to enqueue restore", e); 12236 doRestore = false; 12237 } 12238 } else { 12239 Slog.e(TAG, "Backup Manager not found!"); 12240 doRestore = false; 12241 } 12242 } 12243 12244 if (!doRestore) { 12245 // No restore possible, or the Backup Manager was mysteriously not 12246 // available -- just fire the post-install work request directly. 12247 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12248 12249 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12250 12251 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12252 mHandler.sendMessage(msg); 12253 } 12254 } 12255 }); 12256 } 12257 12258 /** 12259 * Callback from PackageSettings whenever an app is first transitioned out of the 12260 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12261 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12262 * here whether the app is the target of an ongoing install, and only send the 12263 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12264 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12265 * handling. 12266 */ 12267 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12268 // Serialize this with the rest of the install-process message chain. In the 12269 // restore-at-install case, this Runnable will necessarily run before the 12270 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12271 // are coherent. In the non-restore case, the app has already completed install 12272 // and been launched through some other means, so it is not in a problematic 12273 // state for observers to see the FIRST_LAUNCH signal. 12274 mHandler.post(new Runnable() { 12275 @Override 12276 public void run() { 12277 for (int i = 0; i < mRunningInstalls.size(); i++) { 12278 final PostInstallData data = mRunningInstalls.valueAt(i); 12279 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12280 // right package; but is it for the right user? 12281 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12282 if (userId == data.res.newUsers[uIndex]) { 12283 if (DEBUG_BACKUP) { 12284 Slog.i(TAG, "Package " + pkgName 12285 + " being restored so deferring FIRST_LAUNCH"); 12286 } 12287 return; 12288 } 12289 } 12290 } 12291 } 12292 // didn't find it, so not being restored 12293 if (DEBUG_BACKUP) { 12294 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12295 } 12296 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12297 } 12298 }); 12299 } 12300 12301 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12302 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12303 installerPkg, null, userIds); 12304 } 12305 12306 private abstract class HandlerParams { 12307 private static final int MAX_RETRIES = 4; 12308 12309 /** 12310 * Number of times startCopy() has been attempted and had a non-fatal 12311 * error. 12312 */ 12313 private int mRetries = 0; 12314 12315 /** User handle for the user requesting the information or installation. */ 12316 private final UserHandle mUser; 12317 String traceMethod; 12318 int traceCookie; 12319 12320 HandlerParams(UserHandle user) { 12321 mUser = user; 12322 } 12323 12324 UserHandle getUser() { 12325 return mUser; 12326 } 12327 12328 HandlerParams setTraceMethod(String traceMethod) { 12329 this.traceMethod = traceMethod; 12330 return this; 12331 } 12332 12333 HandlerParams setTraceCookie(int traceCookie) { 12334 this.traceCookie = traceCookie; 12335 return this; 12336 } 12337 12338 final boolean startCopy() { 12339 boolean res; 12340 try { 12341 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12342 12343 if (++mRetries > MAX_RETRIES) { 12344 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12345 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12346 handleServiceError(); 12347 return false; 12348 } else { 12349 handleStartCopy(); 12350 res = true; 12351 } 12352 } catch (RemoteException e) { 12353 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12354 mHandler.sendEmptyMessage(MCS_RECONNECT); 12355 res = false; 12356 } 12357 handleReturnCode(); 12358 return res; 12359 } 12360 12361 final void serviceError() { 12362 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12363 handleServiceError(); 12364 handleReturnCode(); 12365 } 12366 12367 abstract void handleStartCopy() throws RemoteException; 12368 abstract void handleServiceError(); 12369 abstract void handleReturnCode(); 12370 } 12371 12372 class MeasureParams extends HandlerParams { 12373 private final PackageStats mStats; 12374 private boolean mSuccess; 12375 12376 private final IPackageStatsObserver mObserver; 12377 12378 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12379 super(new UserHandle(stats.userHandle)); 12380 mObserver = observer; 12381 mStats = stats; 12382 } 12383 12384 @Override 12385 public String toString() { 12386 return "MeasureParams{" 12387 + Integer.toHexString(System.identityHashCode(this)) 12388 + " " + mStats.packageName + "}"; 12389 } 12390 12391 @Override 12392 void handleStartCopy() throws RemoteException { 12393 synchronized (mInstallLock) { 12394 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12395 } 12396 12397 if (mSuccess) { 12398 final boolean mounted; 12399 if (Environment.isExternalStorageEmulated()) { 12400 mounted = true; 12401 } else { 12402 final String status = Environment.getExternalStorageState(); 12403 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12404 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12405 } 12406 12407 if (mounted) { 12408 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12409 12410 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12411 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12412 12413 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12414 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12415 12416 // Always subtract cache size, since it's a subdirectory 12417 mStats.externalDataSize -= mStats.externalCacheSize; 12418 12419 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12420 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12421 12422 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12423 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12424 } 12425 } 12426 } 12427 12428 @Override 12429 void handleReturnCode() { 12430 if (mObserver != null) { 12431 try { 12432 mObserver.onGetStatsCompleted(mStats, mSuccess); 12433 } catch (RemoteException e) { 12434 Slog.i(TAG, "Observer no longer exists."); 12435 } 12436 } 12437 } 12438 12439 @Override 12440 void handleServiceError() { 12441 Slog.e(TAG, "Could not measure application " + mStats.packageName 12442 + " external storage"); 12443 } 12444 } 12445 12446 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12447 throws RemoteException { 12448 long result = 0; 12449 for (File path : paths) { 12450 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12451 } 12452 return result; 12453 } 12454 12455 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12456 for (File path : paths) { 12457 try { 12458 mcs.clearDirectory(path.getAbsolutePath()); 12459 } catch (RemoteException e) { 12460 } 12461 } 12462 } 12463 12464 static class OriginInfo { 12465 /** 12466 * Location where install is coming from, before it has been 12467 * copied/renamed into place. This could be a single monolithic APK 12468 * file, or a cluster directory. This location may be untrusted. 12469 */ 12470 final File file; 12471 final String cid; 12472 12473 /** 12474 * Flag indicating that {@link #file} or {@link #cid} has already been 12475 * staged, meaning downstream users don't need to defensively copy the 12476 * contents. 12477 */ 12478 final boolean staged; 12479 12480 /** 12481 * Flag indicating that {@link #file} or {@link #cid} is an already 12482 * installed app that is being moved. 12483 */ 12484 final boolean existing; 12485 12486 final String resolvedPath; 12487 final File resolvedFile; 12488 12489 static OriginInfo fromNothing() { 12490 return new OriginInfo(null, null, false, false); 12491 } 12492 12493 static OriginInfo fromUntrustedFile(File file) { 12494 return new OriginInfo(file, null, false, false); 12495 } 12496 12497 static OriginInfo fromExistingFile(File file) { 12498 return new OriginInfo(file, null, false, true); 12499 } 12500 12501 static OriginInfo fromStagedFile(File file) { 12502 return new OriginInfo(file, null, true, false); 12503 } 12504 12505 static OriginInfo fromStagedContainer(String cid) { 12506 return new OriginInfo(null, cid, true, false); 12507 } 12508 12509 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12510 this.file = file; 12511 this.cid = cid; 12512 this.staged = staged; 12513 this.existing = existing; 12514 12515 if (cid != null) { 12516 resolvedPath = PackageHelper.getSdDir(cid); 12517 resolvedFile = new File(resolvedPath); 12518 } else if (file != null) { 12519 resolvedPath = file.getAbsolutePath(); 12520 resolvedFile = file; 12521 } else { 12522 resolvedPath = null; 12523 resolvedFile = null; 12524 } 12525 } 12526 } 12527 12528 static class MoveInfo { 12529 final int moveId; 12530 final String fromUuid; 12531 final String toUuid; 12532 final String packageName; 12533 final String dataAppName; 12534 final int appId; 12535 final String seinfo; 12536 final int targetSdkVersion; 12537 12538 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12539 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12540 this.moveId = moveId; 12541 this.fromUuid = fromUuid; 12542 this.toUuid = toUuid; 12543 this.packageName = packageName; 12544 this.dataAppName = dataAppName; 12545 this.appId = appId; 12546 this.seinfo = seinfo; 12547 this.targetSdkVersion = targetSdkVersion; 12548 } 12549 } 12550 12551 static class VerificationInfo { 12552 /** A constant used to indicate that a uid value is not present. */ 12553 public static final int NO_UID = -1; 12554 12555 /** URI referencing where the package was downloaded from. */ 12556 final Uri originatingUri; 12557 12558 /** HTTP referrer URI associated with the originatingURI. */ 12559 final Uri referrer; 12560 12561 /** UID of the application that the install request originated from. */ 12562 final int originatingUid; 12563 12564 /** UID of application requesting the install */ 12565 final int installerUid; 12566 12567 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12568 this.originatingUri = originatingUri; 12569 this.referrer = referrer; 12570 this.originatingUid = originatingUid; 12571 this.installerUid = installerUid; 12572 } 12573 } 12574 12575 class InstallParams extends HandlerParams { 12576 final OriginInfo origin; 12577 final MoveInfo move; 12578 final IPackageInstallObserver2 observer; 12579 int installFlags; 12580 final String installerPackageName; 12581 final String volumeUuid; 12582 private InstallArgs mArgs; 12583 private int mRet; 12584 final String packageAbiOverride; 12585 final String[] grantedRuntimePermissions; 12586 final VerificationInfo verificationInfo; 12587 final Certificate[][] certificates; 12588 12589 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12590 int installFlags, String installerPackageName, String volumeUuid, 12591 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12592 String[] grantedPermissions, Certificate[][] certificates) { 12593 super(user); 12594 this.origin = origin; 12595 this.move = move; 12596 this.observer = observer; 12597 this.installFlags = installFlags; 12598 this.installerPackageName = installerPackageName; 12599 this.volumeUuid = volumeUuid; 12600 this.verificationInfo = verificationInfo; 12601 this.packageAbiOverride = packageAbiOverride; 12602 this.grantedRuntimePermissions = grantedPermissions; 12603 this.certificates = certificates; 12604 } 12605 12606 @Override 12607 public String toString() { 12608 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12609 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12610 } 12611 12612 private int installLocationPolicy(PackageInfoLite pkgLite) { 12613 String packageName = pkgLite.packageName; 12614 int installLocation = pkgLite.installLocation; 12615 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12616 // reader 12617 synchronized (mPackages) { 12618 // Currently installed package which the new package is attempting to replace or 12619 // null if no such package is installed. 12620 PackageParser.Package installedPkg = mPackages.get(packageName); 12621 // Package which currently owns the data which the new package will own if installed. 12622 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12623 // will be null whereas dataOwnerPkg will contain information about the package 12624 // which was uninstalled while keeping its data. 12625 PackageParser.Package dataOwnerPkg = installedPkg; 12626 if (dataOwnerPkg == null) { 12627 PackageSetting ps = mSettings.mPackages.get(packageName); 12628 if (ps != null) { 12629 dataOwnerPkg = ps.pkg; 12630 } 12631 } 12632 12633 if (dataOwnerPkg != null) { 12634 // If installed, the package will get access to data left on the device by its 12635 // predecessor. As a security measure, this is permited only if this is not a 12636 // version downgrade or if the predecessor package is marked as debuggable and 12637 // a downgrade is explicitly requested. 12638 // 12639 // On debuggable platform builds, downgrades are permitted even for 12640 // non-debuggable packages to make testing easier. Debuggable platform builds do 12641 // not offer security guarantees and thus it's OK to disable some security 12642 // mechanisms to make debugging/testing easier on those builds. However, even on 12643 // debuggable builds downgrades of packages are permitted only if requested via 12644 // installFlags. This is because we aim to keep the behavior of debuggable 12645 // platform builds as close as possible to the behavior of non-debuggable 12646 // platform builds. 12647 final boolean downgradeRequested = 12648 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12649 final boolean packageDebuggable = 12650 (dataOwnerPkg.applicationInfo.flags 12651 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12652 final boolean downgradePermitted = 12653 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12654 if (!downgradePermitted) { 12655 try { 12656 checkDowngrade(dataOwnerPkg, pkgLite); 12657 } catch (PackageManagerException e) { 12658 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12659 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12660 } 12661 } 12662 } 12663 12664 if (installedPkg != null) { 12665 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12666 // Check for updated system application. 12667 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12668 if (onSd) { 12669 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12670 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12671 } 12672 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12673 } else { 12674 if (onSd) { 12675 // Install flag overrides everything. 12676 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12677 } 12678 // If current upgrade specifies particular preference 12679 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12680 // Application explicitly specified internal. 12681 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12682 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12683 // App explictly prefers external. Let policy decide 12684 } else { 12685 // Prefer previous location 12686 if (isExternal(installedPkg)) { 12687 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12688 } 12689 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12690 } 12691 } 12692 } else { 12693 // Invalid install. Return error code 12694 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12695 } 12696 } 12697 } 12698 // All the special cases have been taken care of. 12699 // Return result based on recommended install location. 12700 if (onSd) { 12701 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12702 } 12703 return pkgLite.recommendedInstallLocation; 12704 } 12705 12706 /* 12707 * Invoke remote method to get package information and install 12708 * location values. Override install location based on default 12709 * policy if needed and then create install arguments based 12710 * on the install location. 12711 */ 12712 public void handleStartCopy() throws RemoteException { 12713 int ret = PackageManager.INSTALL_SUCCEEDED; 12714 12715 // If we're already staged, we've firmly committed to an install location 12716 if (origin.staged) { 12717 if (origin.file != null) { 12718 installFlags |= PackageManager.INSTALL_INTERNAL; 12719 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12720 } else if (origin.cid != null) { 12721 installFlags |= PackageManager.INSTALL_EXTERNAL; 12722 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12723 } else { 12724 throw new IllegalStateException("Invalid stage location"); 12725 } 12726 } 12727 12728 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12729 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12730 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12731 PackageInfoLite pkgLite = null; 12732 12733 if (onInt && onSd) { 12734 // Check if both bits are set. 12735 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12736 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12737 } else if (onSd && ephemeral) { 12738 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12739 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12740 } else { 12741 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12742 packageAbiOverride); 12743 12744 if (DEBUG_EPHEMERAL && ephemeral) { 12745 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12746 } 12747 12748 /* 12749 * If we have too little free space, try to free cache 12750 * before giving up. 12751 */ 12752 if (!origin.staged && pkgLite.recommendedInstallLocation 12753 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12754 // TODO: focus freeing disk space on the target device 12755 final StorageManager storage = StorageManager.from(mContext); 12756 final long lowThreshold = storage.getStorageLowBytes( 12757 Environment.getDataDirectory()); 12758 12759 final long sizeBytes = mContainerService.calculateInstalledSize( 12760 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12761 12762 try { 12763 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12764 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12765 installFlags, packageAbiOverride); 12766 } catch (InstallerException e) { 12767 Slog.w(TAG, "Failed to free cache", e); 12768 } 12769 12770 /* 12771 * The cache free must have deleted the file we 12772 * downloaded to install. 12773 * 12774 * TODO: fix the "freeCache" call to not delete 12775 * the file we care about. 12776 */ 12777 if (pkgLite.recommendedInstallLocation 12778 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12779 pkgLite.recommendedInstallLocation 12780 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12781 } 12782 } 12783 } 12784 12785 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12786 int loc = pkgLite.recommendedInstallLocation; 12787 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12788 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12789 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12790 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12791 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12792 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12793 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12794 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12795 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12796 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12797 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12798 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12799 } else { 12800 // Override with defaults if needed. 12801 loc = installLocationPolicy(pkgLite); 12802 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12803 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12804 } else if (!onSd && !onInt) { 12805 // Override install location with flags 12806 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12807 // Set the flag to install on external media. 12808 installFlags |= PackageManager.INSTALL_EXTERNAL; 12809 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12810 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12811 if (DEBUG_EPHEMERAL) { 12812 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12813 } 12814 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12815 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12816 |PackageManager.INSTALL_INTERNAL); 12817 } else { 12818 // Make sure the flag for installing on external 12819 // media is unset 12820 installFlags |= PackageManager.INSTALL_INTERNAL; 12821 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12822 } 12823 } 12824 } 12825 } 12826 12827 final InstallArgs args = createInstallArgs(this); 12828 mArgs = args; 12829 12830 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12831 // TODO: http://b/22976637 12832 // Apps installed for "all" users use the device owner to verify the app 12833 UserHandle verifierUser = getUser(); 12834 if (verifierUser == UserHandle.ALL) { 12835 verifierUser = UserHandle.SYSTEM; 12836 } 12837 12838 /* 12839 * Determine if we have any installed package verifiers. If we 12840 * do, then we'll defer to them to verify the packages. 12841 */ 12842 final int requiredUid = mRequiredVerifierPackage == null ? -1 12843 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12844 verifierUser.getIdentifier()); 12845 if (!origin.existing && requiredUid != -1 12846 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12847 final Intent verification = new Intent( 12848 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12849 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12850 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12851 PACKAGE_MIME_TYPE); 12852 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12853 12854 // Query all live verifiers based on current user state 12855 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12856 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12857 12858 if (DEBUG_VERIFY) { 12859 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12860 + verification.toString() + " with " + pkgLite.verifiers.length 12861 + " optional verifiers"); 12862 } 12863 12864 final int verificationId = mPendingVerificationToken++; 12865 12866 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12867 12868 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12869 installerPackageName); 12870 12871 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12872 installFlags); 12873 12874 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12875 pkgLite.packageName); 12876 12877 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12878 pkgLite.versionCode); 12879 12880 if (verificationInfo != null) { 12881 if (verificationInfo.originatingUri != null) { 12882 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12883 verificationInfo.originatingUri); 12884 } 12885 if (verificationInfo.referrer != null) { 12886 verification.putExtra(Intent.EXTRA_REFERRER, 12887 verificationInfo.referrer); 12888 } 12889 if (verificationInfo.originatingUid >= 0) { 12890 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12891 verificationInfo.originatingUid); 12892 } 12893 if (verificationInfo.installerUid >= 0) { 12894 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12895 verificationInfo.installerUid); 12896 } 12897 } 12898 12899 final PackageVerificationState verificationState = new PackageVerificationState( 12900 requiredUid, args); 12901 12902 mPendingVerification.append(verificationId, verificationState); 12903 12904 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12905 receivers, verificationState); 12906 12907 /* 12908 * If any sufficient verifiers were listed in the package 12909 * manifest, attempt to ask them. 12910 */ 12911 if (sufficientVerifiers != null) { 12912 final int N = sufficientVerifiers.size(); 12913 if (N == 0) { 12914 Slog.i(TAG, "Additional verifiers required, but none installed."); 12915 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12916 } else { 12917 for (int i = 0; i < N; i++) { 12918 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12919 12920 final Intent sufficientIntent = new Intent(verification); 12921 sufficientIntent.setComponent(verifierComponent); 12922 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12923 } 12924 } 12925 } 12926 12927 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12928 mRequiredVerifierPackage, receivers); 12929 if (ret == PackageManager.INSTALL_SUCCEEDED 12930 && mRequiredVerifierPackage != null) { 12931 Trace.asyncTraceBegin( 12932 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12933 /* 12934 * Send the intent to the required verification agent, 12935 * but only start the verification timeout after the 12936 * target BroadcastReceivers have run. 12937 */ 12938 verification.setComponent(requiredVerifierComponent); 12939 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12940 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12941 new BroadcastReceiver() { 12942 @Override 12943 public void onReceive(Context context, Intent intent) { 12944 final Message msg = mHandler 12945 .obtainMessage(CHECK_PENDING_VERIFICATION); 12946 msg.arg1 = verificationId; 12947 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12948 } 12949 }, null, 0, null, null); 12950 12951 /* 12952 * We don't want the copy to proceed until verification 12953 * succeeds, so null out this field. 12954 */ 12955 mArgs = null; 12956 } 12957 } else { 12958 /* 12959 * No package verification is enabled, so immediately start 12960 * the remote call to initiate copy using temporary file. 12961 */ 12962 ret = args.copyApk(mContainerService, true); 12963 } 12964 } 12965 12966 mRet = ret; 12967 } 12968 12969 @Override 12970 void handleReturnCode() { 12971 // If mArgs is null, then MCS couldn't be reached. When it 12972 // reconnects, it will try again to install. At that point, this 12973 // will succeed. 12974 if (mArgs != null) { 12975 processPendingInstall(mArgs, mRet); 12976 } 12977 } 12978 12979 @Override 12980 void handleServiceError() { 12981 mArgs = createInstallArgs(this); 12982 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12983 } 12984 12985 public boolean isForwardLocked() { 12986 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12987 } 12988 } 12989 12990 /** 12991 * Used during creation of InstallArgs 12992 * 12993 * @param installFlags package installation flags 12994 * @return true if should be installed on external storage 12995 */ 12996 private static boolean installOnExternalAsec(int installFlags) { 12997 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12998 return false; 12999 } 13000 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13001 return true; 13002 } 13003 return false; 13004 } 13005 13006 /** 13007 * Used during creation of InstallArgs 13008 * 13009 * @param installFlags package installation flags 13010 * @return true if should be installed as forward locked 13011 */ 13012 private static boolean installForwardLocked(int installFlags) { 13013 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13014 } 13015 13016 private InstallArgs createInstallArgs(InstallParams params) { 13017 if (params.move != null) { 13018 return new MoveInstallArgs(params); 13019 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13020 return new AsecInstallArgs(params); 13021 } else { 13022 return new FileInstallArgs(params); 13023 } 13024 } 13025 13026 /** 13027 * Create args that describe an existing installed package. Typically used 13028 * when cleaning up old installs, or used as a move source. 13029 */ 13030 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13031 String resourcePath, String[] instructionSets) { 13032 final boolean isInAsec; 13033 if (installOnExternalAsec(installFlags)) { 13034 /* Apps on SD card are always in ASEC containers. */ 13035 isInAsec = true; 13036 } else if (installForwardLocked(installFlags) 13037 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13038 /* 13039 * Forward-locked apps are only in ASEC containers if they're the 13040 * new style 13041 */ 13042 isInAsec = true; 13043 } else { 13044 isInAsec = false; 13045 } 13046 13047 if (isInAsec) { 13048 return new AsecInstallArgs(codePath, instructionSets, 13049 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13050 } else { 13051 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13052 } 13053 } 13054 13055 static abstract class InstallArgs { 13056 /** @see InstallParams#origin */ 13057 final OriginInfo origin; 13058 /** @see InstallParams#move */ 13059 final MoveInfo move; 13060 13061 final IPackageInstallObserver2 observer; 13062 // Always refers to PackageManager flags only 13063 final int installFlags; 13064 final String installerPackageName; 13065 final String volumeUuid; 13066 final UserHandle user; 13067 final String abiOverride; 13068 final String[] installGrantPermissions; 13069 /** If non-null, drop an async trace when the install completes */ 13070 final String traceMethod; 13071 final int traceCookie; 13072 final Certificate[][] certificates; 13073 13074 // The list of instruction sets supported by this app. This is currently 13075 // only used during the rmdex() phase to clean up resources. We can get rid of this 13076 // if we move dex files under the common app path. 13077 /* nullable */ String[] instructionSets; 13078 13079 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13080 int installFlags, String installerPackageName, String volumeUuid, 13081 UserHandle user, String[] instructionSets, 13082 String abiOverride, String[] installGrantPermissions, 13083 String traceMethod, int traceCookie, Certificate[][] certificates) { 13084 this.origin = origin; 13085 this.move = move; 13086 this.installFlags = installFlags; 13087 this.observer = observer; 13088 this.installerPackageName = installerPackageName; 13089 this.volumeUuid = volumeUuid; 13090 this.user = user; 13091 this.instructionSets = instructionSets; 13092 this.abiOverride = abiOverride; 13093 this.installGrantPermissions = installGrantPermissions; 13094 this.traceMethod = traceMethod; 13095 this.traceCookie = traceCookie; 13096 this.certificates = certificates; 13097 } 13098 13099 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13100 abstract int doPreInstall(int status); 13101 13102 /** 13103 * Rename package into final resting place. All paths on the given 13104 * scanned package should be updated to reflect the rename. 13105 */ 13106 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13107 abstract int doPostInstall(int status, int uid); 13108 13109 /** @see PackageSettingBase#codePathString */ 13110 abstract String getCodePath(); 13111 /** @see PackageSettingBase#resourcePathString */ 13112 abstract String getResourcePath(); 13113 13114 // Need installer lock especially for dex file removal. 13115 abstract void cleanUpResourcesLI(); 13116 abstract boolean doPostDeleteLI(boolean delete); 13117 13118 /** 13119 * Called before the source arguments are copied. This is used mostly 13120 * for MoveParams when it needs to read the source file to put it in the 13121 * destination. 13122 */ 13123 int doPreCopy() { 13124 return PackageManager.INSTALL_SUCCEEDED; 13125 } 13126 13127 /** 13128 * Called after the source arguments are copied. This is used mostly for 13129 * MoveParams when it needs to read the source file to put it in the 13130 * destination. 13131 */ 13132 int doPostCopy(int uid) { 13133 return PackageManager.INSTALL_SUCCEEDED; 13134 } 13135 13136 protected boolean isFwdLocked() { 13137 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13138 } 13139 13140 protected boolean isExternalAsec() { 13141 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13142 } 13143 13144 protected boolean isEphemeral() { 13145 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13146 } 13147 13148 UserHandle getUser() { 13149 return user; 13150 } 13151 } 13152 13153 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13154 if (!allCodePaths.isEmpty()) { 13155 if (instructionSets == null) { 13156 throw new IllegalStateException("instructionSet == null"); 13157 } 13158 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13159 for (String codePath : allCodePaths) { 13160 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13161 try { 13162 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13163 } catch (InstallerException ignored) { 13164 } 13165 } 13166 } 13167 } 13168 } 13169 13170 /** 13171 * Logic to handle installation of non-ASEC applications, including copying 13172 * and renaming logic. 13173 */ 13174 class FileInstallArgs extends InstallArgs { 13175 private File codeFile; 13176 private File resourceFile; 13177 13178 // Example topology: 13179 // /data/app/com.example/base.apk 13180 // /data/app/com.example/split_foo.apk 13181 // /data/app/com.example/lib/arm/libfoo.so 13182 // /data/app/com.example/lib/arm64/libfoo.so 13183 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13184 13185 /** New install */ 13186 FileInstallArgs(InstallParams params) { 13187 super(params.origin, params.move, params.observer, params.installFlags, 13188 params.installerPackageName, params.volumeUuid, 13189 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13190 params.grantedRuntimePermissions, 13191 params.traceMethod, params.traceCookie, params.certificates); 13192 if (isFwdLocked()) { 13193 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13194 } 13195 } 13196 13197 /** Existing install */ 13198 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13199 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13200 null, null, null, 0, null /*certificates*/); 13201 this.codeFile = (codePath != null) ? new File(codePath) : null; 13202 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13203 } 13204 13205 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13206 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13207 try { 13208 return doCopyApk(imcs, temp); 13209 } finally { 13210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13211 } 13212 } 13213 13214 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13215 if (origin.staged) { 13216 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13217 codeFile = origin.file; 13218 resourceFile = origin.file; 13219 return PackageManager.INSTALL_SUCCEEDED; 13220 } 13221 13222 try { 13223 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13224 final File tempDir = 13225 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13226 codeFile = tempDir; 13227 resourceFile = tempDir; 13228 } catch (IOException e) { 13229 Slog.w(TAG, "Failed to create copy file: " + e); 13230 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13231 } 13232 13233 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13234 @Override 13235 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13236 if (!FileUtils.isValidExtFilename(name)) { 13237 throw new IllegalArgumentException("Invalid filename: " + name); 13238 } 13239 try { 13240 final File file = new File(codeFile, name); 13241 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13242 O_RDWR | O_CREAT, 0644); 13243 Os.chmod(file.getAbsolutePath(), 0644); 13244 return new ParcelFileDescriptor(fd); 13245 } catch (ErrnoException e) { 13246 throw new RemoteException("Failed to open: " + e.getMessage()); 13247 } 13248 } 13249 }; 13250 13251 int ret = PackageManager.INSTALL_SUCCEEDED; 13252 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13253 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13254 Slog.e(TAG, "Failed to copy package"); 13255 return ret; 13256 } 13257 13258 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13259 NativeLibraryHelper.Handle handle = null; 13260 try { 13261 handle = NativeLibraryHelper.Handle.create(codeFile); 13262 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13263 abiOverride); 13264 } catch (IOException e) { 13265 Slog.e(TAG, "Copying native libraries failed", e); 13266 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13267 } finally { 13268 IoUtils.closeQuietly(handle); 13269 } 13270 13271 return ret; 13272 } 13273 13274 int doPreInstall(int status) { 13275 if (status != PackageManager.INSTALL_SUCCEEDED) { 13276 cleanUp(); 13277 } 13278 return status; 13279 } 13280 13281 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13282 if (status != PackageManager.INSTALL_SUCCEEDED) { 13283 cleanUp(); 13284 return false; 13285 } 13286 13287 final File targetDir = codeFile.getParentFile(); 13288 final File beforeCodeFile = codeFile; 13289 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13290 13291 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13292 try { 13293 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13294 } catch (ErrnoException e) { 13295 Slog.w(TAG, "Failed to rename", e); 13296 return false; 13297 } 13298 13299 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13300 Slog.w(TAG, "Failed to restorecon"); 13301 return false; 13302 } 13303 13304 // Reflect the rename internally 13305 codeFile = afterCodeFile; 13306 resourceFile = afterCodeFile; 13307 13308 // Reflect the rename in scanned details 13309 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13310 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13311 afterCodeFile, pkg.baseCodePath)); 13312 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13313 afterCodeFile, pkg.splitCodePaths)); 13314 13315 // Reflect the rename in app info 13316 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13317 pkg.setApplicationInfoCodePath(pkg.codePath); 13318 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13319 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13320 pkg.setApplicationInfoResourcePath(pkg.codePath); 13321 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13322 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13323 13324 return true; 13325 } 13326 13327 int doPostInstall(int status, int uid) { 13328 if (status != PackageManager.INSTALL_SUCCEEDED) { 13329 cleanUp(); 13330 } 13331 return status; 13332 } 13333 13334 @Override 13335 String getCodePath() { 13336 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13337 } 13338 13339 @Override 13340 String getResourcePath() { 13341 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13342 } 13343 13344 private boolean cleanUp() { 13345 if (codeFile == null || !codeFile.exists()) { 13346 return false; 13347 } 13348 13349 removeCodePathLI(codeFile); 13350 13351 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13352 resourceFile.delete(); 13353 } 13354 13355 return true; 13356 } 13357 13358 void cleanUpResourcesLI() { 13359 // Try enumerating all code paths before deleting 13360 List<String> allCodePaths = Collections.EMPTY_LIST; 13361 if (codeFile != null && codeFile.exists()) { 13362 try { 13363 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13364 allCodePaths = pkg.getAllCodePaths(); 13365 } catch (PackageParserException e) { 13366 // Ignored; we tried our best 13367 } 13368 } 13369 13370 cleanUp(); 13371 removeDexFiles(allCodePaths, instructionSets); 13372 } 13373 13374 boolean doPostDeleteLI(boolean delete) { 13375 // XXX err, shouldn't we respect the delete flag? 13376 cleanUpResourcesLI(); 13377 return true; 13378 } 13379 } 13380 13381 private boolean isAsecExternal(String cid) { 13382 final String asecPath = PackageHelper.getSdFilesystem(cid); 13383 return !asecPath.startsWith(mAsecInternalPath); 13384 } 13385 13386 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13387 PackageManagerException { 13388 if (copyRet < 0) { 13389 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13390 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13391 throw new PackageManagerException(copyRet, message); 13392 } 13393 } 13394 } 13395 13396 /** 13397 * Extract the MountService "container ID" from the full code path of an 13398 * .apk. 13399 */ 13400 static String cidFromCodePath(String fullCodePath) { 13401 int eidx = fullCodePath.lastIndexOf("/"); 13402 String subStr1 = fullCodePath.substring(0, eidx); 13403 int sidx = subStr1.lastIndexOf("/"); 13404 return subStr1.substring(sidx+1, eidx); 13405 } 13406 13407 /** 13408 * Logic to handle installation of ASEC applications, including copying and 13409 * renaming logic. 13410 */ 13411 class AsecInstallArgs extends InstallArgs { 13412 static final String RES_FILE_NAME = "pkg.apk"; 13413 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13414 13415 String cid; 13416 String packagePath; 13417 String resourcePath; 13418 13419 /** New install */ 13420 AsecInstallArgs(InstallParams params) { 13421 super(params.origin, params.move, params.observer, params.installFlags, 13422 params.installerPackageName, params.volumeUuid, 13423 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13424 params.grantedRuntimePermissions, 13425 params.traceMethod, params.traceCookie, params.certificates); 13426 } 13427 13428 /** Existing install */ 13429 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13430 boolean isExternal, boolean isForwardLocked) { 13431 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13432 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13433 instructionSets, null, null, null, 0, null /*certificates*/); 13434 // Hackily pretend we're still looking at a full code path 13435 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13436 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13437 } 13438 13439 // Extract cid from fullCodePath 13440 int eidx = fullCodePath.lastIndexOf("/"); 13441 String subStr1 = fullCodePath.substring(0, eidx); 13442 int sidx = subStr1.lastIndexOf("/"); 13443 cid = subStr1.substring(sidx+1, eidx); 13444 setMountPath(subStr1); 13445 } 13446 13447 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13448 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13449 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13450 instructionSets, null, null, null, 0, null /*certificates*/); 13451 this.cid = cid; 13452 setMountPath(PackageHelper.getSdDir(cid)); 13453 } 13454 13455 void createCopyFile() { 13456 cid = mInstallerService.allocateExternalStageCidLegacy(); 13457 } 13458 13459 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13460 if (origin.staged && origin.cid != null) { 13461 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13462 cid = origin.cid; 13463 setMountPath(PackageHelper.getSdDir(cid)); 13464 return PackageManager.INSTALL_SUCCEEDED; 13465 } 13466 13467 if (temp) { 13468 createCopyFile(); 13469 } else { 13470 /* 13471 * Pre-emptively destroy the container since it's destroyed if 13472 * copying fails due to it existing anyway. 13473 */ 13474 PackageHelper.destroySdDir(cid); 13475 } 13476 13477 final String newMountPath = imcs.copyPackageToContainer( 13478 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13479 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13480 13481 if (newMountPath != null) { 13482 setMountPath(newMountPath); 13483 return PackageManager.INSTALL_SUCCEEDED; 13484 } else { 13485 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13486 } 13487 } 13488 13489 @Override 13490 String getCodePath() { 13491 return packagePath; 13492 } 13493 13494 @Override 13495 String getResourcePath() { 13496 return resourcePath; 13497 } 13498 13499 int doPreInstall(int status) { 13500 if (status != PackageManager.INSTALL_SUCCEEDED) { 13501 // Destroy container 13502 PackageHelper.destroySdDir(cid); 13503 } else { 13504 boolean mounted = PackageHelper.isContainerMounted(cid); 13505 if (!mounted) { 13506 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13507 Process.SYSTEM_UID); 13508 if (newMountPath != null) { 13509 setMountPath(newMountPath); 13510 } else { 13511 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13512 } 13513 } 13514 } 13515 return status; 13516 } 13517 13518 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13519 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13520 String newMountPath = null; 13521 if (PackageHelper.isContainerMounted(cid)) { 13522 // Unmount the container 13523 if (!PackageHelper.unMountSdDir(cid)) { 13524 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13525 return false; 13526 } 13527 } 13528 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13529 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13530 " which might be stale. Will try to clean up."); 13531 // Clean up the stale container and proceed to recreate. 13532 if (!PackageHelper.destroySdDir(newCacheId)) { 13533 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13534 return false; 13535 } 13536 // Successfully cleaned up stale container. Try to rename again. 13537 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13538 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13539 + " inspite of cleaning it up."); 13540 return false; 13541 } 13542 } 13543 if (!PackageHelper.isContainerMounted(newCacheId)) { 13544 Slog.w(TAG, "Mounting container " + newCacheId); 13545 newMountPath = PackageHelper.mountSdDir(newCacheId, 13546 getEncryptKey(), Process.SYSTEM_UID); 13547 } else { 13548 newMountPath = PackageHelper.getSdDir(newCacheId); 13549 } 13550 if (newMountPath == null) { 13551 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13552 return false; 13553 } 13554 Log.i(TAG, "Succesfully renamed " + cid + 13555 " to " + newCacheId + 13556 " at new path: " + newMountPath); 13557 cid = newCacheId; 13558 13559 final File beforeCodeFile = new File(packagePath); 13560 setMountPath(newMountPath); 13561 final File afterCodeFile = new File(packagePath); 13562 13563 // Reflect the rename in scanned details 13564 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13565 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13566 afterCodeFile, pkg.baseCodePath)); 13567 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13568 afterCodeFile, pkg.splitCodePaths)); 13569 13570 // Reflect the rename in app info 13571 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13572 pkg.setApplicationInfoCodePath(pkg.codePath); 13573 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13574 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13575 pkg.setApplicationInfoResourcePath(pkg.codePath); 13576 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13577 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13578 13579 return true; 13580 } 13581 13582 private void setMountPath(String mountPath) { 13583 final File mountFile = new File(mountPath); 13584 13585 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13586 if (monolithicFile.exists()) { 13587 packagePath = monolithicFile.getAbsolutePath(); 13588 if (isFwdLocked()) { 13589 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13590 } else { 13591 resourcePath = packagePath; 13592 } 13593 } else { 13594 packagePath = mountFile.getAbsolutePath(); 13595 resourcePath = packagePath; 13596 } 13597 } 13598 13599 int doPostInstall(int status, int uid) { 13600 if (status != PackageManager.INSTALL_SUCCEEDED) { 13601 cleanUp(); 13602 } else { 13603 final int groupOwner; 13604 final String protectedFile; 13605 if (isFwdLocked()) { 13606 groupOwner = UserHandle.getSharedAppGid(uid); 13607 protectedFile = RES_FILE_NAME; 13608 } else { 13609 groupOwner = -1; 13610 protectedFile = null; 13611 } 13612 13613 if (uid < Process.FIRST_APPLICATION_UID 13614 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13615 Slog.e(TAG, "Failed to finalize " + cid); 13616 PackageHelper.destroySdDir(cid); 13617 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13618 } 13619 13620 boolean mounted = PackageHelper.isContainerMounted(cid); 13621 if (!mounted) { 13622 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13623 } 13624 } 13625 return status; 13626 } 13627 13628 private void cleanUp() { 13629 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13630 13631 // Destroy secure container 13632 PackageHelper.destroySdDir(cid); 13633 } 13634 13635 private List<String> getAllCodePaths() { 13636 final File codeFile = new File(getCodePath()); 13637 if (codeFile != null && codeFile.exists()) { 13638 try { 13639 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13640 return pkg.getAllCodePaths(); 13641 } catch (PackageParserException e) { 13642 // Ignored; we tried our best 13643 } 13644 } 13645 return Collections.EMPTY_LIST; 13646 } 13647 13648 void cleanUpResourcesLI() { 13649 // Enumerate all code paths before deleting 13650 cleanUpResourcesLI(getAllCodePaths()); 13651 } 13652 13653 private void cleanUpResourcesLI(List<String> allCodePaths) { 13654 cleanUp(); 13655 removeDexFiles(allCodePaths, instructionSets); 13656 } 13657 13658 String getPackageName() { 13659 return getAsecPackageName(cid); 13660 } 13661 13662 boolean doPostDeleteLI(boolean delete) { 13663 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13664 final List<String> allCodePaths = getAllCodePaths(); 13665 boolean mounted = PackageHelper.isContainerMounted(cid); 13666 if (mounted) { 13667 // Unmount first 13668 if (PackageHelper.unMountSdDir(cid)) { 13669 mounted = false; 13670 } 13671 } 13672 if (!mounted && delete) { 13673 cleanUpResourcesLI(allCodePaths); 13674 } 13675 return !mounted; 13676 } 13677 13678 @Override 13679 int doPreCopy() { 13680 if (isFwdLocked()) { 13681 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13682 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13683 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13684 } 13685 } 13686 13687 return PackageManager.INSTALL_SUCCEEDED; 13688 } 13689 13690 @Override 13691 int doPostCopy(int uid) { 13692 if (isFwdLocked()) { 13693 if (uid < Process.FIRST_APPLICATION_UID 13694 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13695 RES_FILE_NAME)) { 13696 Slog.e(TAG, "Failed to finalize " + cid); 13697 PackageHelper.destroySdDir(cid); 13698 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13699 } 13700 } 13701 13702 return PackageManager.INSTALL_SUCCEEDED; 13703 } 13704 } 13705 13706 /** 13707 * Logic to handle movement of existing installed applications. 13708 */ 13709 class MoveInstallArgs extends InstallArgs { 13710 private File codeFile; 13711 private File resourceFile; 13712 13713 /** New install */ 13714 MoveInstallArgs(InstallParams params) { 13715 super(params.origin, params.move, params.observer, params.installFlags, 13716 params.installerPackageName, params.volumeUuid, 13717 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13718 params.grantedRuntimePermissions, 13719 params.traceMethod, params.traceCookie, params.certificates); 13720 } 13721 13722 int copyApk(IMediaContainerService imcs, boolean temp) { 13723 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13724 + move.fromUuid + " to " + move.toUuid); 13725 synchronized (mInstaller) { 13726 try { 13727 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13728 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13729 } catch (InstallerException e) { 13730 Slog.w(TAG, "Failed to move app", e); 13731 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13732 } 13733 } 13734 13735 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13736 resourceFile = codeFile; 13737 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13738 13739 return PackageManager.INSTALL_SUCCEEDED; 13740 } 13741 13742 int doPreInstall(int status) { 13743 if (status != PackageManager.INSTALL_SUCCEEDED) { 13744 cleanUp(move.toUuid); 13745 } 13746 return status; 13747 } 13748 13749 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13750 if (status != PackageManager.INSTALL_SUCCEEDED) { 13751 cleanUp(move.toUuid); 13752 return false; 13753 } 13754 13755 // Reflect the move in app info 13756 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13757 pkg.setApplicationInfoCodePath(pkg.codePath); 13758 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13759 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13760 pkg.setApplicationInfoResourcePath(pkg.codePath); 13761 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13762 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13763 13764 return true; 13765 } 13766 13767 int doPostInstall(int status, int uid) { 13768 if (status == PackageManager.INSTALL_SUCCEEDED) { 13769 cleanUp(move.fromUuid); 13770 } else { 13771 cleanUp(move.toUuid); 13772 } 13773 return status; 13774 } 13775 13776 @Override 13777 String getCodePath() { 13778 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13779 } 13780 13781 @Override 13782 String getResourcePath() { 13783 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13784 } 13785 13786 private boolean cleanUp(String volumeUuid) { 13787 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13788 move.dataAppName); 13789 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13790 final int[] userIds = sUserManager.getUserIds(); 13791 synchronized (mInstallLock) { 13792 // Clean up both app data and code 13793 // All package moves are frozen until finished 13794 for (int userId : userIds) { 13795 try { 13796 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13797 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13798 } catch (InstallerException e) { 13799 Slog.w(TAG, String.valueOf(e)); 13800 } 13801 } 13802 removeCodePathLI(codeFile); 13803 } 13804 return true; 13805 } 13806 13807 void cleanUpResourcesLI() { 13808 throw new UnsupportedOperationException(); 13809 } 13810 13811 boolean doPostDeleteLI(boolean delete) { 13812 throw new UnsupportedOperationException(); 13813 } 13814 } 13815 13816 static String getAsecPackageName(String packageCid) { 13817 int idx = packageCid.lastIndexOf("-"); 13818 if (idx == -1) { 13819 return packageCid; 13820 } 13821 return packageCid.substring(0, idx); 13822 } 13823 13824 // Utility method used to create code paths based on package name and available index. 13825 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13826 String idxStr = ""; 13827 int idx = 1; 13828 // Fall back to default value of idx=1 if prefix is not 13829 // part of oldCodePath 13830 if (oldCodePath != null) { 13831 String subStr = oldCodePath; 13832 // Drop the suffix right away 13833 if (suffix != null && subStr.endsWith(suffix)) { 13834 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13835 } 13836 // If oldCodePath already contains prefix find out the 13837 // ending index to either increment or decrement. 13838 int sidx = subStr.lastIndexOf(prefix); 13839 if (sidx != -1) { 13840 subStr = subStr.substring(sidx + prefix.length()); 13841 if (subStr != null) { 13842 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13843 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13844 } 13845 try { 13846 idx = Integer.parseInt(subStr); 13847 if (idx <= 1) { 13848 idx++; 13849 } else { 13850 idx--; 13851 } 13852 } catch(NumberFormatException e) { 13853 } 13854 } 13855 } 13856 } 13857 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13858 return prefix + idxStr; 13859 } 13860 13861 private File getNextCodePath(File targetDir, String packageName) { 13862 int suffix = 1; 13863 File result; 13864 do { 13865 result = new File(targetDir, packageName + "-" + suffix); 13866 suffix++; 13867 } while (result.exists()); 13868 return result; 13869 } 13870 13871 // Utility method that returns the relative package path with respect 13872 // to the installation directory. Like say for /data/data/com.test-1.apk 13873 // string com.test-1 is returned. 13874 static String deriveCodePathName(String codePath) { 13875 if (codePath == null) { 13876 return null; 13877 } 13878 final File codeFile = new File(codePath); 13879 final String name = codeFile.getName(); 13880 if (codeFile.isDirectory()) { 13881 return name; 13882 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13883 final int lastDot = name.lastIndexOf('.'); 13884 return name.substring(0, lastDot); 13885 } else { 13886 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13887 return null; 13888 } 13889 } 13890 13891 static class PackageInstalledInfo { 13892 String name; 13893 int uid; 13894 // The set of users that originally had this package installed. 13895 int[] origUsers; 13896 // The set of users that now have this package installed. 13897 int[] newUsers; 13898 PackageParser.Package pkg; 13899 int returnCode; 13900 String returnMsg; 13901 PackageRemovedInfo removedInfo; 13902 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13903 13904 public void setError(int code, String msg) { 13905 setReturnCode(code); 13906 setReturnMessage(msg); 13907 Slog.w(TAG, msg); 13908 } 13909 13910 public void setError(String msg, PackageParserException e) { 13911 setReturnCode(e.error); 13912 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13913 Slog.w(TAG, msg, e); 13914 } 13915 13916 public void setError(String msg, PackageManagerException e) { 13917 returnCode = e.error; 13918 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13919 Slog.w(TAG, msg, e); 13920 } 13921 13922 public void setReturnCode(int returnCode) { 13923 this.returnCode = returnCode; 13924 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13925 for (int i = 0; i < childCount; i++) { 13926 addedChildPackages.valueAt(i).returnCode = returnCode; 13927 } 13928 } 13929 13930 private void setReturnMessage(String returnMsg) { 13931 this.returnMsg = returnMsg; 13932 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13933 for (int i = 0; i < childCount; i++) { 13934 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13935 } 13936 } 13937 13938 // In some error cases we want to convey more info back to the observer 13939 String origPackage; 13940 String origPermission; 13941 } 13942 13943 /* 13944 * Install a non-existing package. 13945 */ 13946 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13947 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13948 PackageInstalledInfo res) { 13949 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13950 13951 // Remember this for later, in case we need to rollback this install 13952 String pkgName = pkg.packageName; 13953 13954 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13955 13956 synchronized(mPackages) { 13957 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13958 // A package with the same name is already installed, though 13959 // it has been renamed to an older name. The package we 13960 // are trying to install should be installed as an update to 13961 // the existing one, but that has not been requested, so bail. 13962 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13963 + " without first uninstalling package running as " 13964 + mSettings.mRenamedPackages.get(pkgName)); 13965 return; 13966 } 13967 if (mPackages.containsKey(pkgName)) { 13968 // Don't allow installation over an existing package with the same name. 13969 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13970 + " without first uninstalling."); 13971 return; 13972 } 13973 } 13974 13975 try { 13976 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13977 System.currentTimeMillis(), user); 13978 13979 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13980 13981 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13982 prepareAppDataAfterInstallLIF(newPackage); 13983 13984 } else { 13985 // Remove package from internal structures, but keep around any 13986 // data that might have already existed 13987 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13988 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13989 } 13990 } catch (PackageManagerException e) { 13991 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13992 } 13993 13994 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13995 } 13996 13997 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13998 // Can't rotate keys during boot or if sharedUser. 13999 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14000 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14001 return false; 14002 } 14003 // app is using upgradeKeySets; make sure all are valid 14004 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14005 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14006 for (int i = 0; i < upgradeKeySets.length; i++) { 14007 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14008 Slog.wtf(TAG, "Package " 14009 + (oldPs.name != null ? oldPs.name : "<null>") 14010 + " contains upgrade-key-set reference to unknown key-set: " 14011 + upgradeKeySets[i] 14012 + " reverting to signatures check."); 14013 return false; 14014 } 14015 } 14016 return true; 14017 } 14018 14019 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14020 // Upgrade keysets are being used. Determine if new package has a superset of the 14021 // required keys. 14022 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14023 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14024 for (int i = 0; i < upgradeKeySets.length; i++) { 14025 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14026 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14027 return true; 14028 } 14029 } 14030 return false; 14031 } 14032 14033 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14034 try (DigestInputStream digestStream = 14035 new DigestInputStream(new FileInputStream(file), digest)) { 14036 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14037 } 14038 } 14039 14040 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14041 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14042 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14043 14044 final PackageParser.Package oldPackage; 14045 final String pkgName = pkg.packageName; 14046 final int[] allUsers; 14047 final int[] installedUsers; 14048 14049 synchronized(mPackages) { 14050 oldPackage = mPackages.get(pkgName); 14051 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14052 14053 // don't allow upgrade to target a release SDK from a pre-release SDK 14054 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14055 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14056 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14057 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14058 if (oldTargetsPreRelease 14059 && !newTargetsPreRelease 14060 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14061 Slog.w(TAG, "Can't install package targeting released sdk"); 14062 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14063 return; 14064 } 14065 14066 // don't allow an upgrade from full to ephemeral 14067 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14068 if (isEphemeral && !oldIsEphemeral) { 14069 // can't downgrade from full to ephemeral 14070 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14071 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14072 return; 14073 } 14074 14075 // verify signatures are valid 14076 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14077 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14078 if (!checkUpgradeKeySetLP(ps, pkg)) { 14079 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14080 "New package not signed by keys specified by upgrade-keysets: " 14081 + pkgName); 14082 return; 14083 } 14084 } else { 14085 // default to original signature matching 14086 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14087 != PackageManager.SIGNATURE_MATCH) { 14088 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14089 "New package has a different signature: " + pkgName); 14090 return; 14091 } 14092 } 14093 14094 // don't allow a system upgrade unless the upgrade hash matches 14095 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14096 byte[] digestBytes = null; 14097 try { 14098 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14099 updateDigest(digest, new File(pkg.baseCodePath)); 14100 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14101 for (String path : pkg.splitCodePaths) { 14102 updateDigest(digest, new File(path)); 14103 } 14104 } 14105 digestBytes = digest.digest(); 14106 } catch (NoSuchAlgorithmException | IOException e) { 14107 res.setError(INSTALL_FAILED_INVALID_APK, 14108 "Could not compute hash: " + pkgName); 14109 return; 14110 } 14111 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14112 res.setError(INSTALL_FAILED_INVALID_APK, 14113 "New package fails restrict-update check: " + pkgName); 14114 return; 14115 } 14116 // retain upgrade restriction 14117 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14118 } 14119 14120 // Check for shared user id changes 14121 String invalidPackageName = 14122 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14123 if (invalidPackageName != null) { 14124 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14125 "Package " + invalidPackageName + " tried to change user " 14126 + oldPackage.mSharedUserId); 14127 return; 14128 } 14129 14130 // In case of rollback, remember per-user/profile install state 14131 allUsers = sUserManager.getUserIds(); 14132 installedUsers = ps.queryInstalledUsers(allUsers, true); 14133 } 14134 14135 // Update what is removed 14136 res.removedInfo = new PackageRemovedInfo(); 14137 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14138 res.removedInfo.removedPackage = oldPackage.packageName; 14139 res.removedInfo.isUpdate = true; 14140 res.removedInfo.origUsers = installedUsers; 14141 final int childCount = (oldPackage.childPackages != null) 14142 ? oldPackage.childPackages.size() : 0; 14143 for (int i = 0; i < childCount; i++) { 14144 boolean childPackageUpdated = false; 14145 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14146 if (res.addedChildPackages != null) { 14147 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14148 if (childRes != null) { 14149 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14150 childRes.removedInfo.removedPackage = childPkg.packageName; 14151 childRes.removedInfo.isUpdate = true; 14152 childPackageUpdated = true; 14153 } 14154 } 14155 if (!childPackageUpdated) { 14156 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14157 childRemovedRes.removedPackage = childPkg.packageName; 14158 childRemovedRes.isUpdate = false; 14159 childRemovedRes.dataRemoved = true; 14160 synchronized (mPackages) { 14161 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14162 if (childPs != null) { 14163 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14164 } 14165 } 14166 if (res.removedInfo.removedChildPackages == null) { 14167 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14168 } 14169 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14170 } 14171 } 14172 14173 boolean sysPkg = (isSystemApp(oldPackage)); 14174 if (sysPkg) { 14175 // Set the system/privileged flags as needed 14176 final boolean privileged = 14177 (oldPackage.applicationInfo.privateFlags 14178 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14179 final int systemPolicyFlags = policyFlags 14180 | PackageParser.PARSE_IS_SYSTEM 14181 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14182 14183 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14184 user, allUsers, installerPackageName, res); 14185 } else { 14186 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14187 user, allUsers, installerPackageName, res); 14188 } 14189 } 14190 14191 public List<String> getPreviousCodePaths(String packageName) { 14192 final PackageSetting ps = mSettings.mPackages.get(packageName); 14193 final List<String> result = new ArrayList<String>(); 14194 if (ps != null && ps.oldCodePaths != null) { 14195 result.addAll(ps.oldCodePaths); 14196 } 14197 return result; 14198 } 14199 14200 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14201 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14202 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14203 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14204 + deletedPackage); 14205 14206 String pkgName = deletedPackage.packageName; 14207 boolean deletedPkg = true; 14208 boolean addedPkg = false; 14209 boolean updatedSettings = false; 14210 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14211 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14212 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14213 14214 final long origUpdateTime = (pkg.mExtras != null) 14215 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14216 14217 // First delete the existing package while retaining the data directory 14218 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14219 res.removedInfo, true, pkg)) { 14220 // If the existing package wasn't successfully deleted 14221 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14222 deletedPkg = false; 14223 } else { 14224 // Successfully deleted the old package; proceed with replace. 14225 14226 // If deleted package lived in a container, give users a chance to 14227 // relinquish resources before killing. 14228 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14229 if (DEBUG_INSTALL) { 14230 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14231 } 14232 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14233 final ArrayList<String> pkgList = new ArrayList<String>(1); 14234 pkgList.add(deletedPackage.applicationInfo.packageName); 14235 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14236 } 14237 14238 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14239 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14240 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14241 14242 try { 14243 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14244 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14245 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14246 14247 // Update the in-memory copy of the previous code paths. 14248 PackageSetting ps = mSettings.mPackages.get(pkgName); 14249 if (!killApp) { 14250 if (ps.oldCodePaths == null) { 14251 ps.oldCodePaths = new ArraySet<>(); 14252 } 14253 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14254 if (deletedPackage.splitCodePaths != null) { 14255 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14256 } 14257 } else { 14258 ps.oldCodePaths = null; 14259 } 14260 if (ps.childPackageNames != null) { 14261 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14262 final String childPkgName = ps.childPackageNames.get(i); 14263 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14264 childPs.oldCodePaths = ps.oldCodePaths; 14265 } 14266 } 14267 prepareAppDataAfterInstallLIF(newPackage); 14268 addedPkg = true; 14269 } catch (PackageManagerException e) { 14270 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14271 } 14272 } 14273 14274 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14275 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14276 14277 // Revert all internal state mutations and added folders for the failed install 14278 if (addedPkg) { 14279 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14280 res.removedInfo, true, null); 14281 } 14282 14283 // Restore the old package 14284 if (deletedPkg) { 14285 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14286 File restoreFile = new File(deletedPackage.codePath); 14287 // Parse old package 14288 boolean oldExternal = isExternal(deletedPackage); 14289 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14290 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14291 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14292 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14293 try { 14294 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14295 null); 14296 } catch (PackageManagerException e) { 14297 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14298 + e.getMessage()); 14299 return; 14300 } 14301 14302 synchronized (mPackages) { 14303 // Ensure the installer package name up to date 14304 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14305 14306 // Update permissions for restored package 14307 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14308 14309 mSettings.writeLPr(); 14310 } 14311 14312 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14313 } 14314 } else { 14315 synchronized (mPackages) { 14316 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14317 if (ps != null) { 14318 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14319 if (res.removedInfo.removedChildPackages != null) { 14320 final int childCount = res.removedInfo.removedChildPackages.size(); 14321 // Iterate in reverse as we may modify the collection 14322 for (int i = childCount - 1; i >= 0; i--) { 14323 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14324 if (res.addedChildPackages.containsKey(childPackageName)) { 14325 res.removedInfo.removedChildPackages.removeAt(i); 14326 } else { 14327 PackageRemovedInfo childInfo = res.removedInfo 14328 .removedChildPackages.valueAt(i); 14329 childInfo.removedForAllUsers = mPackages.get( 14330 childInfo.removedPackage) == null; 14331 } 14332 } 14333 } 14334 } 14335 } 14336 } 14337 } 14338 14339 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14340 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14341 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14342 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14343 + ", old=" + deletedPackage); 14344 14345 final boolean disabledSystem; 14346 14347 // Remove existing system package 14348 removePackageLI(deletedPackage, true); 14349 14350 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14351 if (!disabledSystem) { 14352 // We didn't need to disable the .apk as a current system package, 14353 // which means we are replacing another update that is already 14354 // installed. We need to make sure to delete the older one's .apk. 14355 res.removedInfo.args = createInstallArgsForExisting(0, 14356 deletedPackage.applicationInfo.getCodePath(), 14357 deletedPackage.applicationInfo.getResourcePath(), 14358 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14359 } else { 14360 res.removedInfo.args = null; 14361 } 14362 14363 // Successfully disabled the old package. Now proceed with re-installation 14364 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14365 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14366 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14367 14368 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14369 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14370 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14371 14372 PackageParser.Package newPackage = null; 14373 try { 14374 // Add the package to the internal data structures 14375 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14376 14377 // Set the update and install times 14378 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14379 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14380 System.currentTimeMillis()); 14381 14382 // Update the package dynamic state if succeeded 14383 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14384 // Now that the install succeeded make sure we remove data 14385 // directories for any child package the update removed. 14386 final int deletedChildCount = (deletedPackage.childPackages != null) 14387 ? deletedPackage.childPackages.size() : 0; 14388 final int newChildCount = (newPackage.childPackages != null) 14389 ? newPackage.childPackages.size() : 0; 14390 for (int i = 0; i < deletedChildCount; i++) { 14391 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14392 boolean childPackageDeleted = true; 14393 for (int j = 0; j < newChildCount; j++) { 14394 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14395 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14396 childPackageDeleted = false; 14397 break; 14398 } 14399 } 14400 if (childPackageDeleted) { 14401 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14402 deletedChildPkg.packageName); 14403 if (ps != null && res.removedInfo.removedChildPackages != null) { 14404 PackageRemovedInfo removedChildRes = res.removedInfo 14405 .removedChildPackages.get(deletedChildPkg.packageName); 14406 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14407 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14408 } 14409 } 14410 } 14411 14412 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14413 prepareAppDataAfterInstallLIF(newPackage); 14414 } 14415 } catch (PackageManagerException e) { 14416 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14417 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14418 } 14419 14420 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14421 // Re installation failed. Restore old information 14422 // Remove new pkg information 14423 if (newPackage != null) { 14424 removeInstalledPackageLI(newPackage, true); 14425 } 14426 // Add back the old system package 14427 try { 14428 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14429 } catch (PackageManagerException e) { 14430 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14431 } 14432 14433 synchronized (mPackages) { 14434 if (disabledSystem) { 14435 enableSystemPackageLPw(deletedPackage); 14436 } 14437 14438 // Ensure the installer package name up to date 14439 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14440 14441 // Update permissions for restored package 14442 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14443 14444 mSettings.writeLPr(); 14445 } 14446 14447 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14448 + " after failed upgrade"); 14449 } 14450 } 14451 14452 /** 14453 * Checks whether the parent or any of the child packages have a change shared 14454 * user. For a package to be a valid update the shred users of the parent and 14455 * the children should match. We may later support changing child shared users. 14456 * @param oldPkg The updated package. 14457 * @param newPkg The update package. 14458 * @return The shared user that change between the versions. 14459 */ 14460 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14461 PackageParser.Package newPkg) { 14462 // Check parent shared user 14463 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14464 return newPkg.packageName; 14465 } 14466 // Check child shared users 14467 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14468 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14469 for (int i = 0; i < newChildCount; i++) { 14470 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14471 // If this child was present, did it have the same shared user? 14472 for (int j = 0; j < oldChildCount; j++) { 14473 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14474 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14475 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14476 return newChildPkg.packageName; 14477 } 14478 } 14479 } 14480 return null; 14481 } 14482 14483 private void removeNativeBinariesLI(PackageSetting ps) { 14484 // Remove the lib path for the parent package 14485 if (ps != null) { 14486 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14487 // Remove the lib path for the child packages 14488 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14489 for (int i = 0; i < childCount; i++) { 14490 PackageSetting childPs = null; 14491 synchronized (mPackages) { 14492 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14493 } 14494 if (childPs != null) { 14495 NativeLibraryHelper.removeNativeBinariesLI(childPs 14496 .legacyNativeLibraryPathString); 14497 } 14498 } 14499 } 14500 } 14501 14502 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14503 // Enable the parent package 14504 mSettings.enableSystemPackageLPw(pkg.packageName); 14505 // Enable the child packages 14506 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14507 for (int i = 0; i < childCount; i++) { 14508 PackageParser.Package childPkg = pkg.childPackages.get(i); 14509 mSettings.enableSystemPackageLPw(childPkg.packageName); 14510 } 14511 } 14512 14513 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14514 PackageParser.Package newPkg) { 14515 // Disable the parent package (parent always replaced) 14516 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14517 // Disable the child packages 14518 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14519 for (int i = 0; i < childCount; i++) { 14520 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14521 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14522 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14523 } 14524 return disabled; 14525 } 14526 14527 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14528 String installerPackageName) { 14529 // Enable the parent package 14530 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14531 // Enable the child packages 14532 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14533 for (int i = 0; i < childCount; i++) { 14534 PackageParser.Package childPkg = pkg.childPackages.get(i); 14535 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14536 } 14537 } 14538 14539 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14540 // Collect all used permissions in the UID 14541 ArraySet<String> usedPermissions = new ArraySet<>(); 14542 final int packageCount = su.packages.size(); 14543 for (int i = 0; i < packageCount; i++) { 14544 PackageSetting ps = su.packages.valueAt(i); 14545 if (ps.pkg == null) { 14546 continue; 14547 } 14548 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14549 for (int j = 0; j < requestedPermCount; j++) { 14550 String permission = ps.pkg.requestedPermissions.get(j); 14551 BasePermission bp = mSettings.mPermissions.get(permission); 14552 if (bp != null) { 14553 usedPermissions.add(permission); 14554 } 14555 } 14556 } 14557 14558 PermissionsState permissionsState = su.getPermissionsState(); 14559 // Prune install permissions 14560 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14561 final int installPermCount = installPermStates.size(); 14562 for (int i = installPermCount - 1; i >= 0; i--) { 14563 PermissionState permissionState = installPermStates.get(i); 14564 if (!usedPermissions.contains(permissionState.getName())) { 14565 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14566 if (bp != null) { 14567 permissionsState.revokeInstallPermission(bp); 14568 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14569 PackageManager.MASK_PERMISSION_FLAGS, 0); 14570 } 14571 } 14572 } 14573 14574 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14575 14576 // Prune runtime permissions 14577 for (int userId : allUserIds) { 14578 List<PermissionState> runtimePermStates = permissionsState 14579 .getRuntimePermissionStates(userId); 14580 final int runtimePermCount = runtimePermStates.size(); 14581 for (int i = runtimePermCount - 1; i >= 0; i--) { 14582 PermissionState permissionState = runtimePermStates.get(i); 14583 if (!usedPermissions.contains(permissionState.getName())) { 14584 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14585 if (bp != null) { 14586 permissionsState.revokeRuntimePermission(bp, userId); 14587 permissionsState.updatePermissionFlags(bp, userId, 14588 PackageManager.MASK_PERMISSION_FLAGS, 0); 14589 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14590 runtimePermissionChangedUserIds, userId); 14591 } 14592 } 14593 } 14594 } 14595 14596 return runtimePermissionChangedUserIds; 14597 } 14598 14599 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14600 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14601 // Update the parent package setting 14602 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14603 res, user); 14604 // Update the child packages setting 14605 final int childCount = (newPackage.childPackages != null) 14606 ? newPackage.childPackages.size() : 0; 14607 for (int i = 0; i < childCount; i++) { 14608 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14609 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14610 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14611 childRes.origUsers, childRes, user); 14612 } 14613 } 14614 14615 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14616 String installerPackageName, int[] allUsers, int[] installedForUsers, 14617 PackageInstalledInfo res, UserHandle user) { 14618 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14619 14620 String pkgName = newPackage.packageName; 14621 synchronized (mPackages) { 14622 //write settings. the installStatus will be incomplete at this stage. 14623 //note that the new package setting would have already been 14624 //added to mPackages. It hasn't been persisted yet. 14625 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14626 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14627 mSettings.writeLPr(); 14628 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14629 } 14630 14631 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14632 synchronized (mPackages) { 14633 updatePermissionsLPw(newPackage.packageName, newPackage, 14634 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14635 ? UPDATE_PERMISSIONS_ALL : 0)); 14636 // For system-bundled packages, we assume that installing an upgraded version 14637 // of the package implies that the user actually wants to run that new code, 14638 // so we enable the package. 14639 PackageSetting ps = mSettings.mPackages.get(pkgName); 14640 final int userId = user.getIdentifier(); 14641 if (ps != null) { 14642 if (isSystemApp(newPackage)) { 14643 if (DEBUG_INSTALL) { 14644 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14645 } 14646 // Enable system package for requested users 14647 if (res.origUsers != null) { 14648 for (int origUserId : res.origUsers) { 14649 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14650 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14651 origUserId, installerPackageName); 14652 } 14653 } 14654 } 14655 // Also convey the prior install/uninstall state 14656 if (allUsers != null && installedForUsers != null) { 14657 for (int currentUserId : allUsers) { 14658 final boolean installed = ArrayUtils.contains( 14659 installedForUsers, currentUserId); 14660 if (DEBUG_INSTALL) { 14661 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14662 } 14663 ps.setInstalled(installed, currentUserId); 14664 } 14665 // these install state changes will be persisted in the 14666 // upcoming call to mSettings.writeLPr(). 14667 } 14668 } 14669 // It's implied that when a user requests installation, they want the app to be 14670 // installed and enabled. 14671 if (userId != UserHandle.USER_ALL) { 14672 ps.setInstalled(true, userId); 14673 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14674 } 14675 } 14676 res.name = pkgName; 14677 res.uid = newPackage.applicationInfo.uid; 14678 res.pkg = newPackage; 14679 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14680 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14681 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14682 //to update install status 14683 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14684 mSettings.writeLPr(); 14685 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14686 } 14687 14688 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14689 } 14690 14691 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14692 try { 14693 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14694 installPackageLI(args, res); 14695 } finally { 14696 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14697 } 14698 } 14699 14700 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14701 final int installFlags = args.installFlags; 14702 final String installerPackageName = args.installerPackageName; 14703 final String volumeUuid = args.volumeUuid; 14704 final File tmpPackageFile = new File(args.getCodePath()); 14705 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14706 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14707 || (args.volumeUuid != null)); 14708 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14709 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14710 boolean replace = false; 14711 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14712 if (args.move != null) { 14713 // moving a complete application; perform an initial scan on the new install location 14714 scanFlags |= SCAN_INITIAL; 14715 } 14716 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14717 scanFlags |= SCAN_DONT_KILL_APP; 14718 } 14719 14720 // Result object to be returned 14721 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14722 14723 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14724 14725 // Sanity check 14726 if (ephemeral && (forwardLocked || onExternal)) { 14727 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14728 + " external=" + onExternal); 14729 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14730 return; 14731 } 14732 14733 // Retrieve PackageSettings and parse package 14734 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14735 | PackageParser.PARSE_ENFORCE_CODE 14736 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14737 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14738 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14739 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14740 PackageParser pp = new PackageParser(); 14741 pp.setSeparateProcesses(mSeparateProcesses); 14742 pp.setDisplayMetrics(mMetrics); 14743 14744 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14745 final PackageParser.Package pkg; 14746 try { 14747 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14748 } catch (PackageParserException e) { 14749 res.setError("Failed parse during installPackageLI", e); 14750 return; 14751 } finally { 14752 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14753 } 14754 14755 // If we are installing a clustered package add results for the children 14756 if (pkg.childPackages != null) { 14757 synchronized (mPackages) { 14758 final int childCount = pkg.childPackages.size(); 14759 for (int i = 0; i < childCount; i++) { 14760 PackageParser.Package childPkg = pkg.childPackages.get(i); 14761 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14762 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14763 childRes.pkg = childPkg; 14764 childRes.name = childPkg.packageName; 14765 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14766 if (childPs != null) { 14767 childRes.origUsers = childPs.queryInstalledUsers( 14768 sUserManager.getUserIds(), true); 14769 } 14770 if ((mPackages.containsKey(childPkg.packageName))) { 14771 childRes.removedInfo = new PackageRemovedInfo(); 14772 childRes.removedInfo.removedPackage = childPkg.packageName; 14773 } 14774 if (res.addedChildPackages == null) { 14775 res.addedChildPackages = new ArrayMap<>(); 14776 } 14777 res.addedChildPackages.put(childPkg.packageName, childRes); 14778 } 14779 } 14780 } 14781 14782 // If package doesn't declare API override, mark that we have an install 14783 // time CPU ABI override. 14784 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14785 pkg.cpuAbiOverride = args.abiOverride; 14786 } 14787 14788 String pkgName = res.name = pkg.packageName; 14789 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14790 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14791 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14792 return; 14793 } 14794 } 14795 14796 try { 14797 // either use what we've been given or parse directly from the APK 14798 if (args.certificates != null) { 14799 try { 14800 PackageParser.populateCertificates(pkg, args.certificates); 14801 } catch (PackageParserException e) { 14802 // there was something wrong with the certificates we were given; 14803 // try to pull them from the APK 14804 PackageParser.collectCertificates(pkg, parseFlags); 14805 } 14806 } else { 14807 PackageParser.collectCertificates(pkg, parseFlags); 14808 } 14809 } catch (PackageParserException e) { 14810 res.setError("Failed collect during installPackageLI", e); 14811 return; 14812 } 14813 14814 // Get rid of all references to package scan path via parser. 14815 pp = null; 14816 String oldCodePath = null; 14817 boolean systemApp = false; 14818 synchronized (mPackages) { 14819 // Check if installing already existing package 14820 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14821 String oldName = mSettings.mRenamedPackages.get(pkgName); 14822 if (pkg.mOriginalPackages != null 14823 && pkg.mOriginalPackages.contains(oldName) 14824 && mPackages.containsKey(oldName)) { 14825 // This package is derived from an original package, 14826 // and this device has been updating from that original 14827 // name. We must continue using the original name, so 14828 // rename the new package here. 14829 pkg.setPackageName(oldName); 14830 pkgName = pkg.packageName; 14831 replace = true; 14832 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14833 + oldName + " pkgName=" + pkgName); 14834 } else if (mPackages.containsKey(pkgName)) { 14835 // This package, under its official name, already exists 14836 // on the device; we should replace it. 14837 replace = true; 14838 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14839 } 14840 14841 // Child packages are installed through the parent package 14842 if (pkg.parentPackage != null) { 14843 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14844 "Package " + pkg.packageName + " is child of package " 14845 + pkg.parentPackage.parentPackage + ". Child packages " 14846 + "can be updated only through the parent package."); 14847 return; 14848 } 14849 14850 if (replace) { 14851 // Prevent apps opting out from runtime permissions 14852 PackageParser.Package oldPackage = mPackages.get(pkgName); 14853 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14854 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14855 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14856 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14857 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14858 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14859 + " doesn't support runtime permissions but the old" 14860 + " target SDK " + oldTargetSdk + " does."); 14861 return; 14862 } 14863 14864 // Prevent installing of child packages 14865 if (oldPackage.parentPackage != null) { 14866 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14867 "Package " + pkg.packageName + " is child of package " 14868 + oldPackage.parentPackage + ". Child packages " 14869 + "can be updated only through the parent package."); 14870 return; 14871 } 14872 } 14873 } 14874 14875 PackageSetting ps = mSettings.mPackages.get(pkgName); 14876 if (ps != null) { 14877 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14878 14879 // Quick sanity check that we're signed correctly if updating; 14880 // we'll check this again later when scanning, but we want to 14881 // bail early here before tripping over redefined permissions. 14882 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14883 if (!checkUpgradeKeySetLP(ps, pkg)) { 14884 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14885 + pkg.packageName + " upgrade keys do not match the " 14886 + "previously installed version"); 14887 return; 14888 } 14889 } else { 14890 try { 14891 verifySignaturesLP(ps, pkg); 14892 } catch (PackageManagerException e) { 14893 res.setError(e.error, e.getMessage()); 14894 return; 14895 } 14896 } 14897 14898 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14899 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14900 systemApp = (ps.pkg.applicationInfo.flags & 14901 ApplicationInfo.FLAG_SYSTEM) != 0; 14902 } 14903 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14904 } 14905 14906 // Check whether the newly-scanned package wants to define an already-defined perm 14907 int N = pkg.permissions.size(); 14908 for (int i = N-1; i >= 0; i--) { 14909 PackageParser.Permission perm = pkg.permissions.get(i); 14910 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14911 if (bp != null) { 14912 // If the defining package is signed with our cert, it's okay. This 14913 // also includes the "updating the same package" case, of course. 14914 // "updating same package" could also involve key-rotation. 14915 final boolean sigsOk; 14916 if (bp.sourcePackage.equals(pkg.packageName) 14917 && (bp.packageSetting instanceof PackageSetting) 14918 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14919 scanFlags))) { 14920 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14921 } else { 14922 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14923 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14924 } 14925 if (!sigsOk) { 14926 // If the owning package is the system itself, we log but allow 14927 // install to proceed; we fail the install on all other permission 14928 // redefinitions. 14929 if (!bp.sourcePackage.equals("android")) { 14930 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14931 + pkg.packageName + " attempting to redeclare permission " 14932 + perm.info.name + " already owned by " + bp.sourcePackage); 14933 res.origPermission = perm.info.name; 14934 res.origPackage = bp.sourcePackage; 14935 return; 14936 } else { 14937 Slog.w(TAG, "Package " + pkg.packageName 14938 + " attempting to redeclare system permission " 14939 + perm.info.name + "; ignoring new declaration"); 14940 pkg.permissions.remove(i); 14941 } 14942 } 14943 } 14944 } 14945 } 14946 14947 if (systemApp) { 14948 if (onExternal) { 14949 // Abort update; system app can't be replaced with app on sdcard 14950 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14951 "Cannot install updates to system apps on sdcard"); 14952 return; 14953 } else if (ephemeral) { 14954 // Abort update; system app can't be replaced with an ephemeral app 14955 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14956 "Cannot update a system app with an ephemeral app"); 14957 return; 14958 } 14959 } 14960 14961 if (args.move != null) { 14962 // We did an in-place move, so dex is ready to roll 14963 scanFlags |= SCAN_NO_DEX; 14964 scanFlags |= SCAN_MOVE; 14965 14966 synchronized (mPackages) { 14967 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14968 if (ps == null) { 14969 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14970 "Missing settings for moved package " + pkgName); 14971 } 14972 14973 // We moved the entire application as-is, so bring over the 14974 // previously derived ABI information. 14975 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14976 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14977 } 14978 14979 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14980 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14981 scanFlags |= SCAN_NO_DEX; 14982 14983 try { 14984 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14985 args.abiOverride : pkg.cpuAbiOverride); 14986 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14987 true /* extract libs */); 14988 } catch (PackageManagerException pme) { 14989 Slog.e(TAG, "Error deriving application ABI", pme); 14990 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14991 return; 14992 } 14993 14994 // Shared libraries for the package need to be updated. 14995 synchronized (mPackages) { 14996 try { 14997 updateSharedLibrariesLPw(pkg, null); 14998 } catch (PackageManagerException e) { 14999 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15000 } 15001 } 15002 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15003 // Do not run PackageDexOptimizer through the local performDexOpt 15004 // method because `pkg` is not in `mPackages` yet. 15005 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15006 null /* instructionSets */, false /* checkProfiles */, 15007 getCompilerFilterForReason(REASON_INSTALL)); 15008 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15009 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 15010 String msg = "Extracting package failed for " + pkgName; 15011 res.setError(INSTALL_FAILED_DEXOPT, msg); 15012 return; 15013 } 15014 15015 // Notify BackgroundDexOptService that the package has been changed. 15016 // If this is an update of a package which used to fail to compile, 15017 // BDOS will remove it from its blacklist. 15018 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15019 } 15020 15021 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15022 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15023 return; 15024 } 15025 15026 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15027 15028 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15029 "installPackageLI")) { 15030 if (replace) { 15031 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15032 installerPackageName, res); 15033 } else { 15034 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15035 args.user, installerPackageName, volumeUuid, res); 15036 } 15037 } 15038 synchronized (mPackages) { 15039 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15040 if (ps != null) { 15041 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15042 } 15043 15044 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15045 for (int i = 0; i < childCount; i++) { 15046 PackageParser.Package childPkg = pkg.childPackages.get(i); 15047 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15048 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15049 if (childPs != null) { 15050 childRes.newUsers = childPs.queryInstalledUsers( 15051 sUserManager.getUserIds(), true); 15052 } 15053 } 15054 } 15055 } 15056 15057 private void startIntentFilterVerifications(int userId, boolean replacing, 15058 PackageParser.Package pkg) { 15059 if (mIntentFilterVerifierComponent == null) { 15060 Slog.w(TAG, "No IntentFilter verification will not be done as " 15061 + "there is no IntentFilterVerifier available!"); 15062 return; 15063 } 15064 15065 final int verifierUid = getPackageUid( 15066 mIntentFilterVerifierComponent.getPackageName(), 15067 MATCH_DEBUG_TRIAGED_MISSING, 15068 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15069 15070 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15071 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15072 mHandler.sendMessage(msg); 15073 15074 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15075 for (int i = 0; i < childCount; i++) { 15076 PackageParser.Package childPkg = pkg.childPackages.get(i); 15077 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15078 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15079 mHandler.sendMessage(msg); 15080 } 15081 } 15082 15083 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15084 PackageParser.Package pkg) { 15085 int size = pkg.activities.size(); 15086 if (size == 0) { 15087 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15088 "No activity, so no need to verify any IntentFilter!"); 15089 return; 15090 } 15091 15092 final boolean hasDomainURLs = hasDomainURLs(pkg); 15093 if (!hasDomainURLs) { 15094 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15095 "No domain URLs, so no need to verify any IntentFilter!"); 15096 return; 15097 } 15098 15099 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15100 + " if any IntentFilter from the " + size 15101 + " Activities needs verification ..."); 15102 15103 int count = 0; 15104 final String packageName = pkg.packageName; 15105 15106 synchronized (mPackages) { 15107 // If this is a new install and we see that we've already run verification for this 15108 // package, we have nothing to do: it means the state was restored from backup. 15109 if (!replacing) { 15110 IntentFilterVerificationInfo ivi = 15111 mSettings.getIntentFilterVerificationLPr(packageName); 15112 if (ivi != null) { 15113 if (DEBUG_DOMAIN_VERIFICATION) { 15114 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15115 + ivi.getStatusString()); 15116 } 15117 return; 15118 } 15119 } 15120 15121 // If any filters need to be verified, then all need to be. 15122 boolean needToVerify = false; 15123 for (PackageParser.Activity a : pkg.activities) { 15124 for (ActivityIntentInfo filter : a.intents) { 15125 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15126 if (DEBUG_DOMAIN_VERIFICATION) { 15127 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15128 } 15129 needToVerify = true; 15130 break; 15131 } 15132 } 15133 } 15134 15135 if (needToVerify) { 15136 final int verificationId = mIntentFilterVerificationToken++; 15137 for (PackageParser.Activity a : pkg.activities) { 15138 for (ActivityIntentInfo filter : a.intents) { 15139 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15140 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15141 "Verification needed for IntentFilter:" + filter.toString()); 15142 mIntentFilterVerifier.addOneIntentFilterVerification( 15143 verifierUid, userId, verificationId, filter, packageName); 15144 count++; 15145 } 15146 } 15147 } 15148 } 15149 } 15150 15151 if (count > 0) { 15152 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15153 + " IntentFilter verification" + (count > 1 ? "s" : "") 15154 + " for userId:" + userId); 15155 mIntentFilterVerifier.startVerifications(userId); 15156 } else { 15157 if (DEBUG_DOMAIN_VERIFICATION) { 15158 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15159 } 15160 } 15161 } 15162 15163 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15164 final ComponentName cn = filter.activity.getComponentName(); 15165 final String packageName = cn.getPackageName(); 15166 15167 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15168 packageName); 15169 if (ivi == null) { 15170 return true; 15171 } 15172 int status = ivi.getStatus(); 15173 switch (status) { 15174 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15175 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15176 return true; 15177 15178 default: 15179 // Nothing to do 15180 return false; 15181 } 15182 } 15183 15184 private static boolean isMultiArch(ApplicationInfo info) { 15185 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15186 } 15187 15188 private static boolean isExternal(PackageParser.Package pkg) { 15189 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15190 } 15191 15192 private static boolean isExternal(PackageSetting ps) { 15193 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15194 } 15195 15196 private static boolean isEphemeral(PackageParser.Package pkg) { 15197 return pkg.applicationInfo.isEphemeralApp(); 15198 } 15199 15200 private static boolean isEphemeral(PackageSetting ps) { 15201 return ps.pkg != null && isEphemeral(ps.pkg); 15202 } 15203 15204 private static boolean isSystemApp(PackageParser.Package pkg) { 15205 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15206 } 15207 15208 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15209 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15210 } 15211 15212 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15213 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15214 } 15215 15216 private static boolean isSystemApp(PackageSetting ps) { 15217 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15218 } 15219 15220 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15221 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15222 } 15223 15224 private int packageFlagsToInstallFlags(PackageSetting ps) { 15225 int installFlags = 0; 15226 if (isEphemeral(ps)) { 15227 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15228 } 15229 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15230 // This existing package was an external ASEC install when we have 15231 // the external flag without a UUID 15232 installFlags |= PackageManager.INSTALL_EXTERNAL; 15233 } 15234 if (ps.isForwardLocked()) { 15235 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15236 } 15237 return installFlags; 15238 } 15239 15240 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15241 if (isExternal(pkg)) { 15242 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15243 return StorageManager.UUID_PRIMARY_PHYSICAL; 15244 } else { 15245 return pkg.volumeUuid; 15246 } 15247 } else { 15248 return StorageManager.UUID_PRIVATE_INTERNAL; 15249 } 15250 } 15251 15252 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15253 if (isExternal(pkg)) { 15254 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15255 return mSettings.getExternalVersion(); 15256 } else { 15257 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15258 } 15259 } else { 15260 return mSettings.getInternalVersion(); 15261 } 15262 } 15263 15264 private void deleteTempPackageFiles() { 15265 final FilenameFilter filter = new FilenameFilter() { 15266 public boolean accept(File dir, String name) { 15267 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15268 } 15269 }; 15270 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15271 file.delete(); 15272 } 15273 } 15274 15275 @Override 15276 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15277 int flags) { 15278 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15279 flags); 15280 } 15281 15282 @Override 15283 public void deletePackage(final String packageName, 15284 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15285 mContext.enforceCallingOrSelfPermission( 15286 android.Manifest.permission.DELETE_PACKAGES, null); 15287 Preconditions.checkNotNull(packageName); 15288 Preconditions.checkNotNull(observer); 15289 final int uid = Binder.getCallingUid(); 15290 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15291 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15292 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15293 mContext.enforceCallingOrSelfPermission( 15294 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15295 "deletePackage for user " + userId); 15296 } 15297 15298 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15299 try { 15300 observer.onPackageDeleted(packageName, 15301 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15302 } catch (RemoteException re) { 15303 } 15304 return; 15305 } 15306 15307 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15308 try { 15309 observer.onPackageDeleted(packageName, 15310 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15311 } catch (RemoteException re) { 15312 } 15313 return; 15314 } 15315 15316 if (DEBUG_REMOVE) { 15317 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15318 + " deleteAllUsers: " + deleteAllUsers ); 15319 } 15320 // Queue up an async operation since the package deletion may take a little while. 15321 mHandler.post(new Runnable() { 15322 public void run() { 15323 mHandler.removeCallbacks(this); 15324 int returnCode; 15325 if (!deleteAllUsers) { 15326 returnCode = deletePackageX(packageName, userId, deleteFlags); 15327 } else { 15328 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15329 // If nobody is blocking uninstall, proceed with delete for all users 15330 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15331 returnCode = deletePackageX(packageName, userId, deleteFlags); 15332 } else { 15333 // Otherwise uninstall individually for users with blockUninstalls=false 15334 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15335 for (int userId : users) { 15336 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15337 returnCode = deletePackageX(packageName, userId, userFlags); 15338 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15339 Slog.w(TAG, "Package delete failed for user " + userId 15340 + ", returnCode " + returnCode); 15341 } 15342 } 15343 } 15344 // The app has only been marked uninstalled for certain users. 15345 // We still need to report that delete was blocked 15346 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15347 } 15348 } 15349 try { 15350 observer.onPackageDeleted(packageName, returnCode, null); 15351 } catch (RemoteException e) { 15352 Log.i(TAG, "Observer no longer exists."); 15353 } //end catch 15354 } //end run 15355 }); 15356 } 15357 15358 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15359 int[] result = EMPTY_INT_ARRAY; 15360 for (int userId : userIds) { 15361 if (getBlockUninstallForUser(packageName, userId)) { 15362 result = ArrayUtils.appendInt(result, userId); 15363 } 15364 } 15365 return result; 15366 } 15367 15368 @Override 15369 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15370 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15371 } 15372 15373 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15374 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15375 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15376 try { 15377 if (dpm != null) { 15378 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15379 /* callingUserOnly =*/ false); 15380 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15381 : deviceOwnerComponentName.getPackageName(); 15382 // Does the package contains the device owner? 15383 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15384 // this check is probably not needed, since DO should be registered as a device 15385 // admin on some user too. (Original bug for this: b/17657954) 15386 if (packageName.equals(deviceOwnerPackageName)) { 15387 return true; 15388 } 15389 // Does it contain a device admin for any user? 15390 int[] users; 15391 if (userId == UserHandle.USER_ALL) { 15392 users = sUserManager.getUserIds(); 15393 } else { 15394 users = new int[]{userId}; 15395 } 15396 for (int i = 0; i < users.length; ++i) { 15397 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15398 return true; 15399 } 15400 } 15401 } 15402 } catch (RemoteException e) { 15403 } 15404 return false; 15405 } 15406 15407 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15408 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15409 } 15410 15411 /** 15412 * This method is an internal method that could be get invoked either 15413 * to delete an installed package or to clean up a failed installation. 15414 * After deleting an installed package, a broadcast is sent to notify any 15415 * listeners that the package has been removed. For cleaning up a failed 15416 * installation, the broadcast is not necessary since the package's 15417 * installation wouldn't have sent the initial broadcast either 15418 * The key steps in deleting a package are 15419 * deleting the package information in internal structures like mPackages, 15420 * deleting the packages base directories through installd 15421 * updating mSettings to reflect current status 15422 * persisting settings for later use 15423 * sending a broadcast if necessary 15424 */ 15425 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15426 final PackageRemovedInfo info = new PackageRemovedInfo(); 15427 final boolean res; 15428 15429 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15430 ? UserHandle.ALL : new UserHandle(userId); 15431 15432 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15433 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15434 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15435 } 15436 15437 PackageSetting uninstalledPs = null; 15438 15439 // for the uninstall-updates case and restricted profiles, remember the per- 15440 // user handle installed state 15441 int[] allUsers; 15442 synchronized (mPackages) { 15443 uninstalledPs = mSettings.mPackages.get(packageName); 15444 if (uninstalledPs == null) { 15445 Slog.w(TAG, "Not removing non-existent package " + packageName); 15446 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15447 } 15448 allUsers = sUserManager.getUserIds(); 15449 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15450 } 15451 15452 synchronized (mInstallLock) { 15453 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15454 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15455 "deletePackageX")) { 15456 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15457 deleteFlags | REMOVE_CHATTY, info, true, null); 15458 } 15459 synchronized (mPackages) { 15460 if (res) { 15461 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15462 } 15463 } 15464 } 15465 15466 if (res) { 15467 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15468 info.sendPackageRemovedBroadcasts(killApp); 15469 info.sendSystemPackageUpdatedBroadcasts(); 15470 info.sendSystemPackageAppearedBroadcasts(); 15471 } 15472 // Force a gc here. 15473 Runtime.getRuntime().gc(); 15474 // Delete the resources here after sending the broadcast to let 15475 // other processes clean up before deleting resources. 15476 if (info.args != null) { 15477 synchronized (mInstallLock) { 15478 info.args.doPostDeleteLI(true); 15479 } 15480 } 15481 15482 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15483 } 15484 15485 class PackageRemovedInfo { 15486 String removedPackage; 15487 int uid = -1; 15488 int removedAppId = -1; 15489 int[] origUsers; 15490 int[] removedUsers = null; 15491 boolean isRemovedPackageSystemUpdate = false; 15492 boolean isUpdate; 15493 boolean dataRemoved; 15494 boolean removedForAllUsers; 15495 // Clean up resources deleted packages. 15496 InstallArgs args = null; 15497 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15498 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15499 15500 void sendPackageRemovedBroadcasts(boolean killApp) { 15501 sendPackageRemovedBroadcastInternal(killApp); 15502 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15503 for (int i = 0; i < childCount; i++) { 15504 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15505 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15506 } 15507 } 15508 15509 void sendSystemPackageUpdatedBroadcasts() { 15510 if (isRemovedPackageSystemUpdate) { 15511 sendSystemPackageUpdatedBroadcastsInternal(); 15512 final int childCount = (removedChildPackages != null) 15513 ? removedChildPackages.size() : 0; 15514 for (int i = 0; i < childCount; i++) { 15515 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15516 if (childInfo.isRemovedPackageSystemUpdate) { 15517 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15518 } 15519 } 15520 } 15521 } 15522 15523 void sendSystemPackageAppearedBroadcasts() { 15524 final int packageCount = (appearedChildPackages != null) 15525 ? appearedChildPackages.size() : 0; 15526 for (int i = 0; i < packageCount; i++) { 15527 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15528 for (int userId : installedInfo.newUsers) { 15529 sendPackageAddedForUser(installedInfo.name, true, 15530 UserHandle.getAppId(installedInfo.uid), userId); 15531 } 15532 } 15533 } 15534 15535 private void sendSystemPackageUpdatedBroadcastsInternal() { 15536 Bundle extras = new Bundle(2); 15537 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15538 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15539 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15540 extras, 0, null, null, null); 15541 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15542 extras, 0, null, null, null); 15543 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15544 null, 0, removedPackage, null, null); 15545 } 15546 15547 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15548 Bundle extras = new Bundle(2); 15549 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15550 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15551 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15552 if (isUpdate || isRemovedPackageSystemUpdate) { 15553 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15554 } 15555 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15556 if (removedPackage != null) { 15557 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15558 extras, 0, null, null, removedUsers); 15559 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15560 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15561 removedPackage, extras, 0, null, null, removedUsers); 15562 } 15563 } 15564 if (removedAppId >= 0) { 15565 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15566 removedUsers); 15567 } 15568 } 15569 } 15570 15571 /* 15572 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15573 * flag is not set, the data directory is removed as well. 15574 * make sure this flag is set for partially installed apps. If not its meaningless to 15575 * delete a partially installed application. 15576 */ 15577 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15578 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15579 String packageName = ps.name; 15580 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15581 // Retrieve object to delete permissions for shared user later on 15582 final PackageParser.Package deletedPkg; 15583 final PackageSetting deletedPs; 15584 // reader 15585 synchronized (mPackages) { 15586 deletedPkg = mPackages.get(packageName); 15587 deletedPs = mSettings.mPackages.get(packageName); 15588 if (outInfo != null) { 15589 outInfo.removedPackage = packageName; 15590 outInfo.removedUsers = deletedPs != null 15591 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15592 : null; 15593 } 15594 } 15595 15596 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15597 15598 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15599 final PackageParser.Package resolvedPkg; 15600 if (deletedPkg != null) { 15601 resolvedPkg = deletedPkg; 15602 } else { 15603 // We don't have a parsed package when it lives on an ejected 15604 // adopted storage device, so fake something together 15605 resolvedPkg = new PackageParser.Package(ps.name); 15606 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15607 } 15608 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15609 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15610 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15611 if (outInfo != null) { 15612 outInfo.dataRemoved = true; 15613 } 15614 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15615 } 15616 15617 // writer 15618 synchronized (mPackages) { 15619 if (deletedPs != null) { 15620 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15621 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15622 clearDefaultBrowserIfNeeded(packageName); 15623 if (outInfo != null) { 15624 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15625 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15626 } 15627 updatePermissionsLPw(deletedPs.name, null, 0); 15628 if (deletedPs.sharedUser != null) { 15629 // Remove permissions associated with package. Since runtime 15630 // permissions are per user we have to kill the removed package 15631 // or packages running under the shared user of the removed 15632 // package if revoking the permissions requested only by the removed 15633 // package is successful and this causes a change in gids. 15634 for (int userId : UserManagerService.getInstance().getUserIds()) { 15635 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15636 userId); 15637 if (userIdToKill == UserHandle.USER_ALL 15638 || userIdToKill >= UserHandle.USER_SYSTEM) { 15639 // If gids changed for this user, kill all affected packages. 15640 mHandler.post(new Runnable() { 15641 @Override 15642 public void run() { 15643 // This has to happen with no lock held. 15644 killApplication(deletedPs.name, deletedPs.appId, 15645 KILL_APP_REASON_GIDS_CHANGED); 15646 } 15647 }); 15648 break; 15649 } 15650 } 15651 } 15652 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15653 } 15654 // make sure to preserve per-user disabled state if this removal was just 15655 // a downgrade of a system app to the factory package 15656 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15657 if (DEBUG_REMOVE) { 15658 Slog.d(TAG, "Propagating install state across downgrade"); 15659 } 15660 for (int userId : allUserHandles) { 15661 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15662 if (DEBUG_REMOVE) { 15663 Slog.d(TAG, " user " + userId + " => " + installed); 15664 } 15665 ps.setInstalled(installed, userId); 15666 } 15667 } 15668 } 15669 // can downgrade to reader 15670 if (writeSettings) { 15671 // Save settings now 15672 mSettings.writeLPr(); 15673 } 15674 } 15675 if (outInfo != null) { 15676 // A user ID was deleted here. Go through all users and remove it 15677 // from KeyStore. 15678 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15679 } 15680 } 15681 15682 static boolean locationIsPrivileged(File path) { 15683 try { 15684 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15685 .getCanonicalPath(); 15686 return path.getCanonicalPath().startsWith(privilegedAppDir); 15687 } catch (IOException e) { 15688 Slog.e(TAG, "Unable to access code path " + path); 15689 } 15690 return false; 15691 } 15692 15693 /* 15694 * Tries to delete system package. 15695 */ 15696 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15697 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15698 boolean writeSettings) { 15699 if (deletedPs.parentPackageName != null) { 15700 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15701 return false; 15702 } 15703 15704 final boolean applyUserRestrictions 15705 = (allUserHandles != null) && (outInfo.origUsers != null); 15706 final PackageSetting disabledPs; 15707 // Confirm if the system package has been updated 15708 // An updated system app can be deleted. This will also have to restore 15709 // the system pkg from system partition 15710 // reader 15711 synchronized (mPackages) { 15712 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15713 } 15714 15715 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15716 + " disabledPs=" + disabledPs); 15717 15718 if (disabledPs == null) { 15719 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15720 return false; 15721 } else if (DEBUG_REMOVE) { 15722 Slog.d(TAG, "Deleting system pkg from data partition"); 15723 } 15724 15725 if (DEBUG_REMOVE) { 15726 if (applyUserRestrictions) { 15727 Slog.d(TAG, "Remembering install states:"); 15728 for (int userId : allUserHandles) { 15729 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15730 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15731 } 15732 } 15733 } 15734 15735 // Delete the updated package 15736 outInfo.isRemovedPackageSystemUpdate = true; 15737 if (outInfo.removedChildPackages != null) { 15738 final int childCount = (deletedPs.childPackageNames != null) 15739 ? deletedPs.childPackageNames.size() : 0; 15740 for (int i = 0; i < childCount; i++) { 15741 String childPackageName = deletedPs.childPackageNames.get(i); 15742 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15743 .contains(childPackageName)) { 15744 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15745 childPackageName); 15746 if (childInfo != null) { 15747 childInfo.isRemovedPackageSystemUpdate = true; 15748 } 15749 } 15750 } 15751 } 15752 15753 if (disabledPs.versionCode < deletedPs.versionCode) { 15754 // Delete data for downgrades 15755 flags &= ~PackageManager.DELETE_KEEP_DATA; 15756 } else { 15757 // Preserve data by setting flag 15758 flags |= PackageManager.DELETE_KEEP_DATA; 15759 } 15760 15761 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15762 outInfo, writeSettings, disabledPs.pkg); 15763 if (!ret) { 15764 return false; 15765 } 15766 15767 // writer 15768 synchronized (mPackages) { 15769 // Reinstate the old system package 15770 enableSystemPackageLPw(disabledPs.pkg); 15771 // Remove any native libraries from the upgraded package. 15772 removeNativeBinariesLI(deletedPs); 15773 } 15774 15775 // Install the system package 15776 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15777 int parseFlags = mDefParseFlags 15778 | PackageParser.PARSE_MUST_BE_APK 15779 | PackageParser.PARSE_IS_SYSTEM 15780 | PackageParser.PARSE_IS_SYSTEM_DIR; 15781 if (locationIsPrivileged(disabledPs.codePath)) { 15782 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15783 } 15784 15785 final PackageParser.Package newPkg; 15786 try { 15787 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15788 } catch (PackageManagerException e) { 15789 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15790 + e.getMessage()); 15791 return false; 15792 } 15793 15794 prepareAppDataAfterInstallLIF(newPkg); 15795 15796 // writer 15797 synchronized (mPackages) { 15798 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15799 15800 // Propagate the permissions state as we do not want to drop on the floor 15801 // runtime permissions. The update permissions method below will take 15802 // care of removing obsolete permissions and grant install permissions. 15803 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15804 updatePermissionsLPw(newPkg.packageName, newPkg, 15805 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15806 15807 if (applyUserRestrictions) { 15808 if (DEBUG_REMOVE) { 15809 Slog.d(TAG, "Propagating install state across reinstall"); 15810 } 15811 for (int userId : allUserHandles) { 15812 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15813 if (DEBUG_REMOVE) { 15814 Slog.d(TAG, " user " + userId + " => " + installed); 15815 } 15816 ps.setInstalled(installed, userId); 15817 15818 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15819 } 15820 // Regardless of writeSettings we need to ensure that this restriction 15821 // state propagation is persisted 15822 mSettings.writeAllUsersPackageRestrictionsLPr(); 15823 } 15824 // can downgrade to reader here 15825 if (writeSettings) { 15826 mSettings.writeLPr(); 15827 } 15828 } 15829 return true; 15830 } 15831 15832 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15833 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15834 PackageRemovedInfo outInfo, boolean writeSettings, 15835 PackageParser.Package replacingPackage) { 15836 synchronized (mPackages) { 15837 if (outInfo != null) { 15838 outInfo.uid = ps.appId; 15839 } 15840 15841 if (outInfo != null && outInfo.removedChildPackages != null) { 15842 final int childCount = (ps.childPackageNames != null) 15843 ? ps.childPackageNames.size() : 0; 15844 for (int i = 0; i < childCount; i++) { 15845 String childPackageName = ps.childPackageNames.get(i); 15846 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15847 if (childPs == null) { 15848 return false; 15849 } 15850 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15851 childPackageName); 15852 if (childInfo != null) { 15853 childInfo.uid = childPs.appId; 15854 } 15855 } 15856 } 15857 } 15858 15859 // Delete package data from internal structures and also remove data if flag is set 15860 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15861 15862 // Delete the child packages data 15863 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15864 for (int i = 0; i < childCount; i++) { 15865 PackageSetting childPs; 15866 synchronized (mPackages) { 15867 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15868 } 15869 if (childPs != null) { 15870 PackageRemovedInfo childOutInfo = (outInfo != null 15871 && outInfo.removedChildPackages != null) 15872 ? outInfo.removedChildPackages.get(childPs.name) : null; 15873 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15874 && (replacingPackage != null 15875 && !replacingPackage.hasChildPackage(childPs.name)) 15876 ? flags & ~DELETE_KEEP_DATA : flags; 15877 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15878 deleteFlags, writeSettings); 15879 } 15880 } 15881 15882 // Delete application code and resources only for parent packages 15883 if (ps.parentPackageName == null) { 15884 if (deleteCodeAndResources && (outInfo != null)) { 15885 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15886 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15887 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15888 } 15889 } 15890 15891 return true; 15892 } 15893 15894 @Override 15895 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15896 int userId) { 15897 mContext.enforceCallingOrSelfPermission( 15898 android.Manifest.permission.DELETE_PACKAGES, null); 15899 synchronized (mPackages) { 15900 PackageSetting ps = mSettings.mPackages.get(packageName); 15901 if (ps == null) { 15902 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15903 return false; 15904 } 15905 if (!ps.getInstalled(userId)) { 15906 // Can't block uninstall for an app that is not installed or enabled. 15907 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15908 return false; 15909 } 15910 ps.setBlockUninstall(blockUninstall, userId); 15911 mSettings.writePackageRestrictionsLPr(userId); 15912 } 15913 return true; 15914 } 15915 15916 @Override 15917 public boolean getBlockUninstallForUser(String packageName, int userId) { 15918 synchronized (mPackages) { 15919 PackageSetting ps = mSettings.mPackages.get(packageName); 15920 if (ps == null) { 15921 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15922 return false; 15923 } 15924 return ps.getBlockUninstall(userId); 15925 } 15926 } 15927 15928 @Override 15929 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15930 int callingUid = Binder.getCallingUid(); 15931 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15932 throw new SecurityException( 15933 "setRequiredForSystemUser can only be run by the system or root"); 15934 } 15935 synchronized (mPackages) { 15936 PackageSetting ps = mSettings.mPackages.get(packageName); 15937 if (ps == null) { 15938 Log.w(TAG, "Package doesn't exist: " + packageName); 15939 return false; 15940 } 15941 if (systemUserApp) { 15942 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15943 } else { 15944 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15945 } 15946 mSettings.writeLPr(); 15947 } 15948 return true; 15949 } 15950 15951 /* 15952 * This method handles package deletion in general 15953 */ 15954 private boolean deletePackageLIF(String packageName, UserHandle user, 15955 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15956 PackageRemovedInfo outInfo, boolean writeSettings, 15957 PackageParser.Package replacingPackage) { 15958 if (packageName == null) { 15959 Slog.w(TAG, "Attempt to delete null packageName."); 15960 return false; 15961 } 15962 15963 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15964 15965 PackageSetting ps; 15966 15967 synchronized (mPackages) { 15968 ps = mSettings.mPackages.get(packageName); 15969 if (ps == null) { 15970 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15971 return false; 15972 } 15973 15974 if (ps.parentPackageName != null && (!isSystemApp(ps) 15975 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15976 if (DEBUG_REMOVE) { 15977 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15978 + ((user == null) ? UserHandle.USER_ALL : user)); 15979 } 15980 final int removedUserId = (user != null) ? user.getIdentifier() 15981 : UserHandle.USER_ALL; 15982 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15983 return false; 15984 } 15985 markPackageUninstalledForUserLPw(ps, user); 15986 scheduleWritePackageRestrictionsLocked(user); 15987 return true; 15988 } 15989 } 15990 15991 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15992 && user.getIdentifier() != UserHandle.USER_ALL)) { 15993 // The caller is asking that the package only be deleted for a single 15994 // user. To do this, we just mark its uninstalled state and delete 15995 // its data. If this is a system app, we only allow this to happen if 15996 // they have set the special DELETE_SYSTEM_APP which requests different 15997 // semantics than normal for uninstalling system apps. 15998 markPackageUninstalledForUserLPw(ps, user); 15999 16000 if (!isSystemApp(ps)) { 16001 // Do not uninstall the APK if an app should be cached 16002 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16003 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16004 // Other user still have this package installed, so all 16005 // we need to do is clear this user's data and save that 16006 // it is uninstalled. 16007 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16008 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16009 return false; 16010 } 16011 scheduleWritePackageRestrictionsLocked(user); 16012 return true; 16013 } else { 16014 // We need to set it back to 'installed' so the uninstall 16015 // broadcasts will be sent correctly. 16016 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16017 ps.setInstalled(true, user.getIdentifier()); 16018 } 16019 } else { 16020 // This is a system app, so we assume that the 16021 // other users still have this package installed, so all 16022 // we need to do is clear this user's data and save that 16023 // it is uninstalled. 16024 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16025 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16026 return false; 16027 } 16028 scheduleWritePackageRestrictionsLocked(user); 16029 return true; 16030 } 16031 } 16032 16033 // If we are deleting a composite package for all users, keep track 16034 // of result for each child. 16035 if (ps.childPackageNames != null && outInfo != null) { 16036 synchronized (mPackages) { 16037 final int childCount = ps.childPackageNames.size(); 16038 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16039 for (int i = 0; i < childCount; i++) { 16040 String childPackageName = ps.childPackageNames.get(i); 16041 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16042 childInfo.removedPackage = childPackageName; 16043 outInfo.removedChildPackages.put(childPackageName, childInfo); 16044 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16045 if (childPs != null) { 16046 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16047 } 16048 } 16049 } 16050 } 16051 16052 boolean ret = false; 16053 if (isSystemApp(ps)) { 16054 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16055 // When an updated system application is deleted we delete the existing resources 16056 // as well and fall back to existing code in system partition 16057 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16058 } else { 16059 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16060 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16061 outInfo, writeSettings, replacingPackage); 16062 } 16063 16064 // Take a note whether we deleted the package for all users 16065 if (outInfo != null) { 16066 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16067 if (outInfo.removedChildPackages != null) { 16068 synchronized (mPackages) { 16069 final int childCount = outInfo.removedChildPackages.size(); 16070 for (int i = 0; i < childCount; i++) { 16071 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16072 if (childInfo != null) { 16073 childInfo.removedForAllUsers = mPackages.get( 16074 childInfo.removedPackage) == null; 16075 } 16076 } 16077 } 16078 } 16079 // If we uninstalled an update to a system app there may be some 16080 // child packages that appeared as they are declared in the system 16081 // app but were not declared in the update. 16082 if (isSystemApp(ps)) { 16083 synchronized (mPackages) { 16084 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16085 final int childCount = (updatedPs.childPackageNames != null) 16086 ? updatedPs.childPackageNames.size() : 0; 16087 for (int i = 0; i < childCount; i++) { 16088 String childPackageName = updatedPs.childPackageNames.get(i); 16089 if (outInfo.removedChildPackages == null 16090 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16091 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16092 if (childPs == null) { 16093 continue; 16094 } 16095 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16096 installRes.name = childPackageName; 16097 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16098 installRes.pkg = mPackages.get(childPackageName); 16099 installRes.uid = childPs.pkg.applicationInfo.uid; 16100 if (outInfo.appearedChildPackages == null) { 16101 outInfo.appearedChildPackages = new ArrayMap<>(); 16102 } 16103 outInfo.appearedChildPackages.put(childPackageName, installRes); 16104 } 16105 } 16106 } 16107 } 16108 } 16109 16110 return ret; 16111 } 16112 16113 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16114 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16115 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16116 for (int nextUserId : userIds) { 16117 if (DEBUG_REMOVE) { 16118 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16119 } 16120 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16121 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16122 false /*hidden*/, false /*suspended*/, null, null, null, 16123 false /*blockUninstall*/, 16124 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16125 } 16126 } 16127 16128 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16129 PackageRemovedInfo outInfo) { 16130 final PackageParser.Package pkg; 16131 synchronized (mPackages) { 16132 pkg = mPackages.get(ps.name); 16133 } 16134 16135 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16136 : new int[] {userId}; 16137 for (int nextUserId : userIds) { 16138 if (DEBUG_REMOVE) { 16139 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16140 + nextUserId); 16141 } 16142 16143 destroyAppDataLIF(pkg, userId, 16144 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16145 destroyAppProfilesLIF(pkg, userId); 16146 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16147 schedulePackageCleaning(ps.name, nextUserId, false); 16148 synchronized (mPackages) { 16149 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16150 scheduleWritePackageRestrictionsLocked(nextUserId); 16151 } 16152 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16153 } 16154 } 16155 16156 if (outInfo != null) { 16157 outInfo.removedPackage = ps.name; 16158 outInfo.removedAppId = ps.appId; 16159 outInfo.removedUsers = userIds; 16160 } 16161 16162 return true; 16163 } 16164 16165 private final class ClearStorageConnection implements ServiceConnection { 16166 IMediaContainerService mContainerService; 16167 16168 @Override 16169 public void onServiceConnected(ComponentName name, IBinder service) { 16170 synchronized (this) { 16171 mContainerService = IMediaContainerService.Stub.asInterface(service); 16172 notifyAll(); 16173 } 16174 } 16175 16176 @Override 16177 public void onServiceDisconnected(ComponentName name) { 16178 } 16179 } 16180 16181 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16182 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16183 16184 final boolean mounted; 16185 if (Environment.isExternalStorageEmulated()) { 16186 mounted = true; 16187 } else { 16188 final String status = Environment.getExternalStorageState(); 16189 16190 mounted = status.equals(Environment.MEDIA_MOUNTED) 16191 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16192 } 16193 16194 if (!mounted) { 16195 return; 16196 } 16197 16198 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16199 int[] users; 16200 if (userId == UserHandle.USER_ALL) { 16201 users = sUserManager.getUserIds(); 16202 } else { 16203 users = new int[] { userId }; 16204 } 16205 final ClearStorageConnection conn = new ClearStorageConnection(); 16206 if (mContext.bindServiceAsUser( 16207 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16208 try { 16209 for (int curUser : users) { 16210 long timeout = SystemClock.uptimeMillis() + 5000; 16211 synchronized (conn) { 16212 long now = SystemClock.uptimeMillis(); 16213 while (conn.mContainerService == null && now < timeout) { 16214 try { 16215 conn.wait(timeout - now); 16216 } catch (InterruptedException e) { 16217 } 16218 } 16219 } 16220 if (conn.mContainerService == null) { 16221 return; 16222 } 16223 16224 final UserEnvironment userEnv = new UserEnvironment(curUser); 16225 clearDirectory(conn.mContainerService, 16226 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16227 if (allData) { 16228 clearDirectory(conn.mContainerService, 16229 userEnv.buildExternalStorageAppDataDirs(packageName)); 16230 clearDirectory(conn.mContainerService, 16231 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16232 } 16233 } 16234 } finally { 16235 mContext.unbindService(conn); 16236 } 16237 } 16238 } 16239 16240 @Override 16241 public void clearApplicationProfileData(String packageName) { 16242 enforceSystemOrRoot("Only the system can clear all profile data"); 16243 16244 final PackageParser.Package pkg; 16245 synchronized (mPackages) { 16246 pkg = mPackages.get(packageName); 16247 } 16248 16249 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16250 synchronized (mInstallLock) { 16251 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16252 } 16253 } 16254 } 16255 16256 @Override 16257 public void clearApplicationUserData(final String packageName, 16258 final IPackageDataObserver observer, final int userId) { 16259 mContext.enforceCallingOrSelfPermission( 16260 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16261 16262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16263 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16264 16265 final DevicePolicyManagerInternal dpmi = LocalServices 16266 .getService(DevicePolicyManagerInternal.class); 16267 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16268 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16269 } 16270 // Queue up an async operation since the package deletion may take a little while. 16271 mHandler.post(new Runnable() { 16272 public void run() { 16273 mHandler.removeCallbacks(this); 16274 final boolean succeeded; 16275 try (PackageFreezer freezer = freezePackage(packageName, 16276 "clearApplicationUserData")) { 16277 synchronized (mInstallLock) { 16278 succeeded = clearApplicationUserDataLIF(packageName, userId); 16279 } 16280 clearExternalStorageDataSync(packageName, userId, true); 16281 } 16282 if (succeeded) { 16283 // invoke DeviceStorageMonitor's update method to clear any notifications 16284 DeviceStorageMonitorInternal dsm = LocalServices 16285 .getService(DeviceStorageMonitorInternal.class); 16286 if (dsm != null) { 16287 dsm.checkMemory(); 16288 } 16289 } 16290 if(observer != null) { 16291 try { 16292 observer.onRemoveCompleted(packageName, succeeded); 16293 } catch (RemoteException e) { 16294 Log.i(TAG, "Observer no longer exists."); 16295 } 16296 } //end if observer 16297 } //end run 16298 }); 16299 } 16300 16301 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16302 if (packageName == null) { 16303 Slog.w(TAG, "Attempt to delete null packageName."); 16304 return false; 16305 } 16306 16307 // Try finding details about the requested package 16308 PackageParser.Package pkg; 16309 synchronized (mPackages) { 16310 pkg = mPackages.get(packageName); 16311 if (pkg == null) { 16312 final PackageSetting ps = mSettings.mPackages.get(packageName); 16313 if (ps != null) { 16314 pkg = ps.pkg; 16315 } 16316 } 16317 16318 if (pkg == null) { 16319 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16320 return false; 16321 } 16322 16323 PackageSetting ps = (PackageSetting) pkg.mExtras; 16324 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16325 } 16326 16327 clearAppDataLIF(pkg, userId, 16328 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16329 16330 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16331 removeKeystoreDataIfNeeded(userId, appId); 16332 16333 UserManagerInternal umInternal = getUserManagerInternal(); 16334 final int flags; 16335 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16336 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16337 } else if (umInternal.isUserRunning(userId)) { 16338 flags = StorageManager.FLAG_STORAGE_DE; 16339 } else { 16340 flags = 0; 16341 } 16342 prepareAppDataContentsLIF(pkg, userId, flags); 16343 16344 return true; 16345 } 16346 16347 /** 16348 * Reverts user permission state changes (permissions and flags) in 16349 * all packages for a given user. 16350 * 16351 * @param userId The device user for which to do a reset. 16352 */ 16353 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16354 final int packageCount = mPackages.size(); 16355 for (int i = 0; i < packageCount; i++) { 16356 PackageParser.Package pkg = mPackages.valueAt(i); 16357 PackageSetting ps = (PackageSetting) pkg.mExtras; 16358 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16359 } 16360 } 16361 16362 private void resetNetworkPolicies(int userId) { 16363 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16364 } 16365 16366 /** 16367 * Reverts user permission state changes (permissions and flags). 16368 * 16369 * @param ps The package for which to reset. 16370 * @param userId The device user for which to do a reset. 16371 */ 16372 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16373 final PackageSetting ps, final int userId) { 16374 if (ps.pkg == null) { 16375 return; 16376 } 16377 16378 // These are flags that can change base on user actions. 16379 final int userSettableMask = FLAG_PERMISSION_USER_SET 16380 | FLAG_PERMISSION_USER_FIXED 16381 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16382 | FLAG_PERMISSION_REVIEW_REQUIRED; 16383 16384 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16385 | FLAG_PERMISSION_POLICY_FIXED; 16386 16387 boolean writeInstallPermissions = false; 16388 boolean writeRuntimePermissions = false; 16389 16390 final int permissionCount = ps.pkg.requestedPermissions.size(); 16391 for (int i = 0; i < permissionCount; i++) { 16392 String permission = ps.pkg.requestedPermissions.get(i); 16393 16394 BasePermission bp = mSettings.mPermissions.get(permission); 16395 if (bp == null) { 16396 continue; 16397 } 16398 16399 // If shared user we just reset the state to which only this app contributed. 16400 if (ps.sharedUser != null) { 16401 boolean used = false; 16402 final int packageCount = ps.sharedUser.packages.size(); 16403 for (int j = 0; j < packageCount; j++) { 16404 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16405 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16406 && pkg.pkg.requestedPermissions.contains(permission)) { 16407 used = true; 16408 break; 16409 } 16410 } 16411 if (used) { 16412 continue; 16413 } 16414 } 16415 16416 PermissionsState permissionsState = ps.getPermissionsState(); 16417 16418 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16419 16420 // Always clear the user settable flags. 16421 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16422 bp.name) != null; 16423 // If permission review is enabled and this is a legacy app, mark the 16424 // permission as requiring a review as this is the initial state. 16425 int flags = 0; 16426 if (Build.PERMISSIONS_REVIEW_REQUIRED 16427 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16428 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16429 } 16430 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16431 if (hasInstallState) { 16432 writeInstallPermissions = true; 16433 } else { 16434 writeRuntimePermissions = true; 16435 } 16436 } 16437 16438 // Below is only runtime permission handling. 16439 if (!bp.isRuntime()) { 16440 continue; 16441 } 16442 16443 // Never clobber system or policy. 16444 if ((oldFlags & policyOrSystemFlags) != 0) { 16445 continue; 16446 } 16447 16448 // If this permission was granted by default, make sure it is. 16449 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16450 if (permissionsState.grantRuntimePermission(bp, userId) 16451 != PERMISSION_OPERATION_FAILURE) { 16452 writeRuntimePermissions = true; 16453 } 16454 // If permission review is enabled the permissions for a legacy apps 16455 // are represented as constantly granted runtime ones, so don't revoke. 16456 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16457 // Otherwise, reset the permission. 16458 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16459 switch (revokeResult) { 16460 case PERMISSION_OPERATION_SUCCESS: 16461 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16462 writeRuntimePermissions = true; 16463 final int appId = ps.appId; 16464 mHandler.post(new Runnable() { 16465 @Override 16466 public void run() { 16467 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16468 } 16469 }); 16470 } break; 16471 } 16472 } 16473 } 16474 16475 // Synchronously write as we are taking permissions away. 16476 if (writeRuntimePermissions) { 16477 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16478 } 16479 16480 // Synchronously write as we are taking permissions away. 16481 if (writeInstallPermissions) { 16482 mSettings.writeLPr(); 16483 } 16484 } 16485 16486 /** 16487 * Remove entries from the keystore daemon. Will only remove it if the 16488 * {@code appId} is valid. 16489 */ 16490 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16491 if (appId < 0) { 16492 return; 16493 } 16494 16495 final KeyStore keyStore = KeyStore.getInstance(); 16496 if (keyStore != null) { 16497 if (userId == UserHandle.USER_ALL) { 16498 for (final int individual : sUserManager.getUserIds()) { 16499 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16500 } 16501 } else { 16502 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16503 } 16504 } else { 16505 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16506 } 16507 } 16508 16509 @Override 16510 public void deleteApplicationCacheFiles(final String packageName, 16511 final IPackageDataObserver observer) { 16512 final int userId = UserHandle.getCallingUserId(); 16513 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16514 } 16515 16516 @Override 16517 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16518 final IPackageDataObserver observer) { 16519 mContext.enforceCallingOrSelfPermission( 16520 android.Manifest.permission.DELETE_CACHE_FILES, null); 16521 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16522 /* requireFullPermission= */ true, /* checkShell= */ false, 16523 "delete application cache files"); 16524 16525 final PackageParser.Package pkg; 16526 synchronized (mPackages) { 16527 pkg = mPackages.get(packageName); 16528 } 16529 16530 // Queue up an async operation since the package deletion may take a little while. 16531 mHandler.post(new Runnable() { 16532 public void run() { 16533 synchronized (mInstallLock) { 16534 final int flags = StorageManager.FLAG_STORAGE_DE 16535 | StorageManager.FLAG_STORAGE_CE; 16536 // We're only clearing cache files, so we don't care if the 16537 // app is unfrozen and still able to run 16538 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16539 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16540 } 16541 clearExternalStorageDataSync(packageName, userId, false); 16542 if (observer != null) { 16543 try { 16544 observer.onRemoveCompleted(packageName, true); 16545 } catch (RemoteException e) { 16546 Log.i(TAG, "Observer no longer exists."); 16547 } 16548 } 16549 } 16550 }); 16551 } 16552 16553 @Override 16554 public void getPackageSizeInfo(final String packageName, int userHandle, 16555 final IPackageStatsObserver observer) { 16556 mContext.enforceCallingOrSelfPermission( 16557 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16558 if (packageName == null) { 16559 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16560 } 16561 16562 PackageStats stats = new PackageStats(packageName, userHandle); 16563 16564 /* 16565 * Queue up an async operation since the package measurement may take a 16566 * little while. 16567 */ 16568 Message msg = mHandler.obtainMessage(INIT_COPY); 16569 msg.obj = new MeasureParams(stats, observer); 16570 mHandler.sendMessage(msg); 16571 } 16572 16573 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16574 final PackageSetting ps; 16575 synchronized (mPackages) { 16576 ps = mSettings.mPackages.get(packageName); 16577 if (ps == null) { 16578 Slog.w(TAG, "Failed to find settings for " + packageName); 16579 return false; 16580 } 16581 } 16582 try { 16583 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16584 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16585 ps.getCeDataInode(userId), ps.codePathString, stats); 16586 } catch (InstallerException e) { 16587 Slog.w(TAG, String.valueOf(e)); 16588 return false; 16589 } 16590 16591 // For now, ignore code size of packages on system partition 16592 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16593 stats.codeSize = 0; 16594 } 16595 16596 return true; 16597 } 16598 16599 private int getUidTargetSdkVersionLockedLPr(int uid) { 16600 Object obj = mSettings.getUserIdLPr(uid); 16601 if (obj instanceof SharedUserSetting) { 16602 final SharedUserSetting sus = (SharedUserSetting) obj; 16603 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16604 final Iterator<PackageSetting> it = sus.packages.iterator(); 16605 while (it.hasNext()) { 16606 final PackageSetting ps = it.next(); 16607 if (ps.pkg != null) { 16608 int v = ps.pkg.applicationInfo.targetSdkVersion; 16609 if (v < vers) vers = v; 16610 } 16611 } 16612 return vers; 16613 } else if (obj instanceof PackageSetting) { 16614 final PackageSetting ps = (PackageSetting) obj; 16615 if (ps.pkg != null) { 16616 return ps.pkg.applicationInfo.targetSdkVersion; 16617 } 16618 } 16619 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16620 } 16621 16622 @Override 16623 public void addPreferredActivity(IntentFilter filter, int match, 16624 ComponentName[] set, ComponentName activity, int userId) { 16625 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16626 "Adding preferred"); 16627 } 16628 16629 private void addPreferredActivityInternal(IntentFilter filter, int match, 16630 ComponentName[] set, ComponentName activity, boolean always, int userId, 16631 String opname) { 16632 // writer 16633 int callingUid = Binder.getCallingUid(); 16634 enforceCrossUserPermission(callingUid, userId, 16635 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16636 if (filter.countActions() == 0) { 16637 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16638 return; 16639 } 16640 synchronized (mPackages) { 16641 if (mContext.checkCallingOrSelfPermission( 16642 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16643 != PackageManager.PERMISSION_GRANTED) { 16644 if (getUidTargetSdkVersionLockedLPr(callingUid) 16645 < Build.VERSION_CODES.FROYO) { 16646 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16647 + callingUid); 16648 return; 16649 } 16650 mContext.enforceCallingOrSelfPermission( 16651 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16652 } 16653 16654 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16655 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16656 + userId + ":"); 16657 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16658 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16659 scheduleWritePackageRestrictionsLocked(userId); 16660 } 16661 } 16662 16663 @Override 16664 public void replacePreferredActivity(IntentFilter filter, int match, 16665 ComponentName[] set, ComponentName activity, int userId) { 16666 if (filter.countActions() != 1) { 16667 throw new IllegalArgumentException( 16668 "replacePreferredActivity expects filter to have only 1 action."); 16669 } 16670 if (filter.countDataAuthorities() != 0 16671 || filter.countDataPaths() != 0 16672 || filter.countDataSchemes() > 1 16673 || filter.countDataTypes() != 0) { 16674 throw new IllegalArgumentException( 16675 "replacePreferredActivity expects filter to have no data authorities, " + 16676 "paths, or types; and at most one scheme."); 16677 } 16678 16679 final int callingUid = Binder.getCallingUid(); 16680 enforceCrossUserPermission(callingUid, userId, 16681 true /* requireFullPermission */, false /* checkShell */, 16682 "replace preferred activity"); 16683 synchronized (mPackages) { 16684 if (mContext.checkCallingOrSelfPermission( 16685 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16686 != PackageManager.PERMISSION_GRANTED) { 16687 if (getUidTargetSdkVersionLockedLPr(callingUid) 16688 < Build.VERSION_CODES.FROYO) { 16689 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16690 + Binder.getCallingUid()); 16691 return; 16692 } 16693 mContext.enforceCallingOrSelfPermission( 16694 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16695 } 16696 16697 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16698 if (pir != null) { 16699 // Get all of the existing entries that exactly match this filter. 16700 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16701 if (existing != null && existing.size() == 1) { 16702 PreferredActivity cur = existing.get(0); 16703 if (DEBUG_PREFERRED) { 16704 Slog.i(TAG, "Checking replace of preferred:"); 16705 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16706 if (!cur.mPref.mAlways) { 16707 Slog.i(TAG, " -- CUR; not mAlways!"); 16708 } else { 16709 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16710 Slog.i(TAG, " -- CUR: mSet=" 16711 + Arrays.toString(cur.mPref.mSetComponents)); 16712 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16713 Slog.i(TAG, " -- NEW: mMatch=" 16714 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16715 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16716 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16717 } 16718 } 16719 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16720 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16721 && cur.mPref.sameSet(set)) { 16722 // Setting the preferred activity to what it happens to be already 16723 if (DEBUG_PREFERRED) { 16724 Slog.i(TAG, "Replacing with same preferred activity " 16725 + cur.mPref.mShortComponent + " for user " 16726 + userId + ":"); 16727 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16728 } 16729 return; 16730 } 16731 } 16732 16733 if (existing != null) { 16734 if (DEBUG_PREFERRED) { 16735 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16736 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16737 } 16738 for (int i = 0; i < existing.size(); i++) { 16739 PreferredActivity pa = existing.get(i); 16740 if (DEBUG_PREFERRED) { 16741 Slog.i(TAG, "Removing existing preferred activity " 16742 + pa.mPref.mComponent + ":"); 16743 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16744 } 16745 pir.removeFilter(pa); 16746 } 16747 } 16748 } 16749 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16750 "Replacing preferred"); 16751 } 16752 } 16753 16754 @Override 16755 public void clearPackagePreferredActivities(String packageName) { 16756 final int uid = Binder.getCallingUid(); 16757 // writer 16758 synchronized (mPackages) { 16759 PackageParser.Package pkg = mPackages.get(packageName); 16760 if (pkg == null || pkg.applicationInfo.uid != uid) { 16761 if (mContext.checkCallingOrSelfPermission( 16762 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16763 != PackageManager.PERMISSION_GRANTED) { 16764 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16765 < Build.VERSION_CODES.FROYO) { 16766 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16767 + Binder.getCallingUid()); 16768 return; 16769 } 16770 mContext.enforceCallingOrSelfPermission( 16771 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16772 } 16773 } 16774 16775 int user = UserHandle.getCallingUserId(); 16776 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16777 scheduleWritePackageRestrictionsLocked(user); 16778 } 16779 } 16780 } 16781 16782 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16783 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16784 ArrayList<PreferredActivity> removed = null; 16785 boolean changed = false; 16786 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16787 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16788 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16789 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16790 continue; 16791 } 16792 Iterator<PreferredActivity> it = pir.filterIterator(); 16793 while (it.hasNext()) { 16794 PreferredActivity pa = it.next(); 16795 // Mark entry for removal only if it matches the package name 16796 // and the entry is of type "always". 16797 if (packageName == null || 16798 (pa.mPref.mComponent.getPackageName().equals(packageName) 16799 && pa.mPref.mAlways)) { 16800 if (removed == null) { 16801 removed = new ArrayList<PreferredActivity>(); 16802 } 16803 removed.add(pa); 16804 } 16805 } 16806 if (removed != null) { 16807 for (int j=0; j<removed.size(); j++) { 16808 PreferredActivity pa = removed.get(j); 16809 pir.removeFilter(pa); 16810 } 16811 changed = true; 16812 } 16813 } 16814 return changed; 16815 } 16816 16817 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16818 private void clearIntentFilterVerificationsLPw(int userId) { 16819 final int packageCount = mPackages.size(); 16820 for (int i = 0; i < packageCount; i++) { 16821 PackageParser.Package pkg = mPackages.valueAt(i); 16822 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16823 } 16824 } 16825 16826 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16827 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16828 if (userId == UserHandle.USER_ALL) { 16829 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16830 sUserManager.getUserIds())) { 16831 for (int oneUserId : sUserManager.getUserIds()) { 16832 scheduleWritePackageRestrictionsLocked(oneUserId); 16833 } 16834 } 16835 } else { 16836 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16837 scheduleWritePackageRestrictionsLocked(userId); 16838 } 16839 } 16840 } 16841 16842 void clearDefaultBrowserIfNeeded(String packageName) { 16843 for (int oneUserId : sUserManager.getUserIds()) { 16844 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16845 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16846 if (packageName.equals(defaultBrowserPackageName)) { 16847 setDefaultBrowserPackageName(null, oneUserId); 16848 } 16849 } 16850 } 16851 16852 @Override 16853 public void resetApplicationPreferences(int userId) { 16854 mContext.enforceCallingOrSelfPermission( 16855 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16856 final long identity = Binder.clearCallingIdentity(); 16857 // writer 16858 try { 16859 synchronized (mPackages) { 16860 clearPackagePreferredActivitiesLPw(null, userId); 16861 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16862 // TODO: We have to reset the default SMS and Phone. This requires 16863 // significant refactoring to keep all default apps in the package 16864 // manager (cleaner but more work) or have the services provide 16865 // callbacks to the package manager to request a default app reset. 16866 applyFactoryDefaultBrowserLPw(userId); 16867 clearIntentFilterVerificationsLPw(userId); 16868 primeDomainVerificationsLPw(userId); 16869 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16870 scheduleWritePackageRestrictionsLocked(userId); 16871 } 16872 resetNetworkPolicies(userId); 16873 } finally { 16874 Binder.restoreCallingIdentity(identity); 16875 } 16876 } 16877 16878 @Override 16879 public int getPreferredActivities(List<IntentFilter> outFilters, 16880 List<ComponentName> outActivities, String packageName) { 16881 16882 int num = 0; 16883 final int userId = UserHandle.getCallingUserId(); 16884 // reader 16885 synchronized (mPackages) { 16886 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16887 if (pir != null) { 16888 final Iterator<PreferredActivity> it = pir.filterIterator(); 16889 while (it.hasNext()) { 16890 final PreferredActivity pa = it.next(); 16891 if (packageName == null 16892 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16893 && pa.mPref.mAlways)) { 16894 if (outFilters != null) { 16895 outFilters.add(new IntentFilter(pa)); 16896 } 16897 if (outActivities != null) { 16898 outActivities.add(pa.mPref.mComponent); 16899 } 16900 } 16901 } 16902 } 16903 } 16904 16905 return num; 16906 } 16907 16908 @Override 16909 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16910 int userId) { 16911 int callingUid = Binder.getCallingUid(); 16912 if (callingUid != Process.SYSTEM_UID) { 16913 throw new SecurityException( 16914 "addPersistentPreferredActivity can only be run by the system"); 16915 } 16916 if (filter.countActions() == 0) { 16917 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16918 return; 16919 } 16920 synchronized (mPackages) { 16921 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16922 ":"); 16923 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16924 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16925 new PersistentPreferredActivity(filter, activity)); 16926 scheduleWritePackageRestrictionsLocked(userId); 16927 } 16928 } 16929 16930 @Override 16931 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16932 int callingUid = Binder.getCallingUid(); 16933 if (callingUid != Process.SYSTEM_UID) { 16934 throw new SecurityException( 16935 "clearPackagePersistentPreferredActivities can only be run by the system"); 16936 } 16937 ArrayList<PersistentPreferredActivity> removed = null; 16938 boolean changed = false; 16939 synchronized (mPackages) { 16940 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16941 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16942 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16943 .valueAt(i); 16944 if (userId != thisUserId) { 16945 continue; 16946 } 16947 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16948 while (it.hasNext()) { 16949 PersistentPreferredActivity ppa = it.next(); 16950 // Mark entry for removal only if it matches the package name. 16951 if (ppa.mComponent.getPackageName().equals(packageName)) { 16952 if (removed == null) { 16953 removed = new ArrayList<PersistentPreferredActivity>(); 16954 } 16955 removed.add(ppa); 16956 } 16957 } 16958 if (removed != null) { 16959 for (int j=0; j<removed.size(); j++) { 16960 PersistentPreferredActivity ppa = removed.get(j); 16961 ppir.removeFilter(ppa); 16962 } 16963 changed = true; 16964 } 16965 } 16966 16967 if (changed) { 16968 scheduleWritePackageRestrictionsLocked(userId); 16969 } 16970 } 16971 } 16972 16973 /** 16974 * Common machinery for picking apart a restored XML blob and passing 16975 * it to a caller-supplied functor to be applied to the running system. 16976 */ 16977 private void restoreFromXml(XmlPullParser parser, int userId, 16978 String expectedStartTag, BlobXmlRestorer functor) 16979 throws IOException, XmlPullParserException { 16980 int type; 16981 while ((type = parser.next()) != XmlPullParser.START_TAG 16982 && type != XmlPullParser.END_DOCUMENT) { 16983 } 16984 if (type != XmlPullParser.START_TAG) { 16985 // oops didn't find a start tag?! 16986 if (DEBUG_BACKUP) { 16987 Slog.e(TAG, "Didn't find start tag during restore"); 16988 } 16989 return; 16990 } 16991Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16992 // this is supposed to be TAG_PREFERRED_BACKUP 16993 if (!expectedStartTag.equals(parser.getName())) { 16994 if (DEBUG_BACKUP) { 16995 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16996 } 16997 return; 16998 } 16999 17000 // skip interfering stuff, then we're aligned with the backing implementation 17001 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17002Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17003 functor.apply(parser, userId); 17004 } 17005 17006 private interface BlobXmlRestorer { 17007 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17008 } 17009 17010 /** 17011 * Non-Binder method, support for the backup/restore mechanism: write the 17012 * full set of preferred activities in its canonical XML format. Returns the 17013 * XML output as a byte array, or null if there is none. 17014 */ 17015 @Override 17016 public byte[] getPreferredActivityBackup(int userId) { 17017 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17018 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17019 } 17020 17021 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17022 try { 17023 final XmlSerializer serializer = new FastXmlSerializer(); 17024 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17025 serializer.startDocument(null, true); 17026 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17027 17028 synchronized (mPackages) { 17029 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17030 } 17031 17032 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17033 serializer.endDocument(); 17034 serializer.flush(); 17035 } catch (Exception e) { 17036 if (DEBUG_BACKUP) { 17037 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17038 } 17039 return null; 17040 } 17041 17042 return dataStream.toByteArray(); 17043 } 17044 17045 @Override 17046 public void restorePreferredActivities(byte[] backup, int userId) { 17047 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17048 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17049 } 17050 17051 try { 17052 final XmlPullParser parser = Xml.newPullParser(); 17053 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17054 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17055 new BlobXmlRestorer() { 17056 @Override 17057 public void apply(XmlPullParser parser, int userId) 17058 throws XmlPullParserException, IOException { 17059 synchronized (mPackages) { 17060 mSettings.readPreferredActivitiesLPw(parser, userId); 17061 } 17062 } 17063 } ); 17064 } catch (Exception e) { 17065 if (DEBUG_BACKUP) { 17066 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17067 } 17068 } 17069 } 17070 17071 /** 17072 * Non-Binder method, support for the backup/restore mechanism: write the 17073 * default browser (etc) settings in its canonical XML format. Returns the default 17074 * browser XML representation as a byte array, or null if there is none. 17075 */ 17076 @Override 17077 public byte[] getDefaultAppsBackup(int userId) { 17078 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17079 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17080 } 17081 17082 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17083 try { 17084 final XmlSerializer serializer = new FastXmlSerializer(); 17085 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17086 serializer.startDocument(null, true); 17087 serializer.startTag(null, TAG_DEFAULT_APPS); 17088 17089 synchronized (mPackages) { 17090 mSettings.writeDefaultAppsLPr(serializer, userId); 17091 } 17092 17093 serializer.endTag(null, TAG_DEFAULT_APPS); 17094 serializer.endDocument(); 17095 serializer.flush(); 17096 } catch (Exception e) { 17097 if (DEBUG_BACKUP) { 17098 Slog.e(TAG, "Unable to write default apps for backup", e); 17099 } 17100 return null; 17101 } 17102 17103 return dataStream.toByteArray(); 17104 } 17105 17106 @Override 17107 public void restoreDefaultApps(byte[] backup, int userId) { 17108 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17109 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17110 } 17111 17112 try { 17113 final XmlPullParser parser = Xml.newPullParser(); 17114 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17115 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17116 new BlobXmlRestorer() { 17117 @Override 17118 public void apply(XmlPullParser parser, int userId) 17119 throws XmlPullParserException, IOException { 17120 synchronized (mPackages) { 17121 mSettings.readDefaultAppsLPw(parser, userId); 17122 } 17123 } 17124 } ); 17125 } catch (Exception e) { 17126 if (DEBUG_BACKUP) { 17127 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17128 } 17129 } 17130 } 17131 17132 @Override 17133 public byte[] getIntentFilterVerificationBackup(int userId) { 17134 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17135 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17136 } 17137 17138 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17139 try { 17140 final XmlSerializer serializer = new FastXmlSerializer(); 17141 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17142 serializer.startDocument(null, true); 17143 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17144 17145 synchronized (mPackages) { 17146 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17147 } 17148 17149 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17150 serializer.endDocument(); 17151 serializer.flush(); 17152 } catch (Exception e) { 17153 if (DEBUG_BACKUP) { 17154 Slog.e(TAG, "Unable to write default apps for backup", e); 17155 } 17156 return null; 17157 } 17158 17159 return dataStream.toByteArray(); 17160 } 17161 17162 @Override 17163 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17164 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17165 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17166 } 17167 17168 try { 17169 final XmlPullParser parser = Xml.newPullParser(); 17170 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17171 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17172 new BlobXmlRestorer() { 17173 @Override 17174 public void apply(XmlPullParser parser, int userId) 17175 throws XmlPullParserException, IOException { 17176 synchronized (mPackages) { 17177 mSettings.readAllDomainVerificationsLPr(parser, userId); 17178 mSettings.writeLPr(); 17179 } 17180 } 17181 } ); 17182 } catch (Exception e) { 17183 if (DEBUG_BACKUP) { 17184 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17185 } 17186 } 17187 } 17188 17189 @Override 17190 public byte[] getPermissionGrantBackup(int userId) { 17191 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17192 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17193 } 17194 17195 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17196 try { 17197 final XmlSerializer serializer = new FastXmlSerializer(); 17198 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17199 serializer.startDocument(null, true); 17200 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17201 17202 synchronized (mPackages) { 17203 serializeRuntimePermissionGrantsLPr(serializer, userId); 17204 } 17205 17206 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17207 serializer.endDocument(); 17208 serializer.flush(); 17209 } catch (Exception e) { 17210 if (DEBUG_BACKUP) { 17211 Slog.e(TAG, "Unable to write default apps for backup", e); 17212 } 17213 return null; 17214 } 17215 17216 return dataStream.toByteArray(); 17217 } 17218 17219 @Override 17220 public void restorePermissionGrants(byte[] backup, int userId) { 17221 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17222 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17223 } 17224 17225 try { 17226 final XmlPullParser parser = Xml.newPullParser(); 17227 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17228 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17229 new BlobXmlRestorer() { 17230 @Override 17231 public void apply(XmlPullParser parser, int userId) 17232 throws XmlPullParserException, IOException { 17233 synchronized (mPackages) { 17234 processRestoredPermissionGrantsLPr(parser, userId); 17235 } 17236 } 17237 } ); 17238 } catch (Exception e) { 17239 if (DEBUG_BACKUP) { 17240 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17241 } 17242 } 17243 } 17244 17245 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17246 throws IOException { 17247 serializer.startTag(null, TAG_ALL_GRANTS); 17248 17249 final int N = mSettings.mPackages.size(); 17250 for (int i = 0; i < N; i++) { 17251 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17252 boolean pkgGrantsKnown = false; 17253 17254 PermissionsState packagePerms = ps.getPermissionsState(); 17255 17256 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17257 final int grantFlags = state.getFlags(); 17258 // only look at grants that are not system/policy fixed 17259 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17260 final boolean isGranted = state.isGranted(); 17261 // And only back up the user-twiddled state bits 17262 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17263 final String packageName = mSettings.mPackages.keyAt(i); 17264 if (!pkgGrantsKnown) { 17265 serializer.startTag(null, TAG_GRANT); 17266 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17267 pkgGrantsKnown = true; 17268 } 17269 17270 final boolean userSet = 17271 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17272 final boolean userFixed = 17273 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17274 final boolean revoke = 17275 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17276 17277 serializer.startTag(null, TAG_PERMISSION); 17278 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17279 if (isGranted) { 17280 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17281 } 17282 if (userSet) { 17283 serializer.attribute(null, ATTR_USER_SET, "true"); 17284 } 17285 if (userFixed) { 17286 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17287 } 17288 if (revoke) { 17289 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17290 } 17291 serializer.endTag(null, TAG_PERMISSION); 17292 } 17293 } 17294 } 17295 17296 if (pkgGrantsKnown) { 17297 serializer.endTag(null, TAG_GRANT); 17298 } 17299 } 17300 17301 serializer.endTag(null, TAG_ALL_GRANTS); 17302 } 17303 17304 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17305 throws XmlPullParserException, IOException { 17306 String pkgName = null; 17307 int outerDepth = parser.getDepth(); 17308 int type; 17309 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17310 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17311 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17312 continue; 17313 } 17314 17315 final String tagName = parser.getName(); 17316 if (tagName.equals(TAG_GRANT)) { 17317 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17318 if (DEBUG_BACKUP) { 17319 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17320 } 17321 } else if (tagName.equals(TAG_PERMISSION)) { 17322 17323 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17324 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17325 17326 int newFlagSet = 0; 17327 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17328 newFlagSet |= FLAG_PERMISSION_USER_SET; 17329 } 17330 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17331 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17332 } 17333 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17334 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17335 } 17336 if (DEBUG_BACKUP) { 17337 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17338 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17339 } 17340 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17341 if (ps != null) { 17342 // Already installed so we apply the grant immediately 17343 if (DEBUG_BACKUP) { 17344 Slog.v(TAG, " + already installed; applying"); 17345 } 17346 PermissionsState perms = ps.getPermissionsState(); 17347 BasePermission bp = mSettings.mPermissions.get(permName); 17348 if (bp != null) { 17349 if (isGranted) { 17350 perms.grantRuntimePermission(bp, userId); 17351 } 17352 if (newFlagSet != 0) { 17353 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17354 } 17355 } 17356 } else { 17357 // Need to wait for post-restore install to apply the grant 17358 if (DEBUG_BACKUP) { 17359 Slog.v(TAG, " - not yet installed; saving for later"); 17360 } 17361 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17362 isGranted, newFlagSet, userId); 17363 } 17364 } else { 17365 PackageManagerService.reportSettingsProblem(Log.WARN, 17366 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17367 XmlUtils.skipCurrentTag(parser); 17368 } 17369 } 17370 17371 scheduleWriteSettingsLocked(); 17372 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17373 } 17374 17375 @Override 17376 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17377 int sourceUserId, int targetUserId, int flags) { 17378 mContext.enforceCallingOrSelfPermission( 17379 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17380 int callingUid = Binder.getCallingUid(); 17381 enforceOwnerRights(ownerPackage, callingUid); 17382 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17383 if (intentFilter.countActions() == 0) { 17384 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17385 return; 17386 } 17387 synchronized (mPackages) { 17388 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17389 ownerPackage, targetUserId, flags); 17390 CrossProfileIntentResolver resolver = 17391 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17392 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17393 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17394 if (existing != null) { 17395 int size = existing.size(); 17396 for (int i = 0; i < size; i++) { 17397 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17398 return; 17399 } 17400 } 17401 } 17402 resolver.addFilter(newFilter); 17403 scheduleWritePackageRestrictionsLocked(sourceUserId); 17404 } 17405 } 17406 17407 @Override 17408 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17409 mContext.enforceCallingOrSelfPermission( 17410 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17411 int callingUid = Binder.getCallingUid(); 17412 enforceOwnerRights(ownerPackage, callingUid); 17413 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17414 synchronized (mPackages) { 17415 CrossProfileIntentResolver resolver = 17416 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17417 ArraySet<CrossProfileIntentFilter> set = 17418 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17419 for (CrossProfileIntentFilter filter : set) { 17420 if (filter.getOwnerPackage().equals(ownerPackage)) { 17421 resolver.removeFilter(filter); 17422 } 17423 } 17424 scheduleWritePackageRestrictionsLocked(sourceUserId); 17425 } 17426 } 17427 17428 // Enforcing that callingUid is owning pkg on userId 17429 private void enforceOwnerRights(String pkg, int callingUid) { 17430 // The system owns everything. 17431 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17432 return; 17433 } 17434 int callingUserId = UserHandle.getUserId(callingUid); 17435 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17436 if (pi == null) { 17437 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17438 + callingUserId); 17439 } 17440 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17441 throw new SecurityException("Calling uid " + callingUid 17442 + " does not own package " + pkg); 17443 } 17444 } 17445 17446 @Override 17447 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17448 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17449 } 17450 17451 private Intent getHomeIntent() { 17452 Intent intent = new Intent(Intent.ACTION_MAIN); 17453 intent.addCategory(Intent.CATEGORY_HOME); 17454 return intent; 17455 } 17456 17457 private IntentFilter getHomeFilter() { 17458 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17459 filter.addCategory(Intent.CATEGORY_HOME); 17460 filter.addCategory(Intent.CATEGORY_DEFAULT); 17461 return filter; 17462 } 17463 17464 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17465 int userId) { 17466 Intent intent = getHomeIntent(); 17467 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17468 PackageManager.GET_META_DATA, userId); 17469 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17470 true, false, false, userId); 17471 17472 allHomeCandidates.clear(); 17473 if (list != null) { 17474 for (ResolveInfo ri : list) { 17475 allHomeCandidates.add(ri); 17476 } 17477 } 17478 return (preferred == null || preferred.activityInfo == null) 17479 ? null 17480 : new ComponentName(preferred.activityInfo.packageName, 17481 preferred.activityInfo.name); 17482 } 17483 17484 @Override 17485 public void setHomeActivity(ComponentName comp, int userId) { 17486 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17487 getHomeActivitiesAsUser(homeActivities, userId); 17488 17489 boolean found = false; 17490 17491 final int size = homeActivities.size(); 17492 final ComponentName[] set = new ComponentName[size]; 17493 for (int i = 0; i < size; i++) { 17494 final ResolveInfo candidate = homeActivities.get(i); 17495 final ActivityInfo info = candidate.activityInfo; 17496 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17497 set[i] = activityName; 17498 if (!found && activityName.equals(comp)) { 17499 found = true; 17500 } 17501 } 17502 if (!found) { 17503 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17504 + userId); 17505 } 17506 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17507 set, comp, userId); 17508 } 17509 17510 private @Nullable String getSetupWizardPackageName() { 17511 final Intent intent = new Intent(Intent.ACTION_MAIN); 17512 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17513 17514 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17515 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17516 | MATCH_DISABLED_COMPONENTS, 17517 UserHandle.myUserId()); 17518 if (matches.size() == 1) { 17519 return matches.get(0).getComponentInfo().packageName; 17520 } else { 17521 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17522 + ": matches=" + matches); 17523 return null; 17524 } 17525 } 17526 17527 @Override 17528 public void setApplicationEnabledSetting(String appPackageName, 17529 int newState, int flags, int userId, String callingPackage) { 17530 if (!sUserManager.exists(userId)) return; 17531 if (callingPackage == null) { 17532 callingPackage = Integer.toString(Binder.getCallingUid()); 17533 } 17534 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17535 } 17536 17537 @Override 17538 public void setComponentEnabledSetting(ComponentName componentName, 17539 int newState, int flags, int userId) { 17540 if (!sUserManager.exists(userId)) return; 17541 setEnabledSetting(componentName.getPackageName(), 17542 componentName.getClassName(), newState, flags, userId, null); 17543 } 17544 17545 private void setEnabledSetting(final String packageName, String className, int newState, 17546 final int flags, int userId, String callingPackage) { 17547 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17548 || newState == COMPONENT_ENABLED_STATE_ENABLED 17549 || newState == COMPONENT_ENABLED_STATE_DISABLED 17550 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17551 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17552 throw new IllegalArgumentException("Invalid new component state: " 17553 + newState); 17554 } 17555 PackageSetting pkgSetting; 17556 final int uid = Binder.getCallingUid(); 17557 final int permission; 17558 if (uid == Process.SYSTEM_UID) { 17559 permission = PackageManager.PERMISSION_GRANTED; 17560 } else { 17561 permission = mContext.checkCallingOrSelfPermission( 17562 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17563 } 17564 enforceCrossUserPermission(uid, userId, 17565 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17566 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17567 boolean sendNow = false; 17568 boolean isApp = (className == null); 17569 String componentName = isApp ? packageName : className; 17570 int packageUid = -1; 17571 ArrayList<String> components; 17572 17573 // writer 17574 synchronized (mPackages) { 17575 pkgSetting = mSettings.mPackages.get(packageName); 17576 if (pkgSetting == null) { 17577 if (className == null) { 17578 throw new IllegalArgumentException("Unknown package: " + packageName); 17579 } 17580 throw new IllegalArgumentException( 17581 "Unknown component: " + packageName + "/" + className); 17582 } 17583 } 17584 17585 // Limit who can change which apps 17586 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17587 // Don't allow apps that don't have permission to modify other apps 17588 if (!allowedByPermission) { 17589 throw new SecurityException( 17590 "Permission Denial: attempt to change component state from pid=" 17591 + Binder.getCallingPid() 17592 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17593 } 17594 // Don't allow changing profile and device owners. Calling into DPMS, so no locking. 17595 final DevicePolicyManagerInternal dpmi = LocalServices 17596 .getService(DevicePolicyManagerInternal.class); 17597 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 17598 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17599 } 17600 } 17601 17602 synchronized (mPackages) { 17603 if (uid == Process.SHELL_UID) { 17604 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17605 int oldState = pkgSetting.getEnabled(userId); 17606 if (className == null 17607 && 17608 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17609 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17610 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17611 && 17612 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17613 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17614 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17615 // ok 17616 } else { 17617 throw new SecurityException( 17618 "Shell cannot change component state for " + packageName + "/" 17619 + className + " to " + newState); 17620 } 17621 } 17622 if (className == null) { 17623 // We're dealing with an application/package level state change 17624 if (pkgSetting.getEnabled(userId) == newState) { 17625 // Nothing to do 17626 return; 17627 } 17628 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17629 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17630 // Don't care about who enables an app. 17631 callingPackage = null; 17632 } 17633 pkgSetting.setEnabled(newState, userId, callingPackage); 17634 // pkgSetting.pkg.mSetEnabled = newState; 17635 } else { 17636 // We're dealing with a component level state change 17637 // First, verify that this is a valid class name. 17638 PackageParser.Package pkg = pkgSetting.pkg; 17639 if (pkg == null || !pkg.hasComponentClassName(className)) { 17640 if (pkg != null && 17641 pkg.applicationInfo.targetSdkVersion >= 17642 Build.VERSION_CODES.JELLY_BEAN) { 17643 throw new IllegalArgumentException("Component class " + className 17644 + " does not exist in " + packageName); 17645 } else { 17646 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17647 + className + " does not exist in " + packageName); 17648 } 17649 } 17650 switch (newState) { 17651 case COMPONENT_ENABLED_STATE_ENABLED: 17652 if (!pkgSetting.enableComponentLPw(className, userId)) { 17653 return; 17654 } 17655 break; 17656 case COMPONENT_ENABLED_STATE_DISABLED: 17657 if (!pkgSetting.disableComponentLPw(className, userId)) { 17658 return; 17659 } 17660 break; 17661 case COMPONENT_ENABLED_STATE_DEFAULT: 17662 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17663 return; 17664 } 17665 break; 17666 default: 17667 Slog.e(TAG, "Invalid new component state: " + newState); 17668 return; 17669 } 17670 } 17671 scheduleWritePackageRestrictionsLocked(userId); 17672 components = mPendingBroadcasts.get(userId, packageName); 17673 final boolean newPackage = components == null; 17674 if (newPackage) { 17675 components = new ArrayList<String>(); 17676 } 17677 if (!components.contains(componentName)) { 17678 components.add(componentName); 17679 } 17680 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17681 sendNow = true; 17682 // Purge entry from pending broadcast list if another one exists already 17683 // since we are sending one right away. 17684 mPendingBroadcasts.remove(userId, packageName); 17685 } else { 17686 if (newPackage) { 17687 mPendingBroadcasts.put(userId, packageName, components); 17688 } 17689 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17690 // Schedule a message 17691 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17692 } 17693 } 17694 } 17695 17696 long callingId = Binder.clearCallingIdentity(); 17697 try { 17698 if (sendNow) { 17699 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17700 sendPackageChangedBroadcast(packageName, 17701 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17702 } 17703 } finally { 17704 Binder.restoreCallingIdentity(callingId); 17705 } 17706 } 17707 17708 @Override 17709 public void flushPackageRestrictionsAsUser(int userId) { 17710 if (!sUserManager.exists(userId)) { 17711 return; 17712 } 17713 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17714 false /* checkShell */, "flushPackageRestrictions"); 17715 synchronized (mPackages) { 17716 mSettings.writePackageRestrictionsLPr(userId); 17717 mDirtyUsers.remove(userId); 17718 if (mDirtyUsers.isEmpty()) { 17719 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17720 } 17721 } 17722 } 17723 17724 private void sendPackageChangedBroadcast(String packageName, 17725 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17726 if (DEBUG_INSTALL) 17727 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17728 + componentNames); 17729 Bundle extras = new Bundle(4); 17730 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17731 String nameList[] = new String[componentNames.size()]; 17732 componentNames.toArray(nameList); 17733 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17734 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17735 extras.putInt(Intent.EXTRA_UID, packageUid); 17736 // If this is not reporting a change of the overall package, then only send it 17737 // to registered receivers. We don't want to launch a swath of apps for every 17738 // little component state change. 17739 final int flags = !componentNames.contains(packageName) 17740 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17741 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17742 new int[] {UserHandle.getUserId(packageUid)}); 17743 } 17744 17745 @Override 17746 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17747 if (!sUserManager.exists(userId)) return; 17748 final int uid = Binder.getCallingUid(); 17749 final int permission = mContext.checkCallingOrSelfPermission( 17750 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17751 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17752 enforceCrossUserPermission(uid, userId, 17753 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17754 // writer 17755 synchronized (mPackages) { 17756 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17757 allowedByPermission, uid, userId)) { 17758 scheduleWritePackageRestrictionsLocked(userId); 17759 } 17760 } 17761 } 17762 17763 @Override 17764 public String getInstallerPackageName(String packageName) { 17765 // reader 17766 synchronized (mPackages) { 17767 return mSettings.getInstallerPackageNameLPr(packageName); 17768 } 17769 } 17770 17771 public boolean isOrphaned(String packageName) { 17772 // reader 17773 synchronized (mPackages) { 17774 return mSettings.isOrphaned(packageName); 17775 } 17776 } 17777 17778 @Override 17779 public int getApplicationEnabledSetting(String packageName, int userId) { 17780 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17781 int uid = Binder.getCallingUid(); 17782 enforceCrossUserPermission(uid, userId, 17783 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17784 // reader 17785 synchronized (mPackages) { 17786 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17787 } 17788 } 17789 17790 @Override 17791 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17792 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17793 int uid = Binder.getCallingUid(); 17794 enforceCrossUserPermission(uid, userId, 17795 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17796 // reader 17797 synchronized (mPackages) { 17798 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17799 } 17800 } 17801 17802 @Override 17803 public void enterSafeMode() { 17804 enforceSystemOrRoot("Only the system can request entering safe mode"); 17805 17806 if (!mSystemReady) { 17807 mSafeMode = true; 17808 } 17809 } 17810 17811 @Override 17812 public void systemReady() { 17813 mSystemReady = true; 17814 17815 // Read the compatibilty setting when the system is ready. 17816 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17817 mContext.getContentResolver(), 17818 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17819 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17820 if (DEBUG_SETTINGS) { 17821 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17822 } 17823 17824 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17825 17826 synchronized (mPackages) { 17827 // Verify that all of the preferred activity components actually 17828 // exist. It is possible for applications to be updated and at 17829 // that point remove a previously declared activity component that 17830 // had been set as a preferred activity. We try to clean this up 17831 // the next time we encounter that preferred activity, but it is 17832 // possible for the user flow to never be able to return to that 17833 // situation so here we do a sanity check to make sure we haven't 17834 // left any junk around. 17835 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17836 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17837 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17838 removed.clear(); 17839 for (PreferredActivity pa : pir.filterSet()) { 17840 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17841 removed.add(pa); 17842 } 17843 } 17844 if (removed.size() > 0) { 17845 for (int r=0; r<removed.size(); r++) { 17846 PreferredActivity pa = removed.get(r); 17847 Slog.w(TAG, "Removing dangling preferred activity: " 17848 + pa.mPref.mComponent); 17849 pir.removeFilter(pa); 17850 } 17851 mSettings.writePackageRestrictionsLPr( 17852 mSettings.mPreferredActivities.keyAt(i)); 17853 } 17854 } 17855 17856 for (int userId : UserManagerService.getInstance().getUserIds()) { 17857 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17858 grantPermissionsUserIds = ArrayUtils.appendInt( 17859 grantPermissionsUserIds, userId); 17860 } 17861 } 17862 } 17863 sUserManager.systemReady(); 17864 17865 // If we upgraded grant all default permissions before kicking off. 17866 for (int userId : grantPermissionsUserIds) { 17867 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17868 } 17869 17870 // Kick off any messages waiting for system ready 17871 if (mPostSystemReadyMessages != null) { 17872 for (Message msg : mPostSystemReadyMessages) { 17873 msg.sendToTarget(); 17874 } 17875 mPostSystemReadyMessages = null; 17876 } 17877 17878 // Watch for external volumes that come and go over time 17879 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17880 storage.registerListener(mStorageListener); 17881 17882 mInstallerService.systemReady(); 17883 mPackageDexOptimizer.systemReady(); 17884 17885 MountServiceInternal mountServiceInternal = LocalServices.getService( 17886 MountServiceInternal.class); 17887 mountServiceInternal.addExternalStoragePolicy( 17888 new MountServiceInternal.ExternalStorageMountPolicy() { 17889 @Override 17890 public int getMountMode(int uid, String packageName) { 17891 if (Process.isIsolated(uid)) { 17892 return Zygote.MOUNT_EXTERNAL_NONE; 17893 } 17894 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17895 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17896 } 17897 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17898 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17899 } 17900 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17901 return Zygote.MOUNT_EXTERNAL_READ; 17902 } 17903 return Zygote.MOUNT_EXTERNAL_WRITE; 17904 } 17905 17906 @Override 17907 public boolean hasExternalStorage(int uid, String packageName) { 17908 return true; 17909 } 17910 }); 17911 17912 // Now that we're mostly running, clean up stale users and apps 17913 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17914 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17915 } 17916 17917 @Override 17918 public boolean isSafeMode() { 17919 return mSafeMode; 17920 } 17921 17922 @Override 17923 public boolean hasSystemUidErrors() { 17924 return mHasSystemUidErrors; 17925 } 17926 17927 static String arrayToString(int[] array) { 17928 StringBuffer buf = new StringBuffer(128); 17929 buf.append('['); 17930 if (array != null) { 17931 for (int i=0; i<array.length; i++) { 17932 if (i > 0) buf.append(", "); 17933 buf.append(array[i]); 17934 } 17935 } 17936 buf.append(']'); 17937 return buf.toString(); 17938 } 17939 17940 static class DumpState { 17941 public static final int DUMP_LIBS = 1 << 0; 17942 public static final int DUMP_FEATURES = 1 << 1; 17943 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17944 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17945 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17946 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17947 public static final int DUMP_PERMISSIONS = 1 << 6; 17948 public static final int DUMP_PACKAGES = 1 << 7; 17949 public static final int DUMP_SHARED_USERS = 1 << 8; 17950 public static final int DUMP_MESSAGES = 1 << 9; 17951 public static final int DUMP_PROVIDERS = 1 << 10; 17952 public static final int DUMP_VERIFIERS = 1 << 11; 17953 public static final int DUMP_PREFERRED = 1 << 12; 17954 public static final int DUMP_PREFERRED_XML = 1 << 13; 17955 public static final int DUMP_KEYSETS = 1 << 14; 17956 public static final int DUMP_VERSION = 1 << 15; 17957 public static final int DUMP_INSTALLS = 1 << 16; 17958 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17959 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17960 public static final int DUMP_FROZEN = 1 << 19; 17961 public static final int DUMP_DEXOPT = 1 << 20; 17962 17963 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17964 17965 private int mTypes; 17966 17967 private int mOptions; 17968 17969 private boolean mTitlePrinted; 17970 17971 private SharedUserSetting mSharedUser; 17972 17973 public boolean isDumping(int type) { 17974 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17975 return true; 17976 } 17977 17978 return (mTypes & type) != 0; 17979 } 17980 17981 public void setDump(int type) { 17982 mTypes |= type; 17983 } 17984 17985 public boolean isOptionEnabled(int option) { 17986 return (mOptions & option) != 0; 17987 } 17988 17989 public void setOptionEnabled(int option) { 17990 mOptions |= option; 17991 } 17992 17993 public boolean onTitlePrinted() { 17994 final boolean printed = mTitlePrinted; 17995 mTitlePrinted = true; 17996 return printed; 17997 } 17998 17999 public boolean getTitlePrinted() { 18000 return mTitlePrinted; 18001 } 18002 18003 public void setTitlePrinted(boolean enabled) { 18004 mTitlePrinted = enabled; 18005 } 18006 18007 public SharedUserSetting getSharedUser() { 18008 return mSharedUser; 18009 } 18010 18011 public void setSharedUser(SharedUserSetting user) { 18012 mSharedUser = user; 18013 } 18014 } 18015 18016 @Override 18017 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18018 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18019 (new PackageManagerShellCommand(this)).exec( 18020 this, in, out, err, args, resultReceiver); 18021 } 18022 18023 @Override 18024 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18025 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18026 != PackageManager.PERMISSION_GRANTED) { 18027 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18028 + Binder.getCallingPid() 18029 + ", uid=" + Binder.getCallingUid() 18030 + " without permission " 18031 + android.Manifest.permission.DUMP); 18032 return; 18033 } 18034 18035 DumpState dumpState = new DumpState(); 18036 boolean fullPreferred = false; 18037 boolean checkin = false; 18038 18039 String packageName = null; 18040 ArraySet<String> permissionNames = null; 18041 18042 int opti = 0; 18043 while (opti < args.length) { 18044 String opt = args[opti]; 18045 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18046 break; 18047 } 18048 opti++; 18049 18050 if ("-a".equals(opt)) { 18051 // Right now we only know how to print all. 18052 } else if ("-h".equals(opt)) { 18053 pw.println("Package manager dump options:"); 18054 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18055 pw.println(" --checkin: dump for a checkin"); 18056 pw.println(" -f: print details of intent filters"); 18057 pw.println(" -h: print this help"); 18058 pw.println(" cmd may be one of:"); 18059 pw.println(" l[ibraries]: list known shared libraries"); 18060 pw.println(" f[eatures]: list device features"); 18061 pw.println(" k[eysets]: print known keysets"); 18062 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18063 pw.println(" perm[issions]: dump permissions"); 18064 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18065 pw.println(" pref[erred]: print preferred package settings"); 18066 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18067 pw.println(" prov[iders]: dump content providers"); 18068 pw.println(" p[ackages]: dump installed packages"); 18069 pw.println(" s[hared-users]: dump shared user IDs"); 18070 pw.println(" m[essages]: print collected runtime messages"); 18071 pw.println(" v[erifiers]: print package verifier info"); 18072 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18073 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18074 pw.println(" version: print database version info"); 18075 pw.println(" write: write current settings now"); 18076 pw.println(" installs: details about install sessions"); 18077 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18078 pw.println(" dexopt: dump dexopt state"); 18079 pw.println(" <package.name>: info about given package"); 18080 return; 18081 } else if ("--checkin".equals(opt)) { 18082 checkin = true; 18083 } else if ("-f".equals(opt)) { 18084 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18085 } else { 18086 pw.println("Unknown argument: " + opt + "; use -h for help"); 18087 } 18088 } 18089 18090 // Is the caller requesting to dump a particular piece of data? 18091 if (opti < args.length) { 18092 String cmd = args[opti]; 18093 opti++; 18094 // Is this a package name? 18095 if ("android".equals(cmd) || cmd.contains(".")) { 18096 packageName = cmd; 18097 // When dumping a single package, we always dump all of its 18098 // filter information since the amount of data will be reasonable. 18099 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18100 } else if ("check-permission".equals(cmd)) { 18101 if (opti >= args.length) { 18102 pw.println("Error: check-permission missing permission argument"); 18103 return; 18104 } 18105 String perm = args[opti]; 18106 opti++; 18107 if (opti >= args.length) { 18108 pw.println("Error: check-permission missing package argument"); 18109 return; 18110 } 18111 String pkg = args[opti]; 18112 opti++; 18113 int user = UserHandle.getUserId(Binder.getCallingUid()); 18114 if (opti < args.length) { 18115 try { 18116 user = Integer.parseInt(args[opti]); 18117 } catch (NumberFormatException e) { 18118 pw.println("Error: check-permission user argument is not a number: " 18119 + args[opti]); 18120 return; 18121 } 18122 } 18123 pw.println(checkPermission(perm, pkg, user)); 18124 return; 18125 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18126 dumpState.setDump(DumpState.DUMP_LIBS); 18127 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18128 dumpState.setDump(DumpState.DUMP_FEATURES); 18129 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18130 if (opti >= args.length) { 18131 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18132 | DumpState.DUMP_SERVICE_RESOLVERS 18133 | DumpState.DUMP_RECEIVER_RESOLVERS 18134 | DumpState.DUMP_CONTENT_RESOLVERS); 18135 } else { 18136 while (opti < args.length) { 18137 String name = args[opti]; 18138 if ("a".equals(name) || "activity".equals(name)) { 18139 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18140 } else if ("s".equals(name) || "service".equals(name)) { 18141 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18142 } else if ("r".equals(name) || "receiver".equals(name)) { 18143 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18144 } else if ("c".equals(name) || "content".equals(name)) { 18145 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18146 } else { 18147 pw.println("Error: unknown resolver table type: " + name); 18148 return; 18149 } 18150 opti++; 18151 } 18152 } 18153 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18154 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18155 } else if ("permission".equals(cmd)) { 18156 if (opti >= args.length) { 18157 pw.println("Error: permission requires permission name"); 18158 return; 18159 } 18160 permissionNames = new ArraySet<>(); 18161 while (opti < args.length) { 18162 permissionNames.add(args[opti]); 18163 opti++; 18164 } 18165 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18166 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18167 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18168 dumpState.setDump(DumpState.DUMP_PREFERRED); 18169 } else if ("preferred-xml".equals(cmd)) { 18170 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18171 if (opti < args.length && "--full".equals(args[opti])) { 18172 fullPreferred = true; 18173 opti++; 18174 } 18175 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18176 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18177 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18178 dumpState.setDump(DumpState.DUMP_PACKAGES); 18179 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18180 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18181 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18182 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18183 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18184 dumpState.setDump(DumpState.DUMP_MESSAGES); 18185 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18186 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18187 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18188 || "intent-filter-verifiers".equals(cmd)) { 18189 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18190 } else if ("version".equals(cmd)) { 18191 dumpState.setDump(DumpState.DUMP_VERSION); 18192 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18193 dumpState.setDump(DumpState.DUMP_KEYSETS); 18194 } else if ("installs".equals(cmd)) { 18195 dumpState.setDump(DumpState.DUMP_INSTALLS); 18196 } else if ("frozen".equals(cmd)) { 18197 dumpState.setDump(DumpState.DUMP_FROZEN); 18198 } else if ("dexopt".equals(cmd)) { 18199 dumpState.setDump(DumpState.DUMP_DEXOPT); 18200 } else if ("write".equals(cmd)) { 18201 synchronized (mPackages) { 18202 mSettings.writeLPr(); 18203 pw.println("Settings written."); 18204 return; 18205 } 18206 } 18207 } 18208 18209 if (checkin) { 18210 pw.println("vers,1"); 18211 } 18212 18213 // reader 18214 synchronized (mPackages) { 18215 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18216 if (!checkin) { 18217 if (dumpState.onTitlePrinted()) 18218 pw.println(); 18219 pw.println("Database versions:"); 18220 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18221 } 18222 } 18223 18224 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18225 if (!checkin) { 18226 if (dumpState.onTitlePrinted()) 18227 pw.println(); 18228 pw.println("Verifiers:"); 18229 pw.print(" Required: "); 18230 pw.print(mRequiredVerifierPackage); 18231 pw.print(" (uid="); 18232 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18233 UserHandle.USER_SYSTEM)); 18234 pw.println(")"); 18235 } else if (mRequiredVerifierPackage != null) { 18236 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18237 pw.print(","); 18238 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18239 UserHandle.USER_SYSTEM)); 18240 } 18241 } 18242 18243 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18244 packageName == null) { 18245 if (mIntentFilterVerifierComponent != null) { 18246 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18247 if (!checkin) { 18248 if (dumpState.onTitlePrinted()) 18249 pw.println(); 18250 pw.println("Intent Filter Verifier:"); 18251 pw.print(" Using: "); 18252 pw.print(verifierPackageName); 18253 pw.print(" (uid="); 18254 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18255 UserHandle.USER_SYSTEM)); 18256 pw.println(")"); 18257 } else if (verifierPackageName != null) { 18258 pw.print("ifv,"); pw.print(verifierPackageName); 18259 pw.print(","); 18260 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18261 UserHandle.USER_SYSTEM)); 18262 } 18263 } else { 18264 pw.println(); 18265 pw.println("No Intent Filter Verifier available!"); 18266 } 18267 } 18268 18269 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18270 boolean printedHeader = false; 18271 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18272 while (it.hasNext()) { 18273 String name = it.next(); 18274 SharedLibraryEntry ent = mSharedLibraries.get(name); 18275 if (!checkin) { 18276 if (!printedHeader) { 18277 if (dumpState.onTitlePrinted()) 18278 pw.println(); 18279 pw.println("Libraries:"); 18280 printedHeader = true; 18281 } 18282 pw.print(" "); 18283 } else { 18284 pw.print("lib,"); 18285 } 18286 pw.print(name); 18287 if (!checkin) { 18288 pw.print(" -> "); 18289 } 18290 if (ent.path != null) { 18291 if (!checkin) { 18292 pw.print("(jar) "); 18293 pw.print(ent.path); 18294 } else { 18295 pw.print(",jar,"); 18296 pw.print(ent.path); 18297 } 18298 } else { 18299 if (!checkin) { 18300 pw.print("(apk) "); 18301 pw.print(ent.apk); 18302 } else { 18303 pw.print(",apk,"); 18304 pw.print(ent.apk); 18305 } 18306 } 18307 pw.println(); 18308 } 18309 } 18310 18311 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18312 if (dumpState.onTitlePrinted()) 18313 pw.println(); 18314 if (!checkin) { 18315 pw.println("Features:"); 18316 } 18317 18318 for (FeatureInfo feat : mAvailableFeatures.values()) { 18319 if (checkin) { 18320 pw.print("feat,"); 18321 pw.print(feat.name); 18322 pw.print(","); 18323 pw.println(feat.version); 18324 } else { 18325 pw.print(" "); 18326 pw.print(feat.name); 18327 if (feat.version > 0) { 18328 pw.print(" version="); 18329 pw.print(feat.version); 18330 } 18331 pw.println(); 18332 } 18333 } 18334 } 18335 18336 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18337 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18338 : "Activity Resolver Table:", " ", packageName, 18339 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18340 dumpState.setTitlePrinted(true); 18341 } 18342 } 18343 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18344 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18345 : "Receiver Resolver Table:", " ", packageName, 18346 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18347 dumpState.setTitlePrinted(true); 18348 } 18349 } 18350 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18351 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18352 : "Service Resolver Table:", " ", packageName, 18353 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18354 dumpState.setTitlePrinted(true); 18355 } 18356 } 18357 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18358 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18359 : "Provider Resolver Table:", " ", packageName, 18360 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18361 dumpState.setTitlePrinted(true); 18362 } 18363 } 18364 18365 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18366 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18367 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18368 int user = mSettings.mPreferredActivities.keyAt(i); 18369 if (pir.dump(pw, 18370 dumpState.getTitlePrinted() 18371 ? "\nPreferred Activities User " + user + ":" 18372 : "Preferred Activities User " + user + ":", " ", 18373 packageName, true, false)) { 18374 dumpState.setTitlePrinted(true); 18375 } 18376 } 18377 } 18378 18379 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18380 pw.flush(); 18381 FileOutputStream fout = new FileOutputStream(fd); 18382 BufferedOutputStream str = new BufferedOutputStream(fout); 18383 XmlSerializer serializer = new FastXmlSerializer(); 18384 try { 18385 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18386 serializer.startDocument(null, true); 18387 serializer.setFeature( 18388 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18389 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18390 serializer.endDocument(); 18391 serializer.flush(); 18392 } catch (IllegalArgumentException e) { 18393 pw.println("Failed writing: " + e); 18394 } catch (IllegalStateException e) { 18395 pw.println("Failed writing: " + e); 18396 } catch (IOException e) { 18397 pw.println("Failed writing: " + e); 18398 } 18399 } 18400 18401 if (!checkin 18402 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18403 && packageName == null) { 18404 pw.println(); 18405 int count = mSettings.mPackages.size(); 18406 if (count == 0) { 18407 pw.println("No applications!"); 18408 pw.println(); 18409 } else { 18410 final String prefix = " "; 18411 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18412 if (allPackageSettings.size() == 0) { 18413 pw.println("No domain preferred apps!"); 18414 pw.println(); 18415 } else { 18416 pw.println("App verification status:"); 18417 pw.println(); 18418 count = 0; 18419 for (PackageSetting ps : allPackageSettings) { 18420 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18421 if (ivi == null || ivi.getPackageName() == null) continue; 18422 pw.println(prefix + "Package: " + ivi.getPackageName()); 18423 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18424 pw.println(prefix + "Status: " + ivi.getStatusString()); 18425 pw.println(); 18426 count++; 18427 } 18428 if (count == 0) { 18429 pw.println(prefix + "No app verification established."); 18430 pw.println(); 18431 } 18432 for (int userId : sUserManager.getUserIds()) { 18433 pw.println("App linkages for user " + userId + ":"); 18434 pw.println(); 18435 count = 0; 18436 for (PackageSetting ps : allPackageSettings) { 18437 final long status = ps.getDomainVerificationStatusForUser(userId); 18438 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18439 continue; 18440 } 18441 pw.println(prefix + "Package: " + ps.name); 18442 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18443 String statusStr = IntentFilterVerificationInfo. 18444 getStatusStringFromValue(status); 18445 pw.println(prefix + "Status: " + statusStr); 18446 pw.println(); 18447 count++; 18448 } 18449 if (count == 0) { 18450 pw.println(prefix + "No configured app linkages."); 18451 pw.println(); 18452 } 18453 } 18454 } 18455 } 18456 } 18457 18458 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18459 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18460 if (packageName == null && permissionNames == null) { 18461 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18462 if (iperm == 0) { 18463 if (dumpState.onTitlePrinted()) 18464 pw.println(); 18465 pw.println("AppOp Permissions:"); 18466 } 18467 pw.print(" AppOp Permission "); 18468 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18469 pw.println(":"); 18470 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18471 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18472 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18473 } 18474 } 18475 } 18476 } 18477 18478 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18479 boolean printedSomething = false; 18480 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18481 if (packageName != null && !packageName.equals(p.info.packageName)) { 18482 continue; 18483 } 18484 if (!printedSomething) { 18485 if (dumpState.onTitlePrinted()) 18486 pw.println(); 18487 pw.println("Registered ContentProviders:"); 18488 printedSomething = true; 18489 } 18490 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18491 pw.print(" "); pw.println(p.toString()); 18492 } 18493 printedSomething = false; 18494 for (Map.Entry<String, PackageParser.Provider> entry : 18495 mProvidersByAuthority.entrySet()) { 18496 PackageParser.Provider p = entry.getValue(); 18497 if (packageName != null && !packageName.equals(p.info.packageName)) { 18498 continue; 18499 } 18500 if (!printedSomething) { 18501 if (dumpState.onTitlePrinted()) 18502 pw.println(); 18503 pw.println("ContentProvider Authorities:"); 18504 printedSomething = true; 18505 } 18506 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18507 pw.print(" "); pw.println(p.toString()); 18508 if (p.info != null && p.info.applicationInfo != null) { 18509 final String appInfo = p.info.applicationInfo.toString(); 18510 pw.print(" applicationInfo="); pw.println(appInfo); 18511 } 18512 } 18513 } 18514 18515 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18516 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18517 } 18518 18519 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18520 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18521 } 18522 18523 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18524 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18525 } 18526 18527 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18528 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18529 } 18530 18531 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18532 // XXX should handle packageName != null by dumping only install data that 18533 // the given package is involved with. 18534 if (dumpState.onTitlePrinted()) pw.println(); 18535 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18536 } 18537 18538 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18539 // XXX should handle packageName != null by dumping only install data that 18540 // the given package is involved with. 18541 if (dumpState.onTitlePrinted()) pw.println(); 18542 18543 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18544 ipw.println(); 18545 ipw.println("Frozen packages:"); 18546 ipw.increaseIndent(); 18547 if (mFrozenPackages.size() == 0) { 18548 ipw.println("(none)"); 18549 } else { 18550 for (int i = 0; i < mFrozenPackages.size(); i++) { 18551 ipw.println(mFrozenPackages.valueAt(i)); 18552 } 18553 } 18554 ipw.decreaseIndent(); 18555 } 18556 18557 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18558 if (dumpState.onTitlePrinted()) pw.println(); 18559 dumpDexoptStateLPr(pw, packageName); 18560 } 18561 18562 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18563 if (dumpState.onTitlePrinted()) pw.println(); 18564 mSettings.dumpReadMessagesLPr(pw, dumpState); 18565 18566 pw.println(); 18567 pw.println("Package warning messages:"); 18568 BufferedReader in = null; 18569 String line = null; 18570 try { 18571 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18572 while ((line = in.readLine()) != null) { 18573 if (line.contains("ignored: updated version")) continue; 18574 pw.println(line); 18575 } 18576 } catch (IOException ignored) { 18577 } finally { 18578 IoUtils.closeQuietly(in); 18579 } 18580 } 18581 18582 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18583 BufferedReader in = null; 18584 String line = null; 18585 try { 18586 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18587 while ((line = in.readLine()) != null) { 18588 if (line.contains("ignored: updated version")) continue; 18589 pw.print("msg,"); 18590 pw.println(line); 18591 } 18592 } catch (IOException ignored) { 18593 } finally { 18594 IoUtils.closeQuietly(in); 18595 } 18596 } 18597 } 18598 } 18599 18600 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18601 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18602 ipw.println(); 18603 ipw.println("Dexopt state:"); 18604 ipw.increaseIndent(); 18605 Collection<PackageParser.Package> packages = null; 18606 if (packageName != null) { 18607 PackageParser.Package targetPackage = mPackages.get(packageName); 18608 if (targetPackage != null) { 18609 packages = Collections.singletonList(targetPackage); 18610 } else { 18611 ipw.println("Unable to find package: " + packageName); 18612 return; 18613 } 18614 } else { 18615 packages = mPackages.values(); 18616 } 18617 18618 for (PackageParser.Package pkg : packages) { 18619 ipw.println("[" + pkg.packageName + "]"); 18620 ipw.increaseIndent(); 18621 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18622 ipw.decreaseIndent(); 18623 } 18624 } 18625 18626 private String dumpDomainString(String packageName) { 18627 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18628 .getList(); 18629 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18630 18631 ArraySet<String> result = new ArraySet<>(); 18632 if (iviList.size() > 0) { 18633 for (IntentFilterVerificationInfo ivi : iviList) { 18634 for (String host : ivi.getDomains()) { 18635 result.add(host); 18636 } 18637 } 18638 } 18639 if (filters != null && filters.size() > 0) { 18640 for (IntentFilter filter : filters) { 18641 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18642 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18643 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18644 result.addAll(filter.getHostsList()); 18645 } 18646 } 18647 } 18648 18649 StringBuilder sb = new StringBuilder(result.size() * 16); 18650 for (String domain : result) { 18651 if (sb.length() > 0) sb.append(" "); 18652 sb.append(domain); 18653 } 18654 return sb.toString(); 18655 } 18656 18657 // ------- apps on sdcard specific code ------- 18658 static final boolean DEBUG_SD_INSTALL = false; 18659 18660 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18661 18662 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18663 18664 private boolean mMediaMounted = false; 18665 18666 static String getEncryptKey() { 18667 try { 18668 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18669 SD_ENCRYPTION_KEYSTORE_NAME); 18670 if (sdEncKey == null) { 18671 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18672 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18673 if (sdEncKey == null) { 18674 Slog.e(TAG, "Failed to create encryption keys"); 18675 return null; 18676 } 18677 } 18678 return sdEncKey; 18679 } catch (NoSuchAlgorithmException nsae) { 18680 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18681 return null; 18682 } catch (IOException ioe) { 18683 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18684 return null; 18685 } 18686 } 18687 18688 /* 18689 * Update media status on PackageManager. 18690 */ 18691 @Override 18692 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18693 int callingUid = Binder.getCallingUid(); 18694 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18695 throw new SecurityException("Media status can only be updated by the system"); 18696 } 18697 // reader; this apparently protects mMediaMounted, but should probably 18698 // be a different lock in that case. 18699 synchronized (mPackages) { 18700 Log.i(TAG, "Updating external media status from " 18701 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18702 + (mediaStatus ? "mounted" : "unmounted")); 18703 if (DEBUG_SD_INSTALL) 18704 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18705 + ", mMediaMounted=" + mMediaMounted); 18706 if (mediaStatus == mMediaMounted) { 18707 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18708 : 0, -1); 18709 mHandler.sendMessage(msg); 18710 return; 18711 } 18712 mMediaMounted = mediaStatus; 18713 } 18714 // Queue up an async operation since the package installation may take a 18715 // little while. 18716 mHandler.post(new Runnable() { 18717 public void run() { 18718 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18719 } 18720 }); 18721 } 18722 18723 /** 18724 * Called by MountService when the initial ASECs to scan are available. 18725 * Should block until all the ASEC containers are finished being scanned. 18726 */ 18727 public void scanAvailableAsecs() { 18728 updateExternalMediaStatusInner(true, false, false); 18729 } 18730 18731 /* 18732 * Collect information of applications on external media, map them against 18733 * existing containers and update information based on current mount status. 18734 * Please note that we always have to report status if reportStatus has been 18735 * set to true especially when unloading packages. 18736 */ 18737 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18738 boolean externalStorage) { 18739 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18740 int[] uidArr = EmptyArray.INT; 18741 18742 final String[] list = PackageHelper.getSecureContainerList(); 18743 if (ArrayUtils.isEmpty(list)) { 18744 Log.i(TAG, "No secure containers found"); 18745 } else { 18746 // Process list of secure containers and categorize them 18747 // as active or stale based on their package internal state. 18748 18749 // reader 18750 synchronized (mPackages) { 18751 for (String cid : list) { 18752 // Leave stages untouched for now; installer service owns them 18753 if (PackageInstallerService.isStageName(cid)) continue; 18754 18755 if (DEBUG_SD_INSTALL) 18756 Log.i(TAG, "Processing container " + cid); 18757 String pkgName = getAsecPackageName(cid); 18758 if (pkgName == null) { 18759 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18760 continue; 18761 } 18762 if (DEBUG_SD_INSTALL) 18763 Log.i(TAG, "Looking for pkg : " + pkgName); 18764 18765 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18766 if (ps == null) { 18767 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18768 continue; 18769 } 18770 18771 /* 18772 * Skip packages that are not external if we're unmounting 18773 * external storage. 18774 */ 18775 if (externalStorage && !isMounted && !isExternal(ps)) { 18776 continue; 18777 } 18778 18779 final AsecInstallArgs args = new AsecInstallArgs(cid, 18780 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18781 // The package status is changed only if the code path 18782 // matches between settings and the container id. 18783 if (ps.codePathString != null 18784 && ps.codePathString.startsWith(args.getCodePath())) { 18785 if (DEBUG_SD_INSTALL) { 18786 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18787 + " at code path: " + ps.codePathString); 18788 } 18789 18790 // We do have a valid package installed on sdcard 18791 processCids.put(args, ps.codePathString); 18792 final int uid = ps.appId; 18793 if (uid != -1) { 18794 uidArr = ArrayUtils.appendInt(uidArr, uid); 18795 } 18796 } else { 18797 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18798 + ps.codePathString); 18799 } 18800 } 18801 } 18802 18803 Arrays.sort(uidArr); 18804 } 18805 18806 // Process packages with valid entries. 18807 if (isMounted) { 18808 if (DEBUG_SD_INSTALL) 18809 Log.i(TAG, "Loading packages"); 18810 loadMediaPackages(processCids, uidArr, externalStorage); 18811 startCleaningPackages(); 18812 mInstallerService.onSecureContainersAvailable(); 18813 } else { 18814 if (DEBUG_SD_INSTALL) 18815 Log.i(TAG, "Unloading packages"); 18816 unloadMediaPackages(processCids, uidArr, reportStatus); 18817 } 18818 } 18819 18820 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18821 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18822 final int size = infos.size(); 18823 final String[] packageNames = new String[size]; 18824 final int[] packageUids = new int[size]; 18825 for (int i = 0; i < size; i++) { 18826 final ApplicationInfo info = infos.get(i); 18827 packageNames[i] = info.packageName; 18828 packageUids[i] = info.uid; 18829 } 18830 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18831 finishedReceiver); 18832 } 18833 18834 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18835 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18836 sendResourcesChangedBroadcast(mediaStatus, replacing, 18837 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18838 } 18839 18840 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18841 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18842 int size = pkgList.length; 18843 if (size > 0) { 18844 // Send broadcasts here 18845 Bundle extras = new Bundle(); 18846 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18847 if (uidArr != null) { 18848 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18849 } 18850 if (replacing) { 18851 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18852 } 18853 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18854 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18855 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18856 } 18857 } 18858 18859 /* 18860 * Look at potentially valid container ids from processCids If package 18861 * information doesn't match the one on record or package scanning fails, 18862 * the cid is added to list of removeCids. We currently don't delete stale 18863 * containers. 18864 */ 18865 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18866 boolean externalStorage) { 18867 ArrayList<String> pkgList = new ArrayList<String>(); 18868 Set<AsecInstallArgs> keys = processCids.keySet(); 18869 18870 for (AsecInstallArgs args : keys) { 18871 String codePath = processCids.get(args); 18872 if (DEBUG_SD_INSTALL) 18873 Log.i(TAG, "Loading container : " + args.cid); 18874 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18875 try { 18876 // Make sure there are no container errors first. 18877 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18878 Slog.e(TAG, "Failed to mount cid : " + args.cid 18879 + " when installing from sdcard"); 18880 continue; 18881 } 18882 // Check code path here. 18883 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18884 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18885 + " does not match one in settings " + codePath); 18886 continue; 18887 } 18888 // Parse package 18889 int parseFlags = mDefParseFlags; 18890 if (args.isExternalAsec()) { 18891 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18892 } 18893 if (args.isFwdLocked()) { 18894 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18895 } 18896 18897 synchronized (mInstallLock) { 18898 PackageParser.Package pkg = null; 18899 try { 18900 // Sadly we don't know the package name yet to freeze it 18901 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18902 SCAN_IGNORE_FROZEN, 0, null); 18903 } catch (PackageManagerException e) { 18904 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18905 } 18906 // Scan the package 18907 if (pkg != null) { 18908 /* 18909 * TODO why is the lock being held? doPostInstall is 18910 * called in other places without the lock. This needs 18911 * to be straightened out. 18912 */ 18913 // writer 18914 synchronized (mPackages) { 18915 retCode = PackageManager.INSTALL_SUCCEEDED; 18916 pkgList.add(pkg.packageName); 18917 // Post process args 18918 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18919 pkg.applicationInfo.uid); 18920 } 18921 } else { 18922 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18923 } 18924 } 18925 18926 } finally { 18927 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18928 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18929 } 18930 } 18931 } 18932 // writer 18933 synchronized (mPackages) { 18934 // If the platform SDK has changed since the last time we booted, 18935 // we need to re-grant app permission to catch any new ones that 18936 // appear. This is really a hack, and means that apps can in some 18937 // cases get permissions that the user didn't initially explicitly 18938 // allow... it would be nice to have some better way to handle 18939 // this situation. 18940 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18941 : mSettings.getInternalVersion(); 18942 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18943 : StorageManager.UUID_PRIVATE_INTERNAL; 18944 18945 int updateFlags = UPDATE_PERMISSIONS_ALL; 18946 if (ver.sdkVersion != mSdkVersion) { 18947 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18948 + mSdkVersion + "; regranting permissions for external"); 18949 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18950 } 18951 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18952 18953 // Yay, everything is now upgraded 18954 ver.forceCurrent(); 18955 18956 // can downgrade to reader 18957 // Persist settings 18958 mSettings.writeLPr(); 18959 } 18960 // Send a broadcast to let everyone know we are done processing 18961 if (pkgList.size() > 0) { 18962 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18963 } 18964 } 18965 18966 /* 18967 * Utility method to unload a list of specified containers 18968 */ 18969 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18970 // Just unmount all valid containers. 18971 for (AsecInstallArgs arg : cidArgs) { 18972 synchronized (mInstallLock) { 18973 arg.doPostDeleteLI(false); 18974 } 18975 } 18976 } 18977 18978 /* 18979 * Unload packages mounted on external media. This involves deleting package 18980 * data from internal structures, sending broadcasts about disabled packages, 18981 * gc'ing to free up references, unmounting all secure containers 18982 * corresponding to packages on external media, and posting a 18983 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18984 * that we always have to post this message if status has been requested no 18985 * matter what. 18986 */ 18987 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18988 final boolean reportStatus) { 18989 if (DEBUG_SD_INSTALL) 18990 Log.i(TAG, "unloading media packages"); 18991 ArrayList<String> pkgList = new ArrayList<String>(); 18992 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18993 final Set<AsecInstallArgs> keys = processCids.keySet(); 18994 for (AsecInstallArgs args : keys) { 18995 String pkgName = args.getPackageName(); 18996 if (DEBUG_SD_INSTALL) 18997 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18998 // Delete package internally 18999 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19000 synchronized (mInstallLock) { 19001 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19002 final boolean res; 19003 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19004 "unloadMediaPackages")) { 19005 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19006 null); 19007 } 19008 if (res) { 19009 pkgList.add(pkgName); 19010 } else { 19011 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19012 failedList.add(args); 19013 } 19014 } 19015 } 19016 19017 // reader 19018 synchronized (mPackages) { 19019 // We didn't update the settings after removing each package; 19020 // write them now for all packages. 19021 mSettings.writeLPr(); 19022 } 19023 19024 // We have to absolutely send UPDATED_MEDIA_STATUS only 19025 // after confirming that all the receivers processed the ordered 19026 // broadcast when packages get disabled, force a gc to clean things up. 19027 // and unload all the containers. 19028 if (pkgList.size() > 0) { 19029 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19030 new IIntentReceiver.Stub() { 19031 public void performReceive(Intent intent, int resultCode, String data, 19032 Bundle extras, boolean ordered, boolean sticky, 19033 int sendingUser) throws RemoteException { 19034 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19035 reportStatus ? 1 : 0, 1, keys); 19036 mHandler.sendMessage(msg); 19037 } 19038 }); 19039 } else { 19040 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19041 keys); 19042 mHandler.sendMessage(msg); 19043 } 19044 } 19045 19046 private void loadPrivatePackages(final VolumeInfo vol) { 19047 mHandler.post(new Runnable() { 19048 @Override 19049 public void run() { 19050 loadPrivatePackagesInner(vol); 19051 } 19052 }); 19053 } 19054 19055 private void loadPrivatePackagesInner(VolumeInfo vol) { 19056 final String volumeUuid = vol.fsUuid; 19057 if (TextUtils.isEmpty(volumeUuid)) { 19058 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19059 return; 19060 } 19061 19062 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19063 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19064 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19065 19066 final VersionInfo ver; 19067 final List<PackageSetting> packages; 19068 synchronized (mPackages) { 19069 ver = mSettings.findOrCreateVersion(volumeUuid); 19070 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19071 } 19072 19073 for (PackageSetting ps : packages) { 19074 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19075 synchronized (mInstallLock) { 19076 final PackageParser.Package pkg; 19077 try { 19078 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19079 loaded.add(pkg.applicationInfo); 19080 19081 } catch (PackageManagerException e) { 19082 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19083 } 19084 19085 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19086 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19087 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19088 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19089 } 19090 } 19091 } 19092 19093 // Reconcile app data for all started/unlocked users 19094 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19095 final UserManager um = mContext.getSystemService(UserManager.class); 19096 UserManagerInternal umInternal = getUserManagerInternal(); 19097 for (UserInfo user : um.getUsers()) { 19098 final int flags; 19099 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19100 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19101 } else if (umInternal.isUserRunning(user.id)) { 19102 flags = StorageManager.FLAG_STORAGE_DE; 19103 } else { 19104 continue; 19105 } 19106 19107 try { 19108 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19109 synchronized (mInstallLock) { 19110 reconcileAppsDataLI(volumeUuid, user.id, flags); 19111 } 19112 } catch (IllegalStateException e) { 19113 // Device was probably ejected, and we'll process that event momentarily 19114 Slog.w(TAG, "Failed to prepare storage: " + e); 19115 } 19116 } 19117 19118 synchronized (mPackages) { 19119 int updateFlags = UPDATE_PERMISSIONS_ALL; 19120 if (ver.sdkVersion != mSdkVersion) { 19121 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19122 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19123 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19124 } 19125 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19126 19127 // Yay, everything is now upgraded 19128 ver.forceCurrent(); 19129 19130 mSettings.writeLPr(); 19131 } 19132 19133 for (PackageFreezer freezer : freezers) { 19134 freezer.close(); 19135 } 19136 19137 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19138 sendResourcesChangedBroadcast(true, false, loaded, null); 19139 } 19140 19141 private void unloadPrivatePackages(final VolumeInfo vol) { 19142 mHandler.post(new Runnable() { 19143 @Override 19144 public void run() { 19145 unloadPrivatePackagesInner(vol); 19146 } 19147 }); 19148 } 19149 19150 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19151 final String volumeUuid = vol.fsUuid; 19152 if (TextUtils.isEmpty(volumeUuid)) { 19153 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19154 return; 19155 } 19156 19157 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19158 synchronized (mInstallLock) { 19159 synchronized (mPackages) { 19160 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19161 for (PackageSetting ps : packages) { 19162 if (ps.pkg == null) continue; 19163 19164 final ApplicationInfo info = ps.pkg.applicationInfo; 19165 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19166 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19167 19168 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19169 "unloadPrivatePackagesInner")) { 19170 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19171 false, null)) { 19172 unloaded.add(info); 19173 } else { 19174 Slog.w(TAG, "Failed to unload " + ps.codePath); 19175 } 19176 } 19177 19178 // Try very hard to release any references to this package 19179 // so we don't risk the system server being killed due to 19180 // open FDs 19181 AttributeCache.instance().removePackage(ps.name); 19182 } 19183 19184 mSettings.writeLPr(); 19185 } 19186 } 19187 19188 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19189 sendResourcesChangedBroadcast(false, false, unloaded, null); 19190 19191 // Try very hard to release any references to this path so we don't risk 19192 // the system server being killed due to open FDs 19193 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19194 19195 for (int i = 0; i < 3; i++) { 19196 System.gc(); 19197 System.runFinalization(); 19198 } 19199 } 19200 19201 /** 19202 * Prepare storage areas for given user on all mounted devices. 19203 */ 19204 void prepareUserData(int userId, int userSerial, int flags) { 19205 synchronized (mInstallLock) { 19206 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19207 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19208 final String volumeUuid = vol.getFsUuid(); 19209 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19210 } 19211 } 19212 } 19213 19214 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19215 boolean allowRecover) { 19216 // Prepare storage and verify that serial numbers are consistent; if 19217 // there's a mismatch we need to destroy to avoid leaking data 19218 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19219 try { 19220 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19221 19222 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19223 UserManagerService.enforceSerialNumber( 19224 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19225 } 19226 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19227 UserManagerService.enforceSerialNumber( 19228 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19229 } 19230 19231 synchronized (mInstallLock) { 19232 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19233 } 19234 } catch (Exception e) { 19235 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19236 + " because we failed to prepare: " + e); 19237 destroyUserDataLI(volumeUuid, userId, 19238 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19239 19240 if (allowRecover) { 19241 // Try one last time; if we fail again we're really in trouble 19242 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19243 } 19244 } 19245 } 19246 19247 /** 19248 * Destroy storage areas for given user on all mounted devices. 19249 */ 19250 void destroyUserData(int userId, int flags) { 19251 synchronized (mInstallLock) { 19252 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19253 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19254 final String volumeUuid = vol.getFsUuid(); 19255 destroyUserDataLI(volumeUuid, userId, flags); 19256 } 19257 } 19258 } 19259 19260 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19261 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19262 try { 19263 // Clean up app data, profile data, and media data 19264 mInstaller.destroyUserData(volumeUuid, userId, flags); 19265 19266 // Clean up system data 19267 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19268 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19269 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19270 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19271 } 19272 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19273 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19274 } 19275 } 19276 19277 // Data with special labels is now gone, so finish the job 19278 storage.destroyUserStorage(volumeUuid, userId, flags); 19279 19280 } catch (Exception e) { 19281 logCriticalInfo(Log.WARN, 19282 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19283 } 19284 } 19285 19286 /** 19287 * Examine all users present on given mounted volume, and destroy data 19288 * belonging to users that are no longer valid, or whose user ID has been 19289 * recycled. 19290 */ 19291 private void reconcileUsers(String volumeUuid) { 19292 final List<File> files = new ArrayList<>(); 19293 Collections.addAll(files, FileUtils 19294 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19295 Collections.addAll(files, FileUtils 19296 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19297 for (File file : files) { 19298 if (!file.isDirectory()) continue; 19299 19300 final int userId; 19301 final UserInfo info; 19302 try { 19303 userId = Integer.parseInt(file.getName()); 19304 info = sUserManager.getUserInfo(userId); 19305 } catch (NumberFormatException e) { 19306 Slog.w(TAG, "Invalid user directory " + file); 19307 continue; 19308 } 19309 19310 boolean destroyUser = false; 19311 if (info == null) { 19312 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19313 + " because no matching user was found"); 19314 destroyUser = true; 19315 } else if (!mOnlyCore) { 19316 try { 19317 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19318 } catch (IOException e) { 19319 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19320 + " because we failed to enforce serial number: " + e); 19321 destroyUser = true; 19322 } 19323 } 19324 19325 if (destroyUser) { 19326 synchronized (mInstallLock) { 19327 destroyUserDataLI(volumeUuid, userId, 19328 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19329 } 19330 } 19331 } 19332 } 19333 19334 private void assertPackageKnown(String volumeUuid, String packageName) 19335 throws PackageManagerException { 19336 synchronized (mPackages) { 19337 final PackageSetting ps = mSettings.mPackages.get(packageName); 19338 if (ps == null) { 19339 throw new PackageManagerException("Package " + packageName + " is unknown"); 19340 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19341 throw new PackageManagerException( 19342 "Package " + packageName + " found on unknown volume " + volumeUuid 19343 + "; expected volume " + ps.volumeUuid); 19344 } 19345 } 19346 } 19347 19348 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19349 throws PackageManagerException { 19350 synchronized (mPackages) { 19351 final PackageSetting ps = mSettings.mPackages.get(packageName); 19352 if (ps == null) { 19353 throw new PackageManagerException("Package " + packageName + " is unknown"); 19354 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19355 throw new PackageManagerException( 19356 "Package " + packageName + " found on unknown volume " + volumeUuid 19357 + "; expected volume " + ps.volumeUuid); 19358 } else if (!ps.getInstalled(userId)) { 19359 throw new PackageManagerException( 19360 "Package " + packageName + " not installed for user " + userId); 19361 } 19362 } 19363 } 19364 19365 /** 19366 * Examine all apps present on given mounted volume, and destroy apps that 19367 * aren't expected, either due to uninstallation or reinstallation on 19368 * another volume. 19369 */ 19370 private void reconcileApps(String volumeUuid) { 19371 final File[] files = FileUtils 19372 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19373 for (File file : files) { 19374 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19375 && !PackageInstallerService.isStageName(file.getName()); 19376 if (!isPackage) { 19377 // Ignore entries which are not packages 19378 continue; 19379 } 19380 19381 try { 19382 final PackageLite pkg = PackageParser.parsePackageLite(file, 19383 PackageParser.PARSE_MUST_BE_APK); 19384 assertPackageKnown(volumeUuid, pkg.packageName); 19385 19386 } catch (PackageParserException | PackageManagerException e) { 19387 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19388 synchronized (mInstallLock) { 19389 removeCodePathLI(file); 19390 } 19391 } 19392 } 19393 } 19394 19395 /** 19396 * Reconcile all app data for the given user. 19397 * <p> 19398 * Verifies that directories exist and that ownership and labeling is 19399 * correct for all installed apps on all mounted volumes. 19400 */ 19401 void reconcileAppsData(int userId, int flags) { 19402 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19403 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19404 final String volumeUuid = vol.getFsUuid(); 19405 synchronized (mInstallLock) { 19406 reconcileAppsDataLI(volumeUuid, userId, flags); 19407 } 19408 } 19409 } 19410 19411 /** 19412 * Reconcile all app data on given mounted volume. 19413 * <p> 19414 * Destroys app data that isn't expected, either due to uninstallation or 19415 * reinstallation on another volume. 19416 * <p> 19417 * Verifies that directories exist and that ownership and labeling is 19418 * correct for all installed apps. 19419 */ 19420 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19421 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19422 + Integer.toHexString(flags)); 19423 19424 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19425 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19426 19427 boolean restoreconNeeded = false; 19428 19429 // First look for stale data that doesn't belong, and check if things 19430 // have changed since we did our last restorecon 19431 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19432 if (StorageManager.isFileEncryptedNativeOrEmulated() 19433 && !StorageManager.isUserKeyUnlocked(userId)) { 19434 throw new RuntimeException( 19435 "Yikes, someone asked us to reconcile CE storage while " + userId 19436 + " was still locked; this would have caused massive data loss!"); 19437 } 19438 19439 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19440 19441 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19442 for (File file : files) { 19443 final String packageName = file.getName(); 19444 try { 19445 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19446 } catch (PackageManagerException e) { 19447 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19448 try { 19449 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19450 StorageManager.FLAG_STORAGE_CE, 0); 19451 } catch (InstallerException e2) { 19452 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19453 } 19454 } 19455 } 19456 } 19457 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19458 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19459 19460 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19461 for (File file : files) { 19462 final String packageName = file.getName(); 19463 try { 19464 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19465 } catch (PackageManagerException e) { 19466 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19467 try { 19468 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19469 StorageManager.FLAG_STORAGE_DE, 0); 19470 } catch (InstallerException e2) { 19471 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19472 } 19473 } 19474 } 19475 } 19476 19477 // Ensure that data directories are ready to roll for all packages 19478 // installed for this volume and user 19479 final List<PackageSetting> packages; 19480 synchronized (mPackages) { 19481 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19482 } 19483 int preparedCount = 0; 19484 for (PackageSetting ps : packages) { 19485 final String packageName = ps.name; 19486 if (ps.pkg == null) { 19487 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19488 // TODO: might be due to legacy ASEC apps; we should circle back 19489 // and reconcile again once they're scanned 19490 continue; 19491 } 19492 19493 if (ps.getInstalled(userId)) { 19494 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19495 19496 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19497 // We may have just shuffled around app data directories, so 19498 // prepare them one more time 19499 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19500 } 19501 19502 preparedCount++; 19503 } 19504 } 19505 19506 if (restoreconNeeded) { 19507 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19508 SELinuxMMAC.setRestoreconDone(ceDir); 19509 } 19510 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19511 SELinuxMMAC.setRestoreconDone(deDir); 19512 } 19513 } 19514 19515 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19516 + " packages; restoreconNeeded was " + restoreconNeeded); 19517 } 19518 19519 /** 19520 * Prepare app data for the given app just after it was installed or 19521 * upgraded. This method carefully only touches users that it's installed 19522 * for, and it forces a restorecon to handle any seinfo changes. 19523 * <p> 19524 * Verifies that directories exist and that ownership and labeling is 19525 * correct for all installed apps. If there is an ownership mismatch, it 19526 * will try recovering system apps by wiping data; third-party app data is 19527 * left intact. 19528 * <p> 19529 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19530 */ 19531 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19532 final PackageSetting ps; 19533 synchronized (mPackages) { 19534 ps = mSettings.mPackages.get(pkg.packageName); 19535 mSettings.writeKernelMappingLPr(ps); 19536 } 19537 19538 final UserManager um = mContext.getSystemService(UserManager.class); 19539 UserManagerInternal umInternal = getUserManagerInternal(); 19540 for (UserInfo user : um.getUsers()) { 19541 final int flags; 19542 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19543 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19544 } else if (umInternal.isUserRunning(user.id)) { 19545 flags = StorageManager.FLAG_STORAGE_DE; 19546 } else { 19547 continue; 19548 } 19549 19550 if (ps.getInstalled(user.id)) { 19551 // Whenever an app changes, force a restorecon of its data 19552 // TODO: when user data is locked, mark that we're still dirty 19553 prepareAppDataLIF(pkg, user.id, flags, true); 19554 } 19555 } 19556 } 19557 19558 /** 19559 * Prepare app data for the given app. 19560 * <p> 19561 * Verifies that directories exist and that ownership and labeling is 19562 * correct for all installed apps. If there is an ownership mismatch, this 19563 * will try recovering system apps by wiping data; third-party app data is 19564 * left intact. 19565 */ 19566 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19567 boolean restoreconNeeded) { 19568 if (pkg == null) { 19569 Slog.wtf(TAG, "Package was null!", new Throwable()); 19570 return; 19571 } 19572 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19573 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19574 for (int i = 0; i < childCount; i++) { 19575 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19576 } 19577 } 19578 19579 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19580 boolean restoreconNeeded) { 19581 if (DEBUG_APP_DATA) { 19582 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19583 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19584 } 19585 19586 final String volumeUuid = pkg.volumeUuid; 19587 final String packageName = pkg.packageName; 19588 final ApplicationInfo app = pkg.applicationInfo; 19589 final int appId = UserHandle.getAppId(app.uid); 19590 19591 Preconditions.checkNotNull(app.seinfo); 19592 19593 try { 19594 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19595 appId, app.seinfo, app.targetSdkVersion); 19596 } catch (InstallerException e) { 19597 if (app.isSystemApp()) { 19598 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19599 + ", but trying to recover: " + e); 19600 destroyAppDataLeafLIF(pkg, userId, flags); 19601 try { 19602 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19603 appId, app.seinfo, app.targetSdkVersion); 19604 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19605 } catch (InstallerException e2) { 19606 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19607 } 19608 } else { 19609 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19610 } 19611 } 19612 19613 if (restoreconNeeded) { 19614 try { 19615 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19616 app.seinfo); 19617 } catch (InstallerException e) { 19618 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19619 } 19620 } 19621 19622 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19623 try { 19624 // CE storage is unlocked right now, so read out the inode and 19625 // remember for use later when it's locked 19626 // TODO: mark this structure as dirty so we persist it! 19627 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19628 StorageManager.FLAG_STORAGE_CE); 19629 synchronized (mPackages) { 19630 final PackageSetting ps = mSettings.mPackages.get(packageName); 19631 if (ps != null) { 19632 ps.setCeDataInode(ceDataInode, userId); 19633 } 19634 } 19635 } catch (InstallerException e) { 19636 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19637 } 19638 } 19639 19640 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19641 } 19642 19643 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19644 if (pkg == null) { 19645 Slog.wtf(TAG, "Package was null!", new Throwable()); 19646 return; 19647 } 19648 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19649 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19650 for (int i = 0; i < childCount; i++) { 19651 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19652 } 19653 } 19654 19655 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19656 final String volumeUuid = pkg.volumeUuid; 19657 final String packageName = pkg.packageName; 19658 final ApplicationInfo app = pkg.applicationInfo; 19659 19660 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19661 // Create a native library symlink only if we have native libraries 19662 // and if the native libraries are 32 bit libraries. We do not provide 19663 // this symlink for 64 bit libraries. 19664 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19665 final String nativeLibPath = app.nativeLibraryDir; 19666 try { 19667 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19668 nativeLibPath, userId); 19669 } catch (InstallerException e) { 19670 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19671 } 19672 } 19673 } 19674 } 19675 19676 /** 19677 * For system apps on non-FBE devices, this method migrates any existing 19678 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19679 * requested by the app. 19680 */ 19681 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19682 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19683 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19684 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19685 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19686 try { 19687 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19688 storageTarget); 19689 } catch (InstallerException e) { 19690 logCriticalInfo(Log.WARN, 19691 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19692 } 19693 return true; 19694 } else { 19695 return false; 19696 } 19697 } 19698 19699 public PackageFreezer freezePackage(String packageName, String killReason) { 19700 return new PackageFreezer(packageName, killReason); 19701 } 19702 19703 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19704 String killReason) { 19705 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19706 return new PackageFreezer(); 19707 } else { 19708 return freezePackage(packageName, killReason); 19709 } 19710 } 19711 19712 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19713 String killReason) { 19714 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19715 return new PackageFreezer(); 19716 } else { 19717 return freezePackage(packageName, killReason); 19718 } 19719 } 19720 19721 /** 19722 * Class that freezes and kills the given package upon creation, and 19723 * unfreezes it upon closing. This is typically used when doing surgery on 19724 * app code/data to prevent the app from running while you're working. 19725 */ 19726 private class PackageFreezer implements AutoCloseable { 19727 private final String mPackageName; 19728 private final PackageFreezer[] mChildren; 19729 19730 private final boolean mWeFroze; 19731 19732 private final AtomicBoolean mClosed = new AtomicBoolean(); 19733 private final CloseGuard mCloseGuard = CloseGuard.get(); 19734 19735 /** 19736 * Create and return a stub freezer that doesn't actually do anything, 19737 * typically used when someone requested 19738 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19739 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19740 */ 19741 public PackageFreezer() { 19742 mPackageName = null; 19743 mChildren = null; 19744 mWeFroze = false; 19745 mCloseGuard.open("close"); 19746 } 19747 19748 public PackageFreezer(String packageName, String killReason) { 19749 synchronized (mPackages) { 19750 mPackageName = packageName; 19751 mWeFroze = mFrozenPackages.add(mPackageName); 19752 19753 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19754 if (ps != null) { 19755 killApplication(ps.name, ps.appId, killReason); 19756 } 19757 19758 final PackageParser.Package p = mPackages.get(packageName); 19759 if (p != null && p.childPackages != null) { 19760 final int N = p.childPackages.size(); 19761 mChildren = new PackageFreezer[N]; 19762 for (int i = 0; i < N; i++) { 19763 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19764 killReason); 19765 } 19766 } else { 19767 mChildren = null; 19768 } 19769 } 19770 mCloseGuard.open("close"); 19771 } 19772 19773 @Override 19774 protected void finalize() throws Throwable { 19775 try { 19776 mCloseGuard.warnIfOpen(); 19777 close(); 19778 } finally { 19779 super.finalize(); 19780 } 19781 } 19782 19783 @Override 19784 public void close() { 19785 mCloseGuard.close(); 19786 if (mClosed.compareAndSet(false, true)) { 19787 synchronized (mPackages) { 19788 if (mWeFroze) { 19789 mFrozenPackages.remove(mPackageName); 19790 } 19791 19792 if (mChildren != null) { 19793 for (PackageFreezer freezer : mChildren) { 19794 freezer.close(); 19795 } 19796 } 19797 } 19798 } 19799 } 19800 } 19801 19802 /** 19803 * Verify that given package is currently frozen. 19804 */ 19805 private void checkPackageFrozen(String packageName) { 19806 synchronized (mPackages) { 19807 if (!mFrozenPackages.contains(packageName)) { 19808 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19809 } 19810 } 19811 } 19812 19813 @Override 19814 public int movePackage(final String packageName, final String volumeUuid) { 19815 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19816 19817 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19818 final int moveId = mNextMoveId.getAndIncrement(); 19819 mHandler.post(new Runnable() { 19820 @Override 19821 public void run() { 19822 try { 19823 movePackageInternal(packageName, volumeUuid, moveId, user); 19824 } catch (PackageManagerException e) { 19825 Slog.w(TAG, "Failed to move " + packageName, e); 19826 mMoveCallbacks.notifyStatusChanged(moveId, 19827 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19828 } 19829 } 19830 }); 19831 return moveId; 19832 } 19833 19834 private void movePackageInternal(final String packageName, final String volumeUuid, 19835 final int moveId, UserHandle user) throws PackageManagerException { 19836 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19837 final PackageManager pm = mContext.getPackageManager(); 19838 19839 final boolean currentAsec; 19840 final String currentVolumeUuid; 19841 final File codeFile; 19842 final String installerPackageName; 19843 final String packageAbiOverride; 19844 final int appId; 19845 final String seinfo; 19846 final String label; 19847 final int targetSdkVersion; 19848 final PackageFreezer freezer; 19849 final int[] installedUserIds; 19850 19851 // reader 19852 synchronized (mPackages) { 19853 final PackageParser.Package pkg = mPackages.get(packageName); 19854 final PackageSetting ps = mSettings.mPackages.get(packageName); 19855 if (pkg == null || ps == null) { 19856 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19857 } 19858 19859 if (pkg.applicationInfo.isSystemApp()) { 19860 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19861 "Cannot move system application"); 19862 } 19863 19864 if (pkg.applicationInfo.isExternalAsec()) { 19865 currentAsec = true; 19866 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19867 } else if (pkg.applicationInfo.isForwardLocked()) { 19868 currentAsec = true; 19869 currentVolumeUuid = "forward_locked"; 19870 } else { 19871 currentAsec = false; 19872 currentVolumeUuid = ps.volumeUuid; 19873 19874 final File probe = new File(pkg.codePath); 19875 final File probeOat = new File(probe, "oat"); 19876 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19877 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19878 "Move only supported for modern cluster style installs"); 19879 } 19880 } 19881 19882 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19883 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19884 "Package already moved to " + volumeUuid); 19885 } 19886 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19887 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19888 "Device admin cannot be moved"); 19889 } 19890 19891 if (mFrozenPackages.contains(packageName)) { 19892 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19893 "Failed to move already frozen package"); 19894 } 19895 19896 codeFile = new File(pkg.codePath); 19897 installerPackageName = ps.installerPackageName; 19898 packageAbiOverride = ps.cpuAbiOverrideString; 19899 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19900 seinfo = pkg.applicationInfo.seinfo; 19901 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19902 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19903 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19904 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19905 } 19906 19907 final Bundle extras = new Bundle(); 19908 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19909 extras.putString(Intent.EXTRA_TITLE, label); 19910 mMoveCallbacks.notifyCreated(moveId, extras); 19911 19912 int installFlags; 19913 final boolean moveCompleteApp; 19914 final File measurePath; 19915 19916 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19917 installFlags = INSTALL_INTERNAL; 19918 moveCompleteApp = !currentAsec; 19919 measurePath = Environment.getDataAppDirectory(volumeUuid); 19920 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19921 installFlags = INSTALL_EXTERNAL; 19922 moveCompleteApp = false; 19923 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19924 } else { 19925 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19926 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19927 || !volume.isMountedWritable()) { 19928 freezer.close(); 19929 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19930 "Move location not mounted private volume"); 19931 } 19932 19933 Preconditions.checkState(!currentAsec); 19934 19935 installFlags = INSTALL_INTERNAL; 19936 moveCompleteApp = true; 19937 measurePath = Environment.getDataAppDirectory(volumeUuid); 19938 } 19939 19940 final PackageStats stats = new PackageStats(null, -1); 19941 synchronized (mInstaller) { 19942 for (int userId : installedUserIds) { 19943 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19944 freezer.close(); 19945 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19946 "Failed to measure package size"); 19947 } 19948 } 19949 } 19950 19951 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19952 + stats.dataSize); 19953 19954 final long startFreeBytes = measurePath.getFreeSpace(); 19955 final long sizeBytes; 19956 if (moveCompleteApp) { 19957 sizeBytes = stats.codeSize + stats.dataSize; 19958 } else { 19959 sizeBytes = stats.codeSize; 19960 } 19961 19962 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19963 freezer.close(); 19964 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19965 "Not enough free space to move"); 19966 } 19967 19968 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19969 19970 final CountDownLatch installedLatch = new CountDownLatch(1); 19971 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19972 @Override 19973 public void onUserActionRequired(Intent intent) throws RemoteException { 19974 throw new IllegalStateException(); 19975 } 19976 19977 @Override 19978 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19979 Bundle extras) throws RemoteException { 19980 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19981 + PackageManager.installStatusToString(returnCode, msg)); 19982 19983 installedLatch.countDown(); 19984 freezer.close(); 19985 19986 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19987 switch (status) { 19988 case PackageInstaller.STATUS_SUCCESS: 19989 mMoveCallbacks.notifyStatusChanged(moveId, 19990 PackageManager.MOVE_SUCCEEDED); 19991 break; 19992 case PackageInstaller.STATUS_FAILURE_STORAGE: 19993 mMoveCallbacks.notifyStatusChanged(moveId, 19994 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19995 break; 19996 default: 19997 mMoveCallbacks.notifyStatusChanged(moveId, 19998 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19999 break; 20000 } 20001 } 20002 }; 20003 20004 final MoveInfo move; 20005 if (moveCompleteApp) { 20006 // Kick off a thread to report progress estimates 20007 new Thread() { 20008 @Override 20009 public void run() { 20010 while (true) { 20011 try { 20012 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20013 break; 20014 } 20015 } catch (InterruptedException ignored) { 20016 } 20017 20018 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20019 final int progress = 10 + (int) MathUtils.constrain( 20020 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20021 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20022 } 20023 } 20024 }.start(); 20025 20026 final String dataAppName = codeFile.getName(); 20027 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20028 dataAppName, appId, seinfo, targetSdkVersion); 20029 } else { 20030 move = null; 20031 } 20032 20033 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20034 20035 final Message msg = mHandler.obtainMessage(INIT_COPY); 20036 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20037 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20038 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20039 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20040 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20041 msg.obj = params; 20042 20043 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20044 System.identityHashCode(msg.obj)); 20045 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20046 System.identityHashCode(msg.obj)); 20047 20048 mHandler.sendMessage(msg); 20049 } 20050 20051 @Override 20052 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20053 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20054 20055 final int realMoveId = mNextMoveId.getAndIncrement(); 20056 final Bundle extras = new Bundle(); 20057 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20058 mMoveCallbacks.notifyCreated(realMoveId, extras); 20059 20060 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20061 @Override 20062 public void onCreated(int moveId, Bundle extras) { 20063 // Ignored 20064 } 20065 20066 @Override 20067 public void onStatusChanged(int moveId, int status, long estMillis) { 20068 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20069 } 20070 }; 20071 20072 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20073 storage.setPrimaryStorageUuid(volumeUuid, callback); 20074 return realMoveId; 20075 } 20076 20077 @Override 20078 public int getMoveStatus(int moveId) { 20079 mContext.enforceCallingOrSelfPermission( 20080 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20081 return mMoveCallbacks.mLastStatus.get(moveId); 20082 } 20083 20084 @Override 20085 public void registerMoveCallback(IPackageMoveObserver callback) { 20086 mContext.enforceCallingOrSelfPermission( 20087 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20088 mMoveCallbacks.register(callback); 20089 } 20090 20091 @Override 20092 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20093 mContext.enforceCallingOrSelfPermission( 20094 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20095 mMoveCallbacks.unregister(callback); 20096 } 20097 20098 @Override 20099 public boolean setInstallLocation(int loc) { 20100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20101 null); 20102 if (getInstallLocation() == loc) { 20103 return true; 20104 } 20105 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20106 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20107 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20108 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20109 return true; 20110 } 20111 return false; 20112 } 20113 20114 @Override 20115 public int getInstallLocation() { 20116 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20117 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20118 PackageHelper.APP_INSTALL_AUTO); 20119 } 20120 20121 /** Called by UserManagerService */ 20122 void cleanUpUser(UserManagerService userManager, int userHandle) { 20123 synchronized (mPackages) { 20124 mDirtyUsers.remove(userHandle); 20125 mUserNeedsBadging.delete(userHandle); 20126 mSettings.removeUserLPw(userHandle); 20127 mPendingBroadcasts.remove(userHandle); 20128 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20129 removeUnusedPackagesLPw(userManager, userHandle); 20130 } 20131 } 20132 20133 /** 20134 * We're removing userHandle and would like to remove any downloaded packages 20135 * that are no longer in use by any other user. 20136 * @param userHandle the user being removed 20137 */ 20138 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20139 final boolean DEBUG_CLEAN_APKS = false; 20140 int [] users = userManager.getUserIds(); 20141 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20142 while (psit.hasNext()) { 20143 PackageSetting ps = psit.next(); 20144 if (ps.pkg == null) { 20145 continue; 20146 } 20147 final String packageName = ps.pkg.packageName; 20148 // Skip over if system app 20149 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20150 continue; 20151 } 20152 if (DEBUG_CLEAN_APKS) { 20153 Slog.i(TAG, "Checking package " + packageName); 20154 } 20155 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20156 if (keep) { 20157 if (DEBUG_CLEAN_APKS) { 20158 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20159 } 20160 } else { 20161 for (int i = 0; i < users.length; i++) { 20162 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20163 keep = true; 20164 if (DEBUG_CLEAN_APKS) { 20165 Slog.i(TAG, " Keeping package " + packageName + " for user " 20166 + users[i]); 20167 } 20168 break; 20169 } 20170 } 20171 } 20172 if (!keep) { 20173 if (DEBUG_CLEAN_APKS) { 20174 Slog.i(TAG, " Removing package " + packageName); 20175 } 20176 mHandler.post(new Runnable() { 20177 public void run() { 20178 deletePackageX(packageName, userHandle, 0); 20179 } //end run 20180 }); 20181 } 20182 } 20183 } 20184 20185 /** Called by UserManagerService */ 20186 void createNewUser(int userId) { 20187 synchronized (mInstallLock) { 20188 mSettings.createNewUserLI(this, mInstaller, userId); 20189 } 20190 synchronized (mPackages) { 20191 scheduleWritePackageRestrictionsLocked(userId); 20192 scheduleWritePackageListLocked(userId); 20193 applyFactoryDefaultBrowserLPw(userId); 20194 primeDomainVerificationsLPw(userId); 20195 } 20196 } 20197 20198 void onBeforeUserStartUninitialized(final int userId) { 20199 synchronized (mPackages) { 20200 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20201 return; 20202 } 20203 } 20204 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20205 // If permission review for legacy apps is required, we represent 20206 // dagerous permissions for such apps as always granted runtime 20207 // permissions to keep per user flag state whether review is needed. 20208 // Hence, if a new user is added we have to propagate dangerous 20209 // permission grants for these legacy apps. 20210 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20211 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20212 | UPDATE_PERMISSIONS_REPLACE_ALL); 20213 } 20214 } 20215 20216 @Override 20217 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20218 mContext.enforceCallingOrSelfPermission( 20219 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20220 "Only package verification agents can read the verifier device identity"); 20221 20222 synchronized (mPackages) { 20223 return mSettings.getVerifierDeviceIdentityLPw(); 20224 } 20225 } 20226 20227 @Override 20228 public void setPermissionEnforced(String permission, boolean enforced) { 20229 // TODO: Now that we no longer change GID for storage, this should to away. 20230 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20231 "setPermissionEnforced"); 20232 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20233 synchronized (mPackages) { 20234 if (mSettings.mReadExternalStorageEnforced == null 20235 || mSettings.mReadExternalStorageEnforced != enforced) { 20236 mSettings.mReadExternalStorageEnforced = enforced; 20237 mSettings.writeLPr(); 20238 } 20239 } 20240 // kill any non-foreground processes so we restart them and 20241 // grant/revoke the GID. 20242 final IActivityManager am = ActivityManagerNative.getDefault(); 20243 if (am != null) { 20244 final long token = Binder.clearCallingIdentity(); 20245 try { 20246 am.killProcessesBelowForeground("setPermissionEnforcement"); 20247 } catch (RemoteException e) { 20248 } finally { 20249 Binder.restoreCallingIdentity(token); 20250 } 20251 } 20252 } else { 20253 throw new IllegalArgumentException("No selective enforcement for " + permission); 20254 } 20255 } 20256 20257 @Override 20258 @Deprecated 20259 public boolean isPermissionEnforced(String permission) { 20260 return true; 20261 } 20262 20263 @Override 20264 public boolean isStorageLow() { 20265 final long token = Binder.clearCallingIdentity(); 20266 try { 20267 final DeviceStorageMonitorInternal 20268 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20269 if (dsm != null) { 20270 return dsm.isMemoryLow(); 20271 } else { 20272 return false; 20273 } 20274 } finally { 20275 Binder.restoreCallingIdentity(token); 20276 } 20277 } 20278 20279 @Override 20280 public IPackageInstaller getPackageInstaller() { 20281 return mInstallerService; 20282 } 20283 20284 private boolean userNeedsBadging(int userId) { 20285 int index = mUserNeedsBadging.indexOfKey(userId); 20286 if (index < 0) { 20287 final UserInfo userInfo; 20288 final long token = Binder.clearCallingIdentity(); 20289 try { 20290 userInfo = sUserManager.getUserInfo(userId); 20291 } finally { 20292 Binder.restoreCallingIdentity(token); 20293 } 20294 final boolean b; 20295 if (userInfo != null && userInfo.isManagedProfile()) { 20296 b = true; 20297 } else { 20298 b = false; 20299 } 20300 mUserNeedsBadging.put(userId, b); 20301 return b; 20302 } 20303 return mUserNeedsBadging.valueAt(index); 20304 } 20305 20306 @Override 20307 public KeySet getKeySetByAlias(String packageName, String alias) { 20308 if (packageName == null || alias == null) { 20309 return null; 20310 } 20311 synchronized(mPackages) { 20312 final PackageParser.Package pkg = mPackages.get(packageName); 20313 if (pkg == null) { 20314 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20315 throw new IllegalArgumentException("Unknown package: " + packageName); 20316 } 20317 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20318 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20319 } 20320 } 20321 20322 @Override 20323 public KeySet getSigningKeySet(String packageName) { 20324 if (packageName == null) { 20325 return null; 20326 } 20327 synchronized(mPackages) { 20328 final PackageParser.Package pkg = mPackages.get(packageName); 20329 if (pkg == null) { 20330 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20331 throw new IllegalArgumentException("Unknown package: " + packageName); 20332 } 20333 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20334 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20335 throw new SecurityException("May not access signing KeySet of other apps."); 20336 } 20337 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20338 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20339 } 20340 } 20341 20342 @Override 20343 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20344 if (packageName == null || ks == null) { 20345 return false; 20346 } 20347 synchronized(mPackages) { 20348 final PackageParser.Package pkg = mPackages.get(packageName); 20349 if (pkg == null) { 20350 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20351 throw new IllegalArgumentException("Unknown package: " + packageName); 20352 } 20353 IBinder ksh = ks.getToken(); 20354 if (ksh instanceof KeySetHandle) { 20355 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20356 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20357 } 20358 return false; 20359 } 20360 } 20361 20362 @Override 20363 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20364 if (packageName == null || ks == null) { 20365 return false; 20366 } 20367 synchronized(mPackages) { 20368 final PackageParser.Package pkg = mPackages.get(packageName); 20369 if (pkg == null) { 20370 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20371 throw new IllegalArgumentException("Unknown package: " + packageName); 20372 } 20373 IBinder ksh = ks.getToken(); 20374 if (ksh instanceof KeySetHandle) { 20375 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20376 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20377 } 20378 return false; 20379 } 20380 } 20381 20382 private void deletePackageIfUnusedLPr(final String packageName) { 20383 PackageSetting ps = mSettings.mPackages.get(packageName); 20384 if (ps == null) { 20385 return; 20386 } 20387 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20388 // TODO Implement atomic delete if package is unused 20389 // It is currently possible that the package will be deleted even if it is installed 20390 // after this method returns. 20391 mHandler.post(new Runnable() { 20392 public void run() { 20393 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20394 } 20395 }); 20396 } 20397 } 20398 20399 /** 20400 * Check and throw if the given before/after packages would be considered a 20401 * downgrade. 20402 */ 20403 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20404 throws PackageManagerException { 20405 if (after.versionCode < before.mVersionCode) { 20406 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20407 "Update version code " + after.versionCode + " is older than current " 20408 + before.mVersionCode); 20409 } else if (after.versionCode == before.mVersionCode) { 20410 if (after.baseRevisionCode < before.baseRevisionCode) { 20411 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20412 "Update base revision code " + after.baseRevisionCode 20413 + " is older than current " + before.baseRevisionCode); 20414 } 20415 20416 if (!ArrayUtils.isEmpty(after.splitNames)) { 20417 for (int i = 0; i < after.splitNames.length; i++) { 20418 final String splitName = after.splitNames[i]; 20419 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20420 if (j != -1) { 20421 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20422 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20423 "Update split " + splitName + " revision code " 20424 + after.splitRevisionCodes[i] + " is older than current " 20425 + before.splitRevisionCodes[j]); 20426 } 20427 } 20428 } 20429 } 20430 } 20431 } 20432 20433 private static class MoveCallbacks extends Handler { 20434 private static final int MSG_CREATED = 1; 20435 private static final int MSG_STATUS_CHANGED = 2; 20436 20437 private final RemoteCallbackList<IPackageMoveObserver> 20438 mCallbacks = new RemoteCallbackList<>(); 20439 20440 private final SparseIntArray mLastStatus = new SparseIntArray(); 20441 20442 public MoveCallbacks(Looper looper) { 20443 super(looper); 20444 } 20445 20446 public void register(IPackageMoveObserver callback) { 20447 mCallbacks.register(callback); 20448 } 20449 20450 public void unregister(IPackageMoveObserver callback) { 20451 mCallbacks.unregister(callback); 20452 } 20453 20454 @Override 20455 public void handleMessage(Message msg) { 20456 final SomeArgs args = (SomeArgs) msg.obj; 20457 final int n = mCallbacks.beginBroadcast(); 20458 for (int i = 0; i < n; i++) { 20459 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20460 try { 20461 invokeCallback(callback, msg.what, args); 20462 } catch (RemoteException ignored) { 20463 } 20464 } 20465 mCallbacks.finishBroadcast(); 20466 args.recycle(); 20467 } 20468 20469 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20470 throws RemoteException { 20471 switch (what) { 20472 case MSG_CREATED: { 20473 callback.onCreated(args.argi1, (Bundle) args.arg2); 20474 break; 20475 } 20476 case MSG_STATUS_CHANGED: { 20477 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20478 break; 20479 } 20480 } 20481 } 20482 20483 private void notifyCreated(int moveId, Bundle extras) { 20484 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20485 20486 final SomeArgs args = SomeArgs.obtain(); 20487 args.argi1 = moveId; 20488 args.arg2 = extras; 20489 obtainMessage(MSG_CREATED, args).sendToTarget(); 20490 } 20491 20492 private void notifyStatusChanged(int moveId, int status) { 20493 notifyStatusChanged(moveId, status, -1); 20494 } 20495 20496 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20497 Slog.v(TAG, "Move " + moveId + " status " + status); 20498 20499 final SomeArgs args = SomeArgs.obtain(); 20500 args.argi1 = moveId; 20501 args.argi2 = status; 20502 args.arg3 = estMillis; 20503 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20504 20505 synchronized (mLastStatus) { 20506 mLastStatus.put(moveId, status); 20507 } 20508 } 20509 } 20510 20511 private final static class OnPermissionChangeListeners extends Handler { 20512 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20513 20514 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20515 new RemoteCallbackList<>(); 20516 20517 public OnPermissionChangeListeners(Looper looper) { 20518 super(looper); 20519 } 20520 20521 @Override 20522 public void handleMessage(Message msg) { 20523 switch (msg.what) { 20524 case MSG_ON_PERMISSIONS_CHANGED: { 20525 final int uid = msg.arg1; 20526 handleOnPermissionsChanged(uid); 20527 } break; 20528 } 20529 } 20530 20531 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20532 mPermissionListeners.register(listener); 20533 20534 } 20535 20536 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20537 mPermissionListeners.unregister(listener); 20538 } 20539 20540 public void onPermissionsChanged(int uid) { 20541 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20542 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20543 } 20544 } 20545 20546 private void handleOnPermissionsChanged(int uid) { 20547 final int count = mPermissionListeners.beginBroadcast(); 20548 try { 20549 for (int i = 0; i < count; i++) { 20550 IOnPermissionsChangeListener callback = mPermissionListeners 20551 .getBroadcastItem(i); 20552 try { 20553 callback.onPermissionsChanged(uid); 20554 } catch (RemoteException e) { 20555 Log.e(TAG, "Permission listener is dead", e); 20556 } 20557 } 20558 } finally { 20559 mPermissionListeners.finishBroadcast(); 20560 } 20561 } 20562 } 20563 20564 private class PackageManagerInternalImpl extends PackageManagerInternal { 20565 @Override 20566 public void setLocationPackagesProvider(PackagesProvider provider) { 20567 synchronized (mPackages) { 20568 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20569 } 20570 } 20571 20572 @Override 20573 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20574 synchronized (mPackages) { 20575 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20576 } 20577 } 20578 20579 @Override 20580 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20581 synchronized (mPackages) { 20582 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20583 } 20584 } 20585 20586 @Override 20587 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20588 synchronized (mPackages) { 20589 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20590 } 20591 } 20592 20593 @Override 20594 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20595 synchronized (mPackages) { 20596 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20597 } 20598 } 20599 20600 @Override 20601 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20602 synchronized (mPackages) { 20603 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20604 } 20605 } 20606 20607 @Override 20608 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20609 synchronized (mPackages) { 20610 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20611 packageName, userId); 20612 } 20613 } 20614 20615 @Override 20616 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20617 synchronized (mPackages) { 20618 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20619 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20620 packageName, userId); 20621 } 20622 } 20623 20624 @Override 20625 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20626 synchronized (mPackages) { 20627 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20628 packageName, userId); 20629 } 20630 } 20631 20632 @Override 20633 public void setKeepUninstalledPackages(final List<String> packageList) { 20634 Preconditions.checkNotNull(packageList); 20635 List<String> removedFromList = null; 20636 synchronized (mPackages) { 20637 if (mKeepUninstalledPackages != null) { 20638 final int packagesCount = mKeepUninstalledPackages.size(); 20639 for (int i = 0; i < packagesCount; i++) { 20640 String oldPackage = mKeepUninstalledPackages.get(i); 20641 if (packageList != null && packageList.contains(oldPackage)) { 20642 continue; 20643 } 20644 if (removedFromList == null) { 20645 removedFromList = new ArrayList<>(); 20646 } 20647 removedFromList.add(oldPackage); 20648 } 20649 } 20650 mKeepUninstalledPackages = new ArrayList<>(packageList); 20651 if (removedFromList != null) { 20652 final int removedCount = removedFromList.size(); 20653 for (int i = 0; i < removedCount; i++) { 20654 deletePackageIfUnusedLPr(removedFromList.get(i)); 20655 } 20656 } 20657 } 20658 } 20659 20660 @Override 20661 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20662 synchronized (mPackages) { 20663 // If we do not support permission review, done. 20664 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20665 return false; 20666 } 20667 20668 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20669 if (packageSetting == null) { 20670 return false; 20671 } 20672 20673 // Permission review applies only to apps not supporting the new permission model. 20674 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20675 return false; 20676 } 20677 20678 // Legacy apps have the permission and get user consent on launch. 20679 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20680 return permissionsState.isPermissionReviewRequired(userId); 20681 } 20682 } 20683 20684 @Override 20685 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20686 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20687 } 20688 20689 @Override 20690 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20691 int userId) { 20692 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20693 } 20694 } 20695 20696 @Override 20697 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20698 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20699 synchronized (mPackages) { 20700 final long identity = Binder.clearCallingIdentity(); 20701 try { 20702 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20703 packageNames, userId); 20704 } finally { 20705 Binder.restoreCallingIdentity(identity); 20706 } 20707 } 20708 } 20709 20710 private static void enforceSystemOrPhoneCaller(String tag) { 20711 int callingUid = Binder.getCallingUid(); 20712 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20713 throw new SecurityException( 20714 "Cannot call " + tag + " from UID " + callingUid); 20715 } 20716 } 20717 20718 boolean isHistoricalPackageUsageAvailable() { 20719 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20720 } 20721 20722 /** 20723 * Return a <b>copy</b> of the collection of packages known to the package manager. 20724 * @return A copy of the values of mPackages. 20725 */ 20726 Collection<PackageParser.Package> getPackages() { 20727 synchronized (mPackages) { 20728 return new ArrayList<>(mPackages.values()); 20729 } 20730 } 20731 20732 /** 20733 * Logs process start information (including base APK hash) to the security log. 20734 * @hide 20735 */ 20736 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20737 String apkFile, int pid) { 20738 if (!SecurityLog.isLoggingEnabled()) { 20739 return; 20740 } 20741 Bundle data = new Bundle(); 20742 data.putLong("startTimestamp", System.currentTimeMillis()); 20743 data.putString("processName", processName); 20744 data.putInt("uid", uid); 20745 data.putString("seinfo", seinfo); 20746 data.putString("apkFile", apkFile); 20747 data.putInt("pid", pid); 20748 Message msg = mProcessLoggingHandler.obtainMessage( 20749 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20750 msg.setData(data); 20751 mProcessLoggingHandler.sendMessage(msg); 20752 } 20753} 20754