PackageManagerService.java revision ca82e616d3131570bf2ee29778f4796f343720d5
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.security.KeyStore; 199import android.security.SystemKeyStore; 200import android.system.ErrnoException; 201import android.system.Os; 202import android.text.TextUtils; 203import android.text.format.DateUtils; 204import android.util.ArrayMap; 205import android.util.ArraySet; 206import android.util.AtomicFile; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.util.jar.StrictJarFile; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.os.IParcelFileDescriptorFactory; 229import com.android.internal.os.InstallerConnection.InstallerException; 230import com.android.internal.os.SomeArgs; 231import com.android.internal.os.Zygote; 232import com.android.internal.telephony.CarrierAppUtils; 233import com.android.internal.util.ArrayUtils; 234import com.android.internal.util.FastPrintWriter; 235import com.android.internal.util.FastXmlSerializer; 236import com.android.internal.util.IndentingPrintWriter; 237import com.android.internal.util.Preconditions; 238import com.android.internal.util.XmlUtils; 239import com.android.server.EventLogTags; 240import com.android.server.FgThread; 241import com.android.server.IntentResolver; 242import com.android.server.LocalServices; 243import com.android.server.ServiceThread; 244import com.android.server.SystemConfig; 245import com.android.server.Watchdog; 246import com.android.server.pm.PermissionsState.PermissionState; 247import com.android.server.pm.Settings.DatabaseVersion; 248import com.android.server.pm.Settings.VersionInfo; 249import com.android.server.storage.DeviceStorageMonitorInternal; 250 251import dalvik.system.CloseGuard; 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.Certificate; 281import java.security.cert.CertificateEncodingException; 282import java.security.cert.CertificateException; 283import java.text.SimpleDateFormat; 284import java.util.ArrayList; 285import java.util.Arrays; 286import java.util.Collection; 287import java.util.Collections; 288import java.util.Comparator; 289import java.util.Date; 290import java.util.HashSet; 291import java.util.Iterator; 292import java.util.List; 293import java.util.Map; 294import java.util.Objects; 295import java.util.Set; 296import java.util.concurrent.CountDownLatch; 297import java.util.concurrent.TimeUnit; 298import java.util.concurrent.atomic.AtomicBoolean; 299import java.util.concurrent.atomic.AtomicInteger; 300import java.util.concurrent.atomic.AtomicLong; 301 302/** 303 * Keep track of all those APKs everywhere. 304 * <p> 305 * Internally there are two important locks: 306 * <ul> 307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 308 * and other related state. It is a fine-grained lock that should only be held 309 * momentarily, as it's one of the most contended locks in the system. 310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 311 * operations typically involve heavy lifting of application data on disk. Since 312 * {@code installd} is single-threaded, and it's operations can often be slow, 313 * this lock should never be acquired while already holding {@link #mPackages}. 314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 315 * holding {@link #mInstallLock}. 316 * </ul> 317 * Many internal methods rely on the caller to hold the appropriate locks, and 318 * this contract is expressed through method name suffixes: 319 * <ul> 320 * <li>fooLI(): the caller must hold {@link #mInstallLock} 321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 322 * being modified must be frozen 323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 325 * </ul> 326 * <p> 327 * Because this class is very central to the platform's security; please run all 328 * CTS and unit tests whenever making modifications: 329 * 330 * <pre> 331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 333 * </pre> 334 */ 335public class PackageManagerService extends IPackageManager.Stub { 336 static final String TAG = "PackageManager"; 337 static final boolean DEBUG_SETTINGS = false; 338 static final boolean DEBUG_PREFERRED = false; 339 static final boolean DEBUG_UPGRADE = false; 340 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 341 private static final boolean DEBUG_BACKUP = false; 342 private static final boolean DEBUG_INSTALL = false; 343 private static final boolean DEBUG_REMOVE = false; 344 private static final boolean DEBUG_BROADCASTS = false; 345 private static final boolean DEBUG_SHOW_INFO = false; 346 private static final boolean DEBUG_PACKAGE_INFO = false; 347 private static final boolean DEBUG_INTENT_MATCHING = false; 348 private static final boolean DEBUG_PACKAGE_SCANNING = false; 349 private static final boolean DEBUG_VERIFY = false; 350 private static final boolean DEBUG_FILTERS = false; 351 352 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 353 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 354 // user, but by default initialize to this. 355 static final boolean DEBUG_DEXOPT = false; 356 357 private static final boolean DEBUG_ABI_SELECTION = false; 358 private static final boolean DEBUG_EPHEMERAL = false; 359 private static final boolean DEBUG_TRIAGED_MISSING = false; 360 private static final boolean DEBUG_APP_DATA = false; 361 362 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 363 364 private static final boolean DISABLE_EPHEMERAL_APPS = true; 365 366 private static final int RADIO_UID = Process.PHONE_UID; 367 private static final int LOG_UID = Process.LOG_UID; 368 private static final int NFC_UID = Process.NFC_UID; 369 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 370 private static final int SHELL_UID = Process.SHELL_UID; 371 372 // Cap the size of permission trees that 3rd party apps can define 373 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 374 375 // Suffix used during package installation when copying/moving 376 // package apks to install directory. 377 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 378 379 static final int SCAN_NO_DEX = 1<<1; 380 static final int SCAN_FORCE_DEX = 1<<2; 381 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 382 static final int SCAN_NEW_INSTALL = 1<<4; 383 static final int SCAN_NO_PATHS = 1<<5; 384 static final int SCAN_UPDATE_TIME = 1<<6; 385 static final int SCAN_DEFER_DEX = 1<<7; 386 static final int SCAN_BOOTING = 1<<8; 387 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 388 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 389 static final int SCAN_REPLACING = 1<<11; 390 static final int SCAN_REQUIRE_KNOWN = 1<<12; 391 static final int SCAN_MOVE = 1<<13; 392 static final int SCAN_INITIAL = 1<<14; 393 static final int SCAN_CHECK_ONLY = 1<<15; 394 static final int SCAN_DONT_KILL_APP = 1<<17; 395 static final int SCAN_IGNORE_FROZEN = 1<<18; 396 397 static final int REMOVE_CHATTY = 1<<16; 398 399 private static final int[] EMPTY_INT_ARRAY = new int[0]; 400 401 /** 402 * Timeout (in milliseconds) after which the watchdog should declare that 403 * our handler thread is wedged. The usual default for such things is one 404 * minute but we sometimes do very lengthy I/O operations on this thread, 405 * such as installing multi-gigabyte applications, so ours needs to be longer. 406 */ 407 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 408 409 /** 410 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 411 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 412 * settings entry if available, otherwise we use the hardcoded default. If it's been 413 * more than this long since the last fstrim, we force one during the boot sequence. 414 * 415 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 416 * one gets run at the next available charging+idle time. This final mandatory 417 * no-fstrim check kicks in only of the other scheduling criteria is never met. 418 */ 419 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 420 421 /** 422 * Whether verification is enabled by default. 423 */ 424 private static final boolean DEFAULT_VERIFY_ENABLE = true; 425 426 /** 427 * The default maximum time to wait for the verification agent to return in 428 * milliseconds. 429 */ 430 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 431 432 /** 433 * The default response for package verification timeout. 434 * 435 * This can be either PackageManager.VERIFICATION_ALLOW or 436 * PackageManager.VERIFICATION_REJECT. 437 */ 438 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 439 440 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 441 442 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 443 DEFAULT_CONTAINER_PACKAGE, 444 "com.android.defcontainer.DefaultContainerService"); 445 446 private static final String KILL_APP_REASON_GIDS_CHANGED = 447 "permission grant or revoke changed gids"; 448 449 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 450 "permissions revoked"; 451 452 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 453 454 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 455 456 /** Permission grant: not grant the permission. */ 457 private static final int GRANT_DENIED = 1; 458 459 /** Permission grant: grant the permission as an install permission. */ 460 private static final int GRANT_INSTALL = 2; 461 462 /** Permission grant: grant the permission as a runtime one. */ 463 private static final int GRANT_RUNTIME = 3; 464 465 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 466 private static final int GRANT_UPGRADE = 4; 467 468 /** Canonical intent used to identify what counts as a "web browser" app */ 469 private static final Intent sBrowserIntent; 470 static { 471 sBrowserIntent = new Intent(); 472 sBrowserIntent.setAction(Intent.ACTION_VIEW); 473 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 474 sBrowserIntent.setData(Uri.parse("http:")); 475 } 476 477 /** 478 * The set of all protected actions [i.e. those actions for which a high priority 479 * intent filter is disallowed]. 480 */ 481 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 482 static { 483 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 485 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 486 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 487 } 488 489 // Compilation reasons. 490 public static final int REASON_FIRST_BOOT = 0; 491 public static final int REASON_BOOT = 1; 492 public static final int REASON_INSTALL = 2; 493 public static final int REASON_BACKGROUND_DEXOPT = 3; 494 public static final int REASON_AB_OTA = 4; 495 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 496 public static final int REASON_SHARED_APK = 6; 497 public static final int REASON_FORCED_DEXOPT = 7; 498 499 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 500 501 final ServiceThread mHandlerThread; 502 503 final PackageHandler mHandler; 504 505 private final ProcessLoggingHandler mProcessLoggingHandler; 506 507 /** 508 * Messages for {@link #mHandler} that need to wait for system ready before 509 * being dispatched. 510 */ 511 private ArrayList<Message> mPostSystemReadyMessages; 512 513 final int mSdkVersion = Build.VERSION.SDK_INT; 514 515 final Context mContext; 516 final boolean mFactoryTest; 517 final boolean mOnlyCore; 518 final DisplayMetrics mMetrics; 519 final int mDefParseFlags; 520 final String[] mSeparateProcesses; 521 final boolean mIsUpgrade; 522 final boolean mIsPreNUpgrade; 523 524 /** The location for ASEC container files on internal storage. */ 525 final String mAsecInternalPath; 526 527 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 528 // LOCK HELD. Can be called with mInstallLock held. 529 @GuardedBy("mInstallLock") 530 final Installer mInstaller; 531 532 /** Directory where installed third-party apps stored */ 533 final File mAppInstallDir; 534 final File mEphemeralInstallDir; 535 536 /** 537 * Directory to which applications installed internally have their 538 * 32 bit native libraries copied. 539 */ 540 private File mAppLib32InstallDir; 541 542 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 543 // apps. 544 final File mDrmAppPrivateInstallDir; 545 546 // ---------------------------------------------------------------- 547 548 // Lock for state used when installing and doing other long running 549 // operations. Methods that must be called with this lock held have 550 // the suffix "LI". 551 final Object mInstallLock = new Object(); 552 553 // ---------------------------------------------------------------- 554 555 // Keys are String (package name), values are Package. This also serves 556 // as the lock for the global state. Methods that must be called with 557 // this lock held have the prefix "LP". 558 @GuardedBy("mPackages") 559 final ArrayMap<String, PackageParser.Package> mPackages = 560 new ArrayMap<String, PackageParser.Package>(); 561 562 final ArrayMap<String, Set<String>> mKnownCodebase = 563 new ArrayMap<String, Set<String>>(); 564 565 // Tracks available target package names -> overlay package paths. 566 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 567 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 568 569 /** 570 * Tracks new system packages [received in an OTA] that we expect to 571 * find updated user-installed versions. Keys are package name, values 572 * are package location. 573 */ 574 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 575 /** 576 * Tracks high priority intent filters for protected actions. During boot, certain 577 * filter actions are protected and should never be allowed to have a high priority 578 * intent filter for them. However, there is one, and only one exception -- the 579 * setup wizard. It must be able to define a high priority intent filter for these 580 * actions to ensure there are no escapes from the wizard. We need to delay processing 581 * of these during boot as we need to look at all of the system packages in order 582 * to know which component is the setup wizard. 583 */ 584 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 585 /** 586 * Whether or not processing protected filters should be deferred. 587 */ 588 private boolean mDeferProtectedFilters = true; 589 590 /** 591 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 592 */ 593 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 594 /** 595 * Whether or not system app permissions should be promoted from install to runtime. 596 */ 597 boolean mPromoteSystemApps; 598 599 @GuardedBy("mPackages") 600 final Settings mSettings; 601 602 /** 603 * Set of package names that are currently "frozen", which means active 604 * surgery is being done on the code/data for that package. The platform 605 * will refuse to launch frozen packages to avoid race conditions. 606 * 607 * @see PackageFreezer 608 */ 609 @GuardedBy("mPackages") 610 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 611 612 boolean mRestoredSettings; 613 614 // System configuration read by SystemConfig. 615 final int[] mGlobalGids; 616 final SparseArray<ArraySet<String>> mSystemPermissions; 617 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 618 619 // If mac_permissions.xml was found for seinfo labeling. 620 boolean mFoundPolicyFile; 621 622 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 623 624 public static final class SharedLibraryEntry { 625 public final String path; 626 public final String apk; 627 628 SharedLibraryEntry(String _path, String _apk) { 629 path = _path; 630 apk = _apk; 631 } 632 } 633 634 // Currently known shared libraries. 635 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 636 new ArrayMap<String, SharedLibraryEntry>(); 637 638 // All available activities, for your resolving pleasure. 639 final ActivityIntentResolver mActivities = 640 new ActivityIntentResolver(); 641 642 // All available receivers, for your resolving pleasure. 643 final ActivityIntentResolver mReceivers = 644 new ActivityIntentResolver(); 645 646 // All available services, for your resolving pleasure. 647 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 648 649 // All available providers, for your resolving pleasure. 650 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 651 652 // Mapping from provider base names (first directory in content URI codePath) 653 // to the provider information. 654 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 655 new ArrayMap<String, PackageParser.Provider>(); 656 657 // Mapping from instrumentation class names to info about them. 658 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 659 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 660 661 // Mapping from permission names to info about them. 662 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 663 new ArrayMap<String, PackageParser.PermissionGroup>(); 664 665 // Packages whose data we have transfered into another package, thus 666 // should no longer exist. 667 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 668 669 // Broadcast actions that are only available to the system. 670 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 671 672 /** List of packages waiting for verification. */ 673 final SparseArray<PackageVerificationState> mPendingVerification 674 = new SparseArray<PackageVerificationState>(); 675 676 /** Set of packages associated with each app op permission. */ 677 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 678 679 final PackageInstallerService mInstallerService; 680 681 private final PackageDexOptimizer mPackageDexOptimizer; 682 683 private AtomicInteger mNextMoveId = new AtomicInteger(); 684 private final MoveCallbacks mMoveCallbacks; 685 686 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 687 688 // Cache of users who need badging. 689 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 690 691 /** Token for keys in mPendingVerification. */ 692 private int mPendingVerificationToken = 0; 693 694 volatile boolean mSystemReady; 695 volatile boolean mSafeMode; 696 volatile boolean mHasSystemUidErrors; 697 698 ApplicationInfo mAndroidApplication; 699 final ActivityInfo mResolveActivity = new ActivityInfo(); 700 final ResolveInfo mResolveInfo = new ResolveInfo(); 701 ComponentName mResolveComponentName; 702 PackageParser.Package mPlatformPackage; 703 ComponentName mCustomResolverComponentName; 704 705 boolean mResolverReplaced = false; 706 707 private final @Nullable ComponentName mIntentFilterVerifierComponent; 708 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 709 710 private int mIntentFilterVerificationToken = 0; 711 712 /** Component that knows whether or not an ephemeral application exists */ 713 final ComponentName mEphemeralResolverComponent; 714 /** The service connection to the ephemeral resolver */ 715 final EphemeralResolverConnection mEphemeralResolverConnection; 716 717 /** Component used to install ephemeral applications */ 718 final ComponentName mEphemeralInstallerComponent; 719 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 720 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 721 722 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 723 = new SparseArray<IntentFilterVerificationState>(); 724 725 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 726 new DefaultPermissionGrantPolicy(this); 727 728 // List of packages names to keep cached, even if they are uninstalled for all users 729 private List<String> mKeepUninstalledPackages; 730 731 private static class IFVerificationParams { 732 PackageParser.Package pkg; 733 boolean replacing; 734 int userId; 735 int verifierUid; 736 737 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 738 int _userId, int _verifierUid) { 739 pkg = _pkg; 740 replacing = _replacing; 741 userId = _userId; 742 replacing = _replacing; 743 verifierUid = _verifierUid; 744 } 745 } 746 747 private interface IntentFilterVerifier<T extends IntentFilter> { 748 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 749 T filter, String packageName); 750 void startVerifications(int userId); 751 void receiveVerificationResponse(int verificationId); 752 } 753 754 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 755 private Context mContext; 756 private ComponentName mIntentFilterVerifierComponent; 757 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 758 759 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 760 mContext = context; 761 mIntentFilterVerifierComponent = verifierComponent; 762 } 763 764 private String getDefaultScheme() { 765 return IntentFilter.SCHEME_HTTPS; 766 } 767 768 @Override 769 public void startVerifications(int userId) { 770 // Launch verifications requests 771 int count = mCurrentIntentFilterVerifications.size(); 772 for (int n=0; n<count; n++) { 773 int verificationId = mCurrentIntentFilterVerifications.get(n); 774 final IntentFilterVerificationState ivs = 775 mIntentFilterVerificationStates.get(verificationId); 776 777 String packageName = ivs.getPackageName(); 778 779 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 780 final int filterCount = filters.size(); 781 ArraySet<String> domainsSet = new ArraySet<>(); 782 for (int m=0; m<filterCount; m++) { 783 PackageParser.ActivityIntentInfo filter = filters.get(m); 784 domainsSet.addAll(filter.getHostsList()); 785 } 786 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 787 synchronized (mPackages) { 788 if (mSettings.createIntentFilterVerificationIfNeededLPw( 789 packageName, domainsList) != null) { 790 scheduleWriteSettingsLocked(); 791 } 792 } 793 sendVerificationRequest(userId, verificationId, ivs); 794 } 795 mCurrentIntentFilterVerifications.clear(); 796 } 797 798 private void sendVerificationRequest(int userId, int verificationId, 799 IntentFilterVerificationState ivs) { 800 801 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 802 verificationIntent.putExtra( 803 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 804 verificationId); 805 verificationIntent.putExtra( 806 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 807 getDefaultScheme()); 808 verificationIntent.putExtra( 809 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 810 ivs.getHostsString()); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 813 ivs.getPackageName()); 814 verificationIntent.setComponent(mIntentFilterVerifierComponent); 815 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 816 817 UserHandle user = new UserHandle(userId); 818 mContext.sendBroadcastAsUser(verificationIntent, user); 819 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 820 "Sending IntentFilter verification broadcast"); 821 } 822 823 public void receiveVerificationResponse(int verificationId) { 824 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 825 826 final boolean verified = ivs.isVerified(); 827 828 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 829 final int count = filters.size(); 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.i(TAG, "Received verification response " + verificationId 832 + " for " + count + " filters, verified=" + verified); 833 } 834 for (int n=0; n<count; n++) { 835 PackageParser.ActivityIntentInfo filter = filters.get(n); 836 filter.setVerified(verified); 837 838 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 839 + " verified with result:" + verified + " and hosts:" 840 + ivs.getHostsString()); 841 } 842 843 mIntentFilterVerificationStates.remove(verificationId); 844 845 final String packageName = ivs.getPackageName(); 846 IntentFilterVerificationInfo ivi = null; 847 848 synchronized (mPackages) { 849 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 850 } 851 if (ivi == null) { 852 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 853 + verificationId + " packageName:" + packageName); 854 return; 855 } 856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 857 "Updating IntentFilterVerificationInfo for package " + packageName 858 +" verificationId:" + verificationId); 859 860 synchronized (mPackages) { 861 if (verified) { 862 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 863 } else { 864 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 865 } 866 scheduleWriteSettingsLocked(); 867 868 final int userId = ivs.getUserId(); 869 if (userId != UserHandle.USER_ALL) { 870 final int userStatus = 871 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 872 873 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 874 boolean needUpdate = false; 875 876 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 877 // already been set by the User thru the Disambiguation dialog 878 switch (userStatus) { 879 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 880 if (verified) { 881 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 882 } else { 883 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 884 } 885 needUpdate = true; 886 break; 887 888 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 889 if (verified) { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 891 needUpdate = true; 892 } 893 break; 894 895 default: 896 // Nothing to do 897 } 898 899 if (needUpdate) { 900 mSettings.updateIntentFilterVerificationStatusLPw( 901 packageName, updatedStatus, userId); 902 scheduleWritePackageRestrictionsLocked(userId); 903 } 904 } 905 } 906 } 907 908 @Override 909 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 910 ActivityIntentInfo filter, String packageName) { 911 if (!hasValidDomains(filter)) { 912 return false; 913 } 914 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 915 if (ivs == null) { 916 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 917 packageName); 918 } 919 if (DEBUG_DOMAIN_VERIFICATION) { 920 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 921 } 922 ivs.addFilter(filter); 923 return true; 924 } 925 926 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 927 int userId, int verificationId, String packageName) { 928 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 929 verifierUid, userId, packageName); 930 ivs.setPendingState(); 931 synchronized (mPackages) { 932 mIntentFilterVerificationStates.append(verificationId, ivs); 933 mCurrentIntentFilterVerifications.add(verificationId); 934 } 935 return ivs; 936 } 937 } 938 939 private static boolean hasValidDomains(ActivityIntentInfo filter) { 940 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 941 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 942 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 943 } 944 945 // Set of pending broadcasts for aggregating enable/disable of components. 946 static class PendingPackageBroadcasts { 947 // for each user id, a map of <package name -> components within that package> 948 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 949 950 public PendingPackageBroadcasts() { 951 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 952 } 953 954 public ArrayList<String> get(int userId, String packageName) { 955 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 956 return packages.get(packageName); 957 } 958 959 public void put(int userId, String packageName, ArrayList<String> components) { 960 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 961 packages.put(packageName, components); 962 } 963 964 public void remove(int userId, String packageName) { 965 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 966 if (packages != null) { 967 packages.remove(packageName); 968 } 969 } 970 971 public void remove(int userId) { 972 mUidMap.remove(userId); 973 } 974 975 public int userIdCount() { 976 return mUidMap.size(); 977 } 978 979 public int userIdAt(int n) { 980 return mUidMap.keyAt(n); 981 } 982 983 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 984 return mUidMap.get(userId); 985 } 986 987 public int size() { 988 // total number of pending broadcast entries across all userIds 989 int num = 0; 990 for (int i = 0; i< mUidMap.size(); i++) { 991 num += mUidMap.valueAt(i).size(); 992 } 993 return num; 994 } 995 996 public void clear() { 997 mUidMap.clear(); 998 } 999 1000 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1001 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1002 if (map == null) { 1003 map = new ArrayMap<String, ArrayList<String>>(); 1004 mUidMap.put(userId, map); 1005 } 1006 return map; 1007 } 1008 } 1009 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1010 1011 // Service Connection to remote media container service to copy 1012 // package uri's from external media onto secure containers 1013 // or internal storage. 1014 private IMediaContainerService mContainerService = null; 1015 1016 static final int SEND_PENDING_BROADCAST = 1; 1017 static final int MCS_BOUND = 3; 1018 static final int END_COPY = 4; 1019 static final int INIT_COPY = 5; 1020 static final int MCS_UNBIND = 6; 1021 static final int START_CLEANING_PACKAGE = 7; 1022 static final int FIND_INSTALL_LOC = 8; 1023 static final int POST_INSTALL = 9; 1024 static final int MCS_RECONNECT = 10; 1025 static final int MCS_GIVE_UP = 11; 1026 static final int UPDATED_MEDIA_STATUS = 12; 1027 static final int WRITE_SETTINGS = 13; 1028 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1029 static final int PACKAGE_VERIFIED = 15; 1030 static final int CHECK_PENDING_VERIFICATION = 16; 1031 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1032 static final int INTENT_FILTER_VERIFIED = 18; 1033 1034 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1035 1036 // Delay time in millisecs 1037 static final int BROADCAST_DELAY = 10 * 1000; 1038 1039 static UserManagerService sUserManager; 1040 1041 // Stores a list of users whose package restrictions file needs to be updated 1042 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1043 1044 final private DefaultContainerConnection mDefContainerConn = 1045 new DefaultContainerConnection(); 1046 class DefaultContainerConnection implements ServiceConnection { 1047 public void onServiceConnected(ComponentName name, IBinder service) { 1048 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1049 IMediaContainerService imcs = 1050 IMediaContainerService.Stub.asInterface(service); 1051 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1052 } 1053 1054 public void onServiceDisconnected(ComponentName name) { 1055 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1056 } 1057 } 1058 1059 // Recordkeeping of restore-after-install operations that are currently in flight 1060 // between the Package Manager and the Backup Manager 1061 static class PostInstallData { 1062 public InstallArgs args; 1063 public PackageInstalledInfo res; 1064 1065 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1066 args = _a; 1067 res = _r; 1068 } 1069 } 1070 1071 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1072 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1073 1074 // XML tags for backup/restore of various bits of state 1075 private static final String TAG_PREFERRED_BACKUP = "pa"; 1076 private static final String TAG_DEFAULT_APPS = "da"; 1077 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1078 1079 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1080 private static final String TAG_ALL_GRANTS = "rt-grants"; 1081 private static final String TAG_GRANT = "grant"; 1082 private static final String ATTR_PACKAGE_NAME = "pkg"; 1083 1084 private static final String TAG_PERMISSION = "perm"; 1085 private static final String ATTR_PERMISSION_NAME = "name"; 1086 private static final String ATTR_IS_GRANTED = "g"; 1087 private static final String ATTR_USER_SET = "set"; 1088 private static final String ATTR_USER_FIXED = "fixed"; 1089 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1090 1091 // System/policy permission grants are not backed up 1092 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1093 FLAG_PERMISSION_POLICY_FIXED 1094 | FLAG_PERMISSION_SYSTEM_FIXED 1095 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1096 1097 // And we back up these user-adjusted states 1098 private static final int USER_RUNTIME_GRANT_MASK = 1099 FLAG_PERMISSION_USER_SET 1100 | FLAG_PERMISSION_USER_FIXED 1101 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1102 1103 final @Nullable String mRequiredVerifierPackage; 1104 final @NonNull String mRequiredInstallerPackage; 1105 final @Nullable String mSetupWizardPackage; 1106 final @NonNull String mServicesSystemSharedLibraryPackageName; 1107 1108 private final PackageUsage mPackageUsage = new PackageUsage(); 1109 1110 private class PackageUsage { 1111 private static final int WRITE_INTERVAL 1112 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1113 1114 private final Object mFileLock = new Object(); 1115 private final AtomicLong mLastWritten = new AtomicLong(0); 1116 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1117 1118 private boolean mIsHistoricalPackageUsageAvailable = true; 1119 1120 boolean isHistoricalPackageUsageAvailable() { 1121 return mIsHistoricalPackageUsageAvailable; 1122 } 1123 1124 void write(boolean force) { 1125 if (force) { 1126 writeInternal(); 1127 return; 1128 } 1129 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1130 && !DEBUG_DEXOPT) { 1131 return; 1132 } 1133 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1134 new Thread("PackageUsage_DiskWriter") { 1135 @Override 1136 public void run() { 1137 try { 1138 writeInternal(); 1139 } finally { 1140 mBackgroundWriteRunning.set(false); 1141 } 1142 } 1143 }.start(); 1144 } 1145 } 1146 1147 private void writeInternal() { 1148 synchronized (mPackages) { 1149 synchronized (mFileLock) { 1150 AtomicFile file = getFile(); 1151 FileOutputStream f = null; 1152 try { 1153 f = file.startWrite(); 1154 BufferedOutputStream out = new BufferedOutputStream(f); 1155 FileUtils.setPermissions(file.getBaseFile().getPath(), 1156 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1157 StringBuilder sb = new StringBuilder(); 1158 1159 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1160 sb.append('\n'); 1161 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1162 1163 for (PackageParser.Package pkg : mPackages.values()) { 1164 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1165 continue; 1166 } 1167 sb.setLength(0); 1168 sb.append(pkg.packageName); 1169 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1170 sb.append(' '); 1171 sb.append(usageTimeInMillis); 1172 } 1173 sb.append('\n'); 1174 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1175 } 1176 out.flush(); 1177 file.finishWrite(f); 1178 } catch (IOException e) { 1179 if (f != null) { 1180 file.failWrite(f); 1181 } 1182 Log.e(TAG, "Failed to write package usage times", e); 1183 } 1184 } 1185 } 1186 mLastWritten.set(SystemClock.elapsedRealtime()); 1187 } 1188 1189 void readLP() { 1190 synchronized (mFileLock) { 1191 AtomicFile file = getFile(); 1192 BufferedInputStream in = null; 1193 try { 1194 in = new BufferedInputStream(file.openRead()); 1195 StringBuffer sb = new StringBuffer(); 1196 1197 String firstLine = readLine(in, sb); 1198 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1199 readVersion1LP(in, sb); 1200 } else { 1201 readVersion0LP(in, sb, firstLine); 1202 } 1203 } catch (FileNotFoundException expected) { 1204 mIsHistoricalPackageUsageAvailable = false; 1205 } catch (IOException e) { 1206 Log.w(TAG, "Failed to read package usage times", e); 1207 } finally { 1208 IoUtils.closeQuietly(in); 1209 } 1210 } 1211 mLastWritten.set(SystemClock.elapsedRealtime()); 1212 } 1213 1214 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1215 throws IOException { 1216 // Initial version of the file had no version number and stored one 1217 // package-timestamp pair per line. 1218 // Note that the first line has already been read from the InputStream. 1219 String line = firstLine; 1220 while (true) { 1221 if (line == null) { 1222 break; 1223 } 1224 1225 String[] tokens = line.split(" "); 1226 if (tokens.length != 2) { 1227 throw new IOException("Failed to parse " + line + 1228 " as package-timestamp pair."); 1229 } 1230 1231 String packageName = tokens[0]; 1232 PackageParser.Package pkg = mPackages.get(packageName); 1233 if (pkg == null) { 1234 continue; 1235 } 1236 1237 long timestamp = parseAsLong(tokens[1]); 1238 for (int reason = 0; 1239 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1240 reason++) { 1241 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1242 } 1243 1244 line = readLine(in, sb); 1245 } 1246 } 1247 1248 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1249 // Version 1 of the file started with the corresponding version 1250 // number and then stored a package name and eight timestamps per line. 1251 String line; 1252 while ((line = readLine(in, sb)) != null) { 1253 String[] tokens = line.split(" "); 1254 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1255 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1256 } 1257 1258 String packageName = tokens[0]; 1259 PackageParser.Package pkg = mPackages.get(packageName); 1260 if (pkg == null) { 1261 continue; 1262 } 1263 1264 for (int reason = 0; 1265 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1266 reason++) { 1267 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1268 } 1269 } 1270 } 1271 1272 private long parseAsLong(String token) throws IOException { 1273 try { 1274 return Long.parseLong(token); 1275 } catch (NumberFormatException e) { 1276 throw new IOException("Failed to parse " + token + " as a long.", e); 1277 } 1278 } 1279 1280 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1281 return readToken(in, sb, '\n'); 1282 } 1283 1284 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1285 throws IOException { 1286 sb.setLength(0); 1287 while (true) { 1288 int ch = in.read(); 1289 if (ch == -1) { 1290 if (sb.length() == 0) { 1291 return null; 1292 } 1293 throw new IOException("Unexpected EOF"); 1294 } 1295 if (ch == endOfToken) { 1296 return sb.toString(); 1297 } 1298 sb.append((char)ch); 1299 } 1300 } 1301 1302 private AtomicFile getFile() { 1303 File dataDir = Environment.getDataDirectory(); 1304 File systemDir = new File(dataDir, "system"); 1305 File fname = new File(systemDir, "package-usage.list"); 1306 return new AtomicFile(fname); 1307 } 1308 1309 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1310 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1311 } 1312 1313 class PackageHandler extends Handler { 1314 private boolean mBound = false; 1315 final ArrayList<HandlerParams> mPendingInstalls = 1316 new ArrayList<HandlerParams>(); 1317 1318 private boolean connectToService() { 1319 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1320 " DefaultContainerService"); 1321 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1322 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1323 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1324 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1325 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1326 mBound = true; 1327 return true; 1328 } 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1330 return false; 1331 } 1332 1333 private void disconnectService() { 1334 mContainerService = null; 1335 mBound = false; 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1337 mContext.unbindService(mDefContainerConn); 1338 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1339 } 1340 1341 PackageHandler(Looper looper) { 1342 super(looper); 1343 } 1344 1345 public void handleMessage(Message msg) { 1346 try { 1347 doHandleMessage(msg); 1348 } finally { 1349 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1350 } 1351 } 1352 1353 void doHandleMessage(Message msg) { 1354 switch (msg.what) { 1355 case INIT_COPY: { 1356 HandlerParams params = (HandlerParams) msg.obj; 1357 int idx = mPendingInstalls.size(); 1358 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1359 // If a bind was already initiated we dont really 1360 // need to do anything. The pending install 1361 // will be processed later on. 1362 if (!mBound) { 1363 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1364 System.identityHashCode(mHandler)); 1365 // If this is the only one pending we might 1366 // have to bind to the service again. 1367 if (!connectToService()) { 1368 Slog.e(TAG, "Failed to bind to media container service"); 1369 params.serviceError(); 1370 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 if (params.traceMethod != null) { 1373 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1374 params.traceCookie); 1375 } 1376 return; 1377 } else { 1378 // Once we bind to the service, the first 1379 // pending request will be processed. 1380 mPendingInstalls.add(idx, params); 1381 } 1382 } else { 1383 mPendingInstalls.add(idx, params); 1384 // Already bound to the service. Just make 1385 // sure we trigger off processing the first request. 1386 if (idx == 0) { 1387 mHandler.sendEmptyMessage(MCS_BOUND); 1388 } 1389 } 1390 break; 1391 } 1392 case MCS_BOUND: { 1393 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1394 if (msg.obj != null) { 1395 mContainerService = (IMediaContainerService) msg.obj; 1396 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1397 System.identityHashCode(mHandler)); 1398 } 1399 if (mContainerService == null) { 1400 if (!mBound) { 1401 // Something seriously wrong since we are not bound and we are not 1402 // waiting for connection. Bail out. 1403 Slog.e(TAG, "Cannot bind to media container service"); 1404 for (HandlerParams params : mPendingInstalls) { 1405 // Indicate service bind error 1406 params.serviceError(); 1407 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1408 System.identityHashCode(params)); 1409 if (params.traceMethod != null) { 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1411 params.traceMethod, params.traceCookie); 1412 } 1413 return; 1414 } 1415 mPendingInstalls.clear(); 1416 } else { 1417 Slog.w(TAG, "Waiting to connect to media container service"); 1418 } 1419 } else if (mPendingInstalls.size() > 0) { 1420 HandlerParams params = mPendingInstalls.get(0); 1421 if (params != null) { 1422 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1423 System.identityHashCode(params)); 1424 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1425 if (params.startCopy()) { 1426 // We are done... look for more work or to 1427 // go idle. 1428 if (DEBUG_SD_INSTALL) Log.i(TAG, 1429 "Checking for more work or unbind..."); 1430 // Delete pending install 1431 if (mPendingInstalls.size() > 0) { 1432 mPendingInstalls.remove(0); 1433 } 1434 if (mPendingInstalls.size() == 0) { 1435 if (mBound) { 1436 if (DEBUG_SD_INSTALL) Log.i(TAG, 1437 "Posting delayed MCS_UNBIND"); 1438 removeMessages(MCS_UNBIND); 1439 Message ubmsg = obtainMessage(MCS_UNBIND); 1440 // Unbind after a little delay, to avoid 1441 // continual thrashing. 1442 sendMessageDelayed(ubmsg, 10000); 1443 } 1444 } else { 1445 // There are more pending requests in queue. 1446 // Just post MCS_BOUND message to trigger processing 1447 // of next pending install. 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, 1449 "Posting MCS_BOUND for next work"); 1450 mHandler.sendEmptyMessage(MCS_BOUND); 1451 } 1452 } 1453 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1454 } 1455 } else { 1456 // Should never happen ideally. 1457 Slog.w(TAG, "Empty queue"); 1458 } 1459 break; 1460 } 1461 case MCS_RECONNECT: { 1462 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1463 if (mPendingInstalls.size() > 0) { 1464 if (mBound) { 1465 disconnectService(); 1466 } 1467 if (!connectToService()) { 1468 Slog.e(TAG, "Failed to bind to media container service"); 1469 for (HandlerParams params : mPendingInstalls) { 1470 // Indicate service bind error 1471 params.serviceError(); 1472 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1473 System.identityHashCode(params)); 1474 } 1475 mPendingInstalls.clear(); 1476 } 1477 } 1478 break; 1479 } 1480 case MCS_UNBIND: { 1481 // If there is no actual work left, then time to unbind. 1482 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1483 1484 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1485 if (mBound) { 1486 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1487 1488 disconnectService(); 1489 } 1490 } else if (mPendingInstalls.size() > 0) { 1491 // There are more pending requests in queue. 1492 // Just post MCS_BOUND message to trigger processing 1493 // of next pending install. 1494 mHandler.sendEmptyMessage(MCS_BOUND); 1495 } 1496 1497 break; 1498 } 1499 case MCS_GIVE_UP: { 1500 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1501 HandlerParams params = mPendingInstalls.remove(0); 1502 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1503 System.identityHashCode(params)); 1504 break; 1505 } 1506 case SEND_PENDING_BROADCAST: { 1507 String packages[]; 1508 ArrayList<String> components[]; 1509 int size = 0; 1510 int uids[]; 1511 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1512 synchronized (mPackages) { 1513 if (mPendingBroadcasts == null) { 1514 return; 1515 } 1516 size = mPendingBroadcasts.size(); 1517 if (size <= 0) { 1518 // Nothing to be done. Just return 1519 return; 1520 } 1521 packages = new String[size]; 1522 components = new ArrayList[size]; 1523 uids = new int[size]; 1524 int i = 0; // filling out the above arrays 1525 1526 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1527 int packageUserId = mPendingBroadcasts.userIdAt(n); 1528 Iterator<Map.Entry<String, ArrayList<String>>> it 1529 = mPendingBroadcasts.packagesForUserId(packageUserId) 1530 .entrySet().iterator(); 1531 while (it.hasNext() && i < size) { 1532 Map.Entry<String, ArrayList<String>> ent = it.next(); 1533 packages[i] = ent.getKey(); 1534 components[i] = ent.getValue(); 1535 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1536 uids[i] = (ps != null) 1537 ? UserHandle.getUid(packageUserId, ps.appId) 1538 : -1; 1539 i++; 1540 } 1541 } 1542 size = i; 1543 mPendingBroadcasts.clear(); 1544 } 1545 // Send broadcasts 1546 for (int i = 0; i < size; i++) { 1547 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1548 } 1549 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1550 break; 1551 } 1552 case START_CLEANING_PACKAGE: { 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1554 final String packageName = (String)msg.obj; 1555 final int userId = msg.arg1; 1556 final boolean andCode = msg.arg2 != 0; 1557 synchronized (mPackages) { 1558 if (userId == UserHandle.USER_ALL) { 1559 int[] users = sUserManager.getUserIds(); 1560 for (int user : users) { 1561 mSettings.addPackageToCleanLPw( 1562 new PackageCleanItem(user, packageName, andCode)); 1563 } 1564 } else { 1565 mSettings.addPackageToCleanLPw( 1566 new PackageCleanItem(userId, packageName, andCode)); 1567 } 1568 } 1569 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1570 startCleaningPackages(); 1571 } break; 1572 case POST_INSTALL: { 1573 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1574 1575 PostInstallData data = mRunningInstalls.get(msg.arg1); 1576 mRunningInstalls.delete(msg.arg1); 1577 1578 if (data != null) { 1579 InstallArgs args = data.args; 1580 PackageInstalledInfo parentRes = data.res; 1581 1582 final boolean grantPermissions = (args.installFlags 1583 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1584 final boolean killApp = (args.installFlags 1585 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1586 final String[] grantedPermissions = args.installGrantPermissions; 1587 1588 // Handle the parent package 1589 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1590 grantedPermissions, args.observer); 1591 1592 // Handle the child packages 1593 final int childCount = (parentRes.addedChildPackages != null) 1594 ? parentRes.addedChildPackages.size() : 0; 1595 for (int i = 0; i < childCount; i++) { 1596 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1597 handlePackagePostInstall(childRes, grantPermissions, killApp, 1598 grantedPermissions, args.observer); 1599 } 1600 1601 // Log tracing if needed 1602 if (args.traceMethod != null) { 1603 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1604 args.traceCookie); 1605 } 1606 } else { 1607 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1608 } 1609 1610 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1611 } break; 1612 case UPDATED_MEDIA_STATUS: { 1613 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1614 boolean reportStatus = msg.arg1 == 1; 1615 boolean doGc = msg.arg2 == 1; 1616 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1617 if (doGc) { 1618 // Force a gc to clear up stale containers. 1619 Runtime.getRuntime().gc(); 1620 } 1621 if (msg.obj != null) { 1622 @SuppressWarnings("unchecked") 1623 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1624 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1625 // Unload containers 1626 unloadAllContainers(args); 1627 } 1628 if (reportStatus) { 1629 try { 1630 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1631 PackageHelper.getMountService().finishMediaUpdate(); 1632 } catch (RemoteException e) { 1633 Log.e(TAG, "MountService not running?"); 1634 } 1635 } 1636 } break; 1637 case WRITE_SETTINGS: { 1638 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1639 synchronized (mPackages) { 1640 removeMessages(WRITE_SETTINGS); 1641 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1642 mSettings.writeLPr(); 1643 mDirtyUsers.clear(); 1644 } 1645 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1646 } break; 1647 case WRITE_PACKAGE_RESTRICTIONS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1651 for (int userId : mDirtyUsers) { 1652 mSettings.writePackageRestrictionsLPr(userId); 1653 } 1654 mDirtyUsers.clear(); 1655 } 1656 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1657 } break; 1658 case CHECK_PENDING_VERIFICATION: { 1659 final int verificationId = msg.arg1; 1660 final PackageVerificationState state = mPendingVerification.get(verificationId); 1661 1662 if ((state != null) && !state.timeoutExtended()) { 1663 final InstallArgs args = state.getInstallArgs(); 1664 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1665 1666 Slog.i(TAG, "Verification timed out for " + originUri); 1667 mPendingVerification.remove(verificationId); 1668 1669 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1670 1671 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1672 Slog.i(TAG, "Continuing with installation of " + originUri); 1673 state.setVerifierResponse(Binder.getCallingUid(), 1674 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1675 broadcastPackageVerified(verificationId, originUri, 1676 PackageManager.VERIFICATION_ALLOW, 1677 state.getInstallArgs().getUser()); 1678 try { 1679 ret = args.copyApk(mContainerService, true); 1680 } catch (RemoteException e) { 1681 Slog.e(TAG, "Could not contact the ContainerService"); 1682 } 1683 } else { 1684 broadcastPackageVerified(verificationId, originUri, 1685 PackageManager.VERIFICATION_REJECT, 1686 state.getInstallArgs().getUser()); 1687 } 1688 1689 Trace.asyncTraceEnd( 1690 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1691 1692 processPendingInstall(args, ret); 1693 mHandler.sendEmptyMessage(MCS_UNBIND); 1694 } 1695 break; 1696 } 1697 case PACKAGE_VERIFIED: { 1698 final int verificationId = msg.arg1; 1699 1700 final PackageVerificationState state = mPendingVerification.get(verificationId); 1701 if (state == null) { 1702 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1703 break; 1704 } 1705 1706 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1707 1708 state.setVerifierResponse(response.callerUid, response.code); 1709 1710 if (state.isVerificationComplete()) { 1711 mPendingVerification.remove(verificationId); 1712 1713 final InstallArgs args = state.getInstallArgs(); 1714 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1715 1716 int ret; 1717 if (state.isInstallAllowed()) { 1718 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1719 broadcastPackageVerified(verificationId, originUri, 1720 response.code, state.getInstallArgs().getUser()); 1721 try { 1722 ret = args.copyApk(mContainerService, true); 1723 } catch (RemoteException e) { 1724 Slog.e(TAG, "Could not contact the ContainerService"); 1725 } 1726 } else { 1727 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1728 } 1729 1730 Trace.asyncTraceEnd( 1731 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1732 1733 processPendingInstall(args, ret); 1734 mHandler.sendEmptyMessage(MCS_UNBIND); 1735 } 1736 1737 break; 1738 } 1739 case START_INTENT_FILTER_VERIFICATIONS: { 1740 IFVerificationParams params = (IFVerificationParams) msg.obj; 1741 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1742 params.replacing, params.pkg); 1743 break; 1744 } 1745 case INTENT_FILTER_VERIFIED: { 1746 final int verificationId = msg.arg1; 1747 1748 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1749 verificationId); 1750 if (state == null) { 1751 Slog.w(TAG, "Invalid IntentFilter verification token " 1752 + verificationId + " received"); 1753 break; 1754 } 1755 1756 final int userId = state.getUserId(); 1757 1758 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1759 "Processing IntentFilter verification with token:" 1760 + verificationId + " and userId:" + userId); 1761 1762 final IntentFilterVerificationResponse response = 1763 (IntentFilterVerificationResponse) msg.obj; 1764 1765 state.setVerifierResponse(response.callerUid, response.code); 1766 1767 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1768 "IntentFilter verification with token:" + verificationId 1769 + " and userId:" + userId 1770 + " is settings verifier response with response code:" 1771 + response.code); 1772 1773 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1774 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1775 + response.getFailedDomainsString()); 1776 } 1777 1778 if (state.isVerificationComplete()) { 1779 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1780 } else { 1781 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1782 "IntentFilter verification with token:" + verificationId 1783 + " was not said to be complete"); 1784 } 1785 1786 break; 1787 } 1788 } 1789 } 1790 } 1791 1792 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1793 boolean killApp, String[] grantedPermissions, 1794 IPackageInstallObserver2 installObserver) { 1795 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1796 // Send the removed broadcasts 1797 if (res.removedInfo != null) { 1798 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1799 } 1800 1801 // Now that we successfully installed the package, grant runtime 1802 // permissions if requested before broadcasting the install. 1803 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1804 >= Build.VERSION_CODES.M) { 1805 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1806 } 1807 1808 final boolean update = res.removedInfo != null 1809 && res.removedInfo.removedPackage != null; 1810 1811 // If this is the first time we have child packages for a disabled privileged 1812 // app that had no children, we grant requested runtime permissions to the new 1813 // children if the parent on the system image had them already granted. 1814 if (res.pkg.parentPackage != null) { 1815 synchronized (mPackages) { 1816 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1817 } 1818 } 1819 1820 synchronized (mPackages) { 1821 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1822 } 1823 1824 final String packageName = res.pkg.applicationInfo.packageName; 1825 Bundle extras = new Bundle(1); 1826 extras.putInt(Intent.EXTRA_UID, res.uid); 1827 1828 // Determine the set of users who are adding this package for 1829 // the first time vs. those who are seeing an update. 1830 int[] firstUsers = EMPTY_INT_ARRAY; 1831 int[] updateUsers = EMPTY_INT_ARRAY; 1832 if (res.origUsers == null || res.origUsers.length == 0) { 1833 firstUsers = res.newUsers; 1834 } else { 1835 for (int newUser : res.newUsers) { 1836 boolean isNew = true; 1837 for (int origUser : res.origUsers) { 1838 if (origUser == newUser) { 1839 isNew = false; 1840 break; 1841 } 1842 } 1843 if (isNew) { 1844 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1845 } else { 1846 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1847 } 1848 } 1849 } 1850 1851 // Send installed broadcasts if the install/update is not ephemeral 1852 if (!isEphemeral(res.pkg)) { 1853 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1854 1855 // Send added for users that see the package for the first time 1856 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1857 extras, 0 /*flags*/, null /*targetPackage*/, 1858 null /*finishedReceiver*/, firstUsers); 1859 1860 // Send added for users that don't see the package for the first time 1861 if (update) { 1862 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1863 } 1864 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1865 extras, 0 /*flags*/, null /*targetPackage*/, 1866 null /*finishedReceiver*/, updateUsers); 1867 1868 // Send replaced for users that don't see the package for the first time 1869 if (update) { 1870 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1871 packageName, extras, 0 /*flags*/, 1872 null /*targetPackage*/, null /*finishedReceiver*/, 1873 updateUsers); 1874 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1875 null /*package*/, null /*extras*/, 0 /*flags*/, 1876 packageName /*targetPackage*/, 1877 null /*finishedReceiver*/, updateUsers); 1878 } 1879 1880 // Send broadcast package appeared if forward locked/external for all users 1881 // treat asec-hosted packages like removable media on upgrade 1882 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1883 if (DEBUG_INSTALL) { 1884 Slog.i(TAG, "upgrading pkg " + res.pkg 1885 + " is ASEC-hosted -> AVAILABLE"); 1886 } 1887 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1888 ArrayList<String> pkgList = new ArrayList<>(1); 1889 pkgList.add(packageName); 1890 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1891 } 1892 } 1893 1894 // Work that needs to happen on first install within each user 1895 if (firstUsers != null && firstUsers.length > 0) { 1896 synchronized (mPackages) { 1897 for (int userId : firstUsers) { 1898 // If this app is a browser and it's newly-installed for some 1899 // users, clear any default-browser state in those users. The 1900 // app's nature doesn't depend on the user, so we can just check 1901 // its browser nature in any user and generalize. 1902 if (packageIsBrowser(packageName, userId)) { 1903 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1904 } 1905 1906 // We may also need to apply pending (restored) runtime 1907 // permission grants within these users. 1908 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1909 } 1910 } 1911 } 1912 1913 // Log current value of "unknown sources" setting 1914 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1915 getUnknownSourcesSettings()); 1916 1917 // Force a gc to clear up things 1918 Runtime.getRuntime().gc(); 1919 1920 // Remove the replaced package's older resources safely now 1921 // We delete after a gc for applications on sdcard. 1922 if (res.removedInfo != null && res.removedInfo.args != null) { 1923 synchronized (mInstallLock) { 1924 res.removedInfo.args.doPostDeleteLI(true); 1925 } 1926 } 1927 } 1928 1929 // If someone is watching installs - notify them 1930 if (installObserver != null) { 1931 try { 1932 Bundle extras = extrasForInstallResult(res); 1933 installObserver.onPackageInstalled(res.name, res.returnCode, 1934 res.returnMsg, extras); 1935 } catch (RemoteException e) { 1936 Slog.i(TAG, "Observer no longer exists."); 1937 } 1938 } 1939 } 1940 1941 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1942 PackageParser.Package pkg) { 1943 if (pkg.parentPackage == null) { 1944 return; 1945 } 1946 if (pkg.requestedPermissions == null) { 1947 return; 1948 } 1949 final PackageSetting disabledSysParentPs = mSettings 1950 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1951 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1952 || !disabledSysParentPs.isPrivileged() 1953 || (disabledSysParentPs.childPackageNames != null 1954 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1955 return; 1956 } 1957 final int[] allUserIds = sUserManager.getUserIds(); 1958 final int permCount = pkg.requestedPermissions.size(); 1959 for (int i = 0; i < permCount; i++) { 1960 String permission = pkg.requestedPermissions.get(i); 1961 BasePermission bp = mSettings.mPermissions.get(permission); 1962 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1963 continue; 1964 } 1965 for (int userId : allUserIds) { 1966 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1967 permission, userId)) { 1968 grantRuntimePermission(pkg.packageName, permission, userId); 1969 } 1970 } 1971 } 1972 } 1973 1974 private StorageEventListener mStorageListener = new StorageEventListener() { 1975 @Override 1976 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1977 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1978 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1979 final String volumeUuid = vol.getFsUuid(); 1980 1981 // Clean up any users or apps that were removed or recreated 1982 // while this volume was missing 1983 reconcileUsers(volumeUuid); 1984 reconcileApps(volumeUuid); 1985 1986 // Clean up any install sessions that expired or were 1987 // cancelled while this volume was missing 1988 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1989 1990 loadPrivatePackages(vol); 1991 1992 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1993 unloadPrivatePackages(vol); 1994 } 1995 } 1996 1997 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1998 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1999 updateExternalMediaStatus(true, false); 2000 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2001 updateExternalMediaStatus(false, false); 2002 } 2003 } 2004 } 2005 2006 @Override 2007 public void onVolumeForgotten(String fsUuid) { 2008 if (TextUtils.isEmpty(fsUuid)) { 2009 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2010 return; 2011 } 2012 2013 // Remove any apps installed on the forgotten volume 2014 synchronized (mPackages) { 2015 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2016 for (PackageSetting ps : packages) { 2017 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2018 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2019 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2020 } 2021 2022 mSettings.onVolumeForgotten(fsUuid); 2023 mSettings.writeLPr(); 2024 } 2025 } 2026 }; 2027 2028 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2029 String[] grantedPermissions) { 2030 for (int userId : userIds) { 2031 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2032 } 2033 2034 // We could have touched GID membership, so flush out packages.list 2035 synchronized (mPackages) { 2036 mSettings.writePackageListLPr(); 2037 } 2038 } 2039 2040 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2041 String[] grantedPermissions) { 2042 SettingBase sb = (SettingBase) pkg.mExtras; 2043 if (sb == null) { 2044 return; 2045 } 2046 2047 PermissionsState permissionsState = sb.getPermissionsState(); 2048 2049 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2050 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2051 2052 synchronized (mPackages) { 2053 for (String permission : pkg.requestedPermissions) { 2054 BasePermission bp = mSettings.mPermissions.get(permission); 2055 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2056 && (grantedPermissions == null 2057 || ArrayUtils.contains(grantedPermissions, permission))) { 2058 final int flags = permissionsState.getPermissionFlags(permission, userId); 2059 // Installer cannot change immutable permissions. 2060 if ((flags & immutableFlags) == 0) { 2061 grantRuntimePermission(pkg.packageName, permission, userId); 2062 } 2063 } 2064 } 2065 } 2066 } 2067 2068 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2069 Bundle extras = null; 2070 switch (res.returnCode) { 2071 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2072 extras = new Bundle(); 2073 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2074 res.origPermission); 2075 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2076 res.origPackage); 2077 break; 2078 } 2079 case PackageManager.INSTALL_SUCCEEDED: { 2080 extras = new Bundle(); 2081 extras.putBoolean(Intent.EXTRA_REPLACING, 2082 res.removedInfo != null && res.removedInfo.removedPackage != null); 2083 break; 2084 } 2085 } 2086 return extras; 2087 } 2088 2089 void scheduleWriteSettingsLocked() { 2090 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2091 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2092 } 2093 } 2094 2095 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2096 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2097 scheduleWritePackageRestrictionsLocked(userId); 2098 } 2099 2100 void scheduleWritePackageRestrictionsLocked(int userId) { 2101 final int[] userIds = (userId == UserHandle.USER_ALL) 2102 ? sUserManager.getUserIds() : new int[]{userId}; 2103 for (int nextUserId : userIds) { 2104 if (!sUserManager.exists(nextUserId)) return; 2105 mDirtyUsers.add(nextUserId); 2106 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2107 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2108 } 2109 } 2110 } 2111 2112 public static PackageManagerService main(Context context, Installer installer, 2113 boolean factoryTest, boolean onlyCore) { 2114 // Self-check for initial settings. 2115 PackageManagerServiceCompilerMapping.checkProperties(); 2116 2117 PackageManagerService m = new PackageManagerService(context, installer, 2118 factoryTest, onlyCore); 2119 m.enableSystemUserPackages(); 2120 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2121 // disabled after already being started. 2122 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2123 UserHandle.USER_SYSTEM); 2124 ServiceManager.addService("package", m); 2125 return m; 2126 } 2127 2128 private void enableSystemUserPackages() { 2129 if (!UserManager.isSplitSystemUser()) { 2130 return; 2131 } 2132 // For system user, enable apps based on the following conditions: 2133 // - app is whitelisted or belong to one of these groups: 2134 // -- system app which has no launcher icons 2135 // -- system app which has INTERACT_ACROSS_USERS permission 2136 // -- system IME app 2137 // - app is not in the blacklist 2138 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2139 Set<String> enableApps = new ArraySet<>(); 2140 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2141 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2142 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2143 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2144 enableApps.addAll(wlApps); 2145 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2146 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2147 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2148 enableApps.removeAll(blApps); 2149 Log.i(TAG, "Applications installed for system user: " + enableApps); 2150 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2151 UserHandle.SYSTEM); 2152 final int allAppsSize = allAps.size(); 2153 synchronized (mPackages) { 2154 for (int i = 0; i < allAppsSize; i++) { 2155 String pName = allAps.get(i); 2156 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2157 // Should not happen, but we shouldn't be failing if it does 2158 if (pkgSetting == null) { 2159 continue; 2160 } 2161 boolean install = enableApps.contains(pName); 2162 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2163 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2164 + " for system user"); 2165 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2166 } 2167 } 2168 } 2169 } 2170 2171 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2172 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2173 Context.DISPLAY_SERVICE); 2174 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2175 } 2176 2177 public PackageManagerService(Context context, Installer installer, 2178 boolean factoryTest, boolean onlyCore) { 2179 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2180 SystemClock.uptimeMillis()); 2181 2182 if (mSdkVersion <= 0) { 2183 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2184 } 2185 2186 mContext = context; 2187 mFactoryTest = factoryTest; 2188 mOnlyCore = onlyCore; 2189 mMetrics = new DisplayMetrics(); 2190 mSettings = new Settings(mPackages); 2191 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2192 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2193 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2194 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2195 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2196 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2197 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2198 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2199 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2200 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2201 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2202 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2203 2204 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2205 if (separateProcesses != null && separateProcesses.length() > 0) { 2206 if ("*".equals(separateProcesses)) { 2207 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2208 mSeparateProcesses = null; 2209 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2210 } else { 2211 mDefParseFlags = 0; 2212 mSeparateProcesses = separateProcesses.split(","); 2213 Slog.w(TAG, "Running with debug.separate_processes: " 2214 + separateProcesses); 2215 } 2216 } else { 2217 mDefParseFlags = 0; 2218 mSeparateProcesses = null; 2219 } 2220 2221 mInstaller = installer; 2222 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2223 "*dexopt*"); 2224 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2225 2226 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2227 FgThread.get().getLooper()); 2228 2229 getDefaultDisplayMetrics(context, mMetrics); 2230 2231 SystemConfig systemConfig = SystemConfig.getInstance(); 2232 mGlobalGids = systemConfig.getGlobalGids(); 2233 mSystemPermissions = systemConfig.getSystemPermissions(); 2234 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2235 2236 synchronized (mInstallLock) { 2237 // writer 2238 synchronized (mPackages) { 2239 mHandlerThread = new ServiceThread(TAG, 2240 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2241 mHandlerThread.start(); 2242 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2243 mProcessLoggingHandler = new ProcessLoggingHandler(); 2244 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2245 2246 File dataDir = Environment.getDataDirectory(); 2247 mAppInstallDir = new File(dataDir, "app"); 2248 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2249 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2250 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2251 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2252 2253 sUserManager = new UserManagerService(context, this, mPackages); 2254 2255 // Propagate permission configuration in to package manager. 2256 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2257 = systemConfig.getPermissions(); 2258 for (int i=0; i<permConfig.size(); i++) { 2259 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2260 BasePermission bp = mSettings.mPermissions.get(perm.name); 2261 if (bp == null) { 2262 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2263 mSettings.mPermissions.put(perm.name, bp); 2264 } 2265 if (perm.gids != null) { 2266 bp.setGids(perm.gids, perm.perUser); 2267 } 2268 } 2269 2270 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2271 for (int i=0; i<libConfig.size(); i++) { 2272 mSharedLibraries.put(libConfig.keyAt(i), 2273 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2274 } 2275 2276 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2277 2278 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2279 2280 String customResolverActivity = Resources.getSystem().getString( 2281 R.string.config_customResolverActivity); 2282 if (TextUtils.isEmpty(customResolverActivity)) { 2283 customResolverActivity = null; 2284 } else { 2285 mCustomResolverComponentName = ComponentName.unflattenFromString( 2286 customResolverActivity); 2287 } 2288 2289 long startTime = SystemClock.uptimeMillis(); 2290 2291 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2292 startTime); 2293 2294 // Set flag to monitor and not change apk file paths when 2295 // scanning install directories. 2296 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2297 2298 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2299 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2300 2301 if (bootClassPath == null) { 2302 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2303 } 2304 2305 if (systemServerClassPath == null) { 2306 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2307 } 2308 2309 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2310 final String[] dexCodeInstructionSets = 2311 getDexCodeInstructionSets( 2312 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2313 2314 /** 2315 * Ensure all external libraries have had dexopt run on them. 2316 */ 2317 if (mSharedLibraries.size() > 0) { 2318 // NOTE: For now, we're compiling these system "shared libraries" 2319 // (and framework jars) into all available architectures. It's possible 2320 // to compile them only when we come across an app that uses them (there's 2321 // already logic for that in scanPackageLI) but that adds some complexity. 2322 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2323 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2324 final String lib = libEntry.path; 2325 if (lib == null) { 2326 continue; 2327 } 2328 2329 try { 2330 // Shared libraries do not have profiles so we perform a full 2331 // AOT compilation (if needed). 2332 int dexoptNeeded = DexFile.getDexOptNeeded( 2333 lib, dexCodeInstructionSet, 2334 getCompilerFilterForReason(REASON_SHARED_APK), 2335 false /* newProfile */); 2336 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2337 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2338 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2339 getCompilerFilterForReason(REASON_SHARED_APK), 2340 StorageManager.UUID_PRIVATE_INTERNAL); 2341 } 2342 } catch (FileNotFoundException e) { 2343 Slog.w(TAG, "Library not found: " + lib); 2344 } catch (IOException | InstallerException e) { 2345 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2346 + e.getMessage()); 2347 } 2348 } 2349 } 2350 } 2351 2352 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2353 2354 final VersionInfo ver = mSettings.getInternalVersion(); 2355 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2356 2357 // when upgrading from pre-M, promote system app permissions from install to runtime 2358 mPromoteSystemApps = 2359 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2360 2361 // save off the names of pre-existing system packages prior to scanning; we don't 2362 // want to automatically grant runtime permissions for new system apps 2363 if (mPromoteSystemApps) { 2364 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2365 while (pkgSettingIter.hasNext()) { 2366 PackageSetting ps = pkgSettingIter.next(); 2367 if (isSystemApp(ps)) { 2368 mExistingSystemPackages.add(ps.name); 2369 } 2370 } 2371 } 2372 2373 // When upgrading from pre-N, we need to handle package extraction like first boot, 2374 // as there is no profiling data available. 2375 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2376 mSettings.setNWorkDone(); 2377 2378 // Collect vendor overlay packages. 2379 // (Do this before scanning any apps.) 2380 // For security and version matching reason, only consider 2381 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2382 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2383 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2384 | PackageParser.PARSE_IS_SYSTEM 2385 | PackageParser.PARSE_IS_SYSTEM_DIR 2386 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2387 2388 // Find base frameworks (resource packages without code). 2389 scanDirTracedLI(frameworkDir, mDefParseFlags 2390 | PackageParser.PARSE_IS_SYSTEM 2391 | PackageParser.PARSE_IS_SYSTEM_DIR 2392 | PackageParser.PARSE_IS_PRIVILEGED, 2393 scanFlags | SCAN_NO_DEX, 0); 2394 2395 // Collected privileged system packages. 2396 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2397 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2398 | PackageParser.PARSE_IS_SYSTEM 2399 | PackageParser.PARSE_IS_SYSTEM_DIR 2400 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2401 2402 // Collect ordinary system packages. 2403 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2404 scanDirTracedLI(systemAppDir, mDefParseFlags 2405 | PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2407 2408 // Collect all vendor packages. 2409 File vendorAppDir = new File("/vendor/app"); 2410 try { 2411 vendorAppDir = vendorAppDir.getCanonicalFile(); 2412 } catch (IOException e) { 2413 // failed to look up canonical path, continue with original one 2414 } 2415 scanDirTracedLI(vendorAppDir, mDefParseFlags 2416 | PackageParser.PARSE_IS_SYSTEM 2417 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2418 2419 // Collect all OEM packages. 2420 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2421 scanDirTracedLI(oemAppDir, mDefParseFlags 2422 | PackageParser.PARSE_IS_SYSTEM 2423 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2424 2425 // Prune any system packages that no longer exist. 2426 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2427 if (!mOnlyCore) { 2428 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2429 while (psit.hasNext()) { 2430 PackageSetting ps = psit.next(); 2431 2432 /* 2433 * If this is not a system app, it can't be a 2434 * disable system app. 2435 */ 2436 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2437 continue; 2438 } 2439 2440 /* 2441 * If the package is scanned, it's not erased. 2442 */ 2443 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2444 if (scannedPkg != null) { 2445 /* 2446 * If the system app is both scanned and in the 2447 * disabled packages list, then it must have been 2448 * added via OTA. Remove it from the currently 2449 * scanned package so the previously user-installed 2450 * application can be scanned. 2451 */ 2452 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2453 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2454 + ps.name + "; removing system app. Last known codePath=" 2455 + ps.codePathString + ", installStatus=" + ps.installStatus 2456 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2457 + scannedPkg.mVersionCode); 2458 removePackageLI(scannedPkg, true); 2459 mExpectingBetter.put(ps.name, ps.codePath); 2460 } 2461 2462 continue; 2463 } 2464 2465 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2466 psit.remove(); 2467 logCriticalInfo(Log.WARN, "System package " + ps.name 2468 + " no longer exists; it's data will be wiped"); 2469 // Actual deletion of code and data will be handled by later 2470 // reconciliation step 2471 } else { 2472 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2473 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2474 possiblyDeletedUpdatedSystemApps.add(ps.name); 2475 } 2476 } 2477 } 2478 } 2479 2480 //look for any incomplete package installations 2481 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2482 for (int i = 0; i < deletePkgsList.size(); i++) { 2483 // Actual deletion of code and data will be handled by later 2484 // reconciliation step 2485 final String packageName = deletePkgsList.get(i).name; 2486 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2487 synchronized (mPackages) { 2488 mSettings.removePackageLPw(packageName); 2489 } 2490 } 2491 2492 //delete tmp files 2493 deleteTempPackageFiles(); 2494 2495 // Remove any shared userIDs that have no associated packages 2496 mSettings.pruneSharedUsersLPw(); 2497 2498 if (!mOnlyCore) { 2499 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2500 SystemClock.uptimeMillis()); 2501 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2502 2503 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2504 | PackageParser.PARSE_FORWARD_LOCK, 2505 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2506 2507 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2508 | PackageParser.PARSE_IS_EPHEMERAL, 2509 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2510 2511 /** 2512 * Remove disable package settings for any updated system 2513 * apps that were removed via an OTA. If they're not a 2514 * previously-updated app, remove them completely. 2515 * Otherwise, just revoke their system-level permissions. 2516 */ 2517 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2518 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2519 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2520 2521 String msg; 2522 if (deletedPkg == null) { 2523 msg = "Updated system package " + deletedAppName 2524 + " no longer exists; it's data will be wiped"; 2525 // Actual deletion of code and data will be handled by later 2526 // reconciliation step 2527 } else { 2528 msg = "Updated system app + " + deletedAppName 2529 + " no longer present; removing system privileges for " 2530 + deletedAppName; 2531 2532 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2533 2534 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2535 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2536 } 2537 logCriticalInfo(Log.WARN, msg); 2538 } 2539 2540 /** 2541 * Make sure all system apps that we expected to appear on 2542 * the userdata partition actually showed up. If they never 2543 * appeared, crawl back and revive the system version. 2544 */ 2545 for (int i = 0; i < mExpectingBetter.size(); i++) { 2546 final String packageName = mExpectingBetter.keyAt(i); 2547 if (!mPackages.containsKey(packageName)) { 2548 final File scanFile = mExpectingBetter.valueAt(i); 2549 2550 logCriticalInfo(Log.WARN, "Expected better " + packageName 2551 + " but never showed up; reverting to system"); 2552 2553 int reparseFlags = mDefParseFlags; 2554 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2555 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2556 | PackageParser.PARSE_IS_SYSTEM_DIR 2557 | PackageParser.PARSE_IS_PRIVILEGED; 2558 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2559 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2560 | PackageParser.PARSE_IS_SYSTEM_DIR; 2561 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2562 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2563 | PackageParser.PARSE_IS_SYSTEM_DIR; 2564 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2565 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2566 | PackageParser.PARSE_IS_SYSTEM_DIR; 2567 } else { 2568 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2569 continue; 2570 } 2571 2572 mSettings.enableSystemPackageLPw(packageName); 2573 2574 try { 2575 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2576 } catch (PackageManagerException e) { 2577 Slog.e(TAG, "Failed to parse original system package: " 2578 + e.getMessage()); 2579 } 2580 } 2581 } 2582 } 2583 mExpectingBetter.clear(); 2584 2585 // Resolve protected action filters. Only the setup wizard is allowed to 2586 // have a high priority filter for these actions. 2587 mSetupWizardPackage = getSetupWizardPackageName(); 2588 if (mProtectedFilters.size() > 0) { 2589 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2590 Slog.i(TAG, "No setup wizard;" 2591 + " All protected intents capped to priority 0"); 2592 } 2593 for (ActivityIntentInfo filter : mProtectedFilters) { 2594 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2595 if (DEBUG_FILTERS) { 2596 Slog.i(TAG, "Found setup wizard;" 2597 + " allow priority " + filter.getPriority() + ";" 2598 + " package: " + filter.activity.info.packageName 2599 + " activity: " + filter.activity.className 2600 + " priority: " + filter.getPriority()); 2601 } 2602 // skip setup wizard; allow it to keep the high priority filter 2603 continue; 2604 } 2605 Slog.w(TAG, "Protected action; cap priority to 0;" 2606 + " package: " + filter.activity.info.packageName 2607 + " activity: " + filter.activity.className 2608 + " origPrio: " + filter.getPriority()); 2609 filter.setPriority(0); 2610 } 2611 } 2612 mDeferProtectedFilters = false; 2613 mProtectedFilters.clear(); 2614 2615 // Now that we know all of the shared libraries, update all clients to have 2616 // the correct library paths. 2617 updateAllSharedLibrariesLPw(); 2618 2619 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2620 // NOTE: We ignore potential failures here during a system scan (like 2621 // the rest of the commands above) because there's precious little we 2622 // can do about it. A settings error is reported, though. 2623 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2624 false /* boot complete */); 2625 } 2626 2627 // Now that we know all the packages we are keeping, 2628 // read and update their last usage times. 2629 mPackageUsage.readLP(); 2630 2631 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2632 SystemClock.uptimeMillis()); 2633 Slog.i(TAG, "Time to scan packages: " 2634 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2635 + " seconds"); 2636 2637 // If the platform SDK has changed since the last time we booted, 2638 // we need to re-grant app permission to catch any new ones that 2639 // appear. This is really a hack, and means that apps can in some 2640 // cases get permissions that the user didn't initially explicitly 2641 // allow... it would be nice to have some better way to handle 2642 // this situation. 2643 int updateFlags = UPDATE_PERMISSIONS_ALL; 2644 if (ver.sdkVersion != mSdkVersion) { 2645 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2646 + mSdkVersion + "; regranting permissions for internal storage"); 2647 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2648 } 2649 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2650 ver.sdkVersion = mSdkVersion; 2651 2652 // If this is the first boot or an update from pre-M, and it is a normal 2653 // boot, then we need to initialize the default preferred apps across 2654 // all defined users. 2655 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2656 for (UserInfo user : sUserManager.getUsers(true)) { 2657 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2658 applyFactoryDefaultBrowserLPw(user.id); 2659 primeDomainVerificationsLPw(user.id); 2660 } 2661 } 2662 2663 // Prepare storage for system user really early during boot, 2664 // since core system apps like SettingsProvider and SystemUI 2665 // can't wait for user to start 2666 final int storageFlags; 2667 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2668 storageFlags = StorageManager.FLAG_STORAGE_DE; 2669 } else { 2670 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2671 } 2672 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2673 storageFlags); 2674 2675 // If this is first boot after an OTA, and a normal boot, then 2676 // we need to clear code cache directories. 2677 if (mIsUpgrade && !onlyCore) { 2678 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2679 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2680 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2681 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2682 // No apps are running this early, so no need to freeze 2683 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2684 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2685 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2686 } 2687 clearAppProfilesLIF(ps.pkg); 2688 } 2689 ver.fingerprint = Build.FINGERPRINT; 2690 } 2691 2692 checkDefaultBrowser(); 2693 2694 // clear only after permissions and other defaults have been updated 2695 mExistingSystemPackages.clear(); 2696 mPromoteSystemApps = false; 2697 2698 // All the changes are done during package scanning. 2699 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2700 2701 // can downgrade to reader 2702 mSettings.writeLPr(); 2703 2704 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2705 SystemClock.uptimeMillis()); 2706 2707 if (!mOnlyCore) { 2708 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2709 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2710 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2711 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2712 mIntentFilterVerifierComponent); 2713 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2714 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2715 getRequiredSharedLibraryLPr( 2716 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2717 } else { 2718 mRequiredVerifierPackage = null; 2719 mRequiredInstallerPackage = null; 2720 mIntentFilterVerifierComponent = null; 2721 mIntentFilterVerifier = null; 2722 mServicesSystemSharedLibraryPackageName = null; 2723 } 2724 2725 mInstallerService = new PackageInstallerService(context, this); 2726 2727 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2728 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2729 // both the installer and resolver must be present to enable ephemeral 2730 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2731 if (DEBUG_EPHEMERAL) { 2732 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2733 + " installer:" + ephemeralInstallerComponent); 2734 } 2735 mEphemeralResolverComponent = ephemeralResolverComponent; 2736 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2737 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2738 mEphemeralResolverConnection = 2739 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2740 } else { 2741 if (DEBUG_EPHEMERAL) { 2742 final String missingComponent = 2743 (ephemeralResolverComponent == null) 2744 ? (ephemeralInstallerComponent == null) 2745 ? "resolver and installer" 2746 : "resolver" 2747 : "installer"; 2748 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2749 } 2750 mEphemeralResolverComponent = null; 2751 mEphemeralInstallerComponent = null; 2752 mEphemeralResolverConnection = null; 2753 } 2754 2755 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2756 } // synchronized (mPackages) 2757 } // synchronized (mInstallLock) 2758 2759 // Now after opening every single application zip, make sure they 2760 // are all flushed. Not really needed, but keeps things nice and 2761 // tidy. 2762 Runtime.getRuntime().gc(); 2763 2764 // The initial scanning above does many calls into installd while 2765 // holding the mPackages lock, but we're mostly interested in yelling 2766 // once we have a booted system. 2767 mInstaller.setWarnIfHeld(mPackages); 2768 2769 // Expose private service for system components to use. 2770 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2771 } 2772 2773 @Override 2774 public boolean isFirstBoot() { 2775 return !mRestoredSettings; 2776 } 2777 2778 @Override 2779 public boolean isOnlyCoreApps() { 2780 return mOnlyCore; 2781 } 2782 2783 @Override 2784 public boolean isUpgrade() { 2785 return mIsUpgrade; 2786 } 2787 2788 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2789 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2790 2791 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2792 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2793 UserHandle.USER_SYSTEM); 2794 if (matches.size() == 1) { 2795 return matches.get(0).getComponentInfo().packageName; 2796 } else { 2797 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2798 return null; 2799 } 2800 } 2801 2802 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2803 synchronized (mPackages) { 2804 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2805 if (libraryEntry == null) { 2806 throw new IllegalStateException("Missing required shared library:" + libraryName); 2807 } 2808 return libraryEntry.apk; 2809 } 2810 } 2811 2812 private @NonNull String getRequiredInstallerLPr() { 2813 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2814 intent.addCategory(Intent.CATEGORY_DEFAULT); 2815 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2816 2817 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2818 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2819 UserHandle.USER_SYSTEM); 2820 if (matches.size() == 1) { 2821 ResolveInfo resolveInfo = matches.get(0); 2822 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2823 throw new RuntimeException("The installer must be a privileged app"); 2824 } 2825 return matches.get(0).getComponentInfo().packageName; 2826 } else { 2827 throw new RuntimeException("There must be exactly one installer; found " + matches); 2828 } 2829 } 2830 2831 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2832 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2833 2834 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2835 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2836 UserHandle.USER_SYSTEM); 2837 ResolveInfo best = null; 2838 final int N = matches.size(); 2839 for (int i = 0; i < N; i++) { 2840 final ResolveInfo cur = matches.get(i); 2841 final String packageName = cur.getComponentInfo().packageName; 2842 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2843 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2844 continue; 2845 } 2846 2847 if (best == null || cur.priority > best.priority) { 2848 best = cur; 2849 } 2850 } 2851 2852 if (best != null) { 2853 return best.getComponentInfo().getComponentName(); 2854 } else { 2855 throw new RuntimeException("There must be at least one intent filter verifier"); 2856 } 2857 } 2858 2859 private @Nullable ComponentName getEphemeralResolverLPr() { 2860 final String[] packageArray = 2861 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2862 if (packageArray.length == 0) { 2863 if (DEBUG_EPHEMERAL) { 2864 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2865 } 2866 return null; 2867 } 2868 2869 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2870 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2871 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2872 UserHandle.USER_SYSTEM); 2873 2874 final int N = resolvers.size(); 2875 if (N == 0) { 2876 if (DEBUG_EPHEMERAL) { 2877 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2878 } 2879 return null; 2880 } 2881 2882 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2883 for (int i = 0; i < N; i++) { 2884 final ResolveInfo info = resolvers.get(i); 2885 2886 if (info.serviceInfo == null) { 2887 continue; 2888 } 2889 2890 final String packageName = info.serviceInfo.packageName; 2891 if (!possiblePackages.contains(packageName)) { 2892 if (DEBUG_EPHEMERAL) { 2893 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2894 + " pkg: " + packageName + ", info:" + info); 2895 } 2896 continue; 2897 } 2898 2899 if (DEBUG_EPHEMERAL) { 2900 Slog.v(TAG, "Ephemeral resolver found;" 2901 + " pkg: " + packageName + ", info:" + info); 2902 } 2903 return new ComponentName(packageName, info.serviceInfo.name); 2904 } 2905 if (DEBUG_EPHEMERAL) { 2906 Slog.v(TAG, "Ephemeral resolver NOT found"); 2907 } 2908 return null; 2909 } 2910 2911 private @Nullable ComponentName getEphemeralInstallerLPr() { 2912 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2913 intent.addCategory(Intent.CATEGORY_DEFAULT); 2914 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2915 2916 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2917 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2918 UserHandle.USER_SYSTEM); 2919 if (matches.size() == 0) { 2920 return null; 2921 } else if (matches.size() == 1) { 2922 return matches.get(0).getComponentInfo().getComponentName(); 2923 } else { 2924 throw new RuntimeException( 2925 "There must be at most one ephemeral installer; found " + matches); 2926 } 2927 } 2928 2929 private void primeDomainVerificationsLPw(int userId) { 2930 if (DEBUG_DOMAIN_VERIFICATION) { 2931 Slog.d(TAG, "Priming domain verifications in user " + userId); 2932 } 2933 2934 SystemConfig systemConfig = SystemConfig.getInstance(); 2935 ArraySet<String> packages = systemConfig.getLinkedApps(); 2936 ArraySet<String> domains = new ArraySet<String>(); 2937 2938 for (String packageName : packages) { 2939 PackageParser.Package pkg = mPackages.get(packageName); 2940 if (pkg != null) { 2941 if (!pkg.isSystemApp()) { 2942 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2943 continue; 2944 } 2945 2946 domains.clear(); 2947 for (PackageParser.Activity a : pkg.activities) { 2948 for (ActivityIntentInfo filter : a.intents) { 2949 if (hasValidDomains(filter)) { 2950 domains.addAll(filter.getHostsList()); 2951 } 2952 } 2953 } 2954 2955 if (domains.size() > 0) { 2956 if (DEBUG_DOMAIN_VERIFICATION) { 2957 Slog.v(TAG, " + " + packageName); 2958 } 2959 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2960 // state w.r.t. the formal app-linkage "no verification attempted" state; 2961 // and then 'always' in the per-user state actually used for intent resolution. 2962 final IntentFilterVerificationInfo ivi; 2963 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2964 new ArrayList<String>(domains)); 2965 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2966 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2967 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2968 } else { 2969 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2970 + "' does not handle web links"); 2971 } 2972 } else { 2973 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2974 } 2975 } 2976 2977 scheduleWritePackageRestrictionsLocked(userId); 2978 scheduleWriteSettingsLocked(); 2979 } 2980 2981 private void applyFactoryDefaultBrowserLPw(int userId) { 2982 // The default browser app's package name is stored in a string resource, 2983 // with a product-specific overlay used for vendor customization. 2984 String browserPkg = mContext.getResources().getString( 2985 com.android.internal.R.string.default_browser); 2986 if (!TextUtils.isEmpty(browserPkg)) { 2987 // non-empty string => required to be a known package 2988 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2989 if (ps == null) { 2990 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2991 browserPkg = null; 2992 } else { 2993 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2994 } 2995 } 2996 2997 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2998 // default. If there's more than one, just leave everything alone. 2999 if (browserPkg == null) { 3000 calculateDefaultBrowserLPw(userId); 3001 } 3002 } 3003 3004 private void calculateDefaultBrowserLPw(int userId) { 3005 List<String> allBrowsers = resolveAllBrowserApps(userId); 3006 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3007 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3008 } 3009 3010 private List<String> resolveAllBrowserApps(int userId) { 3011 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3012 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3013 PackageManager.MATCH_ALL, userId); 3014 3015 final int count = list.size(); 3016 List<String> result = new ArrayList<String>(count); 3017 for (int i=0; i<count; i++) { 3018 ResolveInfo info = list.get(i); 3019 if (info.activityInfo == null 3020 || !info.handleAllWebDataURI 3021 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3022 || result.contains(info.activityInfo.packageName)) { 3023 continue; 3024 } 3025 result.add(info.activityInfo.packageName); 3026 } 3027 3028 return result; 3029 } 3030 3031 private boolean packageIsBrowser(String packageName, int userId) { 3032 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3033 PackageManager.MATCH_ALL, userId); 3034 final int N = list.size(); 3035 for (int i = 0; i < N; i++) { 3036 ResolveInfo info = list.get(i); 3037 if (packageName.equals(info.activityInfo.packageName)) { 3038 return true; 3039 } 3040 } 3041 return false; 3042 } 3043 3044 private void checkDefaultBrowser() { 3045 final int myUserId = UserHandle.myUserId(); 3046 final String packageName = getDefaultBrowserPackageName(myUserId); 3047 if (packageName != null) { 3048 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3049 if (info == null) { 3050 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3051 synchronized (mPackages) { 3052 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3053 } 3054 } 3055 } 3056 } 3057 3058 @Override 3059 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3060 throws RemoteException { 3061 try { 3062 return super.onTransact(code, data, reply, flags); 3063 } catch (RuntimeException e) { 3064 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3065 Slog.wtf(TAG, "Package Manager Crash", e); 3066 } 3067 throw e; 3068 } 3069 } 3070 3071 static int[] appendInts(int[] cur, int[] add) { 3072 if (add == null) return cur; 3073 if (cur == null) return add; 3074 final int N = add.length; 3075 for (int i=0; i<N; i++) { 3076 cur = appendInt(cur, add[i]); 3077 } 3078 return cur; 3079 } 3080 3081 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3082 if (!sUserManager.exists(userId)) return null; 3083 if (ps == null) { 3084 return null; 3085 } 3086 final PackageParser.Package p = ps.pkg; 3087 if (p == null) { 3088 return null; 3089 } 3090 3091 final PermissionsState permissionsState = ps.getPermissionsState(); 3092 3093 final int[] gids = permissionsState.computeGids(userId); 3094 final Set<String> permissions = permissionsState.getPermissions(userId); 3095 final PackageUserState state = ps.readUserState(userId); 3096 3097 return PackageParser.generatePackageInfo(p, gids, flags, 3098 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3099 } 3100 3101 @Override 3102 public void checkPackageStartable(String packageName, int userId) { 3103 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3104 3105 synchronized (mPackages) { 3106 final PackageSetting ps = mSettings.mPackages.get(packageName); 3107 if (ps == null) { 3108 throw new SecurityException("Package " + packageName + " was not found!"); 3109 } 3110 3111 if (!ps.getInstalled(userId)) { 3112 throw new SecurityException( 3113 "Package " + packageName + " was not installed for user " + userId + "!"); 3114 } 3115 3116 if (mSafeMode && !ps.isSystem()) { 3117 throw new SecurityException("Package " + packageName + " not a system app!"); 3118 } 3119 3120 if (mFrozenPackages.contains(packageName)) { 3121 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3122 } 3123 3124 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3125 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3126 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3127 } 3128 } 3129 } 3130 3131 @Override 3132 public boolean isPackageAvailable(String packageName, int userId) { 3133 if (!sUserManager.exists(userId)) return false; 3134 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3135 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3136 synchronized (mPackages) { 3137 PackageParser.Package p = mPackages.get(packageName); 3138 if (p != null) { 3139 final PackageSetting ps = (PackageSetting) p.mExtras; 3140 if (ps != null) { 3141 final PackageUserState state = ps.readUserState(userId); 3142 if (state != null) { 3143 return PackageParser.isAvailable(state); 3144 } 3145 } 3146 } 3147 } 3148 return false; 3149 } 3150 3151 @Override 3152 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3153 if (!sUserManager.exists(userId)) return null; 3154 flags = updateFlagsForPackage(flags, userId, packageName); 3155 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3156 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3157 // reader 3158 synchronized (mPackages) { 3159 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3160 PackageParser.Package p = null; 3161 if (matchFactoryOnly) { 3162 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3163 if (ps != null) { 3164 return generatePackageInfo(ps, flags, userId); 3165 } 3166 } 3167 if (p == null) { 3168 p = mPackages.get(packageName); 3169 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3170 return null; 3171 } 3172 } 3173 if (DEBUG_PACKAGE_INFO) 3174 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3175 if (p != null) { 3176 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3177 } 3178 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3179 final PackageSetting ps = mSettings.mPackages.get(packageName); 3180 return generatePackageInfo(ps, flags, userId); 3181 } 3182 } 3183 return null; 3184 } 3185 3186 @Override 3187 public String[] currentToCanonicalPackageNames(String[] names) { 3188 String[] out = new String[names.length]; 3189 // reader 3190 synchronized (mPackages) { 3191 for (int i=names.length-1; i>=0; i--) { 3192 PackageSetting ps = mSettings.mPackages.get(names[i]); 3193 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3194 } 3195 } 3196 return out; 3197 } 3198 3199 @Override 3200 public String[] canonicalToCurrentPackageNames(String[] names) { 3201 String[] out = new String[names.length]; 3202 // reader 3203 synchronized (mPackages) { 3204 for (int i=names.length-1; i>=0; i--) { 3205 String cur = mSettings.mRenamedPackages.get(names[i]); 3206 out[i] = cur != null ? cur : names[i]; 3207 } 3208 } 3209 return out; 3210 } 3211 3212 @Override 3213 public int getPackageUid(String packageName, int flags, int userId) { 3214 if (!sUserManager.exists(userId)) return -1; 3215 flags = updateFlagsForPackage(flags, userId, packageName); 3216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3217 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3218 3219 // reader 3220 synchronized (mPackages) { 3221 final PackageParser.Package p = mPackages.get(packageName); 3222 if (p != null && p.isMatch(flags)) { 3223 return UserHandle.getUid(userId, p.applicationInfo.uid); 3224 } 3225 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3226 final PackageSetting ps = mSettings.mPackages.get(packageName); 3227 if (ps != null && ps.isMatch(flags)) { 3228 return UserHandle.getUid(userId, ps.appId); 3229 } 3230 } 3231 } 3232 3233 return -1; 3234 } 3235 3236 @Override 3237 public int[] getPackageGids(String packageName, int flags, int userId) { 3238 if (!sUserManager.exists(userId)) return null; 3239 flags = updateFlagsForPackage(flags, userId, packageName); 3240 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3241 false /* requireFullPermission */, false /* checkShell */, 3242 "getPackageGids"); 3243 3244 // reader 3245 synchronized (mPackages) { 3246 final PackageParser.Package p = mPackages.get(packageName); 3247 if (p != null && p.isMatch(flags)) { 3248 PackageSetting ps = (PackageSetting) p.mExtras; 3249 return ps.getPermissionsState().computeGids(userId); 3250 } 3251 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3252 final PackageSetting ps = mSettings.mPackages.get(packageName); 3253 if (ps != null && ps.isMatch(flags)) { 3254 return ps.getPermissionsState().computeGids(userId); 3255 } 3256 } 3257 } 3258 3259 return null; 3260 } 3261 3262 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3263 if (bp.perm != null) { 3264 return PackageParser.generatePermissionInfo(bp.perm, flags); 3265 } 3266 PermissionInfo pi = new PermissionInfo(); 3267 pi.name = bp.name; 3268 pi.packageName = bp.sourcePackage; 3269 pi.nonLocalizedLabel = bp.name; 3270 pi.protectionLevel = bp.protectionLevel; 3271 return pi; 3272 } 3273 3274 @Override 3275 public PermissionInfo getPermissionInfo(String name, int flags) { 3276 // reader 3277 synchronized (mPackages) { 3278 final BasePermission p = mSettings.mPermissions.get(name); 3279 if (p != null) { 3280 return generatePermissionInfo(p, flags); 3281 } 3282 return null; 3283 } 3284 } 3285 3286 @Override 3287 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3288 int flags) { 3289 // reader 3290 synchronized (mPackages) { 3291 if (group != null && !mPermissionGroups.containsKey(group)) { 3292 // This is thrown as NameNotFoundException 3293 return null; 3294 } 3295 3296 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3297 for (BasePermission p : mSettings.mPermissions.values()) { 3298 if (group == null) { 3299 if (p.perm == null || p.perm.info.group == null) { 3300 out.add(generatePermissionInfo(p, flags)); 3301 } 3302 } else { 3303 if (p.perm != null && group.equals(p.perm.info.group)) { 3304 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3305 } 3306 } 3307 } 3308 return new ParceledListSlice<>(out); 3309 } 3310 } 3311 3312 @Override 3313 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3314 // reader 3315 synchronized (mPackages) { 3316 return PackageParser.generatePermissionGroupInfo( 3317 mPermissionGroups.get(name), flags); 3318 } 3319 } 3320 3321 @Override 3322 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3323 // reader 3324 synchronized (mPackages) { 3325 final int N = mPermissionGroups.size(); 3326 ArrayList<PermissionGroupInfo> out 3327 = new ArrayList<PermissionGroupInfo>(N); 3328 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3329 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3330 } 3331 return new ParceledListSlice<>(out); 3332 } 3333 } 3334 3335 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3336 int userId) { 3337 if (!sUserManager.exists(userId)) return null; 3338 PackageSetting ps = mSettings.mPackages.get(packageName); 3339 if (ps != null) { 3340 if (ps.pkg == null) { 3341 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3342 if (pInfo != null) { 3343 return pInfo.applicationInfo; 3344 } 3345 return null; 3346 } 3347 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3348 ps.readUserState(userId), userId); 3349 } 3350 return null; 3351 } 3352 3353 @Override 3354 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3355 if (!sUserManager.exists(userId)) return null; 3356 flags = updateFlagsForApplication(flags, userId, packageName); 3357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3358 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3359 // writer 3360 synchronized (mPackages) { 3361 PackageParser.Package p = mPackages.get(packageName); 3362 if (DEBUG_PACKAGE_INFO) Log.v( 3363 TAG, "getApplicationInfo " + packageName 3364 + ": " + p); 3365 if (p != null) { 3366 PackageSetting ps = mSettings.mPackages.get(packageName); 3367 if (ps == null) return null; 3368 // Note: isEnabledLP() does not apply here - always return info 3369 return PackageParser.generateApplicationInfo( 3370 p, flags, ps.readUserState(userId), userId); 3371 } 3372 if ("android".equals(packageName)||"system".equals(packageName)) { 3373 return mAndroidApplication; 3374 } 3375 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3376 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3377 } 3378 } 3379 return null; 3380 } 3381 3382 @Override 3383 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3384 final IPackageDataObserver observer) { 3385 mContext.enforceCallingOrSelfPermission( 3386 android.Manifest.permission.CLEAR_APP_CACHE, null); 3387 // Queue up an async operation since clearing cache may take a little while. 3388 mHandler.post(new Runnable() { 3389 public void run() { 3390 mHandler.removeCallbacks(this); 3391 boolean success = true; 3392 synchronized (mInstallLock) { 3393 try { 3394 mInstaller.freeCache(volumeUuid, freeStorageSize); 3395 } catch (InstallerException e) { 3396 Slog.w(TAG, "Couldn't clear application caches: " + e); 3397 success = false; 3398 } 3399 } 3400 if (observer != null) { 3401 try { 3402 observer.onRemoveCompleted(null, success); 3403 } catch (RemoteException e) { 3404 Slog.w(TAG, "RemoveException when invoking call back"); 3405 } 3406 } 3407 } 3408 }); 3409 } 3410 3411 @Override 3412 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3413 final IntentSender pi) { 3414 mContext.enforceCallingOrSelfPermission( 3415 android.Manifest.permission.CLEAR_APP_CACHE, null); 3416 // Queue up an async operation since clearing cache may take a little while. 3417 mHandler.post(new Runnable() { 3418 public void run() { 3419 mHandler.removeCallbacks(this); 3420 boolean success = true; 3421 synchronized (mInstallLock) { 3422 try { 3423 mInstaller.freeCache(volumeUuid, freeStorageSize); 3424 } catch (InstallerException e) { 3425 Slog.w(TAG, "Couldn't clear application caches: " + e); 3426 success = false; 3427 } 3428 } 3429 if(pi != null) { 3430 try { 3431 // Callback via pending intent 3432 int code = success ? 1 : 0; 3433 pi.sendIntent(null, code, null, 3434 null, null); 3435 } catch (SendIntentException e1) { 3436 Slog.i(TAG, "Failed to send pending intent"); 3437 } 3438 } 3439 } 3440 }); 3441 } 3442 3443 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3444 synchronized (mInstallLock) { 3445 try { 3446 mInstaller.freeCache(volumeUuid, freeStorageSize); 3447 } catch (InstallerException e) { 3448 throw new IOException("Failed to free enough space", e); 3449 } 3450 } 3451 } 3452 3453 /** 3454 * Return if the user key is currently unlocked. 3455 */ 3456 private boolean isUserKeyUnlocked(int userId) { 3457 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3458 final IMountService mount = IMountService.Stub 3459 .asInterface(ServiceManager.getService("mount")); 3460 if (mount == null) { 3461 Slog.w(TAG, "Early during boot, assuming locked"); 3462 return false; 3463 } 3464 final long token = Binder.clearCallingIdentity(); 3465 try { 3466 return mount.isUserKeyUnlocked(userId); 3467 } catch (RemoteException e) { 3468 throw e.rethrowAsRuntimeException(); 3469 } finally { 3470 Binder.restoreCallingIdentity(token); 3471 } 3472 } else { 3473 return true; 3474 } 3475 } 3476 3477 /** 3478 * Update given flags based on encryption status of current user. 3479 */ 3480 private int updateFlags(int flags, int userId) { 3481 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3482 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3483 // Caller expressed an explicit opinion about what encryption 3484 // aware/unaware components they want to see, so fall through and 3485 // give them what they want 3486 } else { 3487 // Caller expressed no opinion, so match based on user state 3488 if (isUserKeyUnlocked(userId)) { 3489 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3490 } else { 3491 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3492 } 3493 } 3494 return flags; 3495 } 3496 3497 /** 3498 * Update given flags when being used to request {@link PackageInfo}. 3499 */ 3500 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3501 boolean triaged = true; 3502 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3503 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3504 // Caller is asking for component details, so they'd better be 3505 // asking for specific encryption matching behavior, or be triaged 3506 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3507 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3508 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3509 triaged = false; 3510 } 3511 } 3512 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3513 | PackageManager.MATCH_SYSTEM_ONLY 3514 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3515 triaged = false; 3516 } 3517 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3518 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3519 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3520 } 3521 return updateFlags(flags, userId); 3522 } 3523 3524 /** 3525 * Update given flags when being used to request {@link ApplicationInfo}. 3526 */ 3527 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3528 return updateFlagsForPackage(flags, userId, cookie); 3529 } 3530 3531 /** 3532 * Update given flags when being used to request {@link ComponentInfo}. 3533 */ 3534 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3535 if (cookie instanceof Intent) { 3536 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3537 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3538 } 3539 } 3540 3541 boolean triaged = true; 3542 // Caller is asking for component details, so they'd better be 3543 // asking for specific encryption matching behavior, or be triaged 3544 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3545 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3546 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3547 triaged = false; 3548 } 3549 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3550 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3551 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3552 } 3553 3554 return updateFlags(flags, userId); 3555 } 3556 3557 /** 3558 * Update given flags when being used to request {@link ResolveInfo}. 3559 */ 3560 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3561 // Safe mode means we shouldn't match any third-party components 3562 if (mSafeMode) { 3563 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3564 } 3565 3566 return updateFlagsForComponent(flags, userId, cookie); 3567 } 3568 3569 @Override 3570 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3571 if (!sUserManager.exists(userId)) return null; 3572 flags = updateFlagsForComponent(flags, userId, component); 3573 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3574 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3575 synchronized (mPackages) { 3576 PackageParser.Activity a = mActivities.mActivities.get(component); 3577 3578 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3579 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3580 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3581 if (ps == null) return null; 3582 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3583 userId); 3584 } 3585 if (mResolveComponentName.equals(component)) { 3586 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3587 new PackageUserState(), userId); 3588 } 3589 } 3590 return null; 3591 } 3592 3593 @Override 3594 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3595 String resolvedType) { 3596 synchronized (mPackages) { 3597 if (component.equals(mResolveComponentName)) { 3598 // The resolver supports EVERYTHING! 3599 return true; 3600 } 3601 PackageParser.Activity a = mActivities.mActivities.get(component); 3602 if (a == null) { 3603 return false; 3604 } 3605 for (int i=0; i<a.intents.size(); i++) { 3606 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3607 intent.getData(), intent.getCategories(), TAG) >= 0) { 3608 return true; 3609 } 3610 } 3611 return false; 3612 } 3613 } 3614 3615 @Override 3616 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3617 if (!sUserManager.exists(userId)) return null; 3618 flags = updateFlagsForComponent(flags, userId, component); 3619 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3620 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3621 synchronized (mPackages) { 3622 PackageParser.Activity a = mReceivers.mActivities.get(component); 3623 if (DEBUG_PACKAGE_INFO) Log.v( 3624 TAG, "getReceiverInfo " + component + ": " + a); 3625 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3626 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3627 if (ps == null) return null; 3628 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3629 userId); 3630 } 3631 } 3632 return null; 3633 } 3634 3635 @Override 3636 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3637 if (!sUserManager.exists(userId)) return null; 3638 flags = updateFlagsForComponent(flags, userId, component); 3639 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3640 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3641 synchronized (mPackages) { 3642 PackageParser.Service s = mServices.mServices.get(component); 3643 if (DEBUG_PACKAGE_INFO) Log.v( 3644 TAG, "getServiceInfo " + component + ": " + s); 3645 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3646 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3647 if (ps == null) return null; 3648 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3649 userId); 3650 } 3651 } 3652 return null; 3653 } 3654 3655 @Override 3656 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3657 if (!sUserManager.exists(userId)) return null; 3658 flags = updateFlagsForComponent(flags, userId, component); 3659 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3660 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3661 synchronized (mPackages) { 3662 PackageParser.Provider p = mProviders.mProviders.get(component); 3663 if (DEBUG_PACKAGE_INFO) Log.v( 3664 TAG, "getProviderInfo " + component + ": " + p); 3665 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3666 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3667 if (ps == null) return null; 3668 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3669 userId); 3670 } 3671 } 3672 return null; 3673 } 3674 3675 @Override 3676 public String[] getSystemSharedLibraryNames() { 3677 Set<String> libSet; 3678 synchronized (mPackages) { 3679 libSet = mSharedLibraries.keySet(); 3680 int size = libSet.size(); 3681 if (size > 0) { 3682 String[] libs = new String[size]; 3683 libSet.toArray(libs); 3684 return libs; 3685 } 3686 } 3687 return null; 3688 } 3689 3690 @Override 3691 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3692 synchronized (mPackages) { 3693 return mServicesSystemSharedLibraryPackageName; 3694 } 3695 } 3696 3697 @Override 3698 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3699 synchronized (mPackages) { 3700 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3701 3702 final FeatureInfo fi = new FeatureInfo(); 3703 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3704 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3705 res.add(fi); 3706 3707 return new ParceledListSlice<>(res); 3708 } 3709 } 3710 3711 @Override 3712 public boolean hasSystemFeature(String name, int version) { 3713 synchronized (mPackages) { 3714 final FeatureInfo feat = mAvailableFeatures.get(name); 3715 if (feat == null) { 3716 return false; 3717 } else { 3718 return feat.version >= version; 3719 } 3720 } 3721 } 3722 3723 @Override 3724 public int checkPermission(String permName, String pkgName, int userId) { 3725 if (!sUserManager.exists(userId)) { 3726 return PackageManager.PERMISSION_DENIED; 3727 } 3728 3729 synchronized (mPackages) { 3730 final PackageParser.Package p = mPackages.get(pkgName); 3731 if (p != null && p.mExtras != null) { 3732 final PackageSetting ps = (PackageSetting) p.mExtras; 3733 final PermissionsState permissionsState = ps.getPermissionsState(); 3734 if (permissionsState.hasPermission(permName, userId)) { 3735 return PackageManager.PERMISSION_GRANTED; 3736 } 3737 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3738 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3739 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3740 return PackageManager.PERMISSION_GRANTED; 3741 } 3742 } 3743 } 3744 3745 return PackageManager.PERMISSION_DENIED; 3746 } 3747 3748 @Override 3749 public int checkUidPermission(String permName, int uid) { 3750 final int userId = UserHandle.getUserId(uid); 3751 3752 if (!sUserManager.exists(userId)) { 3753 return PackageManager.PERMISSION_DENIED; 3754 } 3755 3756 synchronized (mPackages) { 3757 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3758 if (obj != null) { 3759 final SettingBase ps = (SettingBase) obj; 3760 final PermissionsState permissionsState = ps.getPermissionsState(); 3761 if (permissionsState.hasPermission(permName, userId)) { 3762 return PackageManager.PERMISSION_GRANTED; 3763 } 3764 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3765 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3766 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3767 return PackageManager.PERMISSION_GRANTED; 3768 } 3769 } else { 3770 ArraySet<String> perms = mSystemPermissions.get(uid); 3771 if (perms != null) { 3772 if (perms.contains(permName)) { 3773 return PackageManager.PERMISSION_GRANTED; 3774 } 3775 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3776 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3777 return PackageManager.PERMISSION_GRANTED; 3778 } 3779 } 3780 } 3781 } 3782 3783 return PackageManager.PERMISSION_DENIED; 3784 } 3785 3786 @Override 3787 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3788 if (UserHandle.getCallingUserId() != userId) { 3789 mContext.enforceCallingPermission( 3790 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3791 "isPermissionRevokedByPolicy for user " + userId); 3792 } 3793 3794 if (checkPermission(permission, packageName, userId) 3795 == PackageManager.PERMISSION_GRANTED) { 3796 return false; 3797 } 3798 3799 final long identity = Binder.clearCallingIdentity(); 3800 try { 3801 final int flags = getPermissionFlags(permission, packageName, userId); 3802 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3803 } finally { 3804 Binder.restoreCallingIdentity(identity); 3805 } 3806 } 3807 3808 @Override 3809 public String getPermissionControllerPackageName() { 3810 synchronized (mPackages) { 3811 return mRequiredInstallerPackage; 3812 } 3813 } 3814 3815 /** 3816 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3817 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3818 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3819 * @param message the message to log on security exception 3820 */ 3821 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3822 boolean checkShell, String message) { 3823 if (userId < 0) { 3824 throw new IllegalArgumentException("Invalid userId " + userId); 3825 } 3826 if (checkShell) { 3827 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3828 } 3829 if (userId == UserHandle.getUserId(callingUid)) return; 3830 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3831 if (requireFullPermission) { 3832 mContext.enforceCallingOrSelfPermission( 3833 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3834 } else { 3835 try { 3836 mContext.enforceCallingOrSelfPermission( 3837 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3838 } catch (SecurityException se) { 3839 mContext.enforceCallingOrSelfPermission( 3840 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3841 } 3842 } 3843 } 3844 } 3845 3846 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3847 if (callingUid == Process.SHELL_UID) { 3848 if (userHandle >= 0 3849 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3850 throw new SecurityException("Shell does not have permission to access user " 3851 + userHandle); 3852 } else if (userHandle < 0) { 3853 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3854 + Debug.getCallers(3)); 3855 } 3856 } 3857 } 3858 3859 private BasePermission findPermissionTreeLP(String permName) { 3860 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3861 if (permName.startsWith(bp.name) && 3862 permName.length() > bp.name.length() && 3863 permName.charAt(bp.name.length()) == '.') { 3864 return bp; 3865 } 3866 } 3867 return null; 3868 } 3869 3870 private BasePermission checkPermissionTreeLP(String permName) { 3871 if (permName != null) { 3872 BasePermission bp = findPermissionTreeLP(permName); 3873 if (bp != null) { 3874 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3875 return bp; 3876 } 3877 throw new SecurityException("Calling uid " 3878 + Binder.getCallingUid() 3879 + " is not allowed to add to permission tree " 3880 + bp.name + " owned by uid " + bp.uid); 3881 } 3882 } 3883 throw new SecurityException("No permission tree found for " + permName); 3884 } 3885 3886 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3887 if (s1 == null) { 3888 return s2 == null; 3889 } 3890 if (s2 == null) { 3891 return false; 3892 } 3893 if (s1.getClass() != s2.getClass()) { 3894 return false; 3895 } 3896 return s1.equals(s2); 3897 } 3898 3899 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3900 if (pi1.icon != pi2.icon) return false; 3901 if (pi1.logo != pi2.logo) return false; 3902 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3903 if (!compareStrings(pi1.name, pi2.name)) return false; 3904 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3905 // We'll take care of setting this one. 3906 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3907 // These are not currently stored in settings. 3908 //if (!compareStrings(pi1.group, pi2.group)) return false; 3909 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3910 //if (pi1.labelRes != pi2.labelRes) return false; 3911 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3912 return true; 3913 } 3914 3915 int permissionInfoFootprint(PermissionInfo info) { 3916 int size = info.name.length(); 3917 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3918 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3919 return size; 3920 } 3921 3922 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3923 int size = 0; 3924 for (BasePermission perm : mSettings.mPermissions.values()) { 3925 if (perm.uid == tree.uid) { 3926 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3927 } 3928 } 3929 return size; 3930 } 3931 3932 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3933 // We calculate the max size of permissions defined by this uid and throw 3934 // if that plus the size of 'info' would exceed our stated maximum. 3935 if (tree.uid != Process.SYSTEM_UID) { 3936 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3937 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3938 throw new SecurityException("Permission tree size cap exceeded"); 3939 } 3940 } 3941 } 3942 3943 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3944 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3945 throw new SecurityException("Label must be specified in permission"); 3946 } 3947 BasePermission tree = checkPermissionTreeLP(info.name); 3948 BasePermission bp = mSettings.mPermissions.get(info.name); 3949 boolean added = bp == null; 3950 boolean changed = true; 3951 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3952 if (added) { 3953 enforcePermissionCapLocked(info, tree); 3954 bp = new BasePermission(info.name, tree.sourcePackage, 3955 BasePermission.TYPE_DYNAMIC); 3956 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3957 throw new SecurityException( 3958 "Not allowed to modify non-dynamic permission " 3959 + info.name); 3960 } else { 3961 if (bp.protectionLevel == fixedLevel 3962 && bp.perm.owner.equals(tree.perm.owner) 3963 && bp.uid == tree.uid 3964 && comparePermissionInfos(bp.perm.info, info)) { 3965 changed = false; 3966 } 3967 } 3968 bp.protectionLevel = fixedLevel; 3969 info = new PermissionInfo(info); 3970 info.protectionLevel = fixedLevel; 3971 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3972 bp.perm.info.packageName = tree.perm.info.packageName; 3973 bp.uid = tree.uid; 3974 if (added) { 3975 mSettings.mPermissions.put(info.name, bp); 3976 } 3977 if (changed) { 3978 if (!async) { 3979 mSettings.writeLPr(); 3980 } else { 3981 scheduleWriteSettingsLocked(); 3982 } 3983 } 3984 return added; 3985 } 3986 3987 @Override 3988 public boolean addPermission(PermissionInfo info) { 3989 synchronized (mPackages) { 3990 return addPermissionLocked(info, false); 3991 } 3992 } 3993 3994 @Override 3995 public boolean addPermissionAsync(PermissionInfo info) { 3996 synchronized (mPackages) { 3997 return addPermissionLocked(info, true); 3998 } 3999 } 4000 4001 @Override 4002 public void removePermission(String name) { 4003 synchronized (mPackages) { 4004 checkPermissionTreeLP(name); 4005 BasePermission bp = mSettings.mPermissions.get(name); 4006 if (bp != null) { 4007 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4008 throw new SecurityException( 4009 "Not allowed to modify non-dynamic permission " 4010 + name); 4011 } 4012 mSettings.mPermissions.remove(name); 4013 mSettings.writeLPr(); 4014 } 4015 } 4016 } 4017 4018 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4019 BasePermission bp) { 4020 int index = pkg.requestedPermissions.indexOf(bp.name); 4021 if (index == -1) { 4022 throw new SecurityException("Package " + pkg.packageName 4023 + " has not requested permission " + bp.name); 4024 } 4025 if (!bp.isRuntime() && !bp.isDevelopment()) { 4026 throw new SecurityException("Permission " + bp.name 4027 + " is not a changeable permission type"); 4028 } 4029 } 4030 4031 @Override 4032 public void grantRuntimePermission(String packageName, String name, final int userId) { 4033 if (!sUserManager.exists(userId)) { 4034 Log.e(TAG, "No such user:" + userId); 4035 return; 4036 } 4037 4038 mContext.enforceCallingOrSelfPermission( 4039 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4040 "grantRuntimePermission"); 4041 4042 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4043 true /* requireFullPermission */, true /* checkShell */, 4044 "grantRuntimePermission"); 4045 4046 final int uid; 4047 final SettingBase sb; 4048 4049 synchronized (mPackages) { 4050 final PackageParser.Package pkg = mPackages.get(packageName); 4051 if (pkg == null) { 4052 throw new IllegalArgumentException("Unknown package: " + packageName); 4053 } 4054 4055 final BasePermission bp = mSettings.mPermissions.get(name); 4056 if (bp == null) { 4057 throw new IllegalArgumentException("Unknown permission: " + name); 4058 } 4059 4060 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4061 4062 // If a permission review is required for legacy apps we represent 4063 // their permissions as always granted runtime ones since we need 4064 // to keep the review required permission flag per user while an 4065 // install permission's state is shared across all users. 4066 if (Build.PERMISSIONS_REVIEW_REQUIRED 4067 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4068 && bp.isRuntime()) { 4069 return; 4070 } 4071 4072 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4073 sb = (SettingBase) pkg.mExtras; 4074 if (sb == null) { 4075 throw new IllegalArgumentException("Unknown package: " + packageName); 4076 } 4077 4078 final PermissionsState permissionsState = sb.getPermissionsState(); 4079 4080 final int flags = permissionsState.getPermissionFlags(name, userId); 4081 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4082 throw new SecurityException("Cannot grant system fixed permission " 4083 + name + " for package " + packageName); 4084 } 4085 4086 if (bp.isDevelopment()) { 4087 // Development permissions must be handled specially, since they are not 4088 // normal runtime permissions. For now they apply to all users. 4089 if (permissionsState.grantInstallPermission(bp) != 4090 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4091 scheduleWriteSettingsLocked(); 4092 } 4093 return; 4094 } 4095 4096 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4097 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4098 return; 4099 } 4100 4101 final int result = permissionsState.grantRuntimePermission(bp, userId); 4102 switch (result) { 4103 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4104 return; 4105 } 4106 4107 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4108 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4109 mHandler.post(new Runnable() { 4110 @Override 4111 public void run() { 4112 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4113 } 4114 }); 4115 } 4116 break; 4117 } 4118 4119 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4120 4121 // Not critical if that is lost - app has to request again. 4122 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4123 } 4124 4125 // Only need to do this if user is initialized. Otherwise it's a new user 4126 // and there are no processes running as the user yet and there's no need 4127 // to make an expensive call to remount processes for the changed permissions. 4128 if (READ_EXTERNAL_STORAGE.equals(name) 4129 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4130 final long token = Binder.clearCallingIdentity(); 4131 try { 4132 if (sUserManager.isInitialized(userId)) { 4133 MountServiceInternal mountServiceInternal = LocalServices.getService( 4134 MountServiceInternal.class); 4135 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4136 } 4137 } finally { 4138 Binder.restoreCallingIdentity(token); 4139 } 4140 } 4141 } 4142 4143 @Override 4144 public void revokeRuntimePermission(String packageName, String name, int userId) { 4145 if (!sUserManager.exists(userId)) { 4146 Log.e(TAG, "No such user:" + userId); 4147 return; 4148 } 4149 4150 mContext.enforceCallingOrSelfPermission( 4151 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4152 "revokeRuntimePermission"); 4153 4154 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4155 true /* requireFullPermission */, true /* checkShell */, 4156 "revokeRuntimePermission"); 4157 4158 final int appId; 4159 4160 synchronized (mPackages) { 4161 final PackageParser.Package pkg = mPackages.get(packageName); 4162 if (pkg == null) { 4163 throw new IllegalArgumentException("Unknown package: " + packageName); 4164 } 4165 4166 final BasePermission bp = mSettings.mPermissions.get(name); 4167 if (bp == null) { 4168 throw new IllegalArgumentException("Unknown permission: " + name); 4169 } 4170 4171 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4172 4173 // If a permission review is required for legacy apps we represent 4174 // their permissions as always granted runtime ones since we need 4175 // to keep the review required permission flag per user while an 4176 // install permission's state is shared across all users. 4177 if (Build.PERMISSIONS_REVIEW_REQUIRED 4178 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4179 && bp.isRuntime()) { 4180 return; 4181 } 4182 4183 SettingBase sb = (SettingBase) pkg.mExtras; 4184 if (sb == null) { 4185 throw new IllegalArgumentException("Unknown package: " + packageName); 4186 } 4187 4188 final PermissionsState permissionsState = sb.getPermissionsState(); 4189 4190 final int flags = permissionsState.getPermissionFlags(name, userId); 4191 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4192 throw new SecurityException("Cannot revoke system fixed permission " 4193 + name + " for package " + packageName); 4194 } 4195 4196 if (bp.isDevelopment()) { 4197 // Development permissions must be handled specially, since they are not 4198 // normal runtime permissions. For now they apply to all users. 4199 if (permissionsState.revokeInstallPermission(bp) != 4200 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4201 scheduleWriteSettingsLocked(); 4202 } 4203 return; 4204 } 4205 4206 if (permissionsState.revokeRuntimePermission(bp, userId) == 4207 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4208 return; 4209 } 4210 4211 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4212 4213 // Critical, after this call app should never have the permission. 4214 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4215 4216 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4217 } 4218 4219 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4220 } 4221 4222 @Override 4223 public void resetRuntimePermissions() { 4224 mContext.enforceCallingOrSelfPermission( 4225 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4226 "revokeRuntimePermission"); 4227 4228 int callingUid = Binder.getCallingUid(); 4229 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4230 mContext.enforceCallingOrSelfPermission( 4231 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4232 "resetRuntimePermissions"); 4233 } 4234 4235 synchronized (mPackages) { 4236 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4237 for (int userId : UserManagerService.getInstance().getUserIds()) { 4238 final int packageCount = mPackages.size(); 4239 for (int i = 0; i < packageCount; i++) { 4240 PackageParser.Package pkg = mPackages.valueAt(i); 4241 if (!(pkg.mExtras instanceof PackageSetting)) { 4242 continue; 4243 } 4244 PackageSetting ps = (PackageSetting) pkg.mExtras; 4245 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4246 } 4247 } 4248 } 4249 } 4250 4251 @Override 4252 public int getPermissionFlags(String name, String packageName, int userId) { 4253 if (!sUserManager.exists(userId)) { 4254 return 0; 4255 } 4256 4257 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4258 4259 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4260 true /* requireFullPermission */, false /* checkShell */, 4261 "getPermissionFlags"); 4262 4263 synchronized (mPackages) { 4264 final PackageParser.Package pkg = mPackages.get(packageName); 4265 if (pkg == null) { 4266 throw new IllegalArgumentException("Unknown package: " + packageName); 4267 } 4268 4269 final BasePermission bp = mSettings.mPermissions.get(name); 4270 if (bp == null) { 4271 throw new IllegalArgumentException("Unknown permission: " + name); 4272 } 4273 4274 SettingBase sb = (SettingBase) pkg.mExtras; 4275 if (sb == null) { 4276 throw new IllegalArgumentException("Unknown package: " + packageName); 4277 } 4278 4279 PermissionsState permissionsState = sb.getPermissionsState(); 4280 return permissionsState.getPermissionFlags(name, userId); 4281 } 4282 } 4283 4284 @Override 4285 public void updatePermissionFlags(String name, String packageName, int flagMask, 4286 int flagValues, int userId) { 4287 if (!sUserManager.exists(userId)) { 4288 return; 4289 } 4290 4291 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4292 4293 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4294 true /* requireFullPermission */, true /* checkShell */, 4295 "updatePermissionFlags"); 4296 4297 // Only the system can change these flags and nothing else. 4298 if (getCallingUid() != Process.SYSTEM_UID) { 4299 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4300 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4301 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4302 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4304 } 4305 4306 synchronized (mPackages) { 4307 final PackageParser.Package pkg = mPackages.get(packageName); 4308 if (pkg == null) { 4309 throw new IllegalArgumentException("Unknown package: " + packageName); 4310 } 4311 4312 final BasePermission bp = mSettings.mPermissions.get(name); 4313 if (bp == null) { 4314 throw new IllegalArgumentException("Unknown permission: " + name); 4315 } 4316 4317 SettingBase sb = (SettingBase) pkg.mExtras; 4318 if (sb == null) { 4319 throw new IllegalArgumentException("Unknown package: " + packageName); 4320 } 4321 4322 PermissionsState permissionsState = sb.getPermissionsState(); 4323 4324 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4325 4326 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4327 // Install and runtime permissions are stored in different places, 4328 // so figure out what permission changed and persist the change. 4329 if (permissionsState.getInstallPermissionState(name) != null) { 4330 scheduleWriteSettingsLocked(); 4331 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4332 || hadState) { 4333 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4334 } 4335 } 4336 } 4337 } 4338 4339 /** 4340 * Update the permission flags for all packages and runtime permissions of a user in order 4341 * to allow device or profile owner to remove POLICY_FIXED. 4342 */ 4343 @Override 4344 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4345 if (!sUserManager.exists(userId)) { 4346 return; 4347 } 4348 4349 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4350 4351 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4352 true /* requireFullPermission */, true /* checkShell */, 4353 "updatePermissionFlagsForAllApps"); 4354 4355 // Only the system can change system fixed flags. 4356 if (getCallingUid() != Process.SYSTEM_UID) { 4357 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4358 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4359 } 4360 4361 synchronized (mPackages) { 4362 boolean changed = false; 4363 final int packageCount = mPackages.size(); 4364 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4365 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4366 SettingBase sb = (SettingBase) pkg.mExtras; 4367 if (sb == null) { 4368 continue; 4369 } 4370 PermissionsState permissionsState = sb.getPermissionsState(); 4371 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4372 userId, flagMask, flagValues); 4373 } 4374 if (changed) { 4375 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4376 } 4377 } 4378 } 4379 4380 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4381 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4382 != PackageManager.PERMISSION_GRANTED 4383 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4384 != PackageManager.PERMISSION_GRANTED) { 4385 throw new SecurityException(message + " requires " 4386 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4387 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4388 } 4389 } 4390 4391 @Override 4392 public boolean shouldShowRequestPermissionRationale(String permissionName, 4393 String packageName, int userId) { 4394 if (UserHandle.getCallingUserId() != userId) { 4395 mContext.enforceCallingPermission( 4396 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4397 "canShowRequestPermissionRationale for user " + userId); 4398 } 4399 4400 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4401 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4402 return false; 4403 } 4404 4405 if (checkPermission(permissionName, packageName, userId) 4406 == PackageManager.PERMISSION_GRANTED) { 4407 return false; 4408 } 4409 4410 final int flags; 4411 4412 final long identity = Binder.clearCallingIdentity(); 4413 try { 4414 flags = getPermissionFlags(permissionName, 4415 packageName, userId); 4416 } finally { 4417 Binder.restoreCallingIdentity(identity); 4418 } 4419 4420 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4421 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4422 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4423 4424 if ((flags & fixedFlags) != 0) { 4425 return false; 4426 } 4427 4428 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4429 } 4430 4431 @Override 4432 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4433 mContext.enforceCallingOrSelfPermission( 4434 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4435 "addOnPermissionsChangeListener"); 4436 4437 synchronized (mPackages) { 4438 mOnPermissionChangeListeners.addListenerLocked(listener); 4439 } 4440 } 4441 4442 @Override 4443 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4444 synchronized (mPackages) { 4445 mOnPermissionChangeListeners.removeListenerLocked(listener); 4446 } 4447 } 4448 4449 @Override 4450 public boolean isProtectedBroadcast(String actionName) { 4451 synchronized (mPackages) { 4452 if (mProtectedBroadcasts.contains(actionName)) { 4453 return true; 4454 } else if (actionName != null) { 4455 // TODO: remove these terrible hacks 4456 if (actionName.startsWith("android.net.netmon.lingerExpired") 4457 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4458 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4459 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4460 return true; 4461 } 4462 } 4463 } 4464 return false; 4465 } 4466 4467 @Override 4468 public int checkSignatures(String pkg1, String pkg2) { 4469 synchronized (mPackages) { 4470 final PackageParser.Package p1 = mPackages.get(pkg1); 4471 final PackageParser.Package p2 = mPackages.get(pkg2); 4472 if (p1 == null || p1.mExtras == null 4473 || p2 == null || p2.mExtras == null) { 4474 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4475 } 4476 return compareSignatures(p1.mSignatures, p2.mSignatures); 4477 } 4478 } 4479 4480 @Override 4481 public int checkUidSignatures(int uid1, int uid2) { 4482 // Map to base uids. 4483 uid1 = UserHandle.getAppId(uid1); 4484 uid2 = UserHandle.getAppId(uid2); 4485 // reader 4486 synchronized (mPackages) { 4487 Signature[] s1; 4488 Signature[] s2; 4489 Object obj = mSettings.getUserIdLPr(uid1); 4490 if (obj != null) { 4491 if (obj instanceof SharedUserSetting) { 4492 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4493 } else if (obj instanceof PackageSetting) { 4494 s1 = ((PackageSetting)obj).signatures.mSignatures; 4495 } else { 4496 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4497 } 4498 } else { 4499 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4500 } 4501 obj = mSettings.getUserIdLPr(uid2); 4502 if (obj != null) { 4503 if (obj instanceof SharedUserSetting) { 4504 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4505 } else if (obj instanceof PackageSetting) { 4506 s2 = ((PackageSetting)obj).signatures.mSignatures; 4507 } else { 4508 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4509 } 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 return compareSignatures(s1, s2); 4514 } 4515 } 4516 4517 /** 4518 * This method should typically only be used when granting or revoking 4519 * permissions, since the app may immediately restart after this call. 4520 * <p> 4521 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4522 * guard your work against the app being relaunched. 4523 */ 4524 private void killUid(int appId, int userId, String reason) { 4525 final long identity = Binder.clearCallingIdentity(); 4526 try { 4527 IActivityManager am = ActivityManagerNative.getDefault(); 4528 if (am != null) { 4529 try { 4530 am.killUid(appId, userId, reason); 4531 } catch (RemoteException e) { 4532 /* ignore - same process */ 4533 } 4534 } 4535 } finally { 4536 Binder.restoreCallingIdentity(identity); 4537 } 4538 } 4539 4540 /** 4541 * Compares two sets of signatures. Returns: 4542 * <br /> 4543 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4544 * <br /> 4545 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4546 * <br /> 4547 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4548 * <br /> 4549 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4550 * <br /> 4551 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4552 */ 4553 static int compareSignatures(Signature[] s1, Signature[] s2) { 4554 if (s1 == null) { 4555 return s2 == null 4556 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4557 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4558 } 4559 4560 if (s2 == null) { 4561 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4562 } 4563 4564 if (s1.length != s2.length) { 4565 return PackageManager.SIGNATURE_NO_MATCH; 4566 } 4567 4568 // Since both signature sets are of size 1, we can compare without HashSets. 4569 if (s1.length == 1) { 4570 return s1[0].equals(s2[0]) ? 4571 PackageManager.SIGNATURE_MATCH : 4572 PackageManager.SIGNATURE_NO_MATCH; 4573 } 4574 4575 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4576 for (Signature sig : s1) { 4577 set1.add(sig); 4578 } 4579 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4580 for (Signature sig : s2) { 4581 set2.add(sig); 4582 } 4583 // Make sure s2 contains all signatures in s1. 4584 if (set1.equals(set2)) { 4585 return PackageManager.SIGNATURE_MATCH; 4586 } 4587 return PackageManager.SIGNATURE_NO_MATCH; 4588 } 4589 4590 /** 4591 * If the database version for this type of package (internal storage or 4592 * external storage) is less than the version where package signatures 4593 * were updated, return true. 4594 */ 4595 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4596 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4597 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4598 } 4599 4600 /** 4601 * Used for backward compatibility to make sure any packages with 4602 * certificate chains get upgraded to the new style. {@code existingSigs} 4603 * will be in the old format (since they were stored on disk from before the 4604 * system upgrade) and {@code scannedSigs} will be in the newer format. 4605 */ 4606 private int compareSignaturesCompat(PackageSignatures existingSigs, 4607 PackageParser.Package scannedPkg) { 4608 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4609 return PackageManager.SIGNATURE_NO_MATCH; 4610 } 4611 4612 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4613 for (Signature sig : existingSigs.mSignatures) { 4614 existingSet.add(sig); 4615 } 4616 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4617 for (Signature sig : scannedPkg.mSignatures) { 4618 try { 4619 Signature[] chainSignatures = sig.getChainSignatures(); 4620 for (Signature chainSig : chainSignatures) { 4621 scannedCompatSet.add(chainSig); 4622 } 4623 } catch (CertificateEncodingException e) { 4624 scannedCompatSet.add(sig); 4625 } 4626 } 4627 /* 4628 * Make sure the expanded scanned set contains all signatures in the 4629 * existing one. 4630 */ 4631 if (scannedCompatSet.equals(existingSet)) { 4632 // Migrate the old signatures to the new scheme. 4633 existingSigs.assignSignatures(scannedPkg.mSignatures); 4634 // The new KeySets will be re-added later in the scanning process. 4635 synchronized (mPackages) { 4636 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4637 } 4638 return PackageManager.SIGNATURE_MATCH; 4639 } 4640 return PackageManager.SIGNATURE_NO_MATCH; 4641 } 4642 4643 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4644 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4645 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4646 } 4647 4648 private int compareSignaturesRecover(PackageSignatures existingSigs, 4649 PackageParser.Package scannedPkg) { 4650 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4651 return PackageManager.SIGNATURE_NO_MATCH; 4652 } 4653 4654 String msg = null; 4655 try { 4656 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4657 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4658 + scannedPkg.packageName); 4659 return PackageManager.SIGNATURE_MATCH; 4660 } 4661 } catch (CertificateException e) { 4662 msg = e.getMessage(); 4663 } 4664 4665 logCriticalInfo(Log.INFO, 4666 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4667 return PackageManager.SIGNATURE_NO_MATCH; 4668 } 4669 4670 @Override 4671 public List<String> getAllPackages() { 4672 synchronized (mPackages) { 4673 return new ArrayList<String>(mPackages.keySet()); 4674 } 4675 } 4676 4677 @Override 4678 public String[] getPackagesForUid(int uid) { 4679 uid = UserHandle.getAppId(uid); 4680 // reader 4681 synchronized (mPackages) { 4682 Object obj = mSettings.getUserIdLPr(uid); 4683 if (obj instanceof SharedUserSetting) { 4684 final SharedUserSetting sus = (SharedUserSetting) obj; 4685 final int N = sus.packages.size(); 4686 final String[] res = new String[N]; 4687 final Iterator<PackageSetting> it = sus.packages.iterator(); 4688 int i = 0; 4689 while (it.hasNext()) { 4690 res[i++] = it.next().name; 4691 } 4692 return res; 4693 } else if (obj instanceof PackageSetting) { 4694 final PackageSetting ps = (PackageSetting) obj; 4695 return new String[] { ps.name }; 4696 } 4697 } 4698 return null; 4699 } 4700 4701 @Override 4702 public String getNameForUid(int uid) { 4703 // reader 4704 synchronized (mPackages) { 4705 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4706 if (obj instanceof SharedUserSetting) { 4707 final SharedUserSetting sus = (SharedUserSetting) obj; 4708 return sus.name + ":" + sus.userId; 4709 } else if (obj instanceof PackageSetting) { 4710 final PackageSetting ps = (PackageSetting) obj; 4711 return ps.name; 4712 } 4713 } 4714 return null; 4715 } 4716 4717 @Override 4718 public int getUidForSharedUser(String sharedUserName) { 4719 if(sharedUserName == null) { 4720 return -1; 4721 } 4722 // reader 4723 synchronized (mPackages) { 4724 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4725 if (suid == null) { 4726 return -1; 4727 } 4728 return suid.userId; 4729 } 4730 } 4731 4732 @Override 4733 public int getFlagsForUid(int uid) { 4734 synchronized (mPackages) { 4735 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4736 if (obj instanceof SharedUserSetting) { 4737 final SharedUserSetting sus = (SharedUserSetting) obj; 4738 return sus.pkgFlags; 4739 } else if (obj instanceof PackageSetting) { 4740 final PackageSetting ps = (PackageSetting) obj; 4741 return ps.pkgFlags; 4742 } 4743 } 4744 return 0; 4745 } 4746 4747 @Override 4748 public int getPrivateFlagsForUid(int uid) { 4749 synchronized (mPackages) { 4750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4751 if (obj instanceof SharedUserSetting) { 4752 final SharedUserSetting sus = (SharedUserSetting) obj; 4753 return sus.pkgPrivateFlags; 4754 } else if (obj instanceof PackageSetting) { 4755 final PackageSetting ps = (PackageSetting) obj; 4756 return ps.pkgPrivateFlags; 4757 } 4758 } 4759 return 0; 4760 } 4761 4762 @Override 4763 public boolean isUidPrivileged(int uid) { 4764 uid = UserHandle.getAppId(uid); 4765 // reader 4766 synchronized (mPackages) { 4767 Object obj = mSettings.getUserIdLPr(uid); 4768 if (obj instanceof SharedUserSetting) { 4769 final SharedUserSetting sus = (SharedUserSetting) obj; 4770 final Iterator<PackageSetting> it = sus.packages.iterator(); 4771 while (it.hasNext()) { 4772 if (it.next().isPrivileged()) { 4773 return true; 4774 } 4775 } 4776 } else if (obj instanceof PackageSetting) { 4777 final PackageSetting ps = (PackageSetting) obj; 4778 return ps.isPrivileged(); 4779 } 4780 } 4781 return false; 4782 } 4783 4784 @Override 4785 public String[] getAppOpPermissionPackages(String permissionName) { 4786 synchronized (mPackages) { 4787 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4788 if (pkgs == null) { 4789 return null; 4790 } 4791 return pkgs.toArray(new String[pkgs.size()]); 4792 } 4793 } 4794 4795 @Override 4796 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4797 int flags, int userId) { 4798 try { 4799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4800 4801 if (!sUserManager.exists(userId)) return null; 4802 flags = updateFlagsForResolve(flags, userId, intent); 4803 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4804 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4805 4806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4807 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4808 flags, userId); 4809 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4810 4811 final ResolveInfo bestChoice = 4812 chooseBestActivity(intent, resolvedType, flags, query, userId); 4813 4814 if (isEphemeralAllowed(intent, query, userId)) { 4815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4816 final EphemeralResolveInfo ai = 4817 getEphemeralResolveInfo(intent, resolvedType, userId); 4818 if (ai != null) { 4819 if (DEBUG_EPHEMERAL) { 4820 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4821 } 4822 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4823 bestChoice.ephemeralResolveInfo = ai; 4824 } 4825 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4826 } 4827 return bestChoice; 4828 } finally { 4829 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4830 } 4831 } 4832 4833 @Override 4834 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4835 IntentFilter filter, int match, ComponentName activity) { 4836 final int userId = UserHandle.getCallingUserId(); 4837 if (DEBUG_PREFERRED) { 4838 Log.v(TAG, "setLastChosenActivity intent=" + intent 4839 + " resolvedType=" + resolvedType 4840 + " flags=" + flags 4841 + " filter=" + filter 4842 + " match=" + match 4843 + " activity=" + activity); 4844 filter.dump(new PrintStreamPrinter(System.out), " "); 4845 } 4846 intent.setComponent(null); 4847 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4848 userId); 4849 // Find any earlier preferred or last chosen entries and nuke them 4850 findPreferredActivity(intent, resolvedType, 4851 flags, query, 0, false, true, false, userId); 4852 // Add the new activity as the last chosen for this filter 4853 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4854 "Setting last chosen"); 4855 } 4856 4857 @Override 4858 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4859 final int userId = UserHandle.getCallingUserId(); 4860 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4861 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4862 userId); 4863 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4864 false, false, false, userId); 4865 } 4866 4867 4868 private boolean isEphemeralAllowed( 4869 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4870 // Short circuit and return early if possible. 4871 if (DISABLE_EPHEMERAL_APPS) { 4872 return false; 4873 } 4874 final int callingUser = UserHandle.getCallingUserId(); 4875 if (callingUser != UserHandle.USER_SYSTEM) { 4876 return false; 4877 } 4878 if (mEphemeralResolverConnection == null) { 4879 return false; 4880 } 4881 if (intent.getComponent() != null) { 4882 return false; 4883 } 4884 if (intent.getPackage() != null) { 4885 return false; 4886 } 4887 final boolean isWebUri = hasWebURI(intent); 4888 if (!isWebUri) { 4889 return false; 4890 } 4891 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4892 synchronized (mPackages) { 4893 final int count = resolvedActivites.size(); 4894 for (int n = 0; n < count; n++) { 4895 ResolveInfo info = resolvedActivites.get(n); 4896 String packageName = info.activityInfo.packageName; 4897 PackageSetting ps = mSettings.mPackages.get(packageName); 4898 if (ps != null) { 4899 // Try to get the status from User settings first 4900 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4901 int status = (int) (packedStatus >> 32); 4902 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4903 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4904 if (DEBUG_EPHEMERAL) { 4905 Slog.v(TAG, "DENY ephemeral apps;" 4906 + " pkg: " + packageName + ", status: " + status); 4907 } 4908 return false; 4909 } 4910 } 4911 } 4912 } 4913 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4914 return true; 4915 } 4916 4917 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4918 int userId) { 4919 MessageDigest digest = null; 4920 try { 4921 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4922 } catch (NoSuchAlgorithmException e) { 4923 // If we can't create a digest, ignore ephemeral apps. 4924 return null; 4925 } 4926 4927 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4928 final byte[] digestBytes = digest.digest(hostBytes); 4929 int shaPrefix = 4930 digestBytes[0] << 24 4931 | digestBytes[1] << 16 4932 | digestBytes[2] << 8 4933 | digestBytes[3] << 0; 4934 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4935 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4936 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4937 // No hash prefix match; there are no ephemeral apps for this domain. 4938 return null; 4939 } 4940 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4941 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4942 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4943 continue; 4944 } 4945 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4946 // No filters; this should never happen. 4947 if (filters.isEmpty()) { 4948 continue; 4949 } 4950 // We have a domain match; resolve the filters to see if anything matches. 4951 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4952 for (int j = filters.size() - 1; j >= 0; --j) { 4953 final EphemeralResolveIntentInfo intentInfo = 4954 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4955 ephemeralResolver.addFilter(intentInfo); 4956 } 4957 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4958 intent, resolvedType, false /*defaultOnly*/, userId); 4959 if (!matchedResolveInfoList.isEmpty()) { 4960 return matchedResolveInfoList.get(0); 4961 } 4962 } 4963 // Hash or filter mis-match; no ephemeral apps for this domain. 4964 return null; 4965 } 4966 4967 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4968 int flags, List<ResolveInfo> query, int userId) { 4969 if (query != null) { 4970 final int N = query.size(); 4971 if (N == 1) { 4972 return query.get(0); 4973 } else if (N > 1) { 4974 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4975 // If there is more than one activity with the same priority, 4976 // then let the user decide between them. 4977 ResolveInfo r0 = query.get(0); 4978 ResolveInfo r1 = query.get(1); 4979 if (DEBUG_INTENT_MATCHING || debug) { 4980 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4981 + r1.activityInfo.name + "=" + r1.priority); 4982 } 4983 // If the first activity has a higher priority, or a different 4984 // default, then it is always desirable to pick it. 4985 if (r0.priority != r1.priority 4986 || r0.preferredOrder != r1.preferredOrder 4987 || r0.isDefault != r1.isDefault) { 4988 return query.get(0); 4989 } 4990 // If we have saved a preference for a preferred activity for 4991 // this Intent, use that. 4992 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4993 flags, query, r0.priority, true, false, debug, userId); 4994 if (ri != null) { 4995 return ri; 4996 } 4997 ri = new ResolveInfo(mResolveInfo); 4998 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4999 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5000 ri.activityInfo.applicationInfo = new ApplicationInfo( 5001 ri.activityInfo.applicationInfo); 5002 if (userId != 0) { 5003 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5004 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5005 } 5006 // Make sure that the resolver is displayable in car mode 5007 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5008 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5009 return ri; 5010 } 5011 } 5012 return null; 5013 } 5014 5015 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5016 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5017 final int N = query.size(); 5018 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5019 .get(userId); 5020 // Get the list of persistent preferred activities that handle the intent 5021 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5022 List<PersistentPreferredActivity> pprefs = ppir != null 5023 ? ppir.queryIntent(intent, resolvedType, 5024 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5025 : null; 5026 if (pprefs != null && pprefs.size() > 0) { 5027 final int M = pprefs.size(); 5028 for (int i=0; i<M; i++) { 5029 final PersistentPreferredActivity ppa = pprefs.get(i); 5030 if (DEBUG_PREFERRED || debug) { 5031 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5032 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5033 + "\n component=" + ppa.mComponent); 5034 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5035 } 5036 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5037 flags | MATCH_DISABLED_COMPONENTS, userId); 5038 if (DEBUG_PREFERRED || debug) { 5039 Slog.v(TAG, "Found persistent preferred activity:"); 5040 if (ai != null) { 5041 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5042 } else { 5043 Slog.v(TAG, " null"); 5044 } 5045 } 5046 if (ai == null) { 5047 // This previously registered persistent preferred activity 5048 // component is no longer known. Ignore it and do NOT remove it. 5049 continue; 5050 } 5051 for (int j=0; j<N; j++) { 5052 final ResolveInfo ri = query.get(j); 5053 if (!ri.activityInfo.applicationInfo.packageName 5054 .equals(ai.applicationInfo.packageName)) { 5055 continue; 5056 } 5057 if (!ri.activityInfo.name.equals(ai.name)) { 5058 continue; 5059 } 5060 // Found a persistent preference that can handle the intent. 5061 if (DEBUG_PREFERRED || debug) { 5062 Slog.v(TAG, "Returning persistent preferred activity: " + 5063 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5064 } 5065 return ri; 5066 } 5067 } 5068 } 5069 return null; 5070 } 5071 5072 // TODO: handle preferred activities missing while user has amnesia 5073 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5074 List<ResolveInfo> query, int priority, boolean always, 5075 boolean removeMatches, boolean debug, int userId) { 5076 if (!sUserManager.exists(userId)) return null; 5077 flags = updateFlagsForResolve(flags, userId, intent); 5078 // writer 5079 synchronized (mPackages) { 5080 if (intent.getSelector() != null) { 5081 intent = intent.getSelector(); 5082 } 5083 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5084 5085 // Try to find a matching persistent preferred activity. 5086 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5087 debug, userId); 5088 5089 // If a persistent preferred activity matched, use it. 5090 if (pri != null) { 5091 return pri; 5092 } 5093 5094 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5095 // Get the list of preferred activities that handle the intent 5096 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5097 List<PreferredActivity> prefs = pir != null 5098 ? pir.queryIntent(intent, resolvedType, 5099 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5100 : null; 5101 if (prefs != null && prefs.size() > 0) { 5102 boolean changed = false; 5103 try { 5104 // First figure out how good the original match set is. 5105 // We will only allow preferred activities that came 5106 // from the same match quality. 5107 int match = 0; 5108 5109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5110 5111 final int N = query.size(); 5112 for (int j=0; j<N; j++) { 5113 final ResolveInfo ri = query.get(j); 5114 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5115 + ": 0x" + Integer.toHexString(match)); 5116 if (ri.match > match) { 5117 match = ri.match; 5118 } 5119 } 5120 5121 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5122 + Integer.toHexString(match)); 5123 5124 match &= IntentFilter.MATCH_CATEGORY_MASK; 5125 final int M = prefs.size(); 5126 for (int i=0; i<M; i++) { 5127 final PreferredActivity pa = prefs.get(i); 5128 if (DEBUG_PREFERRED || debug) { 5129 Slog.v(TAG, "Checking PreferredActivity ds=" 5130 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5131 + "\n component=" + pa.mPref.mComponent); 5132 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5133 } 5134 if (pa.mPref.mMatch != match) { 5135 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5136 + Integer.toHexString(pa.mPref.mMatch)); 5137 continue; 5138 } 5139 // If it's not an "always" type preferred activity and that's what we're 5140 // looking for, skip it. 5141 if (always && !pa.mPref.mAlways) { 5142 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5143 continue; 5144 } 5145 final ActivityInfo ai = getActivityInfo( 5146 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5147 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5148 userId); 5149 if (DEBUG_PREFERRED || debug) { 5150 Slog.v(TAG, "Found preferred activity:"); 5151 if (ai != null) { 5152 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5153 } else { 5154 Slog.v(TAG, " null"); 5155 } 5156 } 5157 if (ai == null) { 5158 // This previously registered preferred activity 5159 // component is no longer known. Most likely an update 5160 // to the app was installed and in the new version this 5161 // component no longer exists. Clean it up by removing 5162 // it from the preferred activities list, and skip it. 5163 Slog.w(TAG, "Removing dangling preferred activity: " 5164 + pa.mPref.mComponent); 5165 pir.removeFilter(pa); 5166 changed = true; 5167 continue; 5168 } 5169 for (int j=0; j<N; j++) { 5170 final ResolveInfo ri = query.get(j); 5171 if (!ri.activityInfo.applicationInfo.packageName 5172 .equals(ai.applicationInfo.packageName)) { 5173 continue; 5174 } 5175 if (!ri.activityInfo.name.equals(ai.name)) { 5176 continue; 5177 } 5178 5179 if (removeMatches) { 5180 pir.removeFilter(pa); 5181 changed = true; 5182 if (DEBUG_PREFERRED) { 5183 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5184 } 5185 break; 5186 } 5187 5188 // Okay we found a previously set preferred or last chosen app. 5189 // If the result set is different from when this 5190 // was created, we need to clear it and re-ask the 5191 // user their preference, if we're looking for an "always" type entry. 5192 if (always && !pa.mPref.sameSet(query)) { 5193 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5194 + intent + " type " + resolvedType); 5195 if (DEBUG_PREFERRED) { 5196 Slog.v(TAG, "Removing preferred activity since set changed " 5197 + pa.mPref.mComponent); 5198 } 5199 pir.removeFilter(pa); 5200 // Re-add the filter as a "last chosen" entry (!always) 5201 PreferredActivity lastChosen = new PreferredActivity( 5202 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5203 pir.addFilter(lastChosen); 5204 changed = true; 5205 return null; 5206 } 5207 5208 // Yay! Either the set matched or we're looking for the last chosen 5209 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5210 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5211 return ri; 5212 } 5213 } 5214 } finally { 5215 if (changed) { 5216 if (DEBUG_PREFERRED) { 5217 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5218 } 5219 scheduleWritePackageRestrictionsLocked(userId); 5220 } 5221 } 5222 } 5223 } 5224 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5225 return null; 5226 } 5227 5228 /* 5229 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5230 */ 5231 @Override 5232 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5233 int targetUserId) { 5234 mContext.enforceCallingOrSelfPermission( 5235 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5236 List<CrossProfileIntentFilter> matches = 5237 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5238 if (matches != null) { 5239 int size = matches.size(); 5240 for (int i = 0; i < size; i++) { 5241 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5242 } 5243 } 5244 if (hasWebURI(intent)) { 5245 // cross-profile app linking works only towards the parent. 5246 final UserInfo parent = getProfileParent(sourceUserId); 5247 synchronized(mPackages) { 5248 int flags = updateFlagsForResolve(0, parent.id, intent); 5249 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5250 intent, resolvedType, flags, sourceUserId, parent.id); 5251 return xpDomainInfo != null; 5252 } 5253 } 5254 return false; 5255 } 5256 5257 private UserInfo getProfileParent(int userId) { 5258 final long identity = Binder.clearCallingIdentity(); 5259 try { 5260 return sUserManager.getProfileParent(userId); 5261 } finally { 5262 Binder.restoreCallingIdentity(identity); 5263 } 5264 } 5265 5266 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5267 String resolvedType, int userId) { 5268 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5269 if (resolver != null) { 5270 return resolver.queryIntent(intent, resolvedType, false, userId); 5271 } 5272 return null; 5273 } 5274 5275 @Override 5276 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5277 String resolvedType, int flags, int userId) { 5278 try { 5279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5280 5281 return new ParceledListSlice<>( 5282 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5283 } finally { 5284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5285 } 5286 } 5287 5288 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5289 String resolvedType, int flags, int userId) { 5290 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5291 flags = updateFlagsForResolve(flags, userId, intent); 5292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5293 false /* requireFullPermission */, false /* checkShell */, 5294 "query intent activities"); 5295 ComponentName comp = intent.getComponent(); 5296 if (comp == null) { 5297 if (intent.getSelector() != null) { 5298 intent = intent.getSelector(); 5299 comp = intent.getComponent(); 5300 } 5301 } 5302 5303 if (comp != null) { 5304 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5305 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5306 if (ai != null) { 5307 final ResolveInfo ri = new ResolveInfo(); 5308 ri.activityInfo = ai; 5309 list.add(ri); 5310 } 5311 return list; 5312 } 5313 5314 // reader 5315 synchronized (mPackages) { 5316 final String pkgName = intent.getPackage(); 5317 if (pkgName == null) { 5318 List<CrossProfileIntentFilter> matchingFilters = 5319 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5320 // Check for results that need to skip the current profile. 5321 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5322 resolvedType, flags, userId); 5323 if (xpResolveInfo != null) { 5324 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5325 result.add(xpResolveInfo); 5326 return filterIfNotSystemUser(result, userId); 5327 } 5328 5329 // Check for results in the current profile. 5330 List<ResolveInfo> result = mActivities.queryIntent( 5331 intent, resolvedType, flags, userId); 5332 result = filterIfNotSystemUser(result, userId); 5333 5334 // Check for cross profile results. 5335 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5336 xpResolveInfo = queryCrossProfileIntents( 5337 matchingFilters, intent, resolvedType, flags, userId, 5338 hasNonNegativePriorityResult); 5339 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5340 boolean isVisibleToUser = filterIfNotSystemUser( 5341 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5342 if (isVisibleToUser) { 5343 result.add(xpResolveInfo); 5344 Collections.sort(result, mResolvePrioritySorter); 5345 } 5346 } 5347 if (hasWebURI(intent)) { 5348 CrossProfileDomainInfo xpDomainInfo = null; 5349 final UserInfo parent = getProfileParent(userId); 5350 if (parent != null) { 5351 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5352 flags, userId, parent.id); 5353 } 5354 if (xpDomainInfo != null) { 5355 if (xpResolveInfo != null) { 5356 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5357 // in the result. 5358 result.remove(xpResolveInfo); 5359 } 5360 if (result.size() == 0) { 5361 result.add(xpDomainInfo.resolveInfo); 5362 return result; 5363 } 5364 } else if (result.size() <= 1) { 5365 return result; 5366 } 5367 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5368 xpDomainInfo, userId); 5369 Collections.sort(result, mResolvePrioritySorter); 5370 } 5371 return result; 5372 } 5373 final PackageParser.Package pkg = mPackages.get(pkgName); 5374 if (pkg != null) { 5375 return filterIfNotSystemUser( 5376 mActivities.queryIntentForPackage( 5377 intent, resolvedType, flags, pkg.activities, userId), 5378 userId); 5379 } 5380 return new ArrayList<ResolveInfo>(); 5381 } 5382 } 5383 5384 private static class CrossProfileDomainInfo { 5385 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5386 ResolveInfo resolveInfo; 5387 /* Best domain verification status of the activities found in the other profile */ 5388 int bestDomainVerificationStatus; 5389 } 5390 5391 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5392 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5393 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5394 sourceUserId)) { 5395 return null; 5396 } 5397 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5398 resolvedType, flags, parentUserId); 5399 5400 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5401 return null; 5402 } 5403 CrossProfileDomainInfo result = null; 5404 int size = resultTargetUser.size(); 5405 for (int i = 0; i < size; i++) { 5406 ResolveInfo riTargetUser = resultTargetUser.get(i); 5407 // Intent filter verification is only for filters that specify a host. So don't return 5408 // those that handle all web uris. 5409 if (riTargetUser.handleAllWebDataURI) { 5410 continue; 5411 } 5412 String packageName = riTargetUser.activityInfo.packageName; 5413 PackageSetting ps = mSettings.mPackages.get(packageName); 5414 if (ps == null) { 5415 continue; 5416 } 5417 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5418 int status = (int)(verificationState >> 32); 5419 if (result == null) { 5420 result = new CrossProfileDomainInfo(); 5421 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5422 sourceUserId, parentUserId); 5423 result.bestDomainVerificationStatus = status; 5424 } else { 5425 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5426 result.bestDomainVerificationStatus); 5427 } 5428 } 5429 // Don't consider matches with status NEVER across profiles. 5430 if (result != null && result.bestDomainVerificationStatus 5431 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5432 return null; 5433 } 5434 return result; 5435 } 5436 5437 /** 5438 * Verification statuses are ordered from the worse to the best, except for 5439 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5440 */ 5441 private int bestDomainVerificationStatus(int status1, int status2) { 5442 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5443 return status2; 5444 } 5445 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5446 return status1; 5447 } 5448 return (int) MathUtils.max(status1, status2); 5449 } 5450 5451 private boolean isUserEnabled(int userId) { 5452 long callingId = Binder.clearCallingIdentity(); 5453 try { 5454 UserInfo userInfo = sUserManager.getUserInfo(userId); 5455 return userInfo != null && userInfo.isEnabled(); 5456 } finally { 5457 Binder.restoreCallingIdentity(callingId); 5458 } 5459 } 5460 5461 /** 5462 * Filter out activities with systemUserOnly flag set, when current user is not System. 5463 * 5464 * @return filtered list 5465 */ 5466 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5467 if (userId == UserHandle.USER_SYSTEM) { 5468 return resolveInfos; 5469 } 5470 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5471 ResolveInfo info = resolveInfos.get(i); 5472 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5473 resolveInfos.remove(i); 5474 } 5475 } 5476 return resolveInfos; 5477 } 5478 5479 /** 5480 * @param resolveInfos list of resolve infos in descending priority order 5481 * @return if the list contains a resolve info with non-negative priority 5482 */ 5483 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5484 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5485 } 5486 5487 private static boolean hasWebURI(Intent intent) { 5488 if (intent.getData() == null) { 5489 return false; 5490 } 5491 final String scheme = intent.getScheme(); 5492 if (TextUtils.isEmpty(scheme)) { 5493 return false; 5494 } 5495 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5496 } 5497 5498 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5499 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5500 int userId) { 5501 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5502 5503 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5504 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5505 candidates.size()); 5506 } 5507 5508 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5509 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5510 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5511 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5512 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5513 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5514 5515 synchronized (mPackages) { 5516 final int count = candidates.size(); 5517 // First, try to use linked apps. Partition the candidates into four lists: 5518 // one for the final results, one for the "do not use ever", one for "undefined status" 5519 // and finally one for "browser app type". 5520 for (int n=0; n<count; n++) { 5521 ResolveInfo info = candidates.get(n); 5522 String packageName = info.activityInfo.packageName; 5523 PackageSetting ps = mSettings.mPackages.get(packageName); 5524 if (ps != null) { 5525 // Add to the special match all list (Browser use case) 5526 if (info.handleAllWebDataURI) { 5527 matchAllList.add(info); 5528 continue; 5529 } 5530 // Try to get the status from User settings first 5531 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5532 int status = (int)(packedStatus >> 32); 5533 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5534 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5535 if (DEBUG_DOMAIN_VERIFICATION) { 5536 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5537 + " : linkgen=" + linkGeneration); 5538 } 5539 // Use link-enabled generation as preferredOrder, i.e. 5540 // prefer newly-enabled over earlier-enabled. 5541 info.preferredOrder = linkGeneration; 5542 alwaysList.add(info); 5543 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5544 if (DEBUG_DOMAIN_VERIFICATION) { 5545 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5546 } 5547 neverList.add(info); 5548 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5549 if (DEBUG_DOMAIN_VERIFICATION) { 5550 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5551 } 5552 alwaysAskList.add(info); 5553 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5554 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5555 if (DEBUG_DOMAIN_VERIFICATION) { 5556 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5557 } 5558 undefinedList.add(info); 5559 } 5560 } 5561 } 5562 5563 // We'll want to include browser possibilities in a few cases 5564 boolean includeBrowser = false; 5565 5566 // First try to add the "always" resolution(s) for the current user, if any 5567 if (alwaysList.size() > 0) { 5568 result.addAll(alwaysList); 5569 } else { 5570 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5571 result.addAll(undefinedList); 5572 // Maybe add one for the other profile. 5573 if (xpDomainInfo != null && ( 5574 xpDomainInfo.bestDomainVerificationStatus 5575 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5576 result.add(xpDomainInfo.resolveInfo); 5577 } 5578 includeBrowser = true; 5579 } 5580 5581 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5582 // If there were 'always' entries their preferred order has been set, so we also 5583 // back that off to make the alternatives equivalent 5584 if (alwaysAskList.size() > 0) { 5585 for (ResolveInfo i : result) { 5586 i.preferredOrder = 0; 5587 } 5588 result.addAll(alwaysAskList); 5589 includeBrowser = true; 5590 } 5591 5592 if (includeBrowser) { 5593 // Also add browsers (all of them or only the default one) 5594 if (DEBUG_DOMAIN_VERIFICATION) { 5595 Slog.v(TAG, " ...including browsers in candidate set"); 5596 } 5597 if ((matchFlags & MATCH_ALL) != 0) { 5598 result.addAll(matchAllList); 5599 } else { 5600 // Browser/generic handling case. If there's a default browser, go straight 5601 // to that (but only if there is no other higher-priority match). 5602 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5603 int maxMatchPrio = 0; 5604 ResolveInfo defaultBrowserMatch = null; 5605 final int numCandidates = matchAllList.size(); 5606 for (int n = 0; n < numCandidates; n++) { 5607 ResolveInfo info = matchAllList.get(n); 5608 // track the highest overall match priority... 5609 if (info.priority > maxMatchPrio) { 5610 maxMatchPrio = info.priority; 5611 } 5612 // ...and the highest-priority default browser match 5613 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5614 if (defaultBrowserMatch == null 5615 || (defaultBrowserMatch.priority < info.priority)) { 5616 if (debug) { 5617 Slog.v(TAG, "Considering default browser match " + info); 5618 } 5619 defaultBrowserMatch = info; 5620 } 5621 } 5622 } 5623 if (defaultBrowserMatch != null 5624 && defaultBrowserMatch.priority >= maxMatchPrio 5625 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5626 { 5627 if (debug) { 5628 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5629 } 5630 result.add(defaultBrowserMatch); 5631 } else { 5632 result.addAll(matchAllList); 5633 } 5634 } 5635 5636 // If there is nothing selected, add all candidates and remove the ones that the user 5637 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5638 if (result.size() == 0) { 5639 result.addAll(candidates); 5640 result.removeAll(neverList); 5641 } 5642 } 5643 } 5644 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5645 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5646 result.size()); 5647 for (ResolveInfo info : result) { 5648 Slog.v(TAG, " + " + info.activityInfo); 5649 } 5650 } 5651 return result; 5652 } 5653 5654 // Returns a packed value as a long: 5655 // 5656 // high 'int'-sized word: link status: undefined/ask/never/always. 5657 // low 'int'-sized word: relative priority among 'always' results. 5658 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5659 long result = ps.getDomainVerificationStatusForUser(userId); 5660 // if none available, get the master status 5661 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5662 if (ps.getIntentFilterVerificationInfo() != null) { 5663 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5664 } 5665 } 5666 return result; 5667 } 5668 5669 private ResolveInfo querySkipCurrentProfileIntents( 5670 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5671 int flags, int sourceUserId) { 5672 if (matchingFilters != null) { 5673 int size = matchingFilters.size(); 5674 for (int i = 0; i < size; i ++) { 5675 CrossProfileIntentFilter filter = matchingFilters.get(i); 5676 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5677 // Checking if there are activities in the target user that can handle the 5678 // intent. 5679 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5680 resolvedType, flags, sourceUserId); 5681 if (resolveInfo != null) { 5682 return resolveInfo; 5683 } 5684 } 5685 } 5686 } 5687 return null; 5688 } 5689 5690 // Return matching ResolveInfo in target user if any. 5691 private ResolveInfo queryCrossProfileIntents( 5692 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5693 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5694 if (matchingFilters != null) { 5695 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5696 // match the same intent. For performance reasons, it is better not to 5697 // run queryIntent twice for the same userId 5698 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5699 int size = matchingFilters.size(); 5700 for (int i = 0; i < size; i++) { 5701 CrossProfileIntentFilter filter = matchingFilters.get(i); 5702 int targetUserId = filter.getTargetUserId(); 5703 boolean skipCurrentProfile = 5704 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5705 boolean skipCurrentProfileIfNoMatchFound = 5706 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5707 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5708 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5709 // Checking if there are activities in the target user that can handle the 5710 // intent. 5711 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5712 resolvedType, flags, sourceUserId); 5713 if (resolveInfo != null) return resolveInfo; 5714 alreadyTriedUserIds.put(targetUserId, true); 5715 } 5716 } 5717 } 5718 return null; 5719 } 5720 5721 /** 5722 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5723 * will forward the intent to the filter's target user. 5724 * Otherwise, returns null. 5725 */ 5726 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5727 String resolvedType, int flags, int sourceUserId) { 5728 int targetUserId = filter.getTargetUserId(); 5729 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5730 resolvedType, flags, targetUserId); 5731 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5732 // If all the matches in the target profile are suspended, return null. 5733 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5734 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5735 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5736 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5737 targetUserId); 5738 } 5739 } 5740 } 5741 return null; 5742 } 5743 5744 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5745 int sourceUserId, int targetUserId) { 5746 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5747 long ident = Binder.clearCallingIdentity(); 5748 boolean targetIsProfile; 5749 try { 5750 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5751 } finally { 5752 Binder.restoreCallingIdentity(ident); 5753 } 5754 String className; 5755 if (targetIsProfile) { 5756 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5757 } else { 5758 className = FORWARD_INTENT_TO_PARENT; 5759 } 5760 ComponentName forwardingActivityComponentName = new ComponentName( 5761 mAndroidApplication.packageName, className); 5762 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5763 sourceUserId); 5764 if (!targetIsProfile) { 5765 forwardingActivityInfo.showUserIcon = targetUserId; 5766 forwardingResolveInfo.noResourceId = true; 5767 } 5768 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5769 forwardingResolveInfo.priority = 0; 5770 forwardingResolveInfo.preferredOrder = 0; 5771 forwardingResolveInfo.match = 0; 5772 forwardingResolveInfo.isDefault = true; 5773 forwardingResolveInfo.filter = filter; 5774 forwardingResolveInfo.targetUserId = targetUserId; 5775 return forwardingResolveInfo; 5776 } 5777 5778 @Override 5779 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5780 Intent[] specifics, String[] specificTypes, Intent intent, 5781 String resolvedType, int flags, int userId) { 5782 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5783 specificTypes, intent, resolvedType, flags, userId)); 5784 } 5785 5786 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5787 Intent[] specifics, String[] specificTypes, Intent intent, 5788 String resolvedType, int flags, int userId) { 5789 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5790 flags = updateFlagsForResolve(flags, userId, intent); 5791 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5792 false /* requireFullPermission */, false /* checkShell */, 5793 "query intent activity options"); 5794 final String resultsAction = intent.getAction(); 5795 5796 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5797 | PackageManager.GET_RESOLVED_FILTER, userId); 5798 5799 if (DEBUG_INTENT_MATCHING) { 5800 Log.v(TAG, "Query " + intent + ": " + results); 5801 } 5802 5803 int specificsPos = 0; 5804 int N; 5805 5806 // todo: note that the algorithm used here is O(N^2). This 5807 // isn't a problem in our current environment, but if we start running 5808 // into situations where we have more than 5 or 10 matches then this 5809 // should probably be changed to something smarter... 5810 5811 // First we go through and resolve each of the specific items 5812 // that were supplied, taking care of removing any corresponding 5813 // duplicate items in the generic resolve list. 5814 if (specifics != null) { 5815 for (int i=0; i<specifics.length; i++) { 5816 final Intent sintent = specifics[i]; 5817 if (sintent == null) { 5818 continue; 5819 } 5820 5821 if (DEBUG_INTENT_MATCHING) { 5822 Log.v(TAG, "Specific #" + i + ": " + sintent); 5823 } 5824 5825 String action = sintent.getAction(); 5826 if (resultsAction != null && resultsAction.equals(action)) { 5827 // If this action was explicitly requested, then don't 5828 // remove things that have it. 5829 action = null; 5830 } 5831 5832 ResolveInfo ri = null; 5833 ActivityInfo ai = null; 5834 5835 ComponentName comp = sintent.getComponent(); 5836 if (comp == null) { 5837 ri = resolveIntent( 5838 sintent, 5839 specificTypes != null ? specificTypes[i] : null, 5840 flags, userId); 5841 if (ri == null) { 5842 continue; 5843 } 5844 if (ri == mResolveInfo) { 5845 // ACK! Must do something better with this. 5846 } 5847 ai = ri.activityInfo; 5848 comp = new ComponentName(ai.applicationInfo.packageName, 5849 ai.name); 5850 } else { 5851 ai = getActivityInfo(comp, flags, userId); 5852 if (ai == null) { 5853 continue; 5854 } 5855 } 5856 5857 // Look for any generic query activities that are duplicates 5858 // of this specific one, and remove them from the results. 5859 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5860 N = results.size(); 5861 int j; 5862 for (j=specificsPos; j<N; j++) { 5863 ResolveInfo sri = results.get(j); 5864 if ((sri.activityInfo.name.equals(comp.getClassName()) 5865 && sri.activityInfo.applicationInfo.packageName.equals( 5866 comp.getPackageName())) 5867 || (action != null && sri.filter.matchAction(action))) { 5868 results.remove(j); 5869 if (DEBUG_INTENT_MATCHING) Log.v( 5870 TAG, "Removing duplicate item from " + j 5871 + " due to specific " + specificsPos); 5872 if (ri == null) { 5873 ri = sri; 5874 } 5875 j--; 5876 N--; 5877 } 5878 } 5879 5880 // Add this specific item to its proper place. 5881 if (ri == null) { 5882 ri = new ResolveInfo(); 5883 ri.activityInfo = ai; 5884 } 5885 results.add(specificsPos, ri); 5886 ri.specificIndex = i; 5887 specificsPos++; 5888 } 5889 } 5890 5891 // Now we go through the remaining generic results and remove any 5892 // duplicate actions that are found here. 5893 N = results.size(); 5894 for (int i=specificsPos; i<N-1; i++) { 5895 final ResolveInfo rii = results.get(i); 5896 if (rii.filter == null) { 5897 continue; 5898 } 5899 5900 // Iterate over all of the actions of this result's intent 5901 // filter... typically this should be just one. 5902 final Iterator<String> it = rii.filter.actionsIterator(); 5903 if (it == null) { 5904 continue; 5905 } 5906 while (it.hasNext()) { 5907 final String action = it.next(); 5908 if (resultsAction != null && resultsAction.equals(action)) { 5909 // If this action was explicitly requested, then don't 5910 // remove things that have it. 5911 continue; 5912 } 5913 for (int j=i+1; j<N; j++) { 5914 final ResolveInfo rij = results.get(j); 5915 if (rij.filter != null && rij.filter.hasAction(action)) { 5916 results.remove(j); 5917 if (DEBUG_INTENT_MATCHING) Log.v( 5918 TAG, "Removing duplicate item from " + j 5919 + " due to action " + action + " at " + i); 5920 j--; 5921 N--; 5922 } 5923 } 5924 } 5925 5926 // If the caller didn't request filter information, drop it now 5927 // so we don't have to marshall/unmarshall it. 5928 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5929 rii.filter = null; 5930 } 5931 } 5932 5933 // Filter out the caller activity if so requested. 5934 if (caller != null) { 5935 N = results.size(); 5936 for (int i=0; i<N; i++) { 5937 ActivityInfo ainfo = results.get(i).activityInfo; 5938 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5939 && caller.getClassName().equals(ainfo.name)) { 5940 results.remove(i); 5941 break; 5942 } 5943 } 5944 } 5945 5946 // If the caller didn't request filter information, 5947 // drop them now so we don't have to 5948 // marshall/unmarshall it. 5949 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5950 N = results.size(); 5951 for (int i=0; i<N; i++) { 5952 results.get(i).filter = null; 5953 } 5954 } 5955 5956 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5957 return results; 5958 } 5959 5960 @Override 5961 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5962 String resolvedType, int flags, int userId) { 5963 return new ParceledListSlice<>( 5964 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5965 } 5966 5967 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5968 String resolvedType, int flags, int userId) { 5969 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5970 flags = updateFlagsForResolve(flags, userId, intent); 5971 ComponentName comp = intent.getComponent(); 5972 if (comp == null) { 5973 if (intent.getSelector() != null) { 5974 intent = intent.getSelector(); 5975 comp = intent.getComponent(); 5976 } 5977 } 5978 if (comp != null) { 5979 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5980 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5981 if (ai != null) { 5982 ResolveInfo ri = new ResolveInfo(); 5983 ri.activityInfo = ai; 5984 list.add(ri); 5985 } 5986 return list; 5987 } 5988 5989 // reader 5990 synchronized (mPackages) { 5991 String pkgName = intent.getPackage(); 5992 if (pkgName == null) { 5993 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5994 } 5995 final PackageParser.Package pkg = mPackages.get(pkgName); 5996 if (pkg != null) { 5997 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5998 userId); 5999 } 6000 return Collections.emptyList(); 6001 } 6002 } 6003 6004 @Override 6005 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6006 if (!sUserManager.exists(userId)) return null; 6007 flags = updateFlagsForResolve(flags, userId, intent); 6008 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6009 if (query != null) { 6010 if (query.size() >= 1) { 6011 // If there is more than one service with the same priority, 6012 // just arbitrarily pick the first one. 6013 return query.get(0); 6014 } 6015 } 6016 return null; 6017 } 6018 6019 @Override 6020 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6021 String resolvedType, int flags, int userId) { 6022 return new ParceledListSlice<>( 6023 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6024 } 6025 6026 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6027 String resolvedType, int flags, int userId) { 6028 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6029 flags = updateFlagsForResolve(flags, userId, intent); 6030 ComponentName comp = intent.getComponent(); 6031 if (comp == null) { 6032 if (intent.getSelector() != null) { 6033 intent = intent.getSelector(); 6034 comp = intent.getComponent(); 6035 } 6036 } 6037 if (comp != null) { 6038 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6039 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6040 if (si != null) { 6041 final ResolveInfo ri = new ResolveInfo(); 6042 ri.serviceInfo = si; 6043 list.add(ri); 6044 } 6045 return list; 6046 } 6047 6048 // reader 6049 synchronized (mPackages) { 6050 String pkgName = intent.getPackage(); 6051 if (pkgName == null) { 6052 return mServices.queryIntent(intent, resolvedType, flags, userId); 6053 } 6054 final PackageParser.Package pkg = mPackages.get(pkgName); 6055 if (pkg != null) { 6056 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6057 userId); 6058 } 6059 return Collections.emptyList(); 6060 } 6061 } 6062 6063 @Override 6064 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6065 String resolvedType, int flags, int userId) { 6066 return new ParceledListSlice<>( 6067 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6068 } 6069 6070 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6071 Intent intent, String resolvedType, int flags, int userId) { 6072 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6073 flags = updateFlagsForResolve(flags, userId, intent); 6074 ComponentName comp = intent.getComponent(); 6075 if (comp == null) { 6076 if (intent.getSelector() != null) { 6077 intent = intent.getSelector(); 6078 comp = intent.getComponent(); 6079 } 6080 } 6081 if (comp != null) { 6082 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6083 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6084 if (pi != null) { 6085 final ResolveInfo ri = new ResolveInfo(); 6086 ri.providerInfo = pi; 6087 list.add(ri); 6088 } 6089 return list; 6090 } 6091 6092 // reader 6093 synchronized (mPackages) { 6094 String pkgName = intent.getPackage(); 6095 if (pkgName == null) { 6096 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6097 } 6098 final PackageParser.Package pkg = mPackages.get(pkgName); 6099 if (pkg != null) { 6100 return mProviders.queryIntentForPackage( 6101 intent, resolvedType, flags, pkg.providers, userId); 6102 } 6103 return Collections.emptyList(); 6104 } 6105 } 6106 6107 @Override 6108 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6109 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6110 flags = updateFlagsForPackage(flags, userId, null); 6111 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6112 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6113 true /* requireFullPermission */, false /* checkShell */, 6114 "get installed packages"); 6115 6116 // writer 6117 synchronized (mPackages) { 6118 ArrayList<PackageInfo> list; 6119 if (listUninstalled) { 6120 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6121 for (PackageSetting ps : mSettings.mPackages.values()) { 6122 final PackageInfo pi; 6123 if (ps.pkg != null) { 6124 pi = generatePackageInfo(ps, flags, userId); 6125 } else { 6126 pi = generatePackageInfo(ps, flags, userId); 6127 } 6128 if (pi != null) { 6129 list.add(pi); 6130 } 6131 } 6132 } else { 6133 list = new ArrayList<PackageInfo>(mPackages.size()); 6134 for (PackageParser.Package p : mPackages.values()) { 6135 final PackageInfo pi = 6136 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6137 if (pi != null) { 6138 list.add(pi); 6139 } 6140 } 6141 } 6142 6143 return new ParceledListSlice<PackageInfo>(list); 6144 } 6145 } 6146 6147 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6148 String[] permissions, boolean[] tmp, int flags, int userId) { 6149 int numMatch = 0; 6150 final PermissionsState permissionsState = ps.getPermissionsState(); 6151 for (int i=0; i<permissions.length; i++) { 6152 final String permission = permissions[i]; 6153 if (permissionsState.hasPermission(permission, userId)) { 6154 tmp[i] = true; 6155 numMatch++; 6156 } else { 6157 tmp[i] = false; 6158 } 6159 } 6160 if (numMatch == 0) { 6161 return; 6162 } 6163 final PackageInfo pi; 6164 if (ps.pkg != null) { 6165 pi = generatePackageInfo(ps, flags, userId); 6166 } else { 6167 pi = generatePackageInfo(ps, flags, userId); 6168 } 6169 // The above might return null in cases of uninstalled apps or install-state 6170 // skew across users/profiles. 6171 if (pi != null) { 6172 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6173 if (numMatch == permissions.length) { 6174 pi.requestedPermissions = permissions; 6175 } else { 6176 pi.requestedPermissions = new String[numMatch]; 6177 numMatch = 0; 6178 for (int i=0; i<permissions.length; i++) { 6179 if (tmp[i]) { 6180 pi.requestedPermissions[numMatch] = permissions[i]; 6181 numMatch++; 6182 } 6183 } 6184 } 6185 } 6186 list.add(pi); 6187 } 6188 } 6189 6190 @Override 6191 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6192 String[] permissions, int flags, int userId) { 6193 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6194 flags = updateFlagsForPackage(flags, userId, permissions); 6195 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6196 6197 // writer 6198 synchronized (mPackages) { 6199 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6200 boolean[] tmpBools = new boolean[permissions.length]; 6201 if (listUninstalled) { 6202 for (PackageSetting ps : mSettings.mPackages.values()) { 6203 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6204 } 6205 } else { 6206 for (PackageParser.Package pkg : mPackages.values()) { 6207 PackageSetting ps = (PackageSetting)pkg.mExtras; 6208 if (ps != null) { 6209 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6210 userId); 6211 } 6212 } 6213 } 6214 6215 return new ParceledListSlice<PackageInfo>(list); 6216 } 6217 } 6218 6219 @Override 6220 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6221 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6222 flags = updateFlagsForApplication(flags, userId, null); 6223 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6224 6225 // writer 6226 synchronized (mPackages) { 6227 ArrayList<ApplicationInfo> list; 6228 if (listUninstalled) { 6229 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6230 for (PackageSetting ps : mSettings.mPackages.values()) { 6231 ApplicationInfo ai; 6232 if (ps.pkg != null) { 6233 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6234 ps.readUserState(userId), userId); 6235 } else { 6236 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6237 } 6238 if (ai != null) { 6239 list.add(ai); 6240 } 6241 } 6242 } else { 6243 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6244 for (PackageParser.Package p : mPackages.values()) { 6245 if (p.mExtras != null) { 6246 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6247 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6248 if (ai != null) { 6249 list.add(ai); 6250 } 6251 } 6252 } 6253 } 6254 6255 return new ParceledListSlice<ApplicationInfo>(list); 6256 } 6257 } 6258 6259 @Override 6260 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6261 if (DISABLE_EPHEMERAL_APPS) { 6262 return null; 6263 } 6264 6265 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6266 "getEphemeralApplications"); 6267 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6268 true /* requireFullPermission */, false /* checkShell */, 6269 "getEphemeralApplications"); 6270 synchronized (mPackages) { 6271 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6272 .getEphemeralApplicationsLPw(userId); 6273 if (ephemeralApps != null) { 6274 return new ParceledListSlice<>(ephemeralApps); 6275 } 6276 } 6277 return null; 6278 } 6279 6280 @Override 6281 public boolean isEphemeralApplication(String packageName, int userId) { 6282 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6283 true /* requireFullPermission */, false /* checkShell */, 6284 "isEphemeral"); 6285 if (DISABLE_EPHEMERAL_APPS) { 6286 return false; 6287 } 6288 6289 if (!isCallerSameApp(packageName)) { 6290 return false; 6291 } 6292 synchronized (mPackages) { 6293 PackageParser.Package pkg = mPackages.get(packageName); 6294 if (pkg != null) { 6295 return pkg.applicationInfo.isEphemeralApp(); 6296 } 6297 } 6298 return false; 6299 } 6300 6301 @Override 6302 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6303 if (DISABLE_EPHEMERAL_APPS) { 6304 return null; 6305 } 6306 6307 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6308 true /* requireFullPermission */, false /* checkShell */, 6309 "getCookie"); 6310 if (!isCallerSameApp(packageName)) { 6311 return null; 6312 } 6313 synchronized (mPackages) { 6314 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6315 packageName, userId); 6316 } 6317 } 6318 6319 @Override 6320 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6321 if (DISABLE_EPHEMERAL_APPS) { 6322 return true; 6323 } 6324 6325 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6326 true /* requireFullPermission */, true /* checkShell */, 6327 "setCookie"); 6328 if (!isCallerSameApp(packageName)) { 6329 return false; 6330 } 6331 synchronized (mPackages) { 6332 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6333 packageName, cookie, userId); 6334 } 6335 } 6336 6337 @Override 6338 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6339 if (DISABLE_EPHEMERAL_APPS) { 6340 return null; 6341 } 6342 6343 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6344 "getEphemeralApplicationIcon"); 6345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6346 true /* requireFullPermission */, false /* checkShell */, 6347 "getEphemeralApplicationIcon"); 6348 synchronized (mPackages) { 6349 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6350 packageName, userId); 6351 } 6352 } 6353 6354 private boolean isCallerSameApp(String packageName) { 6355 PackageParser.Package pkg = mPackages.get(packageName); 6356 return pkg != null 6357 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6358 } 6359 6360 @Override 6361 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6362 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6363 } 6364 6365 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6366 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6367 6368 // reader 6369 synchronized (mPackages) { 6370 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6371 final int userId = UserHandle.getCallingUserId(); 6372 while (i.hasNext()) { 6373 final PackageParser.Package p = i.next(); 6374 if (p.applicationInfo == null) continue; 6375 6376 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6377 && !p.applicationInfo.isDirectBootAware(); 6378 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6379 && p.applicationInfo.isDirectBootAware(); 6380 6381 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6382 && (!mSafeMode || isSystemApp(p)) 6383 && (matchesUnaware || matchesAware)) { 6384 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6385 if (ps != null) { 6386 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6387 ps.readUserState(userId), userId); 6388 if (ai != null) { 6389 finalList.add(ai); 6390 } 6391 } 6392 } 6393 } 6394 } 6395 6396 return finalList; 6397 } 6398 6399 @Override 6400 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6401 if (!sUserManager.exists(userId)) return null; 6402 flags = updateFlagsForComponent(flags, userId, name); 6403 // reader 6404 synchronized (mPackages) { 6405 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6406 PackageSetting ps = provider != null 6407 ? mSettings.mPackages.get(provider.owner.packageName) 6408 : null; 6409 return ps != null 6410 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6411 ? PackageParser.generateProviderInfo(provider, flags, 6412 ps.readUserState(userId), userId) 6413 : null; 6414 } 6415 } 6416 6417 /** 6418 * @deprecated 6419 */ 6420 @Deprecated 6421 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6422 // reader 6423 synchronized (mPackages) { 6424 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6425 .entrySet().iterator(); 6426 final int userId = UserHandle.getCallingUserId(); 6427 while (i.hasNext()) { 6428 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6429 PackageParser.Provider p = entry.getValue(); 6430 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6431 6432 if (ps != null && p.syncable 6433 && (!mSafeMode || (p.info.applicationInfo.flags 6434 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6435 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6436 ps.readUserState(userId), userId); 6437 if (info != null) { 6438 outNames.add(entry.getKey()); 6439 outInfo.add(info); 6440 } 6441 } 6442 } 6443 } 6444 } 6445 6446 @Override 6447 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6448 int uid, int flags) { 6449 final int userId = processName != null ? UserHandle.getUserId(uid) 6450 : UserHandle.getCallingUserId(); 6451 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6452 flags = updateFlagsForComponent(flags, userId, processName); 6453 6454 ArrayList<ProviderInfo> finalList = null; 6455 // reader 6456 synchronized (mPackages) { 6457 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6458 while (i.hasNext()) { 6459 final PackageParser.Provider p = i.next(); 6460 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6461 if (ps != null && p.info.authority != null 6462 && (processName == null 6463 || (p.info.processName.equals(processName) 6464 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6465 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6466 if (finalList == null) { 6467 finalList = new ArrayList<ProviderInfo>(3); 6468 } 6469 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6470 ps.readUserState(userId), userId); 6471 if (info != null) { 6472 finalList.add(info); 6473 } 6474 } 6475 } 6476 } 6477 6478 if (finalList != null) { 6479 Collections.sort(finalList, mProviderInitOrderSorter); 6480 return new ParceledListSlice<ProviderInfo>(finalList); 6481 } 6482 6483 return ParceledListSlice.emptyList(); 6484 } 6485 6486 @Override 6487 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6488 // reader 6489 synchronized (mPackages) { 6490 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6491 return PackageParser.generateInstrumentationInfo(i, flags); 6492 } 6493 } 6494 6495 @Override 6496 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6497 String targetPackage, int flags) { 6498 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6499 } 6500 6501 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6502 int flags) { 6503 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6504 6505 // reader 6506 synchronized (mPackages) { 6507 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6508 while (i.hasNext()) { 6509 final PackageParser.Instrumentation p = i.next(); 6510 if (targetPackage == null 6511 || targetPackage.equals(p.info.targetPackage)) { 6512 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6513 flags); 6514 if (ii != null) { 6515 finalList.add(ii); 6516 } 6517 } 6518 } 6519 } 6520 6521 return finalList; 6522 } 6523 6524 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6525 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6526 if (overlays == null) { 6527 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6528 return; 6529 } 6530 for (PackageParser.Package opkg : overlays.values()) { 6531 // Not much to do if idmap fails: we already logged the error 6532 // and we certainly don't want to abort installation of pkg simply 6533 // because an overlay didn't fit properly. For these reasons, 6534 // ignore the return value of createIdmapForPackagePairLI. 6535 createIdmapForPackagePairLI(pkg, opkg); 6536 } 6537 } 6538 6539 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6540 PackageParser.Package opkg) { 6541 if (!opkg.mTrustedOverlay) { 6542 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6543 opkg.baseCodePath + ": overlay not trusted"); 6544 return false; 6545 } 6546 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6547 if (overlaySet == null) { 6548 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6549 opkg.baseCodePath + " but target package has no known overlays"); 6550 return false; 6551 } 6552 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6553 // TODO: generate idmap for split APKs 6554 try { 6555 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6556 } catch (InstallerException e) { 6557 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6558 + opkg.baseCodePath); 6559 return false; 6560 } 6561 PackageParser.Package[] overlayArray = 6562 overlaySet.values().toArray(new PackageParser.Package[0]); 6563 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6564 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6565 return p1.mOverlayPriority - p2.mOverlayPriority; 6566 } 6567 }; 6568 Arrays.sort(overlayArray, cmp); 6569 6570 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6571 int i = 0; 6572 for (PackageParser.Package p : overlayArray) { 6573 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6574 } 6575 return true; 6576 } 6577 6578 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6579 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6580 try { 6581 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6582 } finally { 6583 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6584 } 6585 } 6586 6587 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6588 final File[] files = dir.listFiles(); 6589 if (ArrayUtils.isEmpty(files)) { 6590 Log.d(TAG, "No files in app dir " + dir); 6591 return; 6592 } 6593 6594 if (DEBUG_PACKAGE_SCANNING) { 6595 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6596 + " flags=0x" + Integer.toHexString(parseFlags)); 6597 } 6598 6599 for (File file : files) { 6600 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6601 && !PackageInstallerService.isStageName(file.getName()); 6602 if (!isPackage) { 6603 // Ignore entries which are not packages 6604 continue; 6605 } 6606 try { 6607 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6608 scanFlags, currentTime, null); 6609 } catch (PackageManagerException e) { 6610 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6611 6612 // Delete invalid userdata apps 6613 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6614 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6615 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6616 removeCodePathLI(file); 6617 } 6618 } 6619 } 6620 } 6621 6622 private static File getSettingsProblemFile() { 6623 File dataDir = Environment.getDataDirectory(); 6624 File systemDir = new File(dataDir, "system"); 6625 File fname = new File(systemDir, "uiderrors.txt"); 6626 return fname; 6627 } 6628 6629 static void reportSettingsProblem(int priority, String msg) { 6630 logCriticalInfo(priority, msg); 6631 } 6632 6633 static void logCriticalInfo(int priority, String msg) { 6634 Slog.println(priority, TAG, msg); 6635 EventLogTags.writePmCriticalInfo(msg); 6636 try { 6637 File fname = getSettingsProblemFile(); 6638 FileOutputStream out = new FileOutputStream(fname, true); 6639 PrintWriter pw = new FastPrintWriter(out); 6640 SimpleDateFormat formatter = new SimpleDateFormat(); 6641 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6642 pw.println(dateString + ": " + msg); 6643 pw.close(); 6644 FileUtils.setPermissions( 6645 fname.toString(), 6646 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6647 -1, -1); 6648 } catch (java.io.IOException e) { 6649 } 6650 } 6651 6652 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6653 final int policyFlags) throws PackageManagerException { 6654 if (ps != null 6655 && ps.codePath.equals(srcFile) 6656 && ps.timeStamp == srcFile.lastModified() 6657 && !isCompatSignatureUpdateNeeded(pkg) 6658 && !isRecoverSignatureUpdateNeeded(pkg)) { 6659 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6660 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6661 ArraySet<PublicKey> signingKs; 6662 synchronized (mPackages) { 6663 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6664 } 6665 if (ps.signatures.mSignatures != null 6666 && ps.signatures.mSignatures.length != 0 6667 && signingKs != null) { 6668 // Optimization: reuse the existing cached certificates 6669 // if the package appears to be unchanged. 6670 pkg.mSignatures = ps.signatures.mSignatures; 6671 pkg.mSigningKeys = signingKs; 6672 return; 6673 } 6674 6675 Slog.w(TAG, "PackageSetting for " + ps.name 6676 + " is missing signatures. Collecting certs again to recover them."); 6677 } else { 6678 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6679 } 6680 6681 try { 6682 PackageParser.collectCertificates(pkg, policyFlags); 6683 } catch (PackageParserException e) { 6684 throw PackageManagerException.from(e); 6685 } 6686 } 6687 6688 /** 6689 * Traces a package scan. 6690 * @see #scanPackageLI(File, int, int, long, UserHandle) 6691 */ 6692 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6693 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6694 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6695 try { 6696 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6697 } finally { 6698 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6699 } 6700 } 6701 6702 /** 6703 * Scans a package and returns the newly parsed package. 6704 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6705 */ 6706 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6707 long currentTime, UserHandle user) throws PackageManagerException { 6708 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6709 PackageParser pp = new PackageParser(); 6710 pp.setSeparateProcesses(mSeparateProcesses); 6711 pp.setOnlyCoreApps(mOnlyCore); 6712 pp.setDisplayMetrics(mMetrics); 6713 6714 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6715 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6716 } 6717 6718 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6719 final PackageParser.Package pkg; 6720 try { 6721 pkg = pp.parsePackage(scanFile, parseFlags); 6722 } catch (PackageParserException e) { 6723 throw PackageManagerException.from(e); 6724 } finally { 6725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6726 } 6727 6728 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6729 } 6730 6731 /** 6732 * Scans a package and returns the newly parsed package. 6733 * @throws PackageManagerException on a parse error. 6734 */ 6735 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6736 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6737 throws PackageManagerException { 6738 // If the package has children and this is the first dive in the function 6739 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6740 // packages (parent and children) would be successfully scanned before the 6741 // actual scan since scanning mutates internal state and we want to atomically 6742 // install the package and its children. 6743 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6744 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6745 scanFlags |= SCAN_CHECK_ONLY; 6746 } 6747 } else { 6748 scanFlags &= ~SCAN_CHECK_ONLY; 6749 } 6750 6751 // Scan the parent 6752 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6753 scanFlags, currentTime, user); 6754 6755 // Scan the children 6756 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6757 for (int i = 0; i < childCount; i++) { 6758 PackageParser.Package childPackage = pkg.childPackages.get(i); 6759 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6760 currentTime, user); 6761 } 6762 6763 6764 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6765 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6766 } 6767 6768 return scannedPkg; 6769 } 6770 6771 /** 6772 * Scans a package and returns the newly parsed package. 6773 * @throws PackageManagerException on a parse error. 6774 */ 6775 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6776 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6777 throws PackageManagerException { 6778 PackageSetting ps = null; 6779 PackageSetting updatedPkg; 6780 // reader 6781 synchronized (mPackages) { 6782 // Look to see if we already know about this package. 6783 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6784 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6785 // This package has been renamed to its original name. Let's 6786 // use that. 6787 ps = mSettings.peekPackageLPr(oldName); 6788 } 6789 // If there was no original package, see one for the real package name. 6790 if (ps == null) { 6791 ps = mSettings.peekPackageLPr(pkg.packageName); 6792 } 6793 // Check to see if this package could be hiding/updating a system 6794 // package. Must look for it either under the original or real 6795 // package name depending on our state. 6796 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6797 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6798 6799 // If this is a package we don't know about on the system partition, we 6800 // may need to remove disabled child packages on the system partition 6801 // or may need to not add child packages if the parent apk is updated 6802 // on the data partition and no longer defines this child package. 6803 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6804 // If this is a parent package for an updated system app and this system 6805 // app got an OTA update which no longer defines some of the child packages 6806 // we have to prune them from the disabled system packages. 6807 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6808 if (disabledPs != null) { 6809 final int scannedChildCount = (pkg.childPackages != null) 6810 ? pkg.childPackages.size() : 0; 6811 final int disabledChildCount = disabledPs.childPackageNames != null 6812 ? disabledPs.childPackageNames.size() : 0; 6813 for (int i = 0; i < disabledChildCount; i++) { 6814 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6815 boolean disabledPackageAvailable = false; 6816 for (int j = 0; j < scannedChildCount; j++) { 6817 PackageParser.Package childPkg = pkg.childPackages.get(j); 6818 if (childPkg.packageName.equals(disabledChildPackageName)) { 6819 disabledPackageAvailable = true; 6820 break; 6821 } 6822 } 6823 if (!disabledPackageAvailable) { 6824 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6825 } 6826 } 6827 } 6828 } 6829 } 6830 6831 boolean updatedPkgBetter = false; 6832 // First check if this is a system package that may involve an update 6833 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6834 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6835 // it needs to drop FLAG_PRIVILEGED. 6836 if (locationIsPrivileged(scanFile)) { 6837 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6838 } else { 6839 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6840 } 6841 6842 if (ps != null && !ps.codePath.equals(scanFile)) { 6843 // The path has changed from what was last scanned... check the 6844 // version of the new path against what we have stored to determine 6845 // what to do. 6846 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6847 if (pkg.mVersionCode <= ps.versionCode) { 6848 // The system package has been updated and the code path does not match 6849 // Ignore entry. Skip it. 6850 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6851 + " ignored: updated version " + ps.versionCode 6852 + " better than this " + pkg.mVersionCode); 6853 if (!updatedPkg.codePath.equals(scanFile)) { 6854 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6855 + ps.name + " changing from " + updatedPkg.codePathString 6856 + " to " + scanFile); 6857 updatedPkg.codePath = scanFile; 6858 updatedPkg.codePathString = scanFile.toString(); 6859 updatedPkg.resourcePath = scanFile; 6860 updatedPkg.resourcePathString = scanFile.toString(); 6861 } 6862 updatedPkg.pkg = pkg; 6863 updatedPkg.versionCode = pkg.mVersionCode; 6864 6865 // Update the disabled system child packages to point to the package too. 6866 final int childCount = updatedPkg.childPackageNames != null 6867 ? updatedPkg.childPackageNames.size() : 0; 6868 for (int i = 0; i < childCount; i++) { 6869 String childPackageName = updatedPkg.childPackageNames.get(i); 6870 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6871 childPackageName); 6872 if (updatedChildPkg != null) { 6873 updatedChildPkg.pkg = pkg; 6874 updatedChildPkg.versionCode = pkg.mVersionCode; 6875 } 6876 } 6877 6878 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6879 + scanFile + " ignored: updated version " + ps.versionCode 6880 + " better than this " + pkg.mVersionCode); 6881 } else { 6882 // The current app on the system partition is better than 6883 // what we have updated to on the data partition; switch 6884 // back to the system partition version. 6885 // At this point, its safely assumed that package installation for 6886 // apps in system partition will go through. If not there won't be a working 6887 // version of the app 6888 // writer 6889 synchronized (mPackages) { 6890 // Just remove the loaded entries from package lists. 6891 mPackages.remove(ps.name); 6892 } 6893 6894 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6895 + " reverting from " + ps.codePathString 6896 + ": new version " + pkg.mVersionCode 6897 + " better than installed " + ps.versionCode); 6898 6899 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6900 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6901 synchronized (mInstallLock) { 6902 args.cleanUpResourcesLI(); 6903 } 6904 synchronized (mPackages) { 6905 mSettings.enableSystemPackageLPw(ps.name); 6906 } 6907 updatedPkgBetter = true; 6908 } 6909 } 6910 } 6911 6912 if (updatedPkg != null) { 6913 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6914 // initially 6915 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6916 6917 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6918 // flag set initially 6919 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6920 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6921 } 6922 } 6923 6924 // Verify certificates against what was last scanned 6925 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6926 6927 /* 6928 * A new system app appeared, but we already had a non-system one of the 6929 * same name installed earlier. 6930 */ 6931 boolean shouldHideSystemApp = false; 6932 if (updatedPkg == null && ps != null 6933 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6934 /* 6935 * Check to make sure the signatures match first. If they don't, 6936 * wipe the installed application and its data. 6937 */ 6938 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6939 != PackageManager.SIGNATURE_MATCH) { 6940 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6941 + " signatures don't match existing userdata copy; removing"); 6942 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6943 "scanPackageInternalLI")) { 6944 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6945 } 6946 ps = null; 6947 } else { 6948 /* 6949 * If the newly-added system app is an older version than the 6950 * already installed version, hide it. It will be scanned later 6951 * and re-added like an update. 6952 */ 6953 if (pkg.mVersionCode <= ps.versionCode) { 6954 shouldHideSystemApp = true; 6955 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6956 + " but new version " + pkg.mVersionCode + " better than installed " 6957 + ps.versionCode + "; hiding system"); 6958 } else { 6959 /* 6960 * The newly found system app is a newer version that the 6961 * one previously installed. Simply remove the 6962 * already-installed application and replace it with our own 6963 * while keeping the application data. 6964 */ 6965 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6966 + " reverting from " + ps.codePathString + ": new version " 6967 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6968 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6969 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6970 synchronized (mInstallLock) { 6971 args.cleanUpResourcesLI(); 6972 } 6973 } 6974 } 6975 } 6976 6977 // The apk is forward locked (not public) if its code and resources 6978 // are kept in different files. (except for app in either system or 6979 // vendor path). 6980 // TODO grab this value from PackageSettings 6981 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6982 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6983 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6984 } 6985 } 6986 6987 // TODO: extend to support forward-locked splits 6988 String resourcePath = null; 6989 String baseResourcePath = null; 6990 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6991 if (ps != null && ps.resourcePathString != null) { 6992 resourcePath = ps.resourcePathString; 6993 baseResourcePath = ps.resourcePathString; 6994 } else { 6995 // Should not happen at all. Just log an error. 6996 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6997 } 6998 } else { 6999 resourcePath = pkg.codePath; 7000 baseResourcePath = pkg.baseCodePath; 7001 } 7002 7003 // Set application objects path explicitly. 7004 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7005 pkg.setApplicationInfoCodePath(pkg.codePath); 7006 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7007 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7008 pkg.setApplicationInfoResourcePath(resourcePath); 7009 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7010 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7011 7012 // Note that we invoke the following method only if we are about to unpack an application 7013 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7014 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7015 7016 /* 7017 * If the system app should be overridden by a previously installed 7018 * data, hide the system app now and let the /data/app scan pick it up 7019 * again. 7020 */ 7021 if (shouldHideSystemApp) { 7022 synchronized (mPackages) { 7023 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7024 } 7025 } 7026 7027 return scannedPkg; 7028 } 7029 7030 private static String fixProcessName(String defProcessName, 7031 String processName, int uid) { 7032 if (processName == null) { 7033 return defProcessName; 7034 } 7035 return processName; 7036 } 7037 7038 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7039 throws PackageManagerException { 7040 if (pkgSetting.signatures.mSignatures != null) { 7041 // Already existing package. Make sure signatures match 7042 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7043 == PackageManager.SIGNATURE_MATCH; 7044 if (!match) { 7045 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7046 == PackageManager.SIGNATURE_MATCH; 7047 } 7048 if (!match) { 7049 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7050 == PackageManager.SIGNATURE_MATCH; 7051 } 7052 if (!match) { 7053 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7054 + pkg.packageName + " signatures do not match the " 7055 + "previously installed version; ignoring!"); 7056 } 7057 } 7058 7059 // Check for shared user signatures 7060 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7061 // Already existing package. Make sure signatures match 7062 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7063 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7064 if (!match) { 7065 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7066 == PackageManager.SIGNATURE_MATCH; 7067 } 7068 if (!match) { 7069 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7070 == PackageManager.SIGNATURE_MATCH; 7071 } 7072 if (!match) { 7073 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7074 "Package " + pkg.packageName 7075 + " has no signatures that match those in shared user " 7076 + pkgSetting.sharedUser.name + "; ignoring!"); 7077 } 7078 } 7079 } 7080 7081 /** 7082 * Enforces that only the system UID or root's UID can call a method exposed 7083 * via Binder. 7084 * 7085 * @param message used as message if SecurityException is thrown 7086 * @throws SecurityException if the caller is not system or root 7087 */ 7088 private static final void enforceSystemOrRoot(String message) { 7089 final int uid = Binder.getCallingUid(); 7090 if (uid != Process.SYSTEM_UID && uid != 0) { 7091 throw new SecurityException(message); 7092 } 7093 } 7094 7095 @Override 7096 public void performFstrimIfNeeded() { 7097 enforceSystemOrRoot("Only the system can request fstrim"); 7098 7099 // Before everything else, see whether we need to fstrim. 7100 try { 7101 IMountService ms = PackageHelper.getMountService(); 7102 if (ms != null) { 7103 final boolean isUpgrade = isUpgrade(); 7104 boolean doTrim = isUpgrade; 7105 if (doTrim) { 7106 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7107 } else { 7108 final long interval = android.provider.Settings.Global.getLong( 7109 mContext.getContentResolver(), 7110 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7111 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7112 if (interval > 0) { 7113 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7114 if (timeSinceLast > interval) { 7115 doTrim = true; 7116 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7117 + "; running immediately"); 7118 } 7119 } 7120 } 7121 if (doTrim) { 7122 if (!isFirstBoot()) { 7123 try { 7124 ActivityManagerNative.getDefault().showBootMessage( 7125 mContext.getResources().getString( 7126 R.string.android_upgrading_fstrim), true); 7127 } catch (RemoteException e) { 7128 } 7129 } 7130 ms.runMaintenance(); 7131 } 7132 } else { 7133 Slog.e(TAG, "Mount service unavailable!"); 7134 } 7135 } catch (RemoteException e) { 7136 // Can't happen; MountService is local 7137 } 7138 } 7139 7140 @Override 7141 public void updatePackagesIfNeeded() { 7142 enforceSystemOrRoot("Only the system can request package update"); 7143 7144 // We need to re-extract after an OTA. 7145 boolean causeUpgrade = isUpgrade(); 7146 7147 // First boot or factory reset. 7148 // Note: we also handle devices that are upgrading to N right now as if it is their 7149 // first boot, as they do not have profile data. 7150 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7151 7152 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7153 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7154 7155 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7156 return; 7157 } 7158 7159 List<PackageParser.Package> pkgs; 7160 synchronized (mPackages) { 7161 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7162 } 7163 7164 int curr = 0; 7165 int total = pkgs.size(); 7166 for (PackageParser.Package pkg : pkgs) { 7167 curr++; 7168 7169 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7170 if (DEBUG_DEXOPT) { 7171 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7172 } 7173 continue; 7174 } 7175 7176 if (DEBUG_DEXOPT) { 7177 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7178 } 7179 7180 if (!isFirstBoot()) { 7181 try { 7182 ActivityManagerNative.getDefault().showBootMessage( 7183 mContext.getResources().getString(R.string.android_upgrading_apk, 7184 curr, total), true); 7185 } catch (RemoteException e) { 7186 } 7187 } 7188 7189 performDexOpt(pkg.packageName, 7190 null /* instructionSet */, 7191 false /* checkProfiles */, 7192 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7193 false /* force */); 7194 } 7195 } 7196 7197 @Override 7198 public void notifyPackageUse(String packageName, int reason) { 7199 synchronized (mPackages) { 7200 PackageParser.Package p = mPackages.get(packageName); 7201 if (p == null) { 7202 return; 7203 } 7204 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7205 } 7206 } 7207 7208 // TODO: this is not used nor needed. Delete it. 7209 @Override 7210 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7211 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7212 getFullCompilerFilter(), false /* force */); 7213 } 7214 7215 @Override 7216 public boolean performDexOpt(String packageName, String instructionSet, 7217 boolean checkProfiles, int compileReason, boolean force) { 7218 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7219 getCompilerFilterForReason(compileReason), force); 7220 } 7221 7222 @Override 7223 public boolean performDexOptMode(String packageName, String instructionSet, 7224 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7225 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7226 targetCompilerFilter, force); 7227 } 7228 7229 private boolean performDexOptTraced(String packageName, String instructionSet, 7230 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7232 try { 7233 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7234 targetCompilerFilter, force); 7235 } finally { 7236 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7237 } 7238 } 7239 7240 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7241 // if the package can now be considered up to date for the given filter. 7242 private boolean performDexOptInternal(String packageName, String instructionSet, 7243 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7244 PackageParser.Package p; 7245 final String targetInstructionSet; 7246 synchronized (mPackages) { 7247 p = mPackages.get(packageName); 7248 if (p == null) { 7249 return false; 7250 } 7251 mPackageUsage.write(false); 7252 7253 targetInstructionSet = instructionSet != null ? instructionSet : 7254 getPrimaryInstructionSet(p.applicationInfo); 7255 } 7256 long callingId = Binder.clearCallingIdentity(); 7257 try { 7258 synchronized (mInstallLock) { 7259 final String[] instructionSets = new String[] { targetInstructionSet }; 7260 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7261 checkProfiles, targetCompilerFilter, force); 7262 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7263 } 7264 } finally { 7265 Binder.restoreCallingIdentity(callingId); 7266 } 7267 } 7268 7269 public ArraySet<String> getOptimizablePackages() { 7270 ArraySet<String> pkgs = new ArraySet<String>(); 7271 synchronized (mPackages) { 7272 for (PackageParser.Package p : mPackages.values()) { 7273 if (PackageDexOptimizer.canOptimizePackage(p)) { 7274 pkgs.add(p.packageName); 7275 } 7276 } 7277 } 7278 return pkgs; 7279 } 7280 7281 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7282 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7283 boolean force) { 7284 // Select the dex optimizer based on the force parameter. 7285 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7286 // allocate an object here. 7287 PackageDexOptimizer pdo = force 7288 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7289 : mPackageDexOptimizer; 7290 7291 // Optimize all dependencies first. Note: we ignore the return value and march on 7292 // on errors. 7293 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7294 if (!deps.isEmpty()) { 7295 for (PackageParser.Package depPackage : deps) { 7296 // TODO: Analyze and investigate if we (should) profile libraries. 7297 // Currently this will do a full compilation of the library by default. 7298 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7299 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7300 } 7301 } 7302 7303 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7304 } 7305 7306 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7307 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7308 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7309 Set<String> collectedNames = new HashSet<>(); 7310 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7311 7312 retValue.remove(p); 7313 7314 return retValue; 7315 } else { 7316 return Collections.emptyList(); 7317 } 7318 } 7319 7320 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7321 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7322 if (!collectedNames.contains(p.packageName)) { 7323 collectedNames.add(p.packageName); 7324 collected.add(p); 7325 7326 if (p.usesLibraries != null) { 7327 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7328 } 7329 if (p.usesOptionalLibraries != null) { 7330 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7331 collectedNames); 7332 } 7333 } 7334 } 7335 7336 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7337 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7338 for (String libName : libs) { 7339 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7340 if (libPkg != null) { 7341 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7342 } 7343 } 7344 } 7345 7346 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7347 synchronized (mPackages) { 7348 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7349 if (lib != null && lib.apk != null) { 7350 return mPackages.get(lib.apk); 7351 } 7352 } 7353 return null; 7354 } 7355 7356 public void shutdown() { 7357 mPackageUsage.write(true); 7358 } 7359 7360 @Override 7361 public void forceDexOpt(String packageName) { 7362 enforceSystemOrRoot("forceDexOpt"); 7363 7364 PackageParser.Package pkg; 7365 synchronized (mPackages) { 7366 pkg = mPackages.get(packageName); 7367 if (pkg == null) { 7368 throw new IllegalArgumentException("Unknown package: " + packageName); 7369 } 7370 } 7371 7372 synchronized (mInstallLock) { 7373 final String[] instructionSets = new String[] { 7374 getPrimaryInstructionSet(pkg.applicationInfo) }; 7375 7376 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7377 7378 // Whoever is calling forceDexOpt wants a fully compiled package. 7379 // Don't use profiles since that may cause compilation to be skipped. 7380 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7381 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7382 true /* force */); 7383 7384 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7385 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7386 throw new IllegalStateException("Failed to dexopt: " + res); 7387 } 7388 } 7389 } 7390 7391 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7392 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7393 Slog.w(TAG, "Unable to update from " + oldPkg.name 7394 + " to " + newPkg.packageName 7395 + ": old package not in system partition"); 7396 return false; 7397 } else if (mPackages.get(oldPkg.name) != null) { 7398 Slog.w(TAG, "Unable to update from " + oldPkg.name 7399 + " to " + newPkg.packageName 7400 + ": old package still exists"); 7401 return false; 7402 } 7403 return true; 7404 } 7405 7406 void removeCodePathLI(File codePath) { 7407 if (codePath.isDirectory()) { 7408 try { 7409 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7410 } catch (InstallerException e) { 7411 Slog.w(TAG, "Failed to remove code path", e); 7412 } 7413 } else { 7414 codePath.delete(); 7415 } 7416 } 7417 7418 private int[] resolveUserIds(int userId) { 7419 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7420 } 7421 7422 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7423 if (pkg == null) { 7424 Slog.wtf(TAG, "Package was null!", new Throwable()); 7425 return; 7426 } 7427 clearAppDataLeafLIF(pkg, userId, flags); 7428 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7429 for (int i = 0; i < childCount; i++) { 7430 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7431 } 7432 } 7433 7434 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7435 final PackageSetting ps; 7436 synchronized (mPackages) { 7437 ps = mSettings.mPackages.get(pkg.packageName); 7438 } 7439 for (int realUserId : resolveUserIds(userId)) { 7440 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7441 try { 7442 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7443 ceDataInode); 7444 } catch (InstallerException e) { 7445 Slog.w(TAG, String.valueOf(e)); 7446 } 7447 } 7448 } 7449 7450 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7451 if (pkg == null) { 7452 Slog.wtf(TAG, "Package was null!", new Throwable()); 7453 return; 7454 } 7455 destroyAppDataLeafLIF(pkg, userId, flags); 7456 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7457 for (int i = 0; i < childCount; i++) { 7458 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7459 } 7460 } 7461 7462 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7463 final PackageSetting ps; 7464 synchronized (mPackages) { 7465 ps = mSettings.mPackages.get(pkg.packageName); 7466 } 7467 for (int realUserId : resolveUserIds(userId)) { 7468 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7469 try { 7470 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7471 ceDataInode); 7472 } catch (InstallerException e) { 7473 Slog.w(TAG, String.valueOf(e)); 7474 } 7475 } 7476 } 7477 7478 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7479 if (pkg == null) { 7480 Slog.wtf(TAG, "Package was null!", new Throwable()); 7481 return; 7482 } 7483 destroyAppProfilesLeafLIF(pkg); 7484 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7485 for (int i = 0; i < childCount; i++) { 7486 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7487 } 7488 } 7489 7490 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7491 try { 7492 mInstaller.destroyAppProfiles(pkg.packageName); 7493 } catch (InstallerException e) { 7494 Slog.w(TAG, String.valueOf(e)); 7495 } 7496 } 7497 7498 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7499 if (pkg == null) { 7500 Slog.wtf(TAG, "Package was null!", new Throwable()); 7501 return; 7502 } 7503 clearAppProfilesLeafLIF(pkg); 7504 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7505 for (int i = 0; i < childCount; i++) { 7506 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7507 } 7508 } 7509 7510 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7511 try { 7512 mInstaller.clearAppProfiles(pkg.packageName); 7513 } catch (InstallerException e) { 7514 Slog.w(TAG, String.valueOf(e)); 7515 } 7516 } 7517 7518 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7519 long lastUpdateTime) { 7520 // Set parent install/update time 7521 PackageSetting ps = (PackageSetting) pkg.mExtras; 7522 if (ps != null) { 7523 ps.firstInstallTime = firstInstallTime; 7524 ps.lastUpdateTime = lastUpdateTime; 7525 } 7526 // Set children install/update time 7527 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7528 for (int i = 0; i < childCount; i++) { 7529 PackageParser.Package childPkg = pkg.childPackages.get(i); 7530 ps = (PackageSetting) childPkg.mExtras; 7531 if (ps != null) { 7532 ps.firstInstallTime = firstInstallTime; 7533 ps.lastUpdateTime = lastUpdateTime; 7534 } 7535 } 7536 } 7537 7538 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7539 PackageParser.Package changingLib) { 7540 if (file.path != null) { 7541 usesLibraryFiles.add(file.path); 7542 return; 7543 } 7544 PackageParser.Package p = mPackages.get(file.apk); 7545 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7546 // If we are doing this while in the middle of updating a library apk, 7547 // then we need to make sure to use that new apk for determining the 7548 // dependencies here. (We haven't yet finished committing the new apk 7549 // to the package manager state.) 7550 if (p == null || p.packageName.equals(changingLib.packageName)) { 7551 p = changingLib; 7552 } 7553 } 7554 if (p != null) { 7555 usesLibraryFiles.addAll(p.getAllCodePaths()); 7556 } 7557 } 7558 7559 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7560 PackageParser.Package changingLib) throws PackageManagerException { 7561 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7562 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7563 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7564 for (int i=0; i<N; i++) { 7565 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7566 if (file == null) { 7567 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7568 "Package " + pkg.packageName + " requires unavailable shared library " 7569 + pkg.usesLibraries.get(i) + "; failing!"); 7570 } 7571 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7572 } 7573 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7574 for (int i=0; i<N; i++) { 7575 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7576 if (file == null) { 7577 Slog.w(TAG, "Package " + pkg.packageName 7578 + " desires unavailable shared library " 7579 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7580 } else { 7581 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7582 } 7583 } 7584 N = usesLibraryFiles.size(); 7585 if (N > 0) { 7586 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7587 } else { 7588 pkg.usesLibraryFiles = null; 7589 } 7590 } 7591 } 7592 7593 private static boolean hasString(List<String> list, List<String> which) { 7594 if (list == null) { 7595 return false; 7596 } 7597 for (int i=list.size()-1; i>=0; i--) { 7598 for (int j=which.size()-1; j>=0; j--) { 7599 if (which.get(j).equals(list.get(i))) { 7600 return true; 7601 } 7602 } 7603 } 7604 return false; 7605 } 7606 7607 private void updateAllSharedLibrariesLPw() { 7608 for (PackageParser.Package pkg : mPackages.values()) { 7609 try { 7610 updateSharedLibrariesLPw(pkg, null); 7611 } catch (PackageManagerException e) { 7612 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7613 } 7614 } 7615 } 7616 7617 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7618 PackageParser.Package changingPkg) { 7619 ArrayList<PackageParser.Package> res = null; 7620 for (PackageParser.Package pkg : mPackages.values()) { 7621 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7622 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7623 if (res == null) { 7624 res = new ArrayList<PackageParser.Package>(); 7625 } 7626 res.add(pkg); 7627 try { 7628 updateSharedLibrariesLPw(pkg, changingPkg); 7629 } catch (PackageManagerException e) { 7630 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7631 } 7632 } 7633 } 7634 return res; 7635 } 7636 7637 /** 7638 * Derive the value of the {@code cpuAbiOverride} based on the provided 7639 * value and an optional stored value from the package settings. 7640 */ 7641 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7642 String cpuAbiOverride = null; 7643 7644 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7645 cpuAbiOverride = null; 7646 } else if (abiOverride != null) { 7647 cpuAbiOverride = abiOverride; 7648 } else if (settings != null) { 7649 cpuAbiOverride = settings.cpuAbiOverrideString; 7650 } 7651 7652 return cpuAbiOverride; 7653 } 7654 7655 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7656 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7657 throws PackageManagerException { 7658 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7659 // If the package has children and this is the first dive in the function 7660 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7661 // whether all packages (parent and children) would be successfully scanned 7662 // before the actual scan since scanning mutates internal state and we want 7663 // to atomically install the package and its children. 7664 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7665 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7666 scanFlags |= SCAN_CHECK_ONLY; 7667 } 7668 } else { 7669 scanFlags &= ~SCAN_CHECK_ONLY; 7670 } 7671 7672 final PackageParser.Package scannedPkg; 7673 try { 7674 // Scan the parent 7675 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7676 // Scan the children 7677 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7678 for (int i = 0; i < childCount; i++) { 7679 PackageParser.Package childPkg = pkg.childPackages.get(i); 7680 scanPackageLI(childPkg, policyFlags, 7681 scanFlags, currentTime, user); 7682 } 7683 } finally { 7684 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7685 } 7686 7687 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7688 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7689 } 7690 7691 return scannedPkg; 7692 } 7693 7694 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7695 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7696 boolean success = false; 7697 try { 7698 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7699 currentTime, user); 7700 success = true; 7701 return res; 7702 } finally { 7703 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7704 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7705 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7706 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7707 destroyAppProfilesLIF(pkg); 7708 } 7709 } 7710 } 7711 7712 /** 7713 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7714 */ 7715 private static boolean apkHasCode(String fileName) { 7716 StrictJarFile jarFile = null; 7717 try { 7718 jarFile = new StrictJarFile(fileName, 7719 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7720 return jarFile.findEntry("classes.dex") != null; 7721 } catch (IOException ignore) { 7722 } finally { 7723 try { 7724 jarFile.close(); 7725 } catch (IOException ignore) {} 7726 } 7727 return false; 7728 } 7729 7730 /** 7731 * Enforces code policy for the package. This ensures that if an APK has 7732 * declared hasCode="true" in its manifest that the APK actually contains 7733 * code. 7734 * 7735 * @throws PackageManagerException If bytecode could not be found when it should exist 7736 */ 7737 private static void enforceCodePolicy(PackageParser.Package pkg) 7738 throws PackageManagerException { 7739 final boolean shouldHaveCode = 7740 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7741 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7742 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7743 "Package " + pkg.baseCodePath + " code is missing"); 7744 } 7745 7746 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7747 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7748 final boolean splitShouldHaveCode = 7749 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7750 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7751 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7752 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7753 } 7754 } 7755 } 7756 } 7757 7758 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7759 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7760 throws PackageManagerException { 7761 final File scanFile = new File(pkg.codePath); 7762 if (pkg.applicationInfo.getCodePath() == null || 7763 pkg.applicationInfo.getResourcePath() == null) { 7764 // Bail out. The resource and code paths haven't been set. 7765 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7766 "Code and resource paths haven't been set correctly"); 7767 } 7768 7769 // Apply policy 7770 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7771 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7772 if (pkg.applicationInfo.isDirectBootAware()) { 7773 // we're direct boot aware; set for all components 7774 for (PackageParser.Service s : pkg.services) { 7775 s.info.encryptionAware = s.info.directBootAware = true; 7776 } 7777 for (PackageParser.Provider p : pkg.providers) { 7778 p.info.encryptionAware = p.info.directBootAware = true; 7779 } 7780 for (PackageParser.Activity a : pkg.activities) { 7781 a.info.encryptionAware = a.info.directBootAware = true; 7782 } 7783 for (PackageParser.Activity r : pkg.receivers) { 7784 r.info.encryptionAware = r.info.directBootAware = true; 7785 } 7786 } 7787 } else { 7788 // Only allow system apps to be flagged as core apps. 7789 pkg.coreApp = false; 7790 // clear flags not applicable to regular apps 7791 pkg.applicationInfo.privateFlags &= 7792 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7793 pkg.applicationInfo.privateFlags &= 7794 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7795 } 7796 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7797 7798 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7799 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7800 } 7801 7802 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7803 enforceCodePolicy(pkg); 7804 } 7805 7806 if (mCustomResolverComponentName != null && 7807 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7808 setUpCustomResolverActivity(pkg); 7809 } 7810 7811 if (pkg.packageName.equals("android")) { 7812 synchronized (mPackages) { 7813 if (mAndroidApplication != null) { 7814 Slog.w(TAG, "*************************************************"); 7815 Slog.w(TAG, "Core android package being redefined. Skipping."); 7816 Slog.w(TAG, " file=" + scanFile); 7817 Slog.w(TAG, "*************************************************"); 7818 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7819 "Core android package being redefined. Skipping."); 7820 } 7821 7822 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7823 // Set up information for our fall-back user intent resolution activity. 7824 mPlatformPackage = pkg; 7825 pkg.mVersionCode = mSdkVersion; 7826 mAndroidApplication = pkg.applicationInfo; 7827 7828 if (!mResolverReplaced) { 7829 mResolveActivity.applicationInfo = mAndroidApplication; 7830 mResolveActivity.name = ResolverActivity.class.getName(); 7831 mResolveActivity.packageName = mAndroidApplication.packageName; 7832 mResolveActivity.processName = "system:ui"; 7833 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7834 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7835 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7836 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7837 mResolveActivity.exported = true; 7838 mResolveActivity.enabled = true; 7839 mResolveInfo.activityInfo = mResolveActivity; 7840 mResolveInfo.priority = 0; 7841 mResolveInfo.preferredOrder = 0; 7842 mResolveInfo.match = 0; 7843 mResolveComponentName = new ComponentName( 7844 mAndroidApplication.packageName, mResolveActivity.name); 7845 } 7846 } 7847 } 7848 } 7849 7850 if (DEBUG_PACKAGE_SCANNING) { 7851 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7852 Log.d(TAG, "Scanning package " + pkg.packageName); 7853 } 7854 7855 synchronized (mPackages) { 7856 if (mPackages.containsKey(pkg.packageName) 7857 || mSharedLibraries.containsKey(pkg.packageName)) { 7858 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7859 "Application package " + pkg.packageName 7860 + " already installed. Skipping duplicate."); 7861 } 7862 7863 // If we're only installing presumed-existing packages, require that the 7864 // scanned APK is both already known and at the path previously established 7865 // for it. Previously unknown packages we pick up normally, but if we have an 7866 // a priori expectation about this package's install presence, enforce it. 7867 // With a singular exception for new system packages. When an OTA contains 7868 // a new system package, we allow the codepath to change from a system location 7869 // to the user-installed location. If we don't allow this change, any newer, 7870 // user-installed version of the application will be ignored. 7871 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7872 if (mExpectingBetter.containsKey(pkg.packageName)) { 7873 logCriticalInfo(Log.WARN, 7874 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7875 } else { 7876 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7877 if (known != null) { 7878 if (DEBUG_PACKAGE_SCANNING) { 7879 Log.d(TAG, "Examining " + pkg.codePath 7880 + " and requiring known paths " + known.codePathString 7881 + " & " + known.resourcePathString); 7882 } 7883 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7884 || !pkg.applicationInfo.getResourcePath().equals( 7885 known.resourcePathString)) { 7886 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7887 "Application package " + pkg.packageName 7888 + " found at " + pkg.applicationInfo.getCodePath() 7889 + " but expected at " + known.codePathString 7890 + "; ignoring."); 7891 } 7892 } 7893 } 7894 } 7895 } 7896 7897 // Initialize package source and resource directories 7898 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7899 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7900 7901 SharedUserSetting suid = null; 7902 PackageSetting pkgSetting = null; 7903 7904 if (!isSystemApp(pkg)) { 7905 // Only system apps can use these features. 7906 pkg.mOriginalPackages = null; 7907 pkg.mRealPackage = null; 7908 pkg.mAdoptPermissions = null; 7909 } 7910 7911 // Getting the package setting may have a side-effect, so if we 7912 // are only checking if scan would succeed, stash a copy of the 7913 // old setting to restore at the end. 7914 PackageSetting nonMutatedPs = null; 7915 7916 // writer 7917 synchronized (mPackages) { 7918 if (pkg.mSharedUserId != null) { 7919 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7920 if (suid == null) { 7921 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7922 "Creating application package " + pkg.packageName 7923 + " for shared user failed"); 7924 } 7925 if (DEBUG_PACKAGE_SCANNING) { 7926 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7927 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7928 + "): packages=" + suid.packages); 7929 } 7930 } 7931 7932 // Check if we are renaming from an original package name. 7933 PackageSetting origPackage = null; 7934 String realName = null; 7935 if (pkg.mOriginalPackages != null) { 7936 // This package may need to be renamed to a previously 7937 // installed name. Let's check on that... 7938 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7939 if (pkg.mOriginalPackages.contains(renamed)) { 7940 // This package had originally been installed as the 7941 // original name, and we have already taken care of 7942 // transitioning to the new one. Just update the new 7943 // one to continue using the old name. 7944 realName = pkg.mRealPackage; 7945 if (!pkg.packageName.equals(renamed)) { 7946 // Callers into this function may have already taken 7947 // care of renaming the package; only do it here if 7948 // it is not already done. 7949 pkg.setPackageName(renamed); 7950 } 7951 7952 } else { 7953 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7954 if ((origPackage = mSettings.peekPackageLPr( 7955 pkg.mOriginalPackages.get(i))) != null) { 7956 // We do have the package already installed under its 7957 // original name... should we use it? 7958 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7959 // New package is not compatible with original. 7960 origPackage = null; 7961 continue; 7962 } else if (origPackage.sharedUser != null) { 7963 // Make sure uid is compatible between packages. 7964 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7965 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7966 + " to " + pkg.packageName + ": old uid " 7967 + origPackage.sharedUser.name 7968 + " differs from " + pkg.mSharedUserId); 7969 origPackage = null; 7970 continue; 7971 } 7972 // TODO: Add case when shared user id is added [b/28144775] 7973 } else { 7974 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7975 + pkg.packageName + " to old name " + origPackage.name); 7976 } 7977 break; 7978 } 7979 } 7980 } 7981 } 7982 7983 if (mTransferedPackages.contains(pkg.packageName)) { 7984 Slog.w(TAG, "Package " + pkg.packageName 7985 + " was transferred to another, but its .apk remains"); 7986 } 7987 7988 // See comments in nonMutatedPs declaration 7989 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7990 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7991 if (foundPs != null) { 7992 nonMutatedPs = new PackageSetting(foundPs); 7993 } 7994 } 7995 7996 // Just create the setting, don't add it yet. For already existing packages 7997 // the PkgSetting exists already and doesn't have to be created. 7998 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7999 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8000 pkg.applicationInfo.primaryCpuAbi, 8001 pkg.applicationInfo.secondaryCpuAbi, 8002 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8003 user, false); 8004 if (pkgSetting == null) { 8005 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8006 "Creating application package " + pkg.packageName + " failed"); 8007 } 8008 8009 if (pkgSetting.origPackage != null) { 8010 // If we are first transitioning from an original package, 8011 // fix up the new package's name now. We need to do this after 8012 // looking up the package under its new name, so getPackageLP 8013 // can take care of fiddling things correctly. 8014 pkg.setPackageName(origPackage.name); 8015 8016 // File a report about this. 8017 String msg = "New package " + pkgSetting.realName 8018 + " renamed to replace old package " + pkgSetting.name; 8019 reportSettingsProblem(Log.WARN, msg); 8020 8021 // Make a note of it. 8022 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8023 mTransferedPackages.add(origPackage.name); 8024 } 8025 8026 // No longer need to retain this. 8027 pkgSetting.origPackage = null; 8028 } 8029 8030 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8031 // Make a note of it. 8032 mTransferedPackages.add(pkg.packageName); 8033 } 8034 8035 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8036 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8037 } 8038 8039 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8040 // Check all shared libraries and map to their actual file path. 8041 // We only do this here for apps not on a system dir, because those 8042 // are the only ones that can fail an install due to this. We 8043 // will take care of the system apps by updating all of their 8044 // library paths after the scan is done. 8045 updateSharedLibrariesLPw(pkg, null); 8046 } 8047 8048 if (mFoundPolicyFile) { 8049 SELinuxMMAC.assignSeinfoValue(pkg); 8050 } 8051 8052 pkg.applicationInfo.uid = pkgSetting.appId; 8053 pkg.mExtras = pkgSetting; 8054 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8055 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8056 // We just determined the app is signed correctly, so bring 8057 // over the latest parsed certs. 8058 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8059 } else { 8060 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8061 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8062 "Package " + pkg.packageName + " upgrade keys do not match the " 8063 + "previously installed version"); 8064 } else { 8065 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8066 String msg = "System package " + pkg.packageName 8067 + " signature changed; retaining data."; 8068 reportSettingsProblem(Log.WARN, msg); 8069 } 8070 } 8071 } else { 8072 try { 8073 verifySignaturesLP(pkgSetting, pkg); 8074 // We just determined the app is signed correctly, so bring 8075 // over the latest parsed certs. 8076 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8077 } catch (PackageManagerException e) { 8078 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8079 throw e; 8080 } 8081 // The signature has changed, but this package is in the system 8082 // image... let's recover! 8083 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8084 // However... if this package is part of a shared user, but it 8085 // doesn't match the signature of the shared user, let's fail. 8086 // What this means is that you can't change the signatures 8087 // associated with an overall shared user, which doesn't seem all 8088 // that unreasonable. 8089 if (pkgSetting.sharedUser != null) { 8090 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8091 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8092 throw new PackageManagerException( 8093 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8094 "Signature mismatch for shared user: " 8095 + pkgSetting.sharedUser); 8096 } 8097 } 8098 // File a report about this. 8099 String msg = "System package " + pkg.packageName 8100 + " signature changed; retaining data."; 8101 reportSettingsProblem(Log.WARN, msg); 8102 } 8103 } 8104 // Verify that this new package doesn't have any content providers 8105 // that conflict with existing packages. Only do this if the 8106 // package isn't already installed, since we don't want to break 8107 // things that are installed. 8108 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8109 final int N = pkg.providers.size(); 8110 int i; 8111 for (i=0; i<N; i++) { 8112 PackageParser.Provider p = pkg.providers.get(i); 8113 if (p.info.authority != null) { 8114 String names[] = p.info.authority.split(";"); 8115 for (int j = 0; j < names.length; j++) { 8116 if (mProvidersByAuthority.containsKey(names[j])) { 8117 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8118 final String otherPackageName = 8119 ((other != null && other.getComponentName() != null) ? 8120 other.getComponentName().getPackageName() : "?"); 8121 throw new PackageManagerException( 8122 INSTALL_FAILED_CONFLICTING_PROVIDER, 8123 "Can't install because provider name " + names[j] 8124 + " (in package " + pkg.applicationInfo.packageName 8125 + ") is already used by " + otherPackageName); 8126 } 8127 } 8128 } 8129 } 8130 } 8131 8132 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8133 // This package wants to adopt ownership of permissions from 8134 // another package. 8135 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8136 final String origName = pkg.mAdoptPermissions.get(i); 8137 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8138 if (orig != null) { 8139 if (verifyPackageUpdateLPr(orig, pkg)) { 8140 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8141 + pkg.packageName); 8142 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8143 } 8144 } 8145 } 8146 } 8147 } 8148 8149 final String pkgName = pkg.packageName; 8150 8151 final long scanFileTime = scanFile.lastModified(); 8152 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8153 pkg.applicationInfo.processName = fixProcessName( 8154 pkg.applicationInfo.packageName, 8155 pkg.applicationInfo.processName, 8156 pkg.applicationInfo.uid); 8157 8158 if (pkg != mPlatformPackage) { 8159 // Get all of our default paths setup 8160 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8161 } 8162 8163 final String path = scanFile.getPath(); 8164 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8165 8166 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8167 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8168 8169 // Some system apps still use directory structure for native libraries 8170 // in which case we might end up not detecting abi solely based on apk 8171 // structure. Try to detect abi based on directory structure. 8172 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8173 pkg.applicationInfo.primaryCpuAbi == null) { 8174 setBundledAppAbisAndRoots(pkg, pkgSetting); 8175 setNativeLibraryPaths(pkg); 8176 } 8177 8178 } else { 8179 if ((scanFlags & SCAN_MOVE) != 0) { 8180 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8181 // but we already have this packages package info in the PackageSetting. We just 8182 // use that and derive the native library path based on the new codepath. 8183 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8184 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8185 } 8186 8187 // Set native library paths again. For moves, the path will be updated based on the 8188 // ABIs we've determined above. For non-moves, the path will be updated based on the 8189 // ABIs we determined during compilation, but the path will depend on the final 8190 // package path (after the rename away from the stage path). 8191 setNativeLibraryPaths(pkg); 8192 } 8193 8194 // This is a special case for the "system" package, where the ABI is 8195 // dictated by the zygote configuration (and init.rc). We should keep track 8196 // of this ABI so that we can deal with "normal" applications that run under 8197 // the same UID correctly. 8198 if (mPlatformPackage == pkg) { 8199 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8200 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8201 } 8202 8203 // If there's a mismatch between the abi-override in the package setting 8204 // and the abiOverride specified for the install. Warn about this because we 8205 // would've already compiled the app without taking the package setting into 8206 // account. 8207 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8208 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8209 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8210 " for package " + pkg.packageName); 8211 } 8212 } 8213 8214 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8215 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8216 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8217 8218 // Copy the derived override back to the parsed package, so that we can 8219 // update the package settings accordingly. 8220 pkg.cpuAbiOverride = cpuAbiOverride; 8221 8222 if (DEBUG_ABI_SELECTION) { 8223 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8224 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8225 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8226 } 8227 8228 // Push the derived path down into PackageSettings so we know what to 8229 // clean up at uninstall time. 8230 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8231 8232 if (DEBUG_ABI_SELECTION) { 8233 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8234 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8235 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8236 } 8237 8238 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8239 // We don't do this here during boot because we can do it all 8240 // at once after scanning all existing packages. 8241 // 8242 // We also do this *before* we perform dexopt on this package, so that 8243 // we can avoid redundant dexopts, and also to make sure we've got the 8244 // code and package path correct. 8245 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8246 pkg, true /* boot complete */); 8247 } 8248 8249 if (mFactoryTest && pkg.requestedPermissions.contains( 8250 android.Manifest.permission.FACTORY_TEST)) { 8251 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8252 } 8253 8254 ArrayList<PackageParser.Package> clientLibPkgs = null; 8255 8256 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8257 if (nonMutatedPs != null) { 8258 synchronized (mPackages) { 8259 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8260 } 8261 } 8262 return pkg; 8263 } 8264 8265 // Only privileged apps and updated privileged apps can add child packages. 8266 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8267 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8268 throw new PackageManagerException("Only privileged apps and updated " 8269 + "privileged apps can add child packages. Ignoring package " 8270 + pkg.packageName); 8271 } 8272 final int childCount = pkg.childPackages.size(); 8273 for (int i = 0; i < childCount; i++) { 8274 PackageParser.Package childPkg = pkg.childPackages.get(i); 8275 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8276 childPkg.packageName)) { 8277 throw new PackageManagerException("Cannot override a child package of " 8278 + "another disabled system app. Ignoring package " + pkg.packageName); 8279 } 8280 } 8281 } 8282 8283 // writer 8284 synchronized (mPackages) { 8285 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8286 // Only system apps can add new shared libraries. 8287 if (pkg.libraryNames != null) { 8288 for (int i=0; i<pkg.libraryNames.size(); i++) { 8289 String name = pkg.libraryNames.get(i); 8290 boolean allowed = false; 8291 if (pkg.isUpdatedSystemApp()) { 8292 // New library entries can only be added through the 8293 // system image. This is important to get rid of a lot 8294 // of nasty edge cases: for example if we allowed a non- 8295 // system update of the app to add a library, then uninstalling 8296 // the update would make the library go away, and assumptions 8297 // we made such as through app install filtering would now 8298 // have allowed apps on the device which aren't compatible 8299 // with it. Better to just have the restriction here, be 8300 // conservative, and create many fewer cases that can negatively 8301 // impact the user experience. 8302 final PackageSetting sysPs = mSettings 8303 .getDisabledSystemPkgLPr(pkg.packageName); 8304 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8305 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8306 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8307 allowed = true; 8308 break; 8309 } 8310 } 8311 } 8312 } else { 8313 allowed = true; 8314 } 8315 if (allowed) { 8316 if (!mSharedLibraries.containsKey(name)) { 8317 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8318 } else if (!name.equals(pkg.packageName)) { 8319 Slog.w(TAG, "Package " + pkg.packageName + " library " 8320 + name + " already exists; skipping"); 8321 } 8322 } else { 8323 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8324 + name + " that is not declared on system image; skipping"); 8325 } 8326 } 8327 if ((scanFlags & SCAN_BOOTING) == 0) { 8328 // If we are not booting, we need to update any applications 8329 // that are clients of our shared library. If we are booting, 8330 // this will all be done once the scan is complete. 8331 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8332 } 8333 } 8334 } 8335 } 8336 8337 if ((scanFlags & SCAN_BOOTING) != 0) { 8338 // No apps can run during boot scan, so they don't need to be frozen 8339 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8340 // Caller asked to not kill app, so it's probably not frozen 8341 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8342 // Caller asked us to ignore frozen check for some reason; they 8343 // probably didn't know the package name 8344 } else { 8345 // We're doing major surgery on this package, so it better be frozen 8346 // right now to keep it from launching 8347 checkPackageFrozen(pkgName); 8348 } 8349 8350 // Also need to kill any apps that are dependent on the library. 8351 if (clientLibPkgs != null) { 8352 for (int i=0; i<clientLibPkgs.size(); i++) { 8353 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8354 killApplication(clientPkg.applicationInfo.packageName, 8355 clientPkg.applicationInfo.uid, "update lib"); 8356 } 8357 } 8358 8359 // Make sure we're not adding any bogus keyset info 8360 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8361 ksms.assertScannedPackageValid(pkg); 8362 8363 // writer 8364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8365 8366 boolean createIdmapFailed = false; 8367 synchronized (mPackages) { 8368 // We don't expect installation to fail beyond this point 8369 8370 // Add the new setting to mSettings 8371 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8372 // Add the new setting to mPackages 8373 mPackages.put(pkg.applicationInfo.packageName, pkg); 8374 // Make sure we don't accidentally delete its data. 8375 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8376 while (iter.hasNext()) { 8377 PackageCleanItem item = iter.next(); 8378 if (pkgName.equals(item.packageName)) { 8379 iter.remove(); 8380 } 8381 } 8382 8383 // Take care of first install / last update times. 8384 if (currentTime != 0) { 8385 if (pkgSetting.firstInstallTime == 0) { 8386 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8387 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8388 pkgSetting.lastUpdateTime = currentTime; 8389 } 8390 } else if (pkgSetting.firstInstallTime == 0) { 8391 // We need *something*. Take time time stamp of the file. 8392 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8393 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8394 if (scanFileTime != pkgSetting.timeStamp) { 8395 // A package on the system image has changed; consider this 8396 // to be an update. 8397 pkgSetting.lastUpdateTime = scanFileTime; 8398 } 8399 } 8400 8401 // Add the package's KeySets to the global KeySetManagerService 8402 ksms.addScannedPackageLPw(pkg); 8403 8404 int N = pkg.providers.size(); 8405 StringBuilder r = null; 8406 int i; 8407 for (i=0; i<N; i++) { 8408 PackageParser.Provider p = pkg.providers.get(i); 8409 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8410 p.info.processName, pkg.applicationInfo.uid); 8411 mProviders.addProvider(p); 8412 p.syncable = p.info.isSyncable; 8413 if (p.info.authority != null) { 8414 String names[] = p.info.authority.split(";"); 8415 p.info.authority = null; 8416 for (int j = 0; j < names.length; j++) { 8417 if (j == 1 && p.syncable) { 8418 // We only want the first authority for a provider to possibly be 8419 // syncable, so if we already added this provider using a different 8420 // authority clear the syncable flag. We copy the provider before 8421 // changing it because the mProviders object contains a reference 8422 // to a provider that we don't want to change. 8423 // Only do this for the second authority since the resulting provider 8424 // object can be the same for all future authorities for this provider. 8425 p = new PackageParser.Provider(p); 8426 p.syncable = false; 8427 } 8428 if (!mProvidersByAuthority.containsKey(names[j])) { 8429 mProvidersByAuthority.put(names[j], p); 8430 if (p.info.authority == null) { 8431 p.info.authority = names[j]; 8432 } else { 8433 p.info.authority = p.info.authority + ";" + names[j]; 8434 } 8435 if (DEBUG_PACKAGE_SCANNING) { 8436 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8437 Log.d(TAG, "Registered content provider: " + names[j] 8438 + ", className = " + p.info.name + ", isSyncable = " 8439 + p.info.isSyncable); 8440 } 8441 } else { 8442 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8443 Slog.w(TAG, "Skipping provider name " + names[j] + 8444 " (in package " + pkg.applicationInfo.packageName + 8445 "): name already used by " 8446 + ((other != null && other.getComponentName() != null) 8447 ? other.getComponentName().getPackageName() : "?")); 8448 } 8449 } 8450 } 8451 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8452 if (r == null) { 8453 r = new StringBuilder(256); 8454 } else { 8455 r.append(' '); 8456 } 8457 r.append(p.info.name); 8458 } 8459 } 8460 if (r != null) { 8461 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8462 } 8463 8464 N = pkg.services.size(); 8465 r = null; 8466 for (i=0; i<N; i++) { 8467 PackageParser.Service s = pkg.services.get(i); 8468 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8469 s.info.processName, pkg.applicationInfo.uid); 8470 mServices.addService(s); 8471 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8472 if (r == null) { 8473 r = new StringBuilder(256); 8474 } else { 8475 r.append(' '); 8476 } 8477 r.append(s.info.name); 8478 } 8479 } 8480 if (r != null) { 8481 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8482 } 8483 8484 N = pkg.receivers.size(); 8485 r = null; 8486 for (i=0; i<N; i++) { 8487 PackageParser.Activity a = pkg.receivers.get(i); 8488 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8489 a.info.processName, pkg.applicationInfo.uid); 8490 mReceivers.addActivity(a, "receiver"); 8491 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8492 if (r == null) { 8493 r = new StringBuilder(256); 8494 } else { 8495 r.append(' '); 8496 } 8497 r.append(a.info.name); 8498 } 8499 } 8500 if (r != null) { 8501 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8502 } 8503 8504 N = pkg.activities.size(); 8505 r = null; 8506 for (i=0; i<N; i++) { 8507 PackageParser.Activity a = pkg.activities.get(i); 8508 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8509 a.info.processName, pkg.applicationInfo.uid); 8510 mActivities.addActivity(a, "activity"); 8511 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8512 if (r == null) { 8513 r = new StringBuilder(256); 8514 } else { 8515 r.append(' '); 8516 } 8517 r.append(a.info.name); 8518 } 8519 } 8520 if (r != null) { 8521 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8522 } 8523 8524 N = pkg.permissionGroups.size(); 8525 r = null; 8526 for (i=0; i<N; i++) { 8527 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8528 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8529 if (cur == null) { 8530 mPermissionGroups.put(pg.info.name, pg); 8531 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8532 if (r == null) { 8533 r = new StringBuilder(256); 8534 } else { 8535 r.append(' '); 8536 } 8537 r.append(pg.info.name); 8538 } 8539 } else { 8540 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8541 + pg.info.packageName + " ignored: original from " 8542 + cur.info.packageName); 8543 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8544 if (r == null) { 8545 r = new StringBuilder(256); 8546 } else { 8547 r.append(' '); 8548 } 8549 r.append("DUP:"); 8550 r.append(pg.info.name); 8551 } 8552 } 8553 } 8554 if (r != null) { 8555 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8556 } 8557 8558 N = pkg.permissions.size(); 8559 r = null; 8560 for (i=0; i<N; i++) { 8561 PackageParser.Permission p = pkg.permissions.get(i); 8562 8563 // Assume by default that we did not install this permission into the system. 8564 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8565 8566 // Now that permission groups have a special meaning, we ignore permission 8567 // groups for legacy apps to prevent unexpected behavior. In particular, 8568 // permissions for one app being granted to someone just becase they happen 8569 // to be in a group defined by another app (before this had no implications). 8570 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8571 p.group = mPermissionGroups.get(p.info.group); 8572 // Warn for a permission in an unknown group. 8573 if (p.info.group != null && p.group == null) { 8574 Slog.w(TAG, "Permission " + p.info.name + " from package " 8575 + p.info.packageName + " in an unknown group " + p.info.group); 8576 } 8577 } 8578 8579 ArrayMap<String, BasePermission> permissionMap = 8580 p.tree ? mSettings.mPermissionTrees 8581 : mSettings.mPermissions; 8582 BasePermission bp = permissionMap.get(p.info.name); 8583 8584 // Allow system apps to redefine non-system permissions 8585 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8586 final boolean currentOwnerIsSystem = (bp.perm != null 8587 && isSystemApp(bp.perm.owner)); 8588 if (isSystemApp(p.owner)) { 8589 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8590 // It's a built-in permission and no owner, take ownership now 8591 bp.packageSetting = pkgSetting; 8592 bp.perm = p; 8593 bp.uid = pkg.applicationInfo.uid; 8594 bp.sourcePackage = p.info.packageName; 8595 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8596 } else if (!currentOwnerIsSystem) { 8597 String msg = "New decl " + p.owner + " of permission " 8598 + p.info.name + " is system; overriding " + bp.sourcePackage; 8599 reportSettingsProblem(Log.WARN, msg); 8600 bp = null; 8601 } 8602 } 8603 } 8604 8605 if (bp == null) { 8606 bp = new BasePermission(p.info.name, p.info.packageName, 8607 BasePermission.TYPE_NORMAL); 8608 permissionMap.put(p.info.name, bp); 8609 } 8610 8611 if (bp.perm == null) { 8612 if (bp.sourcePackage == null 8613 || bp.sourcePackage.equals(p.info.packageName)) { 8614 BasePermission tree = findPermissionTreeLP(p.info.name); 8615 if (tree == null 8616 || tree.sourcePackage.equals(p.info.packageName)) { 8617 bp.packageSetting = pkgSetting; 8618 bp.perm = p; 8619 bp.uid = pkg.applicationInfo.uid; 8620 bp.sourcePackage = p.info.packageName; 8621 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8622 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8623 if (r == null) { 8624 r = new StringBuilder(256); 8625 } else { 8626 r.append(' '); 8627 } 8628 r.append(p.info.name); 8629 } 8630 } else { 8631 Slog.w(TAG, "Permission " + p.info.name + " from package " 8632 + p.info.packageName + " ignored: base tree " 8633 + tree.name + " is from package " 8634 + tree.sourcePackage); 8635 } 8636 } else { 8637 Slog.w(TAG, "Permission " + p.info.name + " from package " 8638 + p.info.packageName + " ignored: original from " 8639 + bp.sourcePackage); 8640 } 8641 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8642 if (r == null) { 8643 r = new StringBuilder(256); 8644 } else { 8645 r.append(' '); 8646 } 8647 r.append("DUP:"); 8648 r.append(p.info.name); 8649 } 8650 if (bp.perm == p) { 8651 bp.protectionLevel = p.info.protectionLevel; 8652 } 8653 } 8654 8655 if (r != null) { 8656 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8657 } 8658 8659 N = pkg.instrumentation.size(); 8660 r = null; 8661 for (i=0; i<N; i++) { 8662 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8663 a.info.packageName = pkg.applicationInfo.packageName; 8664 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8665 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8666 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8667 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8668 a.info.dataDir = pkg.applicationInfo.dataDir; 8669 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8670 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8671 8672 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8673 // need other information about the application, like the ABI and what not ? 8674 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8675 mInstrumentation.put(a.getComponentName(), a); 8676 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8677 if (r == null) { 8678 r = new StringBuilder(256); 8679 } else { 8680 r.append(' '); 8681 } 8682 r.append(a.info.name); 8683 } 8684 } 8685 if (r != null) { 8686 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8687 } 8688 8689 if (pkg.protectedBroadcasts != null) { 8690 N = pkg.protectedBroadcasts.size(); 8691 for (i=0; i<N; i++) { 8692 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8693 } 8694 } 8695 8696 pkgSetting.setTimeStamp(scanFileTime); 8697 8698 // Create idmap files for pairs of (packages, overlay packages). 8699 // Note: "android", ie framework-res.apk, is handled by native layers. 8700 if (pkg.mOverlayTarget != null) { 8701 // This is an overlay package. 8702 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8703 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8704 mOverlays.put(pkg.mOverlayTarget, 8705 new ArrayMap<String, PackageParser.Package>()); 8706 } 8707 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8708 map.put(pkg.packageName, pkg); 8709 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8710 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8711 createIdmapFailed = true; 8712 } 8713 } 8714 } else if (mOverlays.containsKey(pkg.packageName) && 8715 !pkg.packageName.equals("android")) { 8716 // This is a regular package, with one or more known overlay packages. 8717 createIdmapsForPackageLI(pkg); 8718 } 8719 } 8720 8721 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8722 8723 if (createIdmapFailed) { 8724 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8725 "scanPackageLI failed to createIdmap"); 8726 } 8727 return pkg; 8728 } 8729 8730 /** 8731 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8732 * is derived purely on the basis of the contents of {@code scanFile} and 8733 * {@code cpuAbiOverride}. 8734 * 8735 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8736 */ 8737 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8738 String cpuAbiOverride, boolean extractLibs) 8739 throws PackageManagerException { 8740 // TODO: We can probably be smarter about this stuff. For installed apps, 8741 // we can calculate this information at install time once and for all. For 8742 // system apps, we can probably assume that this information doesn't change 8743 // after the first boot scan. As things stand, we do lots of unnecessary work. 8744 8745 // Give ourselves some initial paths; we'll come back for another 8746 // pass once we've determined ABI below. 8747 setNativeLibraryPaths(pkg); 8748 8749 // We would never need to extract libs for forward-locked and external packages, 8750 // since the container service will do it for us. We shouldn't attempt to 8751 // extract libs from system app when it was not updated. 8752 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8753 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8754 extractLibs = false; 8755 } 8756 8757 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8758 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8759 8760 NativeLibraryHelper.Handle handle = null; 8761 try { 8762 handle = NativeLibraryHelper.Handle.create(pkg); 8763 // TODO(multiArch): This can be null for apps that didn't go through the 8764 // usual installation process. We can calculate it again, like we 8765 // do during install time. 8766 // 8767 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8768 // unnecessary. 8769 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8770 8771 // Null out the abis so that they can be recalculated. 8772 pkg.applicationInfo.primaryCpuAbi = null; 8773 pkg.applicationInfo.secondaryCpuAbi = null; 8774 if (isMultiArch(pkg.applicationInfo)) { 8775 // Warn if we've set an abiOverride for multi-lib packages.. 8776 // By definition, we need to copy both 32 and 64 bit libraries for 8777 // such packages. 8778 if (pkg.cpuAbiOverride != null 8779 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8780 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8781 } 8782 8783 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8784 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8785 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8786 if (extractLibs) { 8787 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8788 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8789 useIsaSpecificSubdirs); 8790 } else { 8791 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8792 } 8793 } 8794 8795 maybeThrowExceptionForMultiArchCopy( 8796 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8797 8798 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8799 if (extractLibs) { 8800 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8801 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8802 useIsaSpecificSubdirs); 8803 } else { 8804 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8805 } 8806 } 8807 8808 maybeThrowExceptionForMultiArchCopy( 8809 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8810 8811 if (abi64 >= 0) { 8812 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8813 } 8814 8815 if (abi32 >= 0) { 8816 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8817 if (abi64 >= 0) { 8818 if (pkg.use32bitAbi) { 8819 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8820 pkg.applicationInfo.primaryCpuAbi = abi; 8821 } else { 8822 pkg.applicationInfo.secondaryCpuAbi = abi; 8823 } 8824 } else { 8825 pkg.applicationInfo.primaryCpuAbi = abi; 8826 } 8827 } 8828 8829 } else { 8830 String[] abiList = (cpuAbiOverride != null) ? 8831 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8832 8833 // Enable gross and lame hacks for apps that are built with old 8834 // SDK tools. We must scan their APKs for renderscript bitcode and 8835 // not launch them if it's present. Don't bother checking on devices 8836 // that don't have 64 bit support. 8837 boolean needsRenderScriptOverride = false; 8838 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8839 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8840 abiList = Build.SUPPORTED_32_BIT_ABIS; 8841 needsRenderScriptOverride = true; 8842 } 8843 8844 final int copyRet; 8845 if (extractLibs) { 8846 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8847 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8848 } else { 8849 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8850 } 8851 8852 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8853 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8854 "Error unpackaging native libs for app, errorCode=" + copyRet); 8855 } 8856 8857 if (copyRet >= 0) { 8858 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8859 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8860 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8861 } else if (needsRenderScriptOverride) { 8862 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8863 } 8864 } 8865 } catch (IOException ioe) { 8866 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8867 } finally { 8868 IoUtils.closeQuietly(handle); 8869 } 8870 8871 // Now that we've calculated the ABIs and determined if it's an internal app, 8872 // we will go ahead and populate the nativeLibraryPath. 8873 setNativeLibraryPaths(pkg); 8874 } 8875 8876 /** 8877 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8878 * i.e, so that all packages can be run inside a single process if required. 8879 * 8880 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8881 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8882 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8883 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8884 * updating a package that belongs to a shared user. 8885 * 8886 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8887 * adds unnecessary complexity. 8888 */ 8889 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8890 PackageParser.Package scannedPackage, boolean bootComplete) { 8891 String requiredInstructionSet = null; 8892 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8893 requiredInstructionSet = VMRuntime.getInstructionSet( 8894 scannedPackage.applicationInfo.primaryCpuAbi); 8895 } 8896 8897 PackageSetting requirer = null; 8898 for (PackageSetting ps : packagesForUser) { 8899 // If packagesForUser contains scannedPackage, we skip it. This will happen 8900 // when scannedPackage is an update of an existing package. Without this check, 8901 // we will never be able to change the ABI of any package belonging to a shared 8902 // user, even if it's compatible with other packages. 8903 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8904 if (ps.primaryCpuAbiString == null) { 8905 continue; 8906 } 8907 8908 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8909 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8910 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8911 // this but there's not much we can do. 8912 String errorMessage = "Instruction set mismatch, " 8913 + ((requirer == null) ? "[caller]" : requirer) 8914 + " requires " + requiredInstructionSet + " whereas " + ps 8915 + " requires " + instructionSet; 8916 Slog.w(TAG, errorMessage); 8917 } 8918 8919 if (requiredInstructionSet == null) { 8920 requiredInstructionSet = instructionSet; 8921 requirer = ps; 8922 } 8923 } 8924 } 8925 8926 if (requiredInstructionSet != null) { 8927 String adjustedAbi; 8928 if (requirer != null) { 8929 // requirer != null implies that either scannedPackage was null or that scannedPackage 8930 // did not require an ABI, in which case we have to adjust scannedPackage to match 8931 // the ABI of the set (which is the same as requirer's ABI) 8932 adjustedAbi = requirer.primaryCpuAbiString; 8933 if (scannedPackage != null) { 8934 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8935 } 8936 } else { 8937 // requirer == null implies that we're updating all ABIs in the set to 8938 // match scannedPackage. 8939 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8940 } 8941 8942 for (PackageSetting ps : packagesForUser) { 8943 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8944 if (ps.primaryCpuAbiString != null) { 8945 continue; 8946 } 8947 8948 ps.primaryCpuAbiString = adjustedAbi; 8949 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8950 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8951 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8952 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8953 + " (requirer=" 8954 + (requirer == null ? "null" : requirer.pkg.packageName) 8955 + ", scannedPackage=" 8956 + (scannedPackage != null ? scannedPackage.packageName : "null") 8957 + ")"); 8958 try { 8959 mInstaller.rmdex(ps.codePathString, 8960 getDexCodeInstructionSet(getPreferredInstructionSet())); 8961 } catch (InstallerException ignored) { 8962 } 8963 } 8964 } 8965 } 8966 } 8967 } 8968 8969 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8970 synchronized (mPackages) { 8971 mResolverReplaced = true; 8972 // Set up information for custom user intent resolution activity. 8973 mResolveActivity.applicationInfo = pkg.applicationInfo; 8974 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8975 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8976 mResolveActivity.processName = pkg.applicationInfo.packageName; 8977 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8978 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8979 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8980 mResolveActivity.theme = 0; 8981 mResolveActivity.exported = true; 8982 mResolveActivity.enabled = true; 8983 mResolveInfo.activityInfo = mResolveActivity; 8984 mResolveInfo.priority = 0; 8985 mResolveInfo.preferredOrder = 0; 8986 mResolveInfo.match = 0; 8987 mResolveComponentName = mCustomResolverComponentName; 8988 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8989 mResolveComponentName); 8990 } 8991 } 8992 8993 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8994 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8995 8996 // Set up information for ephemeral installer activity 8997 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8998 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8999 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9000 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9001 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9002 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9003 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9004 mEphemeralInstallerActivity.theme = 0; 9005 mEphemeralInstallerActivity.exported = true; 9006 mEphemeralInstallerActivity.enabled = true; 9007 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9008 mEphemeralInstallerInfo.priority = 0; 9009 mEphemeralInstallerInfo.preferredOrder = 0; 9010 mEphemeralInstallerInfo.match = 0; 9011 9012 if (DEBUG_EPHEMERAL) { 9013 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9014 } 9015 } 9016 9017 private static String calculateBundledApkRoot(final String codePathString) { 9018 final File codePath = new File(codePathString); 9019 final File codeRoot; 9020 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9021 codeRoot = Environment.getRootDirectory(); 9022 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9023 codeRoot = Environment.getOemDirectory(); 9024 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9025 codeRoot = Environment.getVendorDirectory(); 9026 } else { 9027 // Unrecognized code path; take its top real segment as the apk root: 9028 // e.g. /something/app/blah.apk => /something 9029 try { 9030 File f = codePath.getCanonicalFile(); 9031 File parent = f.getParentFile(); // non-null because codePath is a file 9032 File tmp; 9033 while ((tmp = parent.getParentFile()) != null) { 9034 f = parent; 9035 parent = tmp; 9036 } 9037 codeRoot = f; 9038 Slog.w(TAG, "Unrecognized code path " 9039 + codePath + " - using " + codeRoot); 9040 } catch (IOException e) { 9041 // Can't canonicalize the code path -- shenanigans? 9042 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9043 return Environment.getRootDirectory().getPath(); 9044 } 9045 } 9046 return codeRoot.getPath(); 9047 } 9048 9049 /** 9050 * Derive and set the location of native libraries for the given package, 9051 * which varies depending on where and how the package was installed. 9052 */ 9053 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9054 final ApplicationInfo info = pkg.applicationInfo; 9055 final String codePath = pkg.codePath; 9056 final File codeFile = new File(codePath); 9057 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9058 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9059 9060 info.nativeLibraryRootDir = null; 9061 info.nativeLibraryRootRequiresIsa = false; 9062 info.nativeLibraryDir = null; 9063 info.secondaryNativeLibraryDir = null; 9064 9065 if (isApkFile(codeFile)) { 9066 // Monolithic install 9067 if (bundledApp) { 9068 // If "/system/lib64/apkname" exists, assume that is the per-package 9069 // native library directory to use; otherwise use "/system/lib/apkname". 9070 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9071 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9072 getPrimaryInstructionSet(info)); 9073 9074 // This is a bundled system app so choose the path based on the ABI. 9075 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9076 // is just the default path. 9077 final String apkName = deriveCodePathName(codePath); 9078 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9079 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9080 apkName).getAbsolutePath(); 9081 9082 if (info.secondaryCpuAbi != null) { 9083 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9084 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9085 secondaryLibDir, apkName).getAbsolutePath(); 9086 } 9087 } else if (asecApp) { 9088 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9089 .getAbsolutePath(); 9090 } else { 9091 final String apkName = deriveCodePathName(codePath); 9092 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9093 .getAbsolutePath(); 9094 } 9095 9096 info.nativeLibraryRootRequiresIsa = false; 9097 info.nativeLibraryDir = info.nativeLibraryRootDir; 9098 } else { 9099 // Cluster install 9100 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9101 info.nativeLibraryRootRequiresIsa = true; 9102 9103 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9104 getPrimaryInstructionSet(info)).getAbsolutePath(); 9105 9106 if (info.secondaryCpuAbi != null) { 9107 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9108 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9109 } 9110 } 9111 } 9112 9113 /** 9114 * Calculate the abis and roots for a bundled app. These can uniquely 9115 * be determined from the contents of the system partition, i.e whether 9116 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9117 * of this information, and instead assume that the system was built 9118 * sensibly. 9119 */ 9120 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9121 PackageSetting pkgSetting) { 9122 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9123 9124 // If "/system/lib64/apkname" exists, assume that is the per-package 9125 // native library directory to use; otherwise use "/system/lib/apkname". 9126 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9127 setBundledAppAbi(pkg, apkRoot, apkName); 9128 // pkgSetting might be null during rescan following uninstall of updates 9129 // to a bundled app, so accommodate that possibility. The settings in 9130 // that case will be established later from the parsed package. 9131 // 9132 // If the settings aren't null, sync them up with what we've just derived. 9133 // note that apkRoot isn't stored in the package settings. 9134 if (pkgSetting != null) { 9135 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9136 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9137 } 9138 } 9139 9140 /** 9141 * Deduces the ABI of a bundled app and sets the relevant fields on the 9142 * parsed pkg object. 9143 * 9144 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9145 * under which system libraries are installed. 9146 * @param apkName the name of the installed package. 9147 */ 9148 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9149 final File codeFile = new File(pkg.codePath); 9150 9151 final boolean has64BitLibs; 9152 final boolean has32BitLibs; 9153 if (isApkFile(codeFile)) { 9154 // Monolithic install 9155 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9156 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9157 } else { 9158 // Cluster install 9159 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9160 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9161 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9162 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9163 has64BitLibs = (new File(rootDir, isa)).exists(); 9164 } else { 9165 has64BitLibs = false; 9166 } 9167 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9168 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9169 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9170 has32BitLibs = (new File(rootDir, isa)).exists(); 9171 } else { 9172 has32BitLibs = false; 9173 } 9174 } 9175 9176 if (has64BitLibs && !has32BitLibs) { 9177 // The package has 64 bit libs, but not 32 bit libs. Its primary 9178 // ABI should be 64 bit. We can safely assume here that the bundled 9179 // native libraries correspond to the most preferred ABI in the list. 9180 9181 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9182 pkg.applicationInfo.secondaryCpuAbi = null; 9183 } else if (has32BitLibs && !has64BitLibs) { 9184 // The package has 32 bit libs but not 64 bit libs. Its primary 9185 // ABI should be 32 bit. 9186 9187 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9188 pkg.applicationInfo.secondaryCpuAbi = null; 9189 } else if (has32BitLibs && has64BitLibs) { 9190 // The application has both 64 and 32 bit bundled libraries. We check 9191 // here that the app declares multiArch support, and warn if it doesn't. 9192 // 9193 // We will be lenient here and record both ABIs. The primary will be the 9194 // ABI that's higher on the list, i.e, a device that's configured to prefer 9195 // 64 bit apps will see a 64 bit primary ABI, 9196 9197 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9198 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9199 } 9200 9201 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9202 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9203 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9204 } else { 9205 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9206 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9207 } 9208 } else { 9209 pkg.applicationInfo.primaryCpuAbi = null; 9210 pkg.applicationInfo.secondaryCpuAbi = null; 9211 } 9212 } 9213 9214 private void killApplication(String pkgName, int appId, String reason) { 9215 // Request the ActivityManager to kill the process(only for existing packages) 9216 // so that we do not end up in a confused state while the user is still using the older 9217 // version of the application while the new one gets installed. 9218 final long token = Binder.clearCallingIdentity(); 9219 try { 9220 IActivityManager am = ActivityManagerNative.getDefault(); 9221 if (am != null) { 9222 try { 9223 am.killApplicationWithAppId(pkgName, appId, reason); 9224 } catch (RemoteException e) { 9225 } 9226 } 9227 } finally { 9228 Binder.restoreCallingIdentity(token); 9229 } 9230 } 9231 9232 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9233 // Remove the parent package setting 9234 PackageSetting ps = (PackageSetting) pkg.mExtras; 9235 if (ps != null) { 9236 removePackageLI(ps, chatty); 9237 } 9238 // Remove the child package setting 9239 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9240 for (int i = 0; i < childCount; i++) { 9241 PackageParser.Package childPkg = pkg.childPackages.get(i); 9242 ps = (PackageSetting) childPkg.mExtras; 9243 if (ps != null) { 9244 removePackageLI(ps, chatty); 9245 } 9246 } 9247 } 9248 9249 void removePackageLI(PackageSetting ps, boolean chatty) { 9250 if (DEBUG_INSTALL) { 9251 if (chatty) 9252 Log.d(TAG, "Removing package " + ps.name); 9253 } 9254 9255 // writer 9256 synchronized (mPackages) { 9257 mPackages.remove(ps.name); 9258 final PackageParser.Package pkg = ps.pkg; 9259 if (pkg != null) { 9260 cleanPackageDataStructuresLILPw(pkg, chatty); 9261 } 9262 } 9263 } 9264 9265 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9266 if (DEBUG_INSTALL) { 9267 if (chatty) 9268 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9269 } 9270 9271 // writer 9272 synchronized (mPackages) { 9273 // Remove the parent package 9274 mPackages.remove(pkg.applicationInfo.packageName); 9275 cleanPackageDataStructuresLILPw(pkg, chatty); 9276 9277 // Remove the child packages 9278 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9279 for (int i = 0; i < childCount; i++) { 9280 PackageParser.Package childPkg = pkg.childPackages.get(i); 9281 mPackages.remove(childPkg.applicationInfo.packageName); 9282 cleanPackageDataStructuresLILPw(childPkg, chatty); 9283 } 9284 } 9285 } 9286 9287 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9288 int N = pkg.providers.size(); 9289 StringBuilder r = null; 9290 int i; 9291 for (i=0; i<N; i++) { 9292 PackageParser.Provider p = pkg.providers.get(i); 9293 mProviders.removeProvider(p); 9294 if (p.info.authority == null) { 9295 9296 /* There was another ContentProvider with this authority when 9297 * this app was installed so this authority is null, 9298 * Ignore it as we don't have to unregister the provider. 9299 */ 9300 continue; 9301 } 9302 String names[] = p.info.authority.split(";"); 9303 for (int j = 0; j < names.length; j++) { 9304 if (mProvidersByAuthority.get(names[j]) == p) { 9305 mProvidersByAuthority.remove(names[j]); 9306 if (DEBUG_REMOVE) { 9307 if (chatty) 9308 Log.d(TAG, "Unregistered content provider: " + names[j] 9309 + ", className = " + p.info.name + ", isSyncable = " 9310 + p.info.isSyncable); 9311 } 9312 } 9313 } 9314 if (DEBUG_REMOVE && chatty) { 9315 if (r == null) { 9316 r = new StringBuilder(256); 9317 } else { 9318 r.append(' '); 9319 } 9320 r.append(p.info.name); 9321 } 9322 } 9323 if (r != null) { 9324 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9325 } 9326 9327 N = pkg.services.size(); 9328 r = null; 9329 for (i=0; i<N; i++) { 9330 PackageParser.Service s = pkg.services.get(i); 9331 mServices.removeService(s); 9332 if (chatty) { 9333 if (r == null) { 9334 r = new StringBuilder(256); 9335 } else { 9336 r.append(' '); 9337 } 9338 r.append(s.info.name); 9339 } 9340 } 9341 if (r != null) { 9342 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9343 } 9344 9345 N = pkg.receivers.size(); 9346 r = null; 9347 for (i=0; i<N; i++) { 9348 PackageParser.Activity a = pkg.receivers.get(i); 9349 mReceivers.removeActivity(a, "receiver"); 9350 if (DEBUG_REMOVE && chatty) { 9351 if (r == null) { 9352 r = new StringBuilder(256); 9353 } else { 9354 r.append(' '); 9355 } 9356 r.append(a.info.name); 9357 } 9358 } 9359 if (r != null) { 9360 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9361 } 9362 9363 N = pkg.activities.size(); 9364 r = null; 9365 for (i=0; i<N; i++) { 9366 PackageParser.Activity a = pkg.activities.get(i); 9367 mActivities.removeActivity(a, "activity"); 9368 if (DEBUG_REMOVE && chatty) { 9369 if (r == null) { 9370 r = new StringBuilder(256); 9371 } else { 9372 r.append(' '); 9373 } 9374 r.append(a.info.name); 9375 } 9376 } 9377 if (r != null) { 9378 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9379 } 9380 9381 N = pkg.permissions.size(); 9382 r = null; 9383 for (i=0; i<N; i++) { 9384 PackageParser.Permission p = pkg.permissions.get(i); 9385 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9386 if (bp == null) { 9387 bp = mSettings.mPermissionTrees.get(p.info.name); 9388 } 9389 if (bp != null && bp.perm == p) { 9390 bp.perm = null; 9391 if (DEBUG_REMOVE && chatty) { 9392 if (r == null) { 9393 r = new StringBuilder(256); 9394 } else { 9395 r.append(' '); 9396 } 9397 r.append(p.info.name); 9398 } 9399 } 9400 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9401 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9402 if (appOpPkgs != null) { 9403 appOpPkgs.remove(pkg.packageName); 9404 } 9405 } 9406 } 9407 if (r != null) { 9408 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9409 } 9410 9411 N = pkg.requestedPermissions.size(); 9412 r = null; 9413 for (i=0; i<N; i++) { 9414 String perm = pkg.requestedPermissions.get(i); 9415 BasePermission bp = mSettings.mPermissions.get(perm); 9416 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9417 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9418 if (appOpPkgs != null) { 9419 appOpPkgs.remove(pkg.packageName); 9420 if (appOpPkgs.isEmpty()) { 9421 mAppOpPermissionPackages.remove(perm); 9422 } 9423 } 9424 } 9425 } 9426 if (r != null) { 9427 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9428 } 9429 9430 N = pkg.instrumentation.size(); 9431 r = null; 9432 for (i=0; i<N; i++) { 9433 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9434 mInstrumentation.remove(a.getComponentName()); 9435 if (DEBUG_REMOVE && chatty) { 9436 if (r == null) { 9437 r = new StringBuilder(256); 9438 } else { 9439 r.append(' '); 9440 } 9441 r.append(a.info.name); 9442 } 9443 } 9444 if (r != null) { 9445 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9446 } 9447 9448 r = null; 9449 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9450 // Only system apps can hold shared libraries. 9451 if (pkg.libraryNames != null) { 9452 for (i=0; i<pkg.libraryNames.size(); i++) { 9453 String name = pkg.libraryNames.get(i); 9454 SharedLibraryEntry cur = mSharedLibraries.get(name); 9455 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9456 mSharedLibraries.remove(name); 9457 if (DEBUG_REMOVE && chatty) { 9458 if (r == null) { 9459 r = new StringBuilder(256); 9460 } else { 9461 r.append(' '); 9462 } 9463 r.append(name); 9464 } 9465 } 9466 } 9467 } 9468 } 9469 if (r != null) { 9470 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9471 } 9472 } 9473 9474 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9475 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9476 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9477 return true; 9478 } 9479 } 9480 return false; 9481 } 9482 9483 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9484 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9485 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9486 9487 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9488 // Update the parent permissions 9489 updatePermissionsLPw(pkg.packageName, pkg, flags); 9490 // Update the child permissions 9491 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9492 for (int i = 0; i < childCount; i++) { 9493 PackageParser.Package childPkg = pkg.childPackages.get(i); 9494 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9495 } 9496 } 9497 9498 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9499 int flags) { 9500 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9501 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9502 } 9503 9504 private void updatePermissionsLPw(String changingPkg, 9505 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9506 // Make sure there are no dangling permission trees. 9507 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9508 while (it.hasNext()) { 9509 final BasePermission bp = it.next(); 9510 if (bp.packageSetting == null) { 9511 // We may not yet have parsed the package, so just see if 9512 // we still know about its settings. 9513 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9514 } 9515 if (bp.packageSetting == null) { 9516 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9517 + " from package " + bp.sourcePackage); 9518 it.remove(); 9519 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9520 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9521 Slog.i(TAG, "Removing old permission tree: " + bp.name 9522 + " from package " + bp.sourcePackage); 9523 flags |= UPDATE_PERMISSIONS_ALL; 9524 it.remove(); 9525 } 9526 } 9527 } 9528 9529 // Make sure all dynamic permissions have been assigned to a package, 9530 // and make sure there are no dangling permissions. 9531 it = mSettings.mPermissions.values().iterator(); 9532 while (it.hasNext()) { 9533 final BasePermission bp = it.next(); 9534 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9535 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9536 + bp.name + " pkg=" + bp.sourcePackage 9537 + " info=" + bp.pendingInfo); 9538 if (bp.packageSetting == null && bp.pendingInfo != null) { 9539 final BasePermission tree = findPermissionTreeLP(bp.name); 9540 if (tree != null && tree.perm != null) { 9541 bp.packageSetting = tree.packageSetting; 9542 bp.perm = new PackageParser.Permission(tree.perm.owner, 9543 new PermissionInfo(bp.pendingInfo)); 9544 bp.perm.info.packageName = tree.perm.info.packageName; 9545 bp.perm.info.name = bp.name; 9546 bp.uid = tree.uid; 9547 } 9548 } 9549 } 9550 if (bp.packageSetting == null) { 9551 // We may not yet have parsed the package, so just see if 9552 // we still know about its settings. 9553 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9554 } 9555 if (bp.packageSetting == null) { 9556 Slog.w(TAG, "Removing dangling permission: " + bp.name 9557 + " from package " + bp.sourcePackage); 9558 it.remove(); 9559 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9560 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9561 Slog.i(TAG, "Removing old permission: " + bp.name 9562 + " from package " + bp.sourcePackage); 9563 flags |= UPDATE_PERMISSIONS_ALL; 9564 it.remove(); 9565 } 9566 } 9567 } 9568 9569 // Now update the permissions for all packages, in particular 9570 // replace the granted permissions of the system packages. 9571 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9572 for (PackageParser.Package pkg : mPackages.values()) { 9573 if (pkg != pkgInfo) { 9574 // Only replace for packages on requested volume 9575 final String volumeUuid = getVolumeUuidForPackage(pkg); 9576 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9577 && Objects.equals(replaceVolumeUuid, volumeUuid); 9578 grantPermissionsLPw(pkg, replace, changingPkg); 9579 } 9580 } 9581 } 9582 9583 if (pkgInfo != null) { 9584 // Only replace for packages on requested volume 9585 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9586 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9587 && Objects.equals(replaceVolumeUuid, volumeUuid); 9588 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9589 } 9590 } 9591 9592 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9593 String packageOfInterest) { 9594 // IMPORTANT: There are two types of permissions: install and runtime. 9595 // Install time permissions are granted when the app is installed to 9596 // all device users and users added in the future. Runtime permissions 9597 // are granted at runtime explicitly to specific users. Normal and signature 9598 // protected permissions are install time permissions. Dangerous permissions 9599 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9600 // otherwise they are runtime permissions. This function does not manage 9601 // runtime permissions except for the case an app targeting Lollipop MR1 9602 // being upgraded to target a newer SDK, in which case dangerous permissions 9603 // are transformed from install time to runtime ones. 9604 9605 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9606 if (ps == null) { 9607 return; 9608 } 9609 9610 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9611 9612 PermissionsState permissionsState = ps.getPermissionsState(); 9613 PermissionsState origPermissions = permissionsState; 9614 9615 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9616 9617 boolean runtimePermissionsRevoked = false; 9618 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9619 9620 boolean changedInstallPermission = false; 9621 9622 if (replace) { 9623 ps.installPermissionsFixed = false; 9624 if (!ps.isSharedUser()) { 9625 origPermissions = new PermissionsState(permissionsState); 9626 permissionsState.reset(); 9627 } else { 9628 // We need to know only about runtime permission changes since the 9629 // calling code always writes the install permissions state but 9630 // the runtime ones are written only if changed. The only cases of 9631 // changed runtime permissions here are promotion of an install to 9632 // runtime and revocation of a runtime from a shared user. 9633 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9634 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9635 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9636 runtimePermissionsRevoked = true; 9637 } 9638 } 9639 } 9640 9641 permissionsState.setGlobalGids(mGlobalGids); 9642 9643 final int N = pkg.requestedPermissions.size(); 9644 for (int i=0; i<N; i++) { 9645 final String name = pkg.requestedPermissions.get(i); 9646 final BasePermission bp = mSettings.mPermissions.get(name); 9647 9648 if (DEBUG_INSTALL) { 9649 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9650 } 9651 9652 if (bp == null || bp.packageSetting == null) { 9653 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9654 Slog.w(TAG, "Unknown permission " + name 9655 + " in package " + pkg.packageName); 9656 } 9657 continue; 9658 } 9659 9660 final String perm = bp.name; 9661 boolean allowedSig = false; 9662 int grant = GRANT_DENIED; 9663 9664 // Keep track of app op permissions. 9665 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9666 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9667 if (pkgs == null) { 9668 pkgs = new ArraySet<>(); 9669 mAppOpPermissionPackages.put(bp.name, pkgs); 9670 } 9671 pkgs.add(pkg.packageName); 9672 } 9673 9674 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9675 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9676 >= Build.VERSION_CODES.M; 9677 switch (level) { 9678 case PermissionInfo.PROTECTION_NORMAL: { 9679 // For all apps normal permissions are install time ones. 9680 grant = GRANT_INSTALL; 9681 } break; 9682 9683 case PermissionInfo.PROTECTION_DANGEROUS: { 9684 // If a permission review is required for legacy apps we represent 9685 // their permissions as always granted runtime ones since we need 9686 // to keep the review required permission flag per user while an 9687 // install permission's state is shared across all users. 9688 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9689 // For legacy apps dangerous permissions are install time ones. 9690 grant = GRANT_INSTALL; 9691 } else if (origPermissions.hasInstallPermission(bp.name)) { 9692 // For legacy apps that became modern, install becomes runtime. 9693 grant = GRANT_UPGRADE; 9694 } else if (mPromoteSystemApps 9695 && isSystemApp(ps) 9696 && mExistingSystemPackages.contains(ps.name)) { 9697 // For legacy system apps, install becomes runtime. 9698 // We cannot check hasInstallPermission() for system apps since those 9699 // permissions were granted implicitly and not persisted pre-M. 9700 grant = GRANT_UPGRADE; 9701 } else { 9702 // For modern apps keep runtime permissions unchanged. 9703 grant = GRANT_RUNTIME; 9704 } 9705 } break; 9706 9707 case PermissionInfo.PROTECTION_SIGNATURE: { 9708 // For all apps signature permissions are install time ones. 9709 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9710 if (allowedSig) { 9711 grant = GRANT_INSTALL; 9712 } 9713 } break; 9714 } 9715 9716 if (DEBUG_INSTALL) { 9717 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9718 } 9719 9720 if (grant != GRANT_DENIED) { 9721 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9722 // If this is an existing, non-system package, then 9723 // we can't add any new permissions to it. 9724 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9725 // Except... if this is a permission that was added 9726 // to the platform (note: need to only do this when 9727 // updating the platform). 9728 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9729 grant = GRANT_DENIED; 9730 } 9731 } 9732 } 9733 9734 switch (grant) { 9735 case GRANT_INSTALL: { 9736 // Revoke this as runtime permission to handle the case of 9737 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9738 for (int userId : UserManagerService.getInstance().getUserIds()) { 9739 if (origPermissions.getRuntimePermissionState( 9740 bp.name, userId) != null) { 9741 // Revoke the runtime permission and clear the flags. 9742 origPermissions.revokeRuntimePermission(bp, userId); 9743 origPermissions.updatePermissionFlags(bp, userId, 9744 PackageManager.MASK_PERMISSION_FLAGS, 0); 9745 // If we revoked a permission permission, we have to write. 9746 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9747 changedRuntimePermissionUserIds, userId); 9748 } 9749 } 9750 // Grant an install permission. 9751 if (permissionsState.grantInstallPermission(bp) != 9752 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9753 changedInstallPermission = true; 9754 } 9755 } break; 9756 9757 case GRANT_RUNTIME: { 9758 // Grant previously granted runtime permissions. 9759 for (int userId : UserManagerService.getInstance().getUserIds()) { 9760 PermissionState permissionState = origPermissions 9761 .getRuntimePermissionState(bp.name, userId); 9762 int flags = permissionState != null 9763 ? permissionState.getFlags() : 0; 9764 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9765 if (permissionsState.grantRuntimePermission(bp, userId) == 9766 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9767 // If we cannot put the permission as it was, we have to write. 9768 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9769 changedRuntimePermissionUserIds, userId); 9770 } 9771 // If the app supports runtime permissions no need for a review. 9772 if (Build.PERMISSIONS_REVIEW_REQUIRED 9773 && appSupportsRuntimePermissions 9774 && (flags & PackageManager 9775 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9776 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9777 // Since we changed the flags, we have to write. 9778 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9779 changedRuntimePermissionUserIds, userId); 9780 } 9781 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9782 && !appSupportsRuntimePermissions) { 9783 // For legacy apps that need a permission review, every new 9784 // runtime permission is granted but it is pending a review. 9785 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9786 permissionsState.grantRuntimePermission(bp, userId); 9787 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9788 // We changed the permission and flags, hence have to write. 9789 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9790 changedRuntimePermissionUserIds, userId); 9791 } 9792 } 9793 // Propagate the permission flags. 9794 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9795 } 9796 } break; 9797 9798 case GRANT_UPGRADE: { 9799 // Grant runtime permissions for a previously held install permission. 9800 PermissionState permissionState = origPermissions 9801 .getInstallPermissionState(bp.name); 9802 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9803 9804 if (origPermissions.revokeInstallPermission(bp) 9805 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9806 // We will be transferring the permission flags, so clear them. 9807 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9808 PackageManager.MASK_PERMISSION_FLAGS, 0); 9809 changedInstallPermission = true; 9810 } 9811 9812 // If the permission is not to be promoted to runtime we ignore it and 9813 // also its other flags as they are not applicable to install permissions. 9814 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9815 for (int userId : currentUserIds) { 9816 if (permissionsState.grantRuntimePermission(bp, userId) != 9817 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9818 // Transfer the permission flags. 9819 permissionsState.updatePermissionFlags(bp, userId, 9820 flags, flags); 9821 // If we granted the permission, we have to write. 9822 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9823 changedRuntimePermissionUserIds, userId); 9824 } 9825 } 9826 } 9827 } break; 9828 9829 default: { 9830 if (packageOfInterest == null 9831 || packageOfInterest.equals(pkg.packageName)) { 9832 Slog.w(TAG, "Not granting permission " + perm 9833 + " to package " + pkg.packageName 9834 + " because it was previously installed without"); 9835 } 9836 } break; 9837 } 9838 } else { 9839 if (permissionsState.revokeInstallPermission(bp) != 9840 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9841 // Also drop the permission flags. 9842 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9843 PackageManager.MASK_PERMISSION_FLAGS, 0); 9844 changedInstallPermission = true; 9845 Slog.i(TAG, "Un-granting permission " + perm 9846 + " from package " + pkg.packageName 9847 + " (protectionLevel=" + bp.protectionLevel 9848 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9849 + ")"); 9850 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9851 // Don't print warning for app op permissions, since it is fine for them 9852 // not to be granted, there is a UI for the user to decide. 9853 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9854 Slog.w(TAG, "Not granting permission " + perm 9855 + " to package " + pkg.packageName 9856 + " (protectionLevel=" + bp.protectionLevel 9857 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9858 + ")"); 9859 } 9860 } 9861 } 9862 } 9863 9864 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9865 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9866 // This is the first that we have heard about this package, so the 9867 // permissions we have now selected are fixed until explicitly 9868 // changed. 9869 ps.installPermissionsFixed = true; 9870 } 9871 9872 // Persist the runtime permissions state for users with changes. If permissions 9873 // were revoked because no app in the shared user declares them we have to 9874 // write synchronously to avoid losing runtime permissions state. 9875 for (int userId : changedRuntimePermissionUserIds) { 9876 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9877 } 9878 9879 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9880 } 9881 9882 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9883 boolean allowed = false; 9884 final int NP = PackageParser.NEW_PERMISSIONS.length; 9885 for (int ip=0; ip<NP; ip++) { 9886 final PackageParser.NewPermissionInfo npi 9887 = PackageParser.NEW_PERMISSIONS[ip]; 9888 if (npi.name.equals(perm) 9889 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9890 allowed = true; 9891 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9892 + pkg.packageName); 9893 break; 9894 } 9895 } 9896 return allowed; 9897 } 9898 9899 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9900 BasePermission bp, PermissionsState origPermissions) { 9901 boolean allowed; 9902 allowed = (compareSignatures( 9903 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9904 == PackageManager.SIGNATURE_MATCH) 9905 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9906 == PackageManager.SIGNATURE_MATCH); 9907 if (!allowed && (bp.protectionLevel 9908 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9909 if (isSystemApp(pkg)) { 9910 // For updated system applications, a system permission 9911 // is granted only if it had been defined by the original application. 9912 if (pkg.isUpdatedSystemApp()) { 9913 final PackageSetting sysPs = mSettings 9914 .getDisabledSystemPkgLPr(pkg.packageName); 9915 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9916 // If the original was granted this permission, we take 9917 // that grant decision as read and propagate it to the 9918 // update. 9919 if (sysPs.isPrivileged()) { 9920 allowed = true; 9921 } 9922 } else { 9923 // The system apk may have been updated with an older 9924 // version of the one on the data partition, but which 9925 // granted a new system permission that it didn't have 9926 // before. In this case we do want to allow the app to 9927 // now get the new permission if the ancestral apk is 9928 // privileged to get it. 9929 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9930 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9931 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9932 allowed = true; 9933 break; 9934 } 9935 } 9936 } 9937 // Also if a privileged parent package on the system image or any of 9938 // its children requested a privileged permission, the updated child 9939 // packages can also get the permission. 9940 if (pkg.parentPackage != null) { 9941 final PackageSetting disabledSysParentPs = mSettings 9942 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9943 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9944 && disabledSysParentPs.isPrivileged()) { 9945 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9946 allowed = true; 9947 } else if (disabledSysParentPs.pkg.childPackages != null) { 9948 final int count = disabledSysParentPs.pkg.childPackages.size(); 9949 for (int i = 0; i < count; i++) { 9950 PackageParser.Package disabledSysChildPkg = 9951 disabledSysParentPs.pkg.childPackages.get(i); 9952 if (isPackageRequestingPermission(disabledSysChildPkg, 9953 perm)) { 9954 allowed = true; 9955 break; 9956 } 9957 } 9958 } 9959 } 9960 } 9961 } 9962 } else { 9963 allowed = isPrivilegedApp(pkg); 9964 } 9965 } 9966 } 9967 if (!allowed) { 9968 if (!allowed && (bp.protectionLevel 9969 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9970 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9971 // If this was a previously normal/dangerous permission that got moved 9972 // to a system permission as part of the runtime permission redesign, then 9973 // we still want to blindly grant it to old apps. 9974 allowed = true; 9975 } 9976 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9977 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9978 // If this permission is to be granted to the system installer and 9979 // this app is an installer, then it gets the permission. 9980 allowed = true; 9981 } 9982 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9983 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9984 // If this permission is to be granted to the system verifier and 9985 // this app is a verifier, then it gets the permission. 9986 allowed = true; 9987 } 9988 if (!allowed && (bp.protectionLevel 9989 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9990 && isSystemApp(pkg)) { 9991 // Any pre-installed system app is allowed to get this permission. 9992 allowed = true; 9993 } 9994 if (!allowed && (bp.protectionLevel 9995 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9996 // For development permissions, a development permission 9997 // is granted only if it was already granted. 9998 allowed = origPermissions.hasInstallPermission(perm); 9999 } 10000 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10001 && pkg.packageName.equals(mSetupWizardPackage)) { 10002 // If this permission is to be granted to the system setup wizard and 10003 // this app is a setup wizard, then it gets the permission. 10004 allowed = true; 10005 } 10006 } 10007 return allowed; 10008 } 10009 10010 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10011 final int permCount = pkg.requestedPermissions.size(); 10012 for (int j = 0; j < permCount; j++) { 10013 String requestedPermission = pkg.requestedPermissions.get(j); 10014 if (permission.equals(requestedPermission)) { 10015 return true; 10016 } 10017 } 10018 return false; 10019 } 10020 10021 final class ActivityIntentResolver 10022 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10023 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10024 boolean defaultOnly, int userId) { 10025 if (!sUserManager.exists(userId)) return null; 10026 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10027 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10028 } 10029 10030 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10031 int userId) { 10032 if (!sUserManager.exists(userId)) return null; 10033 mFlags = flags; 10034 return super.queryIntent(intent, resolvedType, 10035 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10036 } 10037 10038 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10039 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10040 if (!sUserManager.exists(userId)) return null; 10041 if (packageActivities == null) { 10042 return null; 10043 } 10044 mFlags = flags; 10045 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10046 final int N = packageActivities.size(); 10047 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10048 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10049 10050 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10051 for (int i = 0; i < N; ++i) { 10052 intentFilters = packageActivities.get(i).intents; 10053 if (intentFilters != null && intentFilters.size() > 0) { 10054 PackageParser.ActivityIntentInfo[] array = 10055 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10056 intentFilters.toArray(array); 10057 listCut.add(array); 10058 } 10059 } 10060 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10061 } 10062 10063 /** 10064 * Finds a privileged activity that matches the specified activity names. 10065 */ 10066 private PackageParser.Activity findMatchingActivity( 10067 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10068 for (PackageParser.Activity sysActivity : activityList) { 10069 if (sysActivity.info.name.equals(activityInfo.name)) { 10070 return sysActivity; 10071 } 10072 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10073 return sysActivity; 10074 } 10075 if (sysActivity.info.targetActivity != null) { 10076 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10077 return sysActivity; 10078 } 10079 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10080 return sysActivity; 10081 } 10082 } 10083 } 10084 return null; 10085 } 10086 10087 public class IterGenerator<E> { 10088 public Iterator<E> generate(ActivityIntentInfo info) { 10089 return null; 10090 } 10091 } 10092 10093 public class ActionIterGenerator extends IterGenerator<String> { 10094 @Override 10095 public Iterator<String> generate(ActivityIntentInfo info) { 10096 return info.actionsIterator(); 10097 } 10098 } 10099 10100 public class CategoriesIterGenerator extends IterGenerator<String> { 10101 @Override 10102 public Iterator<String> generate(ActivityIntentInfo info) { 10103 return info.categoriesIterator(); 10104 } 10105 } 10106 10107 public class SchemesIterGenerator extends IterGenerator<String> { 10108 @Override 10109 public Iterator<String> generate(ActivityIntentInfo info) { 10110 return info.schemesIterator(); 10111 } 10112 } 10113 10114 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10115 @Override 10116 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10117 return info.authoritiesIterator(); 10118 } 10119 } 10120 10121 /** 10122 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10123 * MODIFIED. Do not pass in a list that should not be changed. 10124 */ 10125 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10126 IterGenerator<T> generator, Iterator<T> searchIterator) { 10127 // loop through the set of actions; every one must be found in the intent filter 10128 while (searchIterator.hasNext()) { 10129 // we must have at least one filter in the list to consider a match 10130 if (intentList.size() == 0) { 10131 break; 10132 } 10133 10134 final T searchAction = searchIterator.next(); 10135 10136 // loop through the set of intent filters 10137 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10138 while (intentIter.hasNext()) { 10139 final ActivityIntentInfo intentInfo = intentIter.next(); 10140 boolean selectionFound = false; 10141 10142 // loop through the intent filter's selection criteria; at least one 10143 // of them must match the searched criteria 10144 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10145 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10146 final T intentSelection = intentSelectionIter.next(); 10147 if (intentSelection != null && intentSelection.equals(searchAction)) { 10148 selectionFound = true; 10149 break; 10150 } 10151 } 10152 10153 // the selection criteria wasn't found in this filter's set; this filter 10154 // is not a potential match 10155 if (!selectionFound) { 10156 intentIter.remove(); 10157 } 10158 } 10159 } 10160 } 10161 10162 private boolean isProtectedAction(ActivityIntentInfo filter) { 10163 final Iterator<String> actionsIter = filter.actionsIterator(); 10164 while (actionsIter != null && actionsIter.hasNext()) { 10165 final String filterAction = actionsIter.next(); 10166 if (PROTECTED_ACTIONS.contains(filterAction)) { 10167 return true; 10168 } 10169 } 10170 return false; 10171 } 10172 10173 /** 10174 * Adjusts the priority of the given intent filter according to policy. 10175 * <p> 10176 * <ul> 10177 * <li>The priority for non privileged applications is capped to '0'</li> 10178 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10179 * <li>The priority for unbundled updates to privileged applications is capped to the 10180 * priority defined on the system partition</li> 10181 * </ul> 10182 * <p> 10183 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10184 * allowed to obtain any priority on any action. 10185 */ 10186 private void adjustPriority( 10187 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10188 // nothing to do; priority is fine as-is 10189 if (intent.getPriority() <= 0) { 10190 return; 10191 } 10192 10193 final ActivityInfo activityInfo = intent.activity.info; 10194 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10195 10196 final boolean privilegedApp = 10197 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10198 if (!privilegedApp) { 10199 // non-privileged applications can never define a priority >0 10200 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10201 + " package: " + applicationInfo.packageName 10202 + " activity: " + intent.activity.className 10203 + " origPrio: " + intent.getPriority()); 10204 intent.setPriority(0); 10205 return; 10206 } 10207 10208 if (systemActivities == null) { 10209 // the system package is not disabled; we're parsing the system partition 10210 if (isProtectedAction(intent)) { 10211 if (mDeferProtectedFilters) { 10212 // We can't deal with these just yet. No component should ever obtain a 10213 // >0 priority for a protected actions, with ONE exception -- the setup 10214 // wizard. The setup wizard, however, cannot be known until we're able to 10215 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10216 // until all intent filters have been processed. Chicken, meet egg. 10217 // Let the filter temporarily have a high priority and rectify the 10218 // priorities after all system packages have been scanned. 10219 mProtectedFilters.add(intent); 10220 if (DEBUG_FILTERS) { 10221 Slog.i(TAG, "Protected action; save for later;" 10222 + " package: " + applicationInfo.packageName 10223 + " activity: " + intent.activity.className 10224 + " origPrio: " + intent.getPriority()); 10225 } 10226 return; 10227 } else { 10228 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10229 Slog.i(TAG, "No setup wizard;" 10230 + " All protected intents capped to priority 0"); 10231 } 10232 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10233 if (DEBUG_FILTERS) { 10234 Slog.i(TAG, "Found setup wizard;" 10235 + " allow priority " + intent.getPriority() + ";" 10236 + " package: " + intent.activity.info.packageName 10237 + " activity: " + intent.activity.className 10238 + " priority: " + intent.getPriority()); 10239 } 10240 // setup wizard gets whatever it wants 10241 return; 10242 } 10243 Slog.w(TAG, "Protected action; cap priority to 0;" 10244 + " package: " + intent.activity.info.packageName 10245 + " activity: " + intent.activity.className 10246 + " origPrio: " + intent.getPriority()); 10247 intent.setPriority(0); 10248 return; 10249 } 10250 } 10251 // privileged apps on the system image get whatever priority they request 10252 return; 10253 } 10254 10255 // privileged app unbundled update ... try to find the same activity 10256 final PackageParser.Activity foundActivity = 10257 findMatchingActivity(systemActivities, activityInfo); 10258 if (foundActivity == null) { 10259 // this is a new activity; it cannot obtain >0 priority 10260 if (DEBUG_FILTERS) { 10261 Slog.i(TAG, "New activity; cap priority to 0;" 10262 + " package: " + applicationInfo.packageName 10263 + " activity: " + intent.activity.className 10264 + " origPrio: " + intent.getPriority()); 10265 } 10266 intent.setPriority(0); 10267 return; 10268 } 10269 10270 // found activity, now check for filter equivalence 10271 10272 // a shallow copy is enough; we modify the list, not its contents 10273 final List<ActivityIntentInfo> intentListCopy = 10274 new ArrayList<>(foundActivity.intents); 10275 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10276 10277 // find matching action subsets 10278 final Iterator<String> actionsIterator = intent.actionsIterator(); 10279 if (actionsIterator != null) { 10280 getIntentListSubset( 10281 intentListCopy, new ActionIterGenerator(), actionsIterator); 10282 if (intentListCopy.size() == 0) { 10283 // no more intents to match; we're not equivalent 10284 if (DEBUG_FILTERS) { 10285 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10286 + " package: " + applicationInfo.packageName 10287 + " activity: " + intent.activity.className 10288 + " origPrio: " + intent.getPriority()); 10289 } 10290 intent.setPriority(0); 10291 return; 10292 } 10293 } 10294 10295 // find matching category subsets 10296 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10297 if (categoriesIterator != null) { 10298 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10299 categoriesIterator); 10300 if (intentListCopy.size() == 0) { 10301 // no more intents to match; we're not equivalent 10302 if (DEBUG_FILTERS) { 10303 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10304 + " package: " + applicationInfo.packageName 10305 + " activity: " + intent.activity.className 10306 + " origPrio: " + intent.getPriority()); 10307 } 10308 intent.setPriority(0); 10309 return; 10310 } 10311 } 10312 10313 // find matching schemes subsets 10314 final Iterator<String> schemesIterator = intent.schemesIterator(); 10315 if (schemesIterator != null) { 10316 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10317 schemesIterator); 10318 if (intentListCopy.size() == 0) { 10319 // no more intents to match; we're not equivalent 10320 if (DEBUG_FILTERS) { 10321 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10322 + " package: " + applicationInfo.packageName 10323 + " activity: " + intent.activity.className 10324 + " origPrio: " + intent.getPriority()); 10325 } 10326 intent.setPriority(0); 10327 return; 10328 } 10329 } 10330 10331 // find matching authorities subsets 10332 final Iterator<IntentFilter.AuthorityEntry> 10333 authoritiesIterator = intent.authoritiesIterator(); 10334 if (authoritiesIterator != null) { 10335 getIntentListSubset(intentListCopy, 10336 new AuthoritiesIterGenerator(), 10337 authoritiesIterator); 10338 if (intentListCopy.size() == 0) { 10339 // no more intents to match; we're not equivalent 10340 if (DEBUG_FILTERS) { 10341 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10342 + " package: " + applicationInfo.packageName 10343 + " activity: " + intent.activity.className 10344 + " origPrio: " + intent.getPriority()); 10345 } 10346 intent.setPriority(0); 10347 return; 10348 } 10349 } 10350 10351 // we found matching filter(s); app gets the max priority of all intents 10352 int cappedPriority = 0; 10353 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10354 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10355 } 10356 if (intent.getPriority() > cappedPriority) { 10357 if (DEBUG_FILTERS) { 10358 Slog.i(TAG, "Found matching filter(s);" 10359 + " cap priority to " + cappedPriority + ";" 10360 + " package: " + applicationInfo.packageName 10361 + " activity: " + intent.activity.className 10362 + " origPrio: " + intent.getPriority()); 10363 } 10364 intent.setPriority(cappedPriority); 10365 return; 10366 } 10367 // all this for nothing; the requested priority was <= what was on the system 10368 } 10369 10370 public final void addActivity(PackageParser.Activity a, String type) { 10371 mActivities.put(a.getComponentName(), a); 10372 if (DEBUG_SHOW_INFO) 10373 Log.v( 10374 TAG, " " + type + " " + 10375 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10376 if (DEBUG_SHOW_INFO) 10377 Log.v(TAG, " Class=" + a.info.name); 10378 final int NI = a.intents.size(); 10379 for (int j=0; j<NI; j++) { 10380 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10381 if ("activity".equals(type)) { 10382 final PackageSetting ps = 10383 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10384 final List<PackageParser.Activity> systemActivities = 10385 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10386 adjustPriority(systemActivities, intent); 10387 } 10388 if (DEBUG_SHOW_INFO) { 10389 Log.v(TAG, " IntentFilter:"); 10390 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10391 } 10392 if (!intent.debugCheck()) { 10393 Log.w(TAG, "==> For Activity " + a.info.name); 10394 } 10395 addFilter(intent); 10396 } 10397 } 10398 10399 public final void removeActivity(PackageParser.Activity a, String type) { 10400 mActivities.remove(a.getComponentName()); 10401 if (DEBUG_SHOW_INFO) { 10402 Log.v(TAG, " " + type + " " 10403 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10404 : a.info.name) + ":"); 10405 Log.v(TAG, " Class=" + a.info.name); 10406 } 10407 final int NI = a.intents.size(); 10408 for (int j=0; j<NI; j++) { 10409 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10410 if (DEBUG_SHOW_INFO) { 10411 Log.v(TAG, " IntentFilter:"); 10412 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10413 } 10414 removeFilter(intent); 10415 } 10416 } 10417 10418 @Override 10419 protected boolean allowFilterResult( 10420 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10421 ActivityInfo filterAi = filter.activity.info; 10422 for (int i=dest.size()-1; i>=0; i--) { 10423 ActivityInfo destAi = dest.get(i).activityInfo; 10424 if (destAi.name == filterAi.name 10425 && destAi.packageName == filterAi.packageName) { 10426 return false; 10427 } 10428 } 10429 return true; 10430 } 10431 10432 @Override 10433 protected ActivityIntentInfo[] newArray(int size) { 10434 return new ActivityIntentInfo[size]; 10435 } 10436 10437 @Override 10438 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10439 if (!sUserManager.exists(userId)) return true; 10440 PackageParser.Package p = filter.activity.owner; 10441 if (p != null) { 10442 PackageSetting ps = (PackageSetting)p.mExtras; 10443 if (ps != null) { 10444 // System apps are never considered stopped for purposes of 10445 // filtering, because there may be no way for the user to 10446 // actually re-launch them. 10447 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10448 && ps.getStopped(userId); 10449 } 10450 } 10451 return false; 10452 } 10453 10454 @Override 10455 protected boolean isPackageForFilter(String packageName, 10456 PackageParser.ActivityIntentInfo info) { 10457 return packageName.equals(info.activity.owner.packageName); 10458 } 10459 10460 @Override 10461 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10462 int match, int userId) { 10463 if (!sUserManager.exists(userId)) return null; 10464 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10465 return null; 10466 } 10467 final PackageParser.Activity activity = info.activity; 10468 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10469 if (ps == null) { 10470 return null; 10471 } 10472 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10473 ps.readUserState(userId), userId); 10474 if (ai == null) { 10475 return null; 10476 } 10477 final ResolveInfo res = new ResolveInfo(); 10478 res.activityInfo = ai; 10479 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10480 res.filter = info; 10481 } 10482 if (info != null) { 10483 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10484 } 10485 res.priority = info.getPriority(); 10486 res.preferredOrder = activity.owner.mPreferredOrder; 10487 //System.out.println("Result: " + res.activityInfo.className + 10488 // " = " + res.priority); 10489 res.match = match; 10490 res.isDefault = info.hasDefault; 10491 res.labelRes = info.labelRes; 10492 res.nonLocalizedLabel = info.nonLocalizedLabel; 10493 if (userNeedsBadging(userId)) { 10494 res.noResourceId = true; 10495 } else { 10496 res.icon = info.icon; 10497 } 10498 res.iconResourceId = info.icon; 10499 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10500 return res; 10501 } 10502 10503 @Override 10504 protected void sortResults(List<ResolveInfo> results) { 10505 Collections.sort(results, mResolvePrioritySorter); 10506 } 10507 10508 @Override 10509 protected void dumpFilter(PrintWriter out, String prefix, 10510 PackageParser.ActivityIntentInfo filter) { 10511 out.print(prefix); out.print( 10512 Integer.toHexString(System.identityHashCode(filter.activity))); 10513 out.print(' '); 10514 filter.activity.printComponentShortName(out); 10515 out.print(" filter "); 10516 out.println(Integer.toHexString(System.identityHashCode(filter))); 10517 } 10518 10519 @Override 10520 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10521 return filter.activity; 10522 } 10523 10524 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10525 PackageParser.Activity activity = (PackageParser.Activity)label; 10526 out.print(prefix); out.print( 10527 Integer.toHexString(System.identityHashCode(activity))); 10528 out.print(' '); 10529 activity.printComponentShortName(out); 10530 if (count > 1) { 10531 out.print(" ("); out.print(count); out.print(" filters)"); 10532 } 10533 out.println(); 10534 } 10535 10536 // Keys are String (activity class name), values are Activity. 10537 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10538 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10539 private int mFlags; 10540 } 10541 10542 private final class ServiceIntentResolver 10543 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10544 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10545 boolean defaultOnly, int userId) { 10546 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10547 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10548 } 10549 10550 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10551 int userId) { 10552 if (!sUserManager.exists(userId)) return null; 10553 mFlags = flags; 10554 return super.queryIntent(intent, resolvedType, 10555 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10556 } 10557 10558 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10559 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10560 if (!sUserManager.exists(userId)) return null; 10561 if (packageServices == null) { 10562 return null; 10563 } 10564 mFlags = flags; 10565 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10566 final int N = packageServices.size(); 10567 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10568 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10569 10570 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10571 for (int i = 0; i < N; ++i) { 10572 intentFilters = packageServices.get(i).intents; 10573 if (intentFilters != null && intentFilters.size() > 0) { 10574 PackageParser.ServiceIntentInfo[] array = 10575 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10576 intentFilters.toArray(array); 10577 listCut.add(array); 10578 } 10579 } 10580 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10581 } 10582 10583 public final void addService(PackageParser.Service s) { 10584 mServices.put(s.getComponentName(), s); 10585 if (DEBUG_SHOW_INFO) { 10586 Log.v(TAG, " " 10587 + (s.info.nonLocalizedLabel != null 10588 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10589 Log.v(TAG, " Class=" + s.info.name); 10590 } 10591 final int NI = s.intents.size(); 10592 int j; 10593 for (j=0; j<NI; j++) { 10594 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10595 if (DEBUG_SHOW_INFO) { 10596 Log.v(TAG, " IntentFilter:"); 10597 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10598 } 10599 if (!intent.debugCheck()) { 10600 Log.w(TAG, "==> For Service " + s.info.name); 10601 } 10602 addFilter(intent); 10603 } 10604 } 10605 10606 public final void removeService(PackageParser.Service s) { 10607 mServices.remove(s.getComponentName()); 10608 if (DEBUG_SHOW_INFO) { 10609 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10610 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10611 Log.v(TAG, " Class=" + s.info.name); 10612 } 10613 final int NI = s.intents.size(); 10614 int j; 10615 for (j=0; j<NI; j++) { 10616 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10617 if (DEBUG_SHOW_INFO) { 10618 Log.v(TAG, " IntentFilter:"); 10619 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10620 } 10621 removeFilter(intent); 10622 } 10623 } 10624 10625 @Override 10626 protected boolean allowFilterResult( 10627 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10628 ServiceInfo filterSi = filter.service.info; 10629 for (int i=dest.size()-1; i>=0; i--) { 10630 ServiceInfo destAi = dest.get(i).serviceInfo; 10631 if (destAi.name == filterSi.name 10632 && destAi.packageName == filterSi.packageName) { 10633 return false; 10634 } 10635 } 10636 return true; 10637 } 10638 10639 @Override 10640 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10641 return new PackageParser.ServiceIntentInfo[size]; 10642 } 10643 10644 @Override 10645 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10646 if (!sUserManager.exists(userId)) return true; 10647 PackageParser.Package p = filter.service.owner; 10648 if (p != null) { 10649 PackageSetting ps = (PackageSetting)p.mExtras; 10650 if (ps != null) { 10651 // System apps are never considered stopped for purposes of 10652 // filtering, because there may be no way for the user to 10653 // actually re-launch them. 10654 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10655 && ps.getStopped(userId); 10656 } 10657 } 10658 return false; 10659 } 10660 10661 @Override 10662 protected boolean isPackageForFilter(String packageName, 10663 PackageParser.ServiceIntentInfo info) { 10664 return packageName.equals(info.service.owner.packageName); 10665 } 10666 10667 @Override 10668 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10669 int match, int userId) { 10670 if (!sUserManager.exists(userId)) return null; 10671 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10672 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10673 return null; 10674 } 10675 final PackageParser.Service service = info.service; 10676 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10677 if (ps == null) { 10678 return null; 10679 } 10680 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10681 ps.readUserState(userId), userId); 10682 if (si == null) { 10683 return null; 10684 } 10685 final ResolveInfo res = new ResolveInfo(); 10686 res.serviceInfo = si; 10687 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10688 res.filter = filter; 10689 } 10690 res.priority = info.getPriority(); 10691 res.preferredOrder = service.owner.mPreferredOrder; 10692 res.match = match; 10693 res.isDefault = info.hasDefault; 10694 res.labelRes = info.labelRes; 10695 res.nonLocalizedLabel = info.nonLocalizedLabel; 10696 res.icon = info.icon; 10697 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10698 return res; 10699 } 10700 10701 @Override 10702 protected void sortResults(List<ResolveInfo> results) { 10703 Collections.sort(results, mResolvePrioritySorter); 10704 } 10705 10706 @Override 10707 protected void dumpFilter(PrintWriter out, String prefix, 10708 PackageParser.ServiceIntentInfo filter) { 10709 out.print(prefix); out.print( 10710 Integer.toHexString(System.identityHashCode(filter.service))); 10711 out.print(' '); 10712 filter.service.printComponentShortName(out); 10713 out.print(" filter "); 10714 out.println(Integer.toHexString(System.identityHashCode(filter))); 10715 } 10716 10717 @Override 10718 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10719 return filter.service; 10720 } 10721 10722 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10723 PackageParser.Service service = (PackageParser.Service)label; 10724 out.print(prefix); out.print( 10725 Integer.toHexString(System.identityHashCode(service))); 10726 out.print(' '); 10727 service.printComponentShortName(out); 10728 if (count > 1) { 10729 out.print(" ("); out.print(count); out.print(" filters)"); 10730 } 10731 out.println(); 10732 } 10733 10734// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10735// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10736// final List<ResolveInfo> retList = Lists.newArrayList(); 10737// while (i.hasNext()) { 10738// final ResolveInfo resolveInfo = (ResolveInfo) i; 10739// if (isEnabledLP(resolveInfo.serviceInfo)) { 10740// retList.add(resolveInfo); 10741// } 10742// } 10743// return retList; 10744// } 10745 10746 // Keys are String (activity class name), values are Activity. 10747 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10748 = new ArrayMap<ComponentName, PackageParser.Service>(); 10749 private int mFlags; 10750 }; 10751 10752 private final class ProviderIntentResolver 10753 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10754 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10755 boolean defaultOnly, int userId) { 10756 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10757 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10758 } 10759 10760 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10761 int userId) { 10762 if (!sUserManager.exists(userId)) 10763 return null; 10764 mFlags = flags; 10765 return super.queryIntent(intent, resolvedType, 10766 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10767 } 10768 10769 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10770 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10771 if (!sUserManager.exists(userId)) 10772 return null; 10773 if (packageProviders == null) { 10774 return null; 10775 } 10776 mFlags = flags; 10777 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10778 final int N = packageProviders.size(); 10779 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10780 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10781 10782 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10783 for (int i = 0; i < N; ++i) { 10784 intentFilters = packageProviders.get(i).intents; 10785 if (intentFilters != null && intentFilters.size() > 0) { 10786 PackageParser.ProviderIntentInfo[] array = 10787 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10788 intentFilters.toArray(array); 10789 listCut.add(array); 10790 } 10791 } 10792 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10793 } 10794 10795 public final void addProvider(PackageParser.Provider p) { 10796 if (mProviders.containsKey(p.getComponentName())) { 10797 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10798 return; 10799 } 10800 10801 mProviders.put(p.getComponentName(), p); 10802 if (DEBUG_SHOW_INFO) { 10803 Log.v(TAG, " " 10804 + (p.info.nonLocalizedLabel != null 10805 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10806 Log.v(TAG, " Class=" + p.info.name); 10807 } 10808 final int NI = p.intents.size(); 10809 int j; 10810 for (j = 0; j < NI; j++) { 10811 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10812 if (DEBUG_SHOW_INFO) { 10813 Log.v(TAG, " IntentFilter:"); 10814 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10815 } 10816 if (!intent.debugCheck()) { 10817 Log.w(TAG, "==> For Provider " + p.info.name); 10818 } 10819 addFilter(intent); 10820 } 10821 } 10822 10823 public final void removeProvider(PackageParser.Provider p) { 10824 mProviders.remove(p.getComponentName()); 10825 if (DEBUG_SHOW_INFO) { 10826 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10827 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10828 Log.v(TAG, " Class=" + p.info.name); 10829 } 10830 final int NI = p.intents.size(); 10831 int j; 10832 for (j = 0; j < NI; j++) { 10833 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10834 if (DEBUG_SHOW_INFO) { 10835 Log.v(TAG, " IntentFilter:"); 10836 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10837 } 10838 removeFilter(intent); 10839 } 10840 } 10841 10842 @Override 10843 protected boolean allowFilterResult( 10844 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10845 ProviderInfo filterPi = filter.provider.info; 10846 for (int i = dest.size() - 1; i >= 0; i--) { 10847 ProviderInfo destPi = dest.get(i).providerInfo; 10848 if (destPi.name == filterPi.name 10849 && destPi.packageName == filterPi.packageName) { 10850 return false; 10851 } 10852 } 10853 return true; 10854 } 10855 10856 @Override 10857 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10858 return new PackageParser.ProviderIntentInfo[size]; 10859 } 10860 10861 @Override 10862 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10863 if (!sUserManager.exists(userId)) 10864 return true; 10865 PackageParser.Package p = filter.provider.owner; 10866 if (p != null) { 10867 PackageSetting ps = (PackageSetting) p.mExtras; 10868 if (ps != null) { 10869 // System apps are never considered stopped for purposes of 10870 // filtering, because there may be no way for the user to 10871 // actually re-launch them. 10872 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10873 && ps.getStopped(userId); 10874 } 10875 } 10876 return false; 10877 } 10878 10879 @Override 10880 protected boolean isPackageForFilter(String packageName, 10881 PackageParser.ProviderIntentInfo info) { 10882 return packageName.equals(info.provider.owner.packageName); 10883 } 10884 10885 @Override 10886 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10887 int match, int userId) { 10888 if (!sUserManager.exists(userId)) 10889 return null; 10890 final PackageParser.ProviderIntentInfo info = filter; 10891 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10892 return null; 10893 } 10894 final PackageParser.Provider provider = info.provider; 10895 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10896 if (ps == null) { 10897 return null; 10898 } 10899 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10900 ps.readUserState(userId), userId); 10901 if (pi == null) { 10902 return null; 10903 } 10904 final ResolveInfo res = new ResolveInfo(); 10905 res.providerInfo = pi; 10906 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10907 res.filter = filter; 10908 } 10909 res.priority = info.getPriority(); 10910 res.preferredOrder = provider.owner.mPreferredOrder; 10911 res.match = match; 10912 res.isDefault = info.hasDefault; 10913 res.labelRes = info.labelRes; 10914 res.nonLocalizedLabel = info.nonLocalizedLabel; 10915 res.icon = info.icon; 10916 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10917 return res; 10918 } 10919 10920 @Override 10921 protected void sortResults(List<ResolveInfo> results) { 10922 Collections.sort(results, mResolvePrioritySorter); 10923 } 10924 10925 @Override 10926 protected void dumpFilter(PrintWriter out, String prefix, 10927 PackageParser.ProviderIntentInfo filter) { 10928 out.print(prefix); 10929 out.print( 10930 Integer.toHexString(System.identityHashCode(filter.provider))); 10931 out.print(' '); 10932 filter.provider.printComponentShortName(out); 10933 out.print(" filter "); 10934 out.println(Integer.toHexString(System.identityHashCode(filter))); 10935 } 10936 10937 @Override 10938 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10939 return filter.provider; 10940 } 10941 10942 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10943 PackageParser.Provider provider = (PackageParser.Provider)label; 10944 out.print(prefix); out.print( 10945 Integer.toHexString(System.identityHashCode(provider))); 10946 out.print(' '); 10947 provider.printComponentShortName(out); 10948 if (count > 1) { 10949 out.print(" ("); out.print(count); out.print(" filters)"); 10950 } 10951 out.println(); 10952 } 10953 10954 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10955 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10956 private int mFlags; 10957 } 10958 10959 private static final class EphemeralIntentResolver 10960 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10961 @Override 10962 protected EphemeralResolveIntentInfo[] newArray(int size) { 10963 return new EphemeralResolveIntentInfo[size]; 10964 } 10965 10966 @Override 10967 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10968 return true; 10969 } 10970 10971 @Override 10972 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10973 int userId) { 10974 if (!sUserManager.exists(userId)) { 10975 return null; 10976 } 10977 return info.getEphemeralResolveInfo(); 10978 } 10979 } 10980 10981 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10982 new Comparator<ResolveInfo>() { 10983 public int compare(ResolveInfo r1, ResolveInfo r2) { 10984 int v1 = r1.priority; 10985 int v2 = r2.priority; 10986 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10987 if (v1 != v2) { 10988 return (v1 > v2) ? -1 : 1; 10989 } 10990 v1 = r1.preferredOrder; 10991 v2 = r2.preferredOrder; 10992 if (v1 != v2) { 10993 return (v1 > v2) ? -1 : 1; 10994 } 10995 if (r1.isDefault != r2.isDefault) { 10996 return r1.isDefault ? -1 : 1; 10997 } 10998 v1 = r1.match; 10999 v2 = r2.match; 11000 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11001 if (v1 != v2) { 11002 return (v1 > v2) ? -1 : 1; 11003 } 11004 if (r1.system != r2.system) { 11005 return r1.system ? -1 : 1; 11006 } 11007 if (r1.activityInfo != null) { 11008 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11009 } 11010 if (r1.serviceInfo != null) { 11011 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11012 } 11013 if (r1.providerInfo != null) { 11014 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11015 } 11016 return 0; 11017 } 11018 }; 11019 11020 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11021 new Comparator<ProviderInfo>() { 11022 public int compare(ProviderInfo p1, ProviderInfo p2) { 11023 final int v1 = p1.initOrder; 11024 final int v2 = p2.initOrder; 11025 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11026 } 11027 }; 11028 11029 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11030 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11031 final int[] userIds) { 11032 mHandler.post(new Runnable() { 11033 @Override 11034 public void run() { 11035 try { 11036 final IActivityManager am = ActivityManagerNative.getDefault(); 11037 if (am == null) return; 11038 final int[] resolvedUserIds; 11039 if (userIds == null) { 11040 resolvedUserIds = am.getRunningUserIds(); 11041 } else { 11042 resolvedUserIds = userIds; 11043 } 11044 for (int id : resolvedUserIds) { 11045 final Intent intent = new Intent(action, 11046 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11047 if (extras != null) { 11048 intent.putExtras(extras); 11049 } 11050 if (targetPkg != null) { 11051 intent.setPackage(targetPkg); 11052 } 11053 // Modify the UID when posting to other users 11054 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11055 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11056 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11057 intent.putExtra(Intent.EXTRA_UID, uid); 11058 } 11059 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11060 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11061 if (DEBUG_BROADCASTS) { 11062 RuntimeException here = new RuntimeException("here"); 11063 here.fillInStackTrace(); 11064 Slog.d(TAG, "Sending to user " + id + ": " 11065 + intent.toShortString(false, true, false, false) 11066 + " " + intent.getExtras(), here); 11067 } 11068 am.broadcastIntent(null, intent, null, finishedReceiver, 11069 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11070 null, finishedReceiver != null, false, id); 11071 } 11072 } catch (RemoteException ex) { 11073 } 11074 } 11075 }); 11076 } 11077 11078 /** 11079 * Check if the external storage media is available. This is true if there 11080 * is a mounted external storage medium or if the external storage is 11081 * emulated. 11082 */ 11083 private boolean isExternalMediaAvailable() { 11084 return mMediaMounted || Environment.isExternalStorageEmulated(); 11085 } 11086 11087 @Override 11088 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11089 // writer 11090 synchronized (mPackages) { 11091 if (!isExternalMediaAvailable()) { 11092 // If the external storage is no longer mounted at this point, 11093 // the caller may not have been able to delete all of this 11094 // packages files and can not delete any more. Bail. 11095 return null; 11096 } 11097 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11098 if (lastPackage != null) { 11099 pkgs.remove(lastPackage); 11100 } 11101 if (pkgs.size() > 0) { 11102 return pkgs.get(0); 11103 } 11104 } 11105 return null; 11106 } 11107 11108 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11109 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11110 userId, andCode ? 1 : 0, packageName); 11111 if (mSystemReady) { 11112 msg.sendToTarget(); 11113 } else { 11114 if (mPostSystemReadyMessages == null) { 11115 mPostSystemReadyMessages = new ArrayList<>(); 11116 } 11117 mPostSystemReadyMessages.add(msg); 11118 } 11119 } 11120 11121 void startCleaningPackages() { 11122 // reader 11123 if (!isExternalMediaAvailable()) { 11124 return; 11125 } 11126 synchronized (mPackages) { 11127 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11128 return; 11129 } 11130 } 11131 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11132 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11133 IActivityManager am = ActivityManagerNative.getDefault(); 11134 if (am != null) { 11135 try { 11136 am.startService(null, intent, null, mContext.getOpPackageName(), 11137 UserHandle.USER_SYSTEM); 11138 } catch (RemoteException e) { 11139 } 11140 } 11141 } 11142 11143 @Override 11144 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11145 int installFlags, String installerPackageName, int userId) { 11146 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11147 11148 final int callingUid = Binder.getCallingUid(); 11149 enforceCrossUserPermission(callingUid, userId, 11150 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11151 11152 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11153 try { 11154 if (observer != null) { 11155 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11156 } 11157 } catch (RemoteException re) { 11158 } 11159 return; 11160 } 11161 11162 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11163 installFlags |= PackageManager.INSTALL_FROM_ADB; 11164 11165 } else { 11166 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11167 // about installerPackageName. 11168 11169 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11170 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11171 } 11172 11173 UserHandle user; 11174 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11175 user = UserHandle.ALL; 11176 } else { 11177 user = new UserHandle(userId); 11178 } 11179 11180 // Only system components can circumvent runtime permissions when installing. 11181 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11182 && mContext.checkCallingOrSelfPermission(Manifest.permission 11183 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11184 throw new SecurityException("You need the " 11185 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11186 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11187 } 11188 11189 final File originFile = new File(originPath); 11190 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11191 11192 final Message msg = mHandler.obtainMessage(INIT_COPY); 11193 final VerificationInfo verificationInfo = new VerificationInfo( 11194 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11195 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11196 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11197 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11198 null /*certificates*/); 11199 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11200 msg.obj = params; 11201 11202 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11203 System.identityHashCode(msg.obj)); 11204 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11205 System.identityHashCode(msg.obj)); 11206 11207 mHandler.sendMessage(msg); 11208 } 11209 11210 void installStage(String packageName, File stagedDir, String stagedCid, 11211 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11212 String installerPackageName, int installerUid, UserHandle user, 11213 Certificate[][] certificates) { 11214 if (DEBUG_EPHEMERAL) { 11215 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11216 Slog.d(TAG, "Ephemeral install of " + packageName); 11217 } 11218 } 11219 final VerificationInfo verificationInfo = new VerificationInfo( 11220 sessionParams.originatingUri, sessionParams.referrerUri, 11221 sessionParams.originatingUid, installerUid); 11222 11223 final OriginInfo origin; 11224 if (stagedDir != null) { 11225 origin = OriginInfo.fromStagedFile(stagedDir); 11226 } else { 11227 origin = OriginInfo.fromStagedContainer(stagedCid); 11228 } 11229 11230 final Message msg = mHandler.obtainMessage(INIT_COPY); 11231 final InstallParams params = new InstallParams(origin, null, observer, 11232 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11233 verificationInfo, user, sessionParams.abiOverride, 11234 sessionParams.grantedRuntimePermissions, certificates); 11235 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11236 msg.obj = params; 11237 11238 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11239 System.identityHashCode(msg.obj)); 11240 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11241 System.identityHashCode(msg.obj)); 11242 11243 mHandler.sendMessage(msg); 11244 } 11245 11246 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11247 int userId) { 11248 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11249 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11250 } 11251 11252 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11253 int appId, int userId) { 11254 Bundle extras = new Bundle(1); 11255 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11256 11257 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11258 packageName, extras, 0, null, null, new int[] {userId}); 11259 try { 11260 IActivityManager am = ActivityManagerNative.getDefault(); 11261 if (isSystem && am.isUserRunning(userId, 0)) { 11262 // The just-installed/enabled app is bundled on the system, so presumed 11263 // to be able to run automatically without needing an explicit launch. 11264 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11265 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11266 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11267 .setPackage(packageName); 11268 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11269 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11270 } 11271 } catch (RemoteException e) { 11272 // shouldn't happen 11273 Slog.w(TAG, "Unable to bootstrap installed package", e); 11274 } 11275 } 11276 11277 @Override 11278 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11279 int userId) { 11280 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11281 PackageSetting pkgSetting; 11282 final int uid = Binder.getCallingUid(); 11283 enforceCrossUserPermission(uid, userId, 11284 true /* requireFullPermission */, true /* checkShell */, 11285 "setApplicationHiddenSetting for user " + userId); 11286 11287 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11288 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11289 return false; 11290 } 11291 11292 long callingId = Binder.clearCallingIdentity(); 11293 try { 11294 boolean sendAdded = false; 11295 boolean sendRemoved = false; 11296 // writer 11297 synchronized (mPackages) { 11298 pkgSetting = mSettings.mPackages.get(packageName); 11299 if (pkgSetting == null) { 11300 return false; 11301 } 11302 if (pkgSetting.getHidden(userId) != hidden) { 11303 pkgSetting.setHidden(hidden, userId); 11304 mSettings.writePackageRestrictionsLPr(userId); 11305 if (hidden) { 11306 sendRemoved = true; 11307 } else { 11308 sendAdded = true; 11309 } 11310 } 11311 } 11312 if (sendAdded) { 11313 sendPackageAddedForUser(packageName, pkgSetting, userId); 11314 return true; 11315 } 11316 if (sendRemoved) { 11317 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11318 "hiding pkg"); 11319 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11320 return true; 11321 } 11322 } finally { 11323 Binder.restoreCallingIdentity(callingId); 11324 } 11325 return false; 11326 } 11327 11328 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11329 int userId) { 11330 final PackageRemovedInfo info = new PackageRemovedInfo(); 11331 info.removedPackage = packageName; 11332 info.removedUsers = new int[] {userId}; 11333 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11334 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11335 } 11336 11337 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11338 if (pkgList.length > 0) { 11339 Bundle extras = new Bundle(1); 11340 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11341 11342 sendPackageBroadcast( 11343 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11344 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11345 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11346 new int[] {userId}); 11347 } 11348 } 11349 11350 /** 11351 * Returns true if application is not found or there was an error. Otherwise it returns 11352 * the hidden state of the package for the given user. 11353 */ 11354 @Override 11355 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11358 true /* requireFullPermission */, false /* checkShell */, 11359 "getApplicationHidden for user " + userId); 11360 PackageSetting pkgSetting; 11361 long callingId = Binder.clearCallingIdentity(); 11362 try { 11363 // writer 11364 synchronized (mPackages) { 11365 pkgSetting = mSettings.mPackages.get(packageName); 11366 if (pkgSetting == null) { 11367 return true; 11368 } 11369 return pkgSetting.getHidden(userId); 11370 } 11371 } finally { 11372 Binder.restoreCallingIdentity(callingId); 11373 } 11374 } 11375 11376 /** 11377 * @hide 11378 */ 11379 @Override 11380 public int installExistingPackageAsUser(String packageName, int userId) { 11381 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11382 null); 11383 PackageSetting pkgSetting; 11384 final int uid = Binder.getCallingUid(); 11385 enforceCrossUserPermission(uid, userId, 11386 true /* requireFullPermission */, true /* checkShell */, 11387 "installExistingPackage for user " + userId); 11388 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11389 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11390 } 11391 11392 long callingId = Binder.clearCallingIdentity(); 11393 try { 11394 boolean installed = false; 11395 11396 // writer 11397 synchronized (mPackages) { 11398 pkgSetting = mSettings.mPackages.get(packageName); 11399 if (pkgSetting == null) { 11400 return PackageManager.INSTALL_FAILED_INVALID_URI; 11401 } 11402 if (!pkgSetting.getInstalled(userId)) { 11403 pkgSetting.setInstalled(true, userId); 11404 pkgSetting.setHidden(false, userId); 11405 mSettings.writePackageRestrictionsLPr(userId); 11406 installed = true; 11407 } 11408 } 11409 11410 if (installed) { 11411 if (pkgSetting.pkg != null) { 11412 synchronized (mInstallLock) { 11413 // We don't need to freeze for a brand new install 11414 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11415 } 11416 } 11417 sendPackageAddedForUser(packageName, pkgSetting, userId); 11418 } 11419 } finally { 11420 Binder.restoreCallingIdentity(callingId); 11421 } 11422 11423 return PackageManager.INSTALL_SUCCEEDED; 11424 } 11425 11426 boolean isUserRestricted(int userId, String restrictionKey) { 11427 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11428 if (restrictions.getBoolean(restrictionKey, false)) { 11429 Log.w(TAG, "User is restricted: " + restrictionKey); 11430 return true; 11431 } 11432 return false; 11433 } 11434 11435 @Override 11436 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11437 int userId) { 11438 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11439 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11440 true /* requireFullPermission */, true /* checkShell */, 11441 "setPackagesSuspended for user " + userId); 11442 11443 if (ArrayUtils.isEmpty(packageNames)) { 11444 return packageNames; 11445 } 11446 11447 // List of package names for whom the suspended state has changed. 11448 List<String> changedPackages = new ArrayList<>(packageNames.length); 11449 // List of package names for whom the suspended state is not set as requested in this 11450 // method. 11451 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11452 for (int i = 0; i < packageNames.length; i++) { 11453 String packageName = packageNames[i]; 11454 long callingId = Binder.clearCallingIdentity(); 11455 try { 11456 boolean changed = false; 11457 final int appId; 11458 synchronized (mPackages) { 11459 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11460 if (pkgSetting == null) { 11461 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11462 + "\". Skipping suspending/un-suspending."); 11463 unactionedPackages.add(packageName); 11464 continue; 11465 } 11466 appId = pkgSetting.appId; 11467 if (pkgSetting.getSuspended(userId) != suspended) { 11468 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11469 unactionedPackages.add(packageName); 11470 continue; 11471 } 11472 pkgSetting.setSuspended(suspended, userId); 11473 mSettings.writePackageRestrictionsLPr(userId); 11474 changed = true; 11475 changedPackages.add(packageName); 11476 } 11477 } 11478 11479 if (changed && suspended) { 11480 killApplication(packageName, UserHandle.getUid(userId, appId), 11481 "suspending package"); 11482 } 11483 } finally { 11484 Binder.restoreCallingIdentity(callingId); 11485 } 11486 } 11487 11488 if (!changedPackages.isEmpty()) { 11489 sendPackagesSuspendedForUser(changedPackages.toArray( 11490 new String[changedPackages.size()]), userId, suspended); 11491 } 11492 11493 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11494 } 11495 11496 @Override 11497 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11498 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11499 true /* requireFullPermission */, false /* checkShell */, 11500 "isPackageSuspendedForUser for user " + userId); 11501 synchronized (mPackages) { 11502 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11503 if (pkgSetting == null) { 11504 throw new IllegalArgumentException("Unknown target package: " + packageName); 11505 } 11506 return pkgSetting.getSuspended(userId); 11507 } 11508 } 11509 11510 /** 11511 * TODO: cache and disallow blocking the active dialer. 11512 * 11513 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11514 */ 11515 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11516 if (isPackageDeviceAdmin(packageName, userId)) { 11517 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11518 + "\": has an active device admin"); 11519 return false; 11520 } 11521 11522 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11523 if (packageName.equals(activeLauncherPackageName)) { 11524 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11525 + "\": contains the active launcher"); 11526 return false; 11527 } 11528 11529 if (packageName.equals(mRequiredInstallerPackage)) { 11530 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11531 + "\": required for package installation"); 11532 return false; 11533 } 11534 11535 if (packageName.equals(mRequiredVerifierPackage)) { 11536 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11537 + "\": required for package verification"); 11538 return false; 11539 } 11540 11541 final PackageParser.Package pkg = mPackages.get(packageName); 11542 if (pkg != null && isPrivilegedApp(pkg)) { 11543 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11544 + "\": is a privileged app"); 11545 return false; 11546 } 11547 11548 return true; 11549 } 11550 11551 private String getActiveLauncherPackageName(int userId) { 11552 Intent intent = new Intent(Intent.ACTION_MAIN); 11553 intent.addCategory(Intent.CATEGORY_HOME); 11554 ResolveInfo resolveInfo = resolveIntent( 11555 intent, 11556 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11557 PackageManager.MATCH_DEFAULT_ONLY, 11558 userId); 11559 11560 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11561 } 11562 11563 @Override 11564 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11565 mContext.enforceCallingOrSelfPermission( 11566 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11567 "Only package verification agents can verify applications"); 11568 11569 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11570 final PackageVerificationResponse response = new PackageVerificationResponse( 11571 verificationCode, Binder.getCallingUid()); 11572 msg.arg1 = id; 11573 msg.obj = response; 11574 mHandler.sendMessage(msg); 11575 } 11576 11577 @Override 11578 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11579 long millisecondsToDelay) { 11580 mContext.enforceCallingOrSelfPermission( 11581 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11582 "Only package verification agents can extend verification timeouts"); 11583 11584 final PackageVerificationState state = mPendingVerification.get(id); 11585 final PackageVerificationResponse response = new PackageVerificationResponse( 11586 verificationCodeAtTimeout, Binder.getCallingUid()); 11587 11588 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11589 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11590 } 11591 if (millisecondsToDelay < 0) { 11592 millisecondsToDelay = 0; 11593 } 11594 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11595 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11596 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11597 } 11598 11599 if ((state != null) && !state.timeoutExtended()) { 11600 state.extendTimeout(); 11601 11602 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11603 msg.arg1 = id; 11604 msg.obj = response; 11605 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11606 } 11607 } 11608 11609 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11610 int verificationCode, UserHandle user) { 11611 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11612 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11613 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11614 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11615 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11616 11617 mContext.sendBroadcastAsUser(intent, user, 11618 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11619 } 11620 11621 private ComponentName matchComponentForVerifier(String packageName, 11622 List<ResolveInfo> receivers) { 11623 ActivityInfo targetReceiver = null; 11624 11625 final int NR = receivers.size(); 11626 for (int i = 0; i < NR; i++) { 11627 final ResolveInfo info = receivers.get(i); 11628 if (info.activityInfo == null) { 11629 continue; 11630 } 11631 11632 if (packageName.equals(info.activityInfo.packageName)) { 11633 targetReceiver = info.activityInfo; 11634 break; 11635 } 11636 } 11637 11638 if (targetReceiver == null) { 11639 return null; 11640 } 11641 11642 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11643 } 11644 11645 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11646 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11647 if (pkgInfo.verifiers.length == 0) { 11648 return null; 11649 } 11650 11651 final int N = pkgInfo.verifiers.length; 11652 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11653 for (int i = 0; i < N; i++) { 11654 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11655 11656 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11657 receivers); 11658 if (comp == null) { 11659 continue; 11660 } 11661 11662 final int verifierUid = getUidForVerifier(verifierInfo); 11663 if (verifierUid == -1) { 11664 continue; 11665 } 11666 11667 if (DEBUG_VERIFY) { 11668 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11669 + " with the correct signature"); 11670 } 11671 sufficientVerifiers.add(comp); 11672 verificationState.addSufficientVerifier(verifierUid); 11673 } 11674 11675 return sufficientVerifiers; 11676 } 11677 11678 private int getUidForVerifier(VerifierInfo verifierInfo) { 11679 synchronized (mPackages) { 11680 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11681 if (pkg == null) { 11682 return -1; 11683 } else if (pkg.mSignatures.length != 1) { 11684 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11685 + " has more than one signature; ignoring"); 11686 return -1; 11687 } 11688 11689 /* 11690 * If the public key of the package's signature does not match 11691 * our expected public key, then this is a different package and 11692 * we should skip. 11693 */ 11694 11695 final byte[] expectedPublicKey; 11696 try { 11697 final Signature verifierSig = pkg.mSignatures[0]; 11698 final PublicKey publicKey = verifierSig.getPublicKey(); 11699 expectedPublicKey = publicKey.getEncoded(); 11700 } catch (CertificateException e) { 11701 return -1; 11702 } 11703 11704 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11705 11706 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11707 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11708 + " does not have the expected public key; ignoring"); 11709 return -1; 11710 } 11711 11712 return pkg.applicationInfo.uid; 11713 } 11714 } 11715 11716 @Override 11717 public void finishPackageInstall(int token) { 11718 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11719 11720 if (DEBUG_INSTALL) { 11721 Slog.v(TAG, "BM finishing package install for " + token); 11722 } 11723 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11724 11725 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11726 mHandler.sendMessage(msg); 11727 } 11728 11729 /** 11730 * Get the verification agent timeout. 11731 * 11732 * @return verification timeout in milliseconds 11733 */ 11734 private long getVerificationTimeout() { 11735 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11736 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11737 DEFAULT_VERIFICATION_TIMEOUT); 11738 } 11739 11740 /** 11741 * Get the default verification agent response code. 11742 * 11743 * @return default verification response code 11744 */ 11745 private int getDefaultVerificationResponse() { 11746 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11747 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11748 DEFAULT_VERIFICATION_RESPONSE); 11749 } 11750 11751 /** 11752 * Check whether or not package verification has been enabled. 11753 * 11754 * @return true if verification should be performed 11755 */ 11756 private boolean isVerificationEnabled(int userId, int installFlags) { 11757 if (!DEFAULT_VERIFY_ENABLE) { 11758 return false; 11759 } 11760 // Ephemeral apps don't get the full verification treatment 11761 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11762 if (DEBUG_EPHEMERAL) { 11763 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11764 } 11765 return false; 11766 } 11767 11768 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11769 11770 // Check if installing from ADB 11771 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11772 // Do not run verification in a test harness environment 11773 if (ActivityManager.isRunningInTestHarness()) { 11774 return false; 11775 } 11776 if (ensureVerifyAppsEnabled) { 11777 return true; 11778 } 11779 // Check if the developer does not want package verification for ADB installs 11780 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11781 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11782 return false; 11783 } 11784 } 11785 11786 if (ensureVerifyAppsEnabled) { 11787 return true; 11788 } 11789 11790 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11791 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11792 } 11793 11794 @Override 11795 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11796 throws RemoteException { 11797 mContext.enforceCallingOrSelfPermission( 11798 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11799 "Only intentfilter verification agents can verify applications"); 11800 11801 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11802 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11803 Binder.getCallingUid(), verificationCode, failedDomains); 11804 msg.arg1 = id; 11805 msg.obj = response; 11806 mHandler.sendMessage(msg); 11807 } 11808 11809 @Override 11810 public int getIntentVerificationStatus(String packageName, int userId) { 11811 synchronized (mPackages) { 11812 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11813 } 11814 } 11815 11816 @Override 11817 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11818 mContext.enforceCallingOrSelfPermission( 11819 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11820 11821 boolean result = false; 11822 synchronized (mPackages) { 11823 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11824 } 11825 if (result) { 11826 scheduleWritePackageRestrictionsLocked(userId); 11827 } 11828 return result; 11829 } 11830 11831 @Override 11832 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11833 String packageName) { 11834 synchronized (mPackages) { 11835 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11836 } 11837 } 11838 11839 @Override 11840 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11841 if (TextUtils.isEmpty(packageName)) { 11842 return ParceledListSlice.emptyList(); 11843 } 11844 synchronized (mPackages) { 11845 PackageParser.Package pkg = mPackages.get(packageName); 11846 if (pkg == null || pkg.activities == null) { 11847 return ParceledListSlice.emptyList(); 11848 } 11849 final int count = pkg.activities.size(); 11850 ArrayList<IntentFilter> result = new ArrayList<>(); 11851 for (int n=0; n<count; n++) { 11852 PackageParser.Activity activity = pkg.activities.get(n); 11853 if (activity.intents != null && activity.intents.size() > 0) { 11854 result.addAll(activity.intents); 11855 } 11856 } 11857 return new ParceledListSlice<>(result); 11858 } 11859 } 11860 11861 @Override 11862 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11863 mContext.enforceCallingOrSelfPermission( 11864 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11865 11866 synchronized (mPackages) { 11867 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11868 if (packageName != null) { 11869 result |= updateIntentVerificationStatus(packageName, 11870 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11871 userId); 11872 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11873 packageName, userId); 11874 } 11875 return result; 11876 } 11877 } 11878 11879 @Override 11880 public String getDefaultBrowserPackageName(int userId) { 11881 synchronized (mPackages) { 11882 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11883 } 11884 } 11885 11886 /** 11887 * Get the "allow unknown sources" setting. 11888 * 11889 * @return the current "allow unknown sources" setting 11890 */ 11891 private int getUnknownSourcesSettings() { 11892 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11893 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11894 -1); 11895 } 11896 11897 @Override 11898 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11899 final int uid = Binder.getCallingUid(); 11900 // writer 11901 synchronized (mPackages) { 11902 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11903 if (targetPackageSetting == null) { 11904 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11905 } 11906 11907 PackageSetting installerPackageSetting; 11908 if (installerPackageName != null) { 11909 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11910 if (installerPackageSetting == null) { 11911 throw new IllegalArgumentException("Unknown installer package: " 11912 + installerPackageName); 11913 } 11914 } else { 11915 installerPackageSetting = null; 11916 } 11917 11918 Signature[] callerSignature; 11919 Object obj = mSettings.getUserIdLPr(uid); 11920 if (obj != null) { 11921 if (obj instanceof SharedUserSetting) { 11922 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11923 } else if (obj instanceof PackageSetting) { 11924 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11925 } else { 11926 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11927 } 11928 } else { 11929 throw new SecurityException("Unknown calling UID: " + uid); 11930 } 11931 11932 // Verify: can't set installerPackageName to a package that is 11933 // not signed with the same cert as the caller. 11934 if (installerPackageSetting != null) { 11935 if (compareSignatures(callerSignature, 11936 installerPackageSetting.signatures.mSignatures) 11937 != PackageManager.SIGNATURE_MATCH) { 11938 throw new SecurityException( 11939 "Caller does not have same cert as new installer package " 11940 + installerPackageName); 11941 } 11942 } 11943 11944 // Verify: if target already has an installer package, it must 11945 // be signed with the same cert as the caller. 11946 if (targetPackageSetting.installerPackageName != null) { 11947 PackageSetting setting = mSettings.mPackages.get( 11948 targetPackageSetting.installerPackageName); 11949 // If the currently set package isn't valid, then it's always 11950 // okay to change it. 11951 if (setting != null) { 11952 if (compareSignatures(callerSignature, 11953 setting.signatures.mSignatures) 11954 != PackageManager.SIGNATURE_MATCH) { 11955 throw new SecurityException( 11956 "Caller does not have same cert as old installer package " 11957 + targetPackageSetting.installerPackageName); 11958 } 11959 } 11960 } 11961 11962 // Okay! 11963 targetPackageSetting.installerPackageName = installerPackageName; 11964 if (installerPackageName != null) { 11965 mSettings.mInstallerPackages.add(installerPackageName); 11966 } 11967 scheduleWriteSettingsLocked(); 11968 } 11969 } 11970 11971 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11972 // Queue up an async operation since the package installation may take a little while. 11973 mHandler.post(new Runnable() { 11974 public void run() { 11975 mHandler.removeCallbacks(this); 11976 // Result object to be returned 11977 PackageInstalledInfo res = new PackageInstalledInfo(); 11978 res.setReturnCode(currentStatus); 11979 res.uid = -1; 11980 res.pkg = null; 11981 res.removedInfo = null; 11982 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11983 args.doPreInstall(res.returnCode); 11984 synchronized (mInstallLock) { 11985 installPackageTracedLI(args, res); 11986 } 11987 args.doPostInstall(res.returnCode, res.uid); 11988 } 11989 11990 // A restore should be performed at this point if (a) the install 11991 // succeeded, (b) the operation is not an update, and (c) the new 11992 // package has not opted out of backup participation. 11993 final boolean update = res.removedInfo != null 11994 && res.removedInfo.removedPackage != null; 11995 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11996 boolean doRestore = !update 11997 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11998 11999 // Set up the post-install work request bookkeeping. This will be used 12000 // and cleaned up by the post-install event handling regardless of whether 12001 // there's a restore pass performed. Token values are >= 1. 12002 int token; 12003 if (mNextInstallToken < 0) mNextInstallToken = 1; 12004 token = mNextInstallToken++; 12005 12006 PostInstallData data = new PostInstallData(args, res); 12007 mRunningInstalls.put(token, data); 12008 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12009 12010 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12011 // Pass responsibility to the Backup Manager. It will perform a 12012 // restore if appropriate, then pass responsibility back to the 12013 // Package Manager to run the post-install observer callbacks 12014 // and broadcasts. 12015 IBackupManager bm = IBackupManager.Stub.asInterface( 12016 ServiceManager.getService(Context.BACKUP_SERVICE)); 12017 if (bm != null) { 12018 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12019 + " to BM for possible restore"); 12020 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12021 try { 12022 // TODO: http://b/22388012 12023 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12024 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12025 } else { 12026 doRestore = false; 12027 } 12028 } catch (RemoteException e) { 12029 // can't happen; the backup manager is local 12030 } catch (Exception e) { 12031 Slog.e(TAG, "Exception trying to enqueue restore", e); 12032 doRestore = false; 12033 } 12034 } else { 12035 Slog.e(TAG, "Backup Manager not found!"); 12036 doRestore = false; 12037 } 12038 } 12039 12040 if (!doRestore) { 12041 // No restore possible, or the Backup Manager was mysteriously not 12042 // available -- just fire the post-install work request directly. 12043 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12044 12045 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12046 12047 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12048 mHandler.sendMessage(msg); 12049 } 12050 } 12051 }); 12052 } 12053 12054 private abstract class HandlerParams { 12055 private static final int MAX_RETRIES = 4; 12056 12057 /** 12058 * Number of times startCopy() has been attempted and had a non-fatal 12059 * error. 12060 */ 12061 private int mRetries = 0; 12062 12063 /** User handle for the user requesting the information or installation. */ 12064 private final UserHandle mUser; 12065 String traceMethod; 12066 int traceCookie; 12067 12068 HandlerParams(UserHandle user) { 12069 mUser = user; 12070 } 12071 12072 UserHandle getUser() { 12073 return mUser; 12074 } 12075 12076 HandlerParams setTraceMethod(String traceMethod) { 12077 this.traceMethod = traceMethod; 12078 return this; 12079 } 12080 12081 HandlerParams setTraceCookie(int traceCookie) { 12082 this.traceCookie = traceCookie; 12083 return this; 12084 } 12085 12086 final boolean startCopy() { 12087 boolean res; 12088 try { 12089 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12090 12091 if (++mRetries > MAX_RETRIES) { 12092 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12093 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12094 handleServiceError(); 12095 return false; 12096 } else { 12097 handleStartCopy(); 12098 res = true; 12099 } 12100 } catch (RemoteException e) { 12101 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12102 mHandler.sendEmptyMessage(MCS_RECONNECT); 12103 res = false; 12104 } 12105 handleReturnCode(); 12106 return res; 12107 } 12108 12109 final void serviceError() { 12110 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12111 handleServiceError(); 12112 handleReturnCode(); 12113 } 12114 12115 abstract void handleStartCopy() throws RemoteException; 12116 abstract void handleServiceError(); 12117 abstract void handleReturnCode(); 12118 } 12119 12120 class MeasureParams extends HandlerParams { 12121 private final PackageStats mStats; 12122 private boolean mSuccess; 12123 12124 private final IPackageStatsObserver mObserver; 12125 12126 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12127 super(new UserHandle(stats.userHandle)); 12128 mObserver = observer; 12129 mStats = stats; 12130 } 12131 12132 @Override 12133 public String toString() { 12134 return "MeasureParams{" 12135 + Integer.toHexString(System.identityHashCode(this)) 12136 + " " + mStats.packageName + "}"; 12137 } 12138 12139 @Override 12140 void handleStartCopy() throws RemoteException { 12141 synchronized (mInstallLock) { 12142 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12143 } 12144 12145 if (mSuccess) { 12146 final boolean mounted; 12147 if (Environment.isExternalStorageEmulated()) { 12148 mounted = true; 12149 } else { 12150 final String status = Environment.getExternalStorageState(); 12151 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12152 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12153 } 12154 12155 if (mounted) { 12156 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12157 12158 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12159 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12160 12161 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12162 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12163 12164 // Always subtract cache size, since it's a subdirectory 12165 mStats.externalDataSize -= mStats.externalCacheSize; 12166 12167 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12168 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12169 12170 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12171 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12172 } 12173 } 12174 } 12175 12176 @Override 12177 void handleReturnCode() { 12178 if (mObserver != null) { 12179 try { 12180 mObserver.onGetStatsCompleted(mStats, mSuccess); 12181 } catch (RemoteException e) { 12182 Slog.i(TAG, "Observer no longer exists."); 12183 } 12184 } 12185 } 12186 12187 @Override 12188 void handleServiceError() { 12189 Slog.e(TAG, "Could not measure application " + mStats.packageName 12190 + " external storage"); 12191 } 12192 } 12193 12194 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12195 throws RemoteException { 12196 long result = 0; 12197 for (File path : paths) { 12198 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12199 } 12200 return result; 12201 } 12202 12203 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12204 for (File path : paths) { 12205 try { 12206 mcs.clearDirectory(path.getAbsolutePath()); 12207 } catch (RemoteException e) { 12208 } 12209 } 12210 } 12211 12212 static class OriginInfo { 12213 /** 12214 * Location where install is coming from, before it has been 12215 * copied/renamed into place. This could be a single monolithic APK 12216 * file, or a cluster directory. This location may be untrusted. 12217 */ 12218 final File file; 12219 final String cid; 12220 12221 /** 12222 * Flag indicating that {@link #file} or {@link #cid} has already been 12223 * staged, meaning downstream users don't need to defensively copy the 12224 * contents. 12225 */ 12226 final boolean staged; 12227 12228 /** 12229 * Flag indicating that {@link #file} or {@link #cid} is an already 12230 * installed app that is being moved. 12231 */ 12232 final boolean existing; 12233 12234 final String resolvedPath; 12235 final File resolvedFile; 12236 12237 static OriginInfo fromNothing() { 12238 return new OriginInfo(null, null, false, false); 12239 } 12240 12241 static OriginInfo fromUntrustedFile(File file) { 12242 return new OriginInfo(file, null, false, false); 12243 } 12244 12245 static OriginInfo fromExistingFile(File file) { 12246 return new OriginInfo(file, null, false, true); 12247 } 12248 12249 static OriginInfo fromStagedFile(File file) { 12250 return new OriginInfo(file, null, true, false); 12251 } 12252 12253 static OriginInfo fromStagedContainer(String cid) { 12254 return new OriginInfo(null, cid, true, false); 12255 } 12256 12257 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12258 this.file = file; 12259 this.cid = cid; 12260 this.staged = staged; 12261 this.existing = existing; 12262 12263 if (cid != null) { 12264 resolvedPath = PackageHelper.getSdDir(cid); 12265 resolvedFile = new File(resolvedPath); 12266 } else if (file != null) { 12267 resolvedPath = file.getAbsolutePath(); 12268 resolvedFile = file; 12269 } else { 12270 resolvedPath = null; 12271 resolvedFile = null; 12272 } 12273 } 12274 } 12275 12276 static class MoveInfo { 12277 final int moveId; 12278 final String fromUuid; 12279 final String toUuid; 12280 final String packageName; 12281 final String dataAppName; 12282 final int appId; 12283 final String seinfo; 12284 final int targetSdkVersion; 12285 12286 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12287 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12288 this.moveId = moveId; 12289 this.fromUuid = fromUuid; 12290 this.toUuid = toUuid; 12291 this.packageName = packageName; 12292 this.dataAppName = dataAppName; 12293 this.appId = appId; 12294 this.seinfo = seinfo; 12295 this.targetSdkVersion = targetSdkVersion; 12296 } 12297 } 12298 12299 static class VerificationInfo { 12300 /** A constant used to indicate that a uid value is not present. */ 12301 public static final int NO_UID = -1; 12302 12303 /** URI referencing where the package was downloaded from. */ 12304 final Uri originatingUri; 12305 12306 /** HTTP referrer URI associated with the originatingURI. */ 12307 final Uri referrer; 12308 12309 /** UID of the application that the install request originated from. */ 12310 final int originatingUid; 12311 12312 /** UID of application requesting the install */ 12313 final int installerUid; 12314 12315 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12316 this.originatingUri = originatingUri; 12317 this.referrer = referrer; 12318 this.originatingUid = originatingUid; 12319 this.installerUid = installerUid; 12320 } 12321 } 12322 12323 class InstallParams extends HandlerParams { 12324 final OriginInfo origin; 12325 final MoveInfo move; 12326 final IPackageInstallObserver2 observer; 12327 int installFlags; 12328 final String installerPackageName; 12329 final String volumeUuid; 12330 private InstallArgs mArgs; 12331 private int mRet; 12332 final String packageAbiOverride; 12333 final String[] grantedRuntimePermissions; 12334 final VerificationInfo verificationInfo; 12335 final Certificate[][] certificates; 12336 12337 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12338 int installFlags, String installerPackageName, String volumeUuid, 12339 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12340 String[] grantedPermissions, Certificate[][] certificates) { 12341 super(user); 12342 this.origin = origin; 12343 this.move = move; 12344 this.observer = observer; 12345 this.installFlags = installFlags; 12346 this.installerPackageName = installerPackageName; 12347 this.volumeUuid = volumeUuid; 12348 this.verificationInfo = verificationInfo; 12349 this.packageAbiOverride = packageAbiOverride; 12350 this.grantedRuntimePermissions = grantedPermissions; 12351 this.certificates = certificates; 12352 } 12353 12354 @Override 12355 public String toString() { 12356 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12357 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12358 } 12359 12360 private int installLocationPolicy(PackageInfoLite pkgLite) { 12361 String packageName = pkgLite.packageName; 12362 int installLocation = pkgLite.installLocation; 12363 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12364 // reader 12365 synchronized (mPackages) { 12366 // Currently installed package which the new package is attempting to replace or 12367 // null if no such package is installed. 12368 PackageParser.Package installedPkg = mPackages.get(packageName); 12369 // Package which currently owns the data which the new package will own if installed. 12370 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12371 // will be null whereas dataOwnerPkg will contain information about the package 12372 // which was uninstalled while keeping its data. 12373 PackageParser.Package dataOwnerPkg = installedPkg; 12374 if (dataOwnerPkg == null) { 12375 PackageSetting ps = mSettings.mPackages.get(packageName); 12376 if (ps != null) { 12377 dataOwnerPkg = ps.pkg; 12378 } 12379 } 12380 12381 if (dataOwnerPkg != null) { 12382 // If installed, the package will get access to data left on the device by its 12383 // predecessor. As a security measure, this is permited only if this is not a 12384 // version downgrade or if the predecessor package is marked as debuggable and 12385 // a downgrade is explicitly requested. 12386 // 12387 // On debuggable platform builds, downgrades are permitted even for 12388 // non-debuggable packages to make testing easier. Debuggable platform builds do 12389 // not offer security guarantees and thus it's OK to disable some security 12390 // mechanisms to make debugging/testing easier on those builds. However, even on 12391 // debuggable builds downgrades of packages are permitted only if requested via 12392 // installFlags. This is because we aim to keep the behavior of debuggable 12393 // platform builds as close as possible to the behavior of non-debuggable 12394 // platform builds. 12395 final boolean downgradeRequested = 12396 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12397 final boolean packageDebuggable = 12398 (dataOwnerPkg.applicationInfo.flags 12399 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12400 final boolean downgradePermitted = 12401 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12402 if (!downgradePermitted) { 12403 try { 12404 checkDowngrade(dataOwnerPkg, pkgLite); 12405 } catch (PackageManagerException e) { 12406 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12407 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12408 } 12409 } 12410 } 12411 12412 if (installedPkg != null) { 12413 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12414 // Check for updated system application. 12415 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12416 if (onSd) { 12417 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12418 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12419 } 12420 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12421 } else { 12422 if (onSd) { 12423 // Install flag overrides everything. 12424 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12425 } 12426 // If current upgrade specifies particular preference 12427 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12428 // Application explicitly specified internal. 12429 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12430 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12431 // App explictly prefers external. Let policy decide 12432 } else { 12433 // Prefer previous location 12434 if (isExternal(installedPkg)) { 12435 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12436 } 12437 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12438 } 12439 } 12440 } else { 12441 // Invalid install. Return error code 12442 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12443 } 12444 } 12445 } 12446 // All the special cases have been taken care of. 12447 // Return result based on recommended install location. 12448 if (onSd) { 12449 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12450 } 12451 return pkgLite.recommendedInstallLocation; 12452 } 12453 12454 /* 12455 * Invoke remote method to get package information and install 12456 * location values. Override install location based on default 12457 * policy if needed and then create install arguments based 12458 * on the install location. 12459 */ 12460 public void handleStartCopy() throws RemoteException { 12461 int ret = PackageManager.INSTALL_SUCCEEDED; 12462 12463 // If we're already staged, we've firmly committed to an install location 12464 if (origin.staged) { 12465 if (origin.file != null) { 12466 installFlags |= PackageManager.INSTALL_INTERNAL; 12467 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12468 } else if (origin.cid != null) { 12469 installFlags |= PackageManager.INSTALL_EXTERNAL; 12470 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12471 } else { 12472 throw new IllegalStateException("Invalid stage location"); 12473 } 12474 } 12475 12476 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12477 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12478 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12479 PackageInfoLite pkgLite = null; 12480 12481 if (onInt && onSd) { 12482 // Check if both bits are set. 12483 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12484 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12485 } else if (onSd && ephemeral) { 12486 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12487 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12488 } else { 12489 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12490 packageAbiOverride); 12491 12492 if (DEBUG_EPHEMERAL && ephemeral) { 12493 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12494 } 12495 12496 /* 12497 * If we have too little free space, try to free cache 12498 * before giving up. 12499 */ 12500 if (!origin.staged && pkgLite.recommendedInstallLocation 12501 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12502 // TODO: focus freeing disk space on the target device 12503 final StorageManager storage = StorageManager.from(mContext); 12504 final long lowThreshold = storage.getStorageLowBytes( 12505 Environment.getDataDirectory()); 12506 12507 final long sizeBytes = mContainerService.calculateInstalledSize( 12508 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12509 12510 try { 12511 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12512 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12513 installFlags, packageAbiOverride); 12514 } catch (InstallerException e) { 12515 Slog.w(TAG, "Failed to free cache", e); 12516 } 12517 12518 /* 12519 * The cache free must have deleted the file we 12520 * downloaded to install. 12521 * 12522 * TODO: fix the "freeCache" call to not delete 12523 * the file we care about. 12524 */ 12525 if (pkgLite.recommendedInstallLocation 12526 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12527 pkgLite.recommendedInstallLocation 12528 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12529 } 12530 } 12531 } 12532 12533 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12534 int loc = pkgLite.recommendedInstallLocation; 12535 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12536 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12537 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12538 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12539 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12540 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12541 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12542 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12543 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12544 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12545 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12546 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12547 } else { 12548 // Override with defaults if needed. 12549 loc = installLocationPolicy(pkgLite); 12550 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12551 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12552 } else if (!onSd && !onInt) { 12553 // Override install location with flags 12554 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12555 // Set the flag to install on external media. 12556 installFlags |= PackageManager.INSTALL_EXTERNAL; 12557 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12558 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12559 if (DEBUG_EPHEMERAL) { 12560 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12561 } 12562 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12563 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12564 |PackageManager.INSTALL_INTERNAL); 12565 } else { 12566 // Make sure the flag for installing on external 12567 // media is unset 12568 installFlags |= PackageManager.INSTALL_INTERNAL; 12569 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12570 } 12571 } 12572 } 12573 } 12574 12575 final InstallArgs args = createInstallArgs(this); 12576 mArgs = args; 12577 12578 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12579 // TODO: http://b/22976637 12580 // Apps installed for "all" users use the device owner to verify the app 12581 UserHandle verifierUser = getUser(); 12582 if (verifierUser == UserHandle.ALL) { 12583 verifierUser = UserHandle.SYSTEM; 12584 } 12585 12586 /* 12587 * Determine if we have any installed package verifiers. If we 12588 * do, then we'll defer to them to verify the packages. 12589 */ 12590 final int requiredUid = mRequiredVerifierPackage == null ? -1 12591 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12592 verifierUser.getIdentifier()); 12593 if (!origin.existing && requiredUid != -1 12594 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12595 final Intent verification = new Intent( 12596 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12597 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12598 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12599 PACKAGE_MIME_TYPE); 12600 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12601 12602 // Query all live verifiers based on current user state 12603 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12604 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12605 12606 if (DEBUG_VERIFY) { 12607 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12608 + verification.toString() + " with " + pkgLite.verifiers.length 12609 + " optional verifiers"); 12610 } 12611 12612 final int verificationId = mPendingVerificationToken++; 12613 12614 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12615 12616 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12617 installerPackageName); 12618 12619 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12620 installFlags); 12621 12622 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12623 pkgLite.packageName); 12624 12625 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12626 pkgLite.versionCode); 12627 12628 if (verificationInfo != null) { 12629 if (verificationInfo.originatingUri != null) { 12630 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12631 verificationInfo.originatingUri); 12632 } 12633 if (verificationInfo.referrer != null) { 12634 verification.putExtra(Intent.EXTRA_REFERRER, 12635 verificationInfo.referrer); 12636 } 12637 if (verificationInfo.originatingUid >= 0) { 12638 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12639 verificationInfo.originatingUid); 12640 } 12641 if (verificationInfo.installerUid >= 0) { 12642 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12643 verificationInfo.installerUid); 12644 } 12645 } 12646 12647 final PackageVerificationState verificationState = new PackageVerificationState( 12648 requiredUid, args); 12649 12650 mPendingVerification.append(verificationId, verificationState); 12651 12652 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12653 receivers, verificationState); 12654 12655 /* 12656 * If any sufficient verifiers were listed in the package 12657 * manifest, attempt to ask them. 12658 */ 12659 if (sufficientVerifiers != null) { 12660 final int N = sufficientVerifiers.size(); 12661 if (N == 0) { 12662 Slog.i(TAG, "Additional verifiers required, but none installed."); 12663 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12664 } else { 12665 for (int i = 0; i < N; i++) { 12666 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12667 12668 final Intent sufficientIntent = new Intent(verification); 12669 sufficientIntent.setComponent(verifierComponent); 12670 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12671 } 12672 } 12673 } 12674 12675 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12676 mRequiredVerifierPackage, receivers); 12677 if (ret == PackageManager.INSTALL_SUCCEEDED 12678 && mRequiredVerifierPackage != null) { 12679 Trace.asyncTraceBegin( 12680 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12681 /* 12682 * Send the intent to the required verification agent, 12683 * but only start the verification timeout after the 12684 * target BroadcastReceivers have run. 12685 */ 12686 verification.setComponent(requiredVerifierComponent); 12687 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12689 new BroadcastReceiver() { 12690 @Override 12691 public void onReceive(Context context, Intent intent) { 12692 final Message msg = mHandler 12693 .obtainMessage(CHECK_PENDING_VERIFICATION); 12694 msg.arg1 = verificationId; 12695 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12696 } 12697 }, null, 0, null, null); 12698 12699 /* 12700 * We don't want the copy to proceed until verification 12701 * succeeds, so null out this field. 12702 */ 12703 mArgs = null; 12704 } 12705 } else { 12706 /* 12707 * No package verification is enabled, so immediately start 12708 * the remote call to initiate copy using temporary file. 12709 */ 12710 ret = args.copyApk(mContainerService, true); 12711 } 12712 } 12713 12714 mRet = ret; 12715 } 12716 12717 @Override 12718 void handleReturnCode() { 12719 // If mArgs is null, then MCS couldn't be reached. When it 12720 // reconnects, it will try again to install. At that point, this 12721 // will succeed. 12722 if (mArgs != null) { 12723 processPendingInstall(mArgs, mRet); 12724 } 12725 } 12726 12727 @Override 12728 void handleServiceError() { 12729 mArgs = createInstallArgs(this); 12730 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12731 } 12732 12733 public boolean isForwardLocked() { 12734 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12735 } 12736 } 12737 12738 /** 12739 * Used during creation of InstallArgs 12740 * 12741 * @param installFlags package installation flags 12742 * @return true if should be installed on external storage 12743 */ 12744 private static boolean installOnExternalAsec(int installFlags) { 12745 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12746 return false; 12747 } 12748 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12749 return true; 12750 } 12751 return false; 12752 } 12753 12754 /** 12755 * Used during creation of InstallArgs 12756 * 12757 * @param installFlags package installation flags 12758 * @return true if should be installed as forward locked 12759 */ 12760 private static boolean installForwardLocked(int installFlags) { 12761 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12762 } 12763 12764 private InstallArgs createInstallArgs(InstallParams params) { 12765 if (params.move != null) { 12766 return new MoveInstallArgs(params); 12767 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12768 return new AsecInstallArgs(params); 12769 } else { 12770 return new FileInstallArgs(params); 12771 } 12772 } 12773 12774 /** 12775 * Create args that describe an existing installed package. Typically used 12776 * when cleaning up old installs, or used as a move source. 12777 */ 12778 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12779 String resourcePath, String[] instructionSets) { 12780 final boolean isInAsec; 12781 if (installOnExternalAsec(installFlags)) { 12782 /* Apps on SD card are always in ASEC containers. */ 12783 isInAsec = true; 12784 } else if (installForwardLocked(installFlags) 12785 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12786 /* 12787 * Forward-locked apps are only in ASEC containers if they're the 12788 * new style 12789 */ 12790 isInAsec = true; 12791 } else { 12792 isInAsec = false; 12793 } 12794 12795 if (isInAsec) { 12796 return new AsecInstallArgs(codePath, instructionSets, 12797 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12798 } else { 12799 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12800 } 12801 } 12802 12803 static abstract class InstallArgs { 12804 /** @see InstallParams#origin */ 12805 final OriginInfo origin; 12806 /** @see InstallParams#move */ 12807 final MoveInfo move; 12808 12809 final IPackageInstallObserver2 observer; 12810 // Always refers to PackageManager flags only 12811 final int installFlags; 12812 final String installerPackageName; 12813 final String volumeUuid; 12814 final UserHandle user; 12815 final String abiOverride; 12816 final String[] installGrantPermissions; 12817 /** If non-null, drop an async trace when the install completes */ 12818 final String traceMethod; 12819 final int traceCookie; 12820 final Certificate[][] certificates; 12821 12822 // The list of instruction sets supported by this app. This is currently 12823 // only used during the rmdex() phase to clean up resources. We can get rid of this 12824 // if we move dex files under the common app path. 12825 /* nullable */ String[] instructionSets; 12826 12827 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12828 int installFlags, String installerPackageName, String volumeUuid, 12829 UserHandle user, String[] instructionSets, 12830 String abiOverride, String[] installGrantPermissions, 12831 String traceMethod, int traceCookie, Certificate[][] certificates) { 12832 this.origin = origin; 12833 this.move = move; 12834 this.installFlags = installFlags; 12835 this.observer = observer; 12836 this.installerPackageName = installerPackageName; 12837 this.volumeUuid = volumeUuid; 12838 this.user = user; 12839 this.instructionSets = instructionSets; 12840 this.abiOverride = abiOverride; 12841 this.installGrantPermissions = installGrantPermissions; 12842 this.traceMethod = traceMethod; 12843 this.traceCookie = traceCookie; 12844 this.certificates = certificates; 12845 } 12846 12847 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12848 abstract int doPreInstall(int status); 12849 12850 /** 12851 * Rename package into final resting place. All paths on the given 12852 * scanned package should be updated to reflect the rename. 12853 */ 12854 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12855 abstract int doPostInstall(int status, int uid); 12856 12857 /** @see PackageSettingBase#codePathString */ 12858 abstract String getCodePath(); 12859 /** @see PackageSettingBase#resourcePathString */ 12860 abstract String getResourcePath(); 12861 12862 // Need installer lock especially for dex file removal. 12863 abstract void cleanUpResourcesLI(); 12864 abstract boolean doPostDeleteLI(boolean delete); 12865 12866 /** 12867 * Called before the source arguments are copied. This is used mostly 12868 * for MoveParams when it needs to read the source file to put it in the 12869 * destination. 12870 */ 12871 int doPreCopy() { 12872 return PackageManager.INSTALL_SUCCEEDED; 12873 } 12874 12875 /** 12876 * Called after the source arguments are copied. This is used mostly for 12877 * MoveParams when it needs to read the source file to put it in the 12878 * destination. 12879 */ 12880 int doPostCopy(int uid) { 12881 return PackageManager.INSTALL_SUCCEEDED; 12882 } 12883 12884 protected boolean isFwdLocked() { 12885 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12886 } 12887 12888 protected boolean isExternalAsec() { 12889 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12890 } 12891 12892 protected boolean isEphemeral() { 12893 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12894 } 12895 12896 UserHandle getUser() { 12897 return user; 12898 } 12899 } 12900 12901 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12902 if (!allCodePaths.isEmpty()) { 12903 if (instructionSets == null) { 12904 throw new IllegalStateException("instructionSet == null"); 12905 } 12906 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12907 for (String codePath : allCodePaths) { 12908 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12909 try { 12910 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12911 } catch (InstallerException ignored) { 12912 } 12913 } 12914 } 12915 } 12916 } 12917 12918 /** 12919 * Logic to handle installation of non-ASEC applications, including copying 12920 * and renaming logic. 12921 */ 12922 class FileInstallArgs extends InstallArgs { 12923 private File codeFile; 12924 private File resourceFile; 12925 12926 // Example topology: 12927 // /data/app/com.example/base.apk 12928 // /data/app/com.example/split_foo.apk 12929 // /data/app/com.example/lib/arm/libfoo.so 12930 // /data/app/com.example/lib/arm64/libfoo.so 12931 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12932 12933 /** New install */ 12934 FileInstallArgs(InstallParams params) { 12935 super(params.origin, params.move, params.observer, params.installFlags, 12936 params.installerPackageName, params.volumeUuid, 12937 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12938 params.grantedRuntimePermissions, 12939 params.traceMethod, params.traceCookie, params.certificates); 12940 if (isFwdLocked()) { 12941 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12942 } 12943 } 12944 12945 /** Existing install */ 12946 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12947 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12948 null, null, null, 0, null /*certificates*/); 12949 this.codeFile = (codePath != null) ? new File(codePath) : null; 12950 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12951 } 12952 12953 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12954 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12955 try { 12956 return doCopyApk(imcs, temp); 12957 } finally { 12958 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12959 } 12960 } 12961 12962 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12963 if (origin.staged) { 12964 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12965 codeFile = origin.file; 12966 resourceFile = origin.file; 12967 return PackageManager.INSTALL_SUCCEEDED; 12968 } 12969 12970 try { 12971 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12972 final File tempDir = 12973 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12974 codeFile = tempDir; 12975 resourceFile = tempDir; 12976 } catch (IOException e) { 12977 Slog.w(TAG, "Failed to create copy file: " + e); 12978 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12979 } 12980 12981 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12982 @Override 12983 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12984 if (!FileUtils.isValidExtFilename(name)) { 12985 throw new IllegalArgumentException("Invalid filename: " + name); 12986 } 12987 try { 12988 final File file = new File(codeFile, name); 12989 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12990 O_RDWR | O_CREAT, 0644); 12991 Os.chmod(file.getAbsolutePath(), 0644); 12992 return new ParcelFileDescriptor(fd); 12993 } catch (ErrnoException e) { 12994 throw new RemoteException("Failed to open: " + e.getMessage()); 12995 } 12996 } 12997 }; 12998 12999 int ret = PackageManager.INSTALL_SUCCEEDED; 13000 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13001 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13002 Slog.e(TAG, "Failed to copy package"); 13003 return ret; 13004 } 13005 13006 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13007 NativeLibraryHelper.Handle handle = null; 13008 try { 13009 handle = NativeLibraryHelper.Handle.create(codeFile); 13010 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13011 abiOverride); 13012 } catch (IOException e) { 13013 Slog.e(TAG, "Copying native libraries failed", e); 13014 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13015 } finally { 13016 IoUtils.closeQuietly(handle); 13017 } 13018 13019 return ret; 13020 } 13021 13022 int doPreInstall(int status) { 13023 if (status != PackageManager.INSTALL_SUCCEEDED) { 13024 cleanUp(); 13025 } 13026 return status; 13027 } 13028 13029 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13030 if (status != PackageManager.INSTALL_SUCCEEDED) { 13031 cleanUp(); 13032 return false; 13033 } 13034 13035 final File targetDir = codeFile.getParentFile(); 13036 final File beforeCodeFile = codeFile; 13037 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13038 13039 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13040 try { 13041 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13042 } catch (ErrnoException e) { 13043 Slog.w(TAG, "Failed to rename", e); 13044 return false; 13045 } 13046 13047 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13048 Slog.w(TAG, "Failed to restorecon"); 13049 return false; 13050 } 13051 13052 // Reflect the rename internally 13053 codeFile = afterCodeFile; 13054 resourceFile = afterCodeFile; 13055 13056 // Reflect the rename in scanned details 13057 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13058 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13059 afterCodeFile, pkg.baseCodePath)); 13060 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13061 afterCodeFile, pkg.splitCodePaths)); 13062 13063 // Reflect the rename in app info 13064 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13065 pkg.setApplicationInfoCodePath(pkg.codePath); 13066 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13067 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13068 pkg.setApplicationInfoResourcePath(pkg.codePath); 13069 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13070 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13071 13072 return true; 13073 } 13074 13075 int doPostInstall(int status, int uid) { 13076 if (status != PackageManager.INSTALL_SUCCEEDED) { 13077 cleanUp(); 13078 } 13079 return status; 13080 } 13081 13082 @Override 13083 String getCodePath() { 13084 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13085 } 13086 13087 @Override 13088 String getResourcePath() { 13089 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13090 } 13091 13092 private boolean cleanUp() { 13093 if (codeFile == null || !codeFile.exists()) { 13094 return false; 13095 } 13096 13097 removeCodePathLI(codeFile); 13098 13099 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13100 resourceFile.delete(); 13101 } 13102 13103 return true; 13104 } 13105 13106 void cleanUpResourcesLI() { 13107 // Try enumerating all code paths before deleting 13108 List<String> allCodePaths = Collections.EMPTY_LIST; 13109 if (codeFile != null && codeFile.exists()) { 13110 try { 13111 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13112 allCodePaths = pkg.getAllCodePaths(); 13113 } catch (PackageParserException e) { 13114 // Ignored; we tried our best 13115 } 13116 } 13117 13118 cleanUp(); 13119 removeDexFiles(allCodePaths, instructionSets); 13120 } 13121 13122 boolean doPostDeleteLI(boolean delete) { 13123 // XXX err, shouldn't we respect the delete flag? 13124 cleanUpResourcesLI(); 13125 return true; 13126 } 13127 } 13128 13129 private boolean isAsecExternal(String cid) { 13130 final String asecPath = PackageHelper.getSdFilesystem(cid); 13131 return !asecPath.startsWith(mAsecInternalPath); 13132 } 13133 13134 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13135 PackageManagerException { 13136 if (copyRet < 0) { 13137 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13138 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13139 throw new PackageManagerException(copyRet, message); 13140 } 13141 } 13142 } 13143 13144 /** 13145 * Extract the MountService "container ID" from the full code path of an 13146 * .apk. 13147 */ 13148 static String cidFromCodePath(String fullCodePath) { 13149 int eidx = fullCodePath.lastIndexOf("/"); 13150 String subStr1 = fullCodePath.substring(0, eidx); 13151 int sidx = subStr1.lastIndexOf("/"); 13152 return subStr1.substring(sidx+1, eidx); 13153 } 13154 13155 /** 13156 * Logic to handle installation of ASEC applications, including copying and 13157 * renaming logic. 13158 */ 13159 class AsecInstallArgs extends InstallArgs { 13160 static final String RES_FILE_NAME = "pkg.apk"; 13161 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13162 13163 String cid; 13164 String packagePath; 13165 String resourcePath; 13166 13167 /** New install */ 13168 AsecInstallArgs(InstallParams params) { 13169 super(params.origin, params.move, params.observer, params.installFlags, 13170 params.installerPackageName, params.volumeUuid, 13171 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13172 params.grantedRuntimePermissions, 13173 params.traceMethod, params.traceCookie, params.certificates); 13174 } 13175 13176 /** Existing install */ 13177 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13178 boolean isExternal, boolean isForwardLocked) { 13179 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13180 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13181 instructionSets, null, null, null, 0, null /*certificates*/); 13182 // Hackily pretend we're still looking at a full code path 13183 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13184 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13185 } 13186 13187 // Extract cid from fullCodePath 13188 int eidx = fullCodePath.lastIndexOf("/"); 13189 String subStr1 = fullCodePath.substring(0, eidx); 13190 int sidx = subStr1.lastIndexOf("/"); 13191 cid = subStr1.substring(sidx+1, eidx); 13192 setMountPath(subStr1); 13193 } 13194 13195 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13196 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13197 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13198 instructionSets, null, null, null, 0, null /*certificates*/); 13199 this.cid = cid; 13200 setMountPath(PackageHelper.getSdDir(cid)); 13201 } 13202 13203 void createCopyFile() { 13204 cid = mInstallerService.allocateExternalStageCidLegacy(); 13205 } 13206 13207 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13208 if (origin.staged && origin.cid != null) { 13209 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13210 cid = origin.cid; 13211 setMountPath(PackageHelper.getSdDir(cid)); 13212 return PackageManager.INSTALL_SUCCEEDED; 13213 } 13214 13215 if (temp) { 13216 createCopyFile(); 13217 } else { 13218 /* 13219 * Pre-emptively destroy the container since it's destroyed if 13220 * copying fails due to it existing anyway. 13221 */ 13222 PackageHelper.destroySdDir(cid); 13223 } 13224 13225 final String newMountPath = imcs.copyPackageToContainer( 13226 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13227 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13228 13229 if (newMountPath != null) { 13230 setMountPath(newMountPath); 13231 return PackageManager.INSTALL_SUCCEEDED; 13232 } else { 13233 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13234 } 13235 } 13236 13237 @Override 13238 String getCodePath() { 13239 return packagePath; 13240 } 13241 13242 @Override 13243 String getResourcePath() { 13244 return resourcePath; 13245 } 13246 13247 int doPreInstall(int status) { 13248 if (status != PackageManager.INSTALL_SUCCEEDED) { 13249 // Destroy container 13250 PackageHelper.destroySdDir(cid); 13251 } else { 13252 boolean mounted = PackageHelper.isContainerMounted(cid); 13253 if (!mounted) { 13254 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13255 Process.SYSTEM_UID); 13256 if (newMountPath != null) { 13257 setMountPath(newMountPath); 13258 } else { 13259 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13260 } 13261 } 13262 } 13263 return status; 13264 } 13265 13266 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13267 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13268 String newMountPath = null; 13269 if (PackageHelper.isContainerMounted(cid)) { 13270 // Unmount the container 13271 if (!PackageHelper.unMountSdDir(cid)) { 13272 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13273 return false; 13274 } 13275 } 13276 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13277 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13278 " which might be stale. Will try to clean up."); 13279 // Clean up the stale container and proceed to recreate. 13280 if (!PackageHelper.destroySdDir(newCacheId)) { 13281 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13282 return false; 13283 } 13284 // Successfully cleaned up stale container. Try to rename again. 13285 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13286 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13287 + " inspite of cleaning it up."); 13288 return false; 13289 } 13290 } 13291 if (!PackageHelper.isContainerMounted(newCacheId)) { 13292 Slog.w(TAG, "Mounting container " + newCacheId); 13293 newMountPath = PackageHelper.mountSdDir(newCacheId, 13294 getEncryptKey(), Process.SYSTEM_UID); 13295 } else { 13296 newMountPath = PackageHelper.getSdDir(newCacheId); 13297 } 13298 if (newMountPath == null) { 13299 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13300 return false; 13301 } 13302 Log.i(TAG, "Succesfully renamed " + cid + 13303 " to " + newCacheId + 13304 " at new path: " + newMountPath); 13305 cid = newCacheId; 13306 13307 final File beforeCodeFile = new File(packagePath); 13308 setMountPath(newMountPath); 13309 final File afterCodeFile = new File(packagePath); 13310 13311 // Reflect the rename in scanned details 13312 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13313 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13314 afterCodeFile, pkg.baseCodePath)); 13315 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13316 afterCodeFile, pkg.splitCodePaths)); 13317 13318 // Reflect the rename in app info 13319 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13320 pkg.setApplicationInfoCodePath(pkg.codePath); 13321 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13322 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13323 pkg.setApplicationInfoResourcePath(pkg.codePath); 13324 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13325 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13326 13327 return true; 13328 } 13329 13330 private void setMountPath(String mountPath) { 13331 final File mountFile = new File(mountPath); 13332 13333 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13334 if (monolithicFile.exists()) { 13335 packagePath = monolithicFile.getAbsolutePath(); 13336 if (isFwdLocked()) { 13337 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13338 } else { 13339 resourcePath = packagePath; 13340 } 13341 } else { 13342 packagePath = mountFile.getAbsolutePath(); 13343 resourcePath = packagePath; 13344 } 13345 } 13346 13347 int doPostInstall(int status, int uid) { 13348 if (status != PackageManager.INSTALL_SUCCEEDED) { 13349 cleanUp(); 13350 } else { 13351 final int groupOwner; 13352 final String protectedFile; 13353 if (isFwdLocked()) { 13354 groupOwner = UserHandle.getSharedAppGid(uid); 13355 protectedFile = RES_FILE_NAME; 13356 } else { 13357 groupOwner = -1; 13358 protectedFile = null; 13359 } 13360 13361 if (uid < Process.FIRST_APPLICATION_UID 13362 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13363 Slog.e(TAG, "Failed to finalize " + cid); 13364 PackageHelper.destroySdDir(cid); 13365 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13366 } 13367 13368 boolean mounted = PackageHelper.isContainerMounted(cid); 13369 if (!mounted) { 13370 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13371 } 13372 } 13373 return status; 13374 } 13375 13376 private void cleanUp() { 13377 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13378 13379 // Destroy secure container 13380 PackageHelper.destroySdDir(cid); 13381 } 13382 13383 private List<String> getAllCodePaths() { 13384 final File codeFile = new File(getCodePath()); 13385 if (codeFile != null && codeFile.exists()) { 13386 try { 13387 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13388 return pkg.getAllCodePaths(); 13389 } catch (PackageParserException e) { 13390 // Ignored; we tried our best 13391 } 13392 } 13393 return Collections.EMPTY_LIST; 13394 } 13395 13396 void cleanUpResourcesLI() { 13397 // Enumerate all code paths before deleting 13398 cleanUpResourcesLI(getAllCodePaths()); 13399 } 13400 13401 private void cleanUpResourcesLI(List<String> allCodePaths) { 13402 cleanUp(); 13403 removeDexFiles(allCodePaths, instructionSets); 13404 } 13405 13406 String getPackageName() { 13407 return getAsecPackageName(cid); 13408 } 13409 13410 boolean doPostDeleteLI(boolean delete) { 13411 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13412 final List<String> allCodePaths = getAllCodePaths(); 13413 boolean mounted = PackageHelper.isContainerMounted(cid); 13414 if (mounted) { 13415 // Unmount first 13416 if (PackageHelper.unMountSdDir(cid)) { 13417 mounted = false; 13418 } 13419 } 13420 if (!mounted && delete) { 13421 cleanUpResourcesLI(allCodePaths); 13422 } 13423 return !mounted; 13424 } 13425 13426 @Override 13427 int doPreCopy() { 13428 if (isFwdLocked()) { 13429 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13430 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13431 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13432 } 13433 } 13434 13435 return PackageManager.INSTALL_SUCCEEDED; 13436 } 13437 13438 @Override 13439 int doPostCopy(int uid) { 13440 if (isFwdLocked()) { 13441 if (uid < Process.FIRST_APPLICATION_UID 13442 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13443 RES_FILE_NAME)) { 13444 Slog.e(TAG, "Failed to finalize " + cid); 13445 PackageHelper.destroySdDir(cid); 13446 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13447 } 13448 } 13449 13450 return PackageManager.INSTALL_SUCCEEDED; 13451 } 13452 } 13453 13454 /** 13455 * Logic to handle movement of existing installed applications. 13456 */ 13457 class MoveInstallArgs extends InstallArgs { 13458 private File codeFile; 13459 private File resourceFile; 13460 13461 /** New install */ 13462 MoveInstallArgs(InstallParams params) { 13463 super(params.origin, params.move, params.observer, params.installFlags, 13464 params.installerPackageName, params.volumeUuid, 13465 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13466 params.grantedRuntimePermissions, 13467 params.traceMethod, params.traceCookie, params.certificates); 13468 } 13469 13470 int copyApk(IMediaContainerService imcs, boolean temp) { 13471 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13472 + move.fromUuid + " to " + move.toUuid); 13473 synchronized (mInstaller) { 13474 try { 13475 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13476 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13477 } catch (InstallerException e) { 13478 Slog.w(TAG, "Failed to move app", e); 13479 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13480 } 13481 } 13482 13483 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13484 resourceFile = codeFile; 13485 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13486 13487 return PackageManager.INSTALL_SUCCEEDED; 13488 } 13489 13490 int doPreInstall(int status) { 13491 if (status != PackageManager.INSTALL_SUCCEEDED) { 13492 cleanUp(move.toUuid); 13493 } 13494 return status; 13495 } 13496 13497 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13498 if (status != PackageManager.INSTALL_SUCCEEDED) { 13499 cleanUp(move.toUuid); 13500 return false; 13501 } 13502 13503 // Reflect the move in app info 13504 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13505 pkg.setApplicationInfoCodePath(pkg.codePath); 13506 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13507 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13508 pkg.setApplicationInfoResourcePath(pkg.codePath); 13509 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13510 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13511 13512 return true; 13513 } 13514 13515 int doPostInstall(int status, int uid) { 13516 if (status == PackageManager.INSTALL_SUCCEEDED) { 13517 cleanUp(move.fromUuid); 13518 } else { 13519 cleanUp(move.toUuid); 13520 } 13521 return status; 13522 } 13523 13524 @Override 13525 String getCodePath() { 13526 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13527 } 13528 13529 @Override 13530 String getResourcePath() { 13531 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13532 } 13533 13534 private boolean cleanUp(String volumeUuid) { 13535 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13536 move.dataAppName); 13537 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13538 final int[] userIds = sUserManager.getUserIds(); 13539 synchronized (mInstallLock) { 13540 // Clean up both app data and code 13541 // All package moves are frozen until finished 13542 for (int userId : userIds) { 13543 try { 13544 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13545 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13546 } catch (InstallerException e) { 13547 Slog.w(TAG, String.valueOf(e)); 13548 } 13549 } 13550 removeCodePathLI(codeFile); 13551 } 13552 return true; 13553 } 13554 13555 void cleanUpResourcesLI() { 13556 throw new UnsupportedOperationException(); 13557 } 13558 13559 boolean doPostDeleteLI(boolean delete) { 13560 throw new UnsupportedOperationException(); 13561 } 13562 } 13563 13564 static String getAsecPackageName(String packageCid) { 13565 int idx = packageCid.lastIndexOf("-"); 13566 if (idx == -1) { 13567 return packageCid; 13568 } 13569 return packageCid.substring(0, idx); 13570 } 13571 13572 // Utility method used to create code paths based on package name and available index. 13573 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13574 String idxStr = ""; 13575 int idx = 1; 13576 // Fall back to default value of idx=1 if prefix is not 13577 // part of oldCodePath 13578 if (oldCodePath != null) { 13579 String subStr = oldCodePath; 13580 // Drop the suffix right away 13581 if (suffix != null && subStr.endsWith(suffix)) { 13582 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13583 } 13584 // If oldCodePath already contains prefix find out the 13585 // ending index to either increment or decrement. 13586 int sidx = subStr.lastIndexOf(prefix); 13587 if (sidx != -1) { 13588 subStr = subStr.substring(sidx + prefix.length()); 13589 if (subStr != null) { 13590 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13591 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13592 } 13593 try { 13594 idx = Integer.parseInt(subStr); 13595 if (idx <= 1) { 13596 idx++; 13597 } else { 13598 idx--; 13599 } 13600 } catch(NumberFormatException e) { 13601 } 13602 } 13603 } 13604 } 13605 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13606 return prefix + idxStr; 13607 } 13608 13609 private File getNextCodePath(File targetDir, String packageName) { 13610 int suffix = 1; 13611 File result; 13612 do { 13613 result = new File(targetDir, packageName + "-" + suffix); 13614 suffix++; 13615 } while (result.exists()); 13616 return result; 13617 } 13618 13619 // Utility method that returns the relative package path with respect 13620 // to the installation directory. Like say for /data/data/com.test-1.apk 13621 // string com.test-1 is returned. 13622 static String deriveCodePathName(String codePath) { 13623 if (codePath == null) { 13624 return null; 13625 } 13626 final File codeFile = new File(codePath); 13627 final String name = codeFile.getName(); 13628 if (codeFile.isDirectory()) { 13629 return name; 13630 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13631 final int lastDot = name.lastIndexOf('.'); 13632 return name.substring(0, lastDot); 13633 } else { 13634 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13635 return null; 13636 } 13637 } 13638 13639 static class PackageInstalledInfo { 13640 String name; 13641 int uid; 13642 // The set of users that originally had this package installed. 13643 int[] origUsers; 13644 // The set of users that now have this package installed. 13645 int[] newUsers; 13646 PackageParser.Package pkg; 13647 int returnCode; 13648 String returnMsg; 13649 PackageRemovedInfo removedInfo; 13650 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13651 13652 public void setError(int code, String msg) { 13653 setReturnCode(code); 13654 setReturnMessage(msg); 13655 Slog.w(TAG, msg); 13656 } 13657 13658 public void setError(String msg, PackageParserException e) { 13659 setReturnCode(e.error); 13660 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13661 Slog.w(TAG, msg, e); 13662 } 13663 13664 public void setError(String msg, PackageManagerException e) { 13665 returnCode = e.error; 13666 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13667 Slog.w(TAG, msg, e); 13668 } 13669 13670 public void setReturnCode(int returnCode) { 13671 this.returnCode = returnCode; 13672 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13673 for (int i = 0; i < childCount; i++) { 13674 addedChildPackages.valueAt(i).returnCode = returnCode; 13675 } 13676 } 13677 13678 private void setReturnMessage(String returnMsg) { 13679 this.returnMsg = returnMsg; 13680 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13681 for (int i = 0; i < childCount; i++) { 13682 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13683 } 13684 } 13685 13686 // In some error cases we want to convey more info back to the observer 13687 String origPackage; 13688 String origPermission; 13689 } 13690 13691 /* 13692 * Install a non-existing package. 13693 */ 13694 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13695 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13696 PackageInstalledInfo res) { 13697 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13698 13699 // Remember this for later, in case we need to rollback this install 13700 String pkgName = pkg.packageName; 13701 13702 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13703 13704 synchronized(mPackages) { 13705 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13706 // A package with the same name is already installed, though 13707 // it has been renamed to an older name. The package we 13708 // are trying to install should be installed as an update to 13709 // the existing one, but that has not been requested, so bail. 13710 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13711 + " without first uninstalling package running as " 13712 + mSettings.mRenamedPackages.get(pkgName)); 13713 return; 13714 } 13715 if (mPackages.containsKey(pkgName)) { 13716 // Don't allow installation over an existing package with the same name. 13717 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13718 + " without first uninstalling."); 13719 return; 13720 } 13721 } 13722 13723 try { 13724 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13725 System.currentTimeMillis(), user); 13726 13727 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13728 13729 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13730 prepareAppDataAfterInstallLIF(newPackage); 13731 13732 } else { 13733 // Remove package from internal structures, but keep around any 13734 // data that might have already existed 13735 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13736 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13737 } 13738 } catch (PackageManagerException e) { 13739 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13740 } 13741 13742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13743 } 13744 13745 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13746 // Can't rotate keys during boot or if sharedUser. 13747 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13748 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13749 return false; 13750 } 13751 // app is using upgradeKeySets; make sure all are valid 13752 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13753 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13754 for (int i = 0; i < upgradeKeySets.length; i++) { 13755 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13756 Slog.wtf(TAG, "Package " 13757 + (oldPs.name != null ? oldPs.name : "<null>") 13758 + " contains upgrade-key-set reference to unknown key-set: " 13759 + upgradeKeySets[i] 13760 + " reverting to signatures check."); 13761 return false; 13762 } 13763 } 13764 return true; 13765 } 13766 13767 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13768 // Upgrade keysets are being used. Determine if new package has a superset of the 13769 // required keys. 13770 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13771 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13772 for (int i = 0; i < upgradeKeySets.length; i++) { 13773 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13774 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13775 return true; 13776 } 13777 } 13778 return false; 13779 } 13780 13781 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13782 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13783 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13784 13785 final PackageParser.Package oldPackage; 13786 final String pkgName = pkg.packageName; 13787 final int[] allUsers; 13788 13789 // First find the old package info and check signatures 13790 synchronized(mPackages) { 13791 oldPackage = mPackages.get(pkgName); 13792 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13793 if (isEphemeral && !oldIsEphemeral) { 13794 // can't downgrade from full to ephemeral 13795 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13796 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13797 return; 13798 } 13799 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13800 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13801 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13802 if (!checkUpgradeKeySetLP(ps, pkg)) { 13803 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13804 "New package not signed by keys specified by upgrade-keysets: " 13805 + pkgName); 13806 return; 13807 } 13808 } else { 13809 // default to original signature matching 13810 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13811 != PackageManager.SIGNATURE_MATCH) { 13812 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13813 "New package has a different signature: " + pkgName); 13814 return; 13815 } 13816 } 13817 13818 // Check for shared user id changes 13819 String invalidPackageName = 13820 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13821 if (invalidPackageName != null) { 13822 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13823 "Package " + invalidPackageName + " tried to change user " 13824 + oldPackage.mSharedUserId); 13825 return; 13826 } 13827 13828 // In case of rollback, remember per-user/profile install state 13829 allUsers = sUserManager.getUserIds(); 13830 } 13831 13832 // Update what is removed 13833 res.removedInfo = new PackageRemovedInfo(); 13834 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13835 res.removedInfo.removedPackage = oldPackage.packageName; 13836 res.removedInfo.isUpdate = true; 13837 final int childCount = (oldPackage.childPackages != null) 13838 ? oldPackage.childPackages.size() : 0; 13839 for (int i = 0; i < childCount; i++) { 13840 boolean childPackageUpdated = false; 13841 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13842 if (res.addedChildPackages != null) { 13843 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13844 if (childRes != null) { 13845 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13846 childRes.removedInfo.removedPackage = childPkg.packageName; 13847 childRes.removedInfo.isUpdate = true; 13848 childPackageUpdated = true; 13849 } 13850 } 13851 if (!childPackageUpdated) { 13852 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13853 childRemovedRes.removedPackage = childPkg.packageName; 13854 childRemovedRes.isUpdate = false; 13855 childRemovedRes.dataRemoved = true; 13856 synchronized (mPackages) { 13857 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13858 if (childPs != null) { 13859 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13860 } 13861 } 13862 if (res.removedInfo.removedChildPackages == null) { 13863 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13864 } 13865 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13866 } 13867 } 13868 13869 boolean sysPkg = (isSystemApp(oldPackage)); 13870 if (sysPkg) { 13871 // Set the system/privileged flags as needed 13872 final boolean privileged = 13873 (oldPackage.applicationInfo.privateFlags 13874 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13875 final int systemPolicyFlags = policyFlags 13876 | PackageParser.PARSE_IS_SYSTEM 13877 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13878 13879 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13880 user, allUsers, installerPackageName, res); 13881 } else { 13882 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13883 user, allUsers, installerPackageName, res); 13884 } 13885 } 13886 13887 public List<String> getPreviousCodePaths(String packageName) { 13888 final PackageSetting ps = mSettings.mPackages.get(packageName); 13889 final List<String> result = new ArrayList<String>(); 13890 if (ps != null && ps.oldCodePaths != null) { 13891 result.addAll(ps.oldCodePaths); 13892 } 13893 return result; 13894 } 13895 13896 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13897 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13898 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13899 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13900 + deletedPackage); 13901 13902 String pkgName = deletedPackage.packageName; 13903 boolean deletedPkg = true; 13904 boolean addedPkg = false; 13905 boolean updatedSettings = false; 13906 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13907 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13908 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13909 13910 final long origUpdateTime = (pkg.mExtras != null) 13911 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13912 13913 // First delete the existing package while retaining the data directory 13914 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13915 res.removedInfo, true, pkg)) { 13916 // If the existing package wasn't successfully deleted 13917 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13918 deletedPkg = false; 13919 } else { 13920 // Successfully deleted the old package; proceed with replace. 13921 13922 // If deleted package lived in a container, give users a chance to 13923 // relinquish resources before killing. 13924 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13925 if (DEBUG_INSTALL) { 13926 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13927 } 13928 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13929 final ArrayList<String> pkgList = new ArrayList<String>(1); 13930 pkgList.add(deletedPackage.applicationInfo.packageName); 13931 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13932 } 13933 13934 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13935 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13936 clearAppProfilesLIF(pkg); 13937 13938 try { 13939 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13940 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13941 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13942 13943 // Update the in-memory copy of the previous code paths. 13944 PackageSetting ps = mSettings.mPackages.get(pkgName); 13945 if (!killApp) { 13946 if (ps.oldCodePaths == null) { 13947 ps.oldCodePaths = new ArraySet<>(); 13948 } 13949 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13950 if (deletedPackage.splitCodePaths != null) { 13951 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13952 } 13953 } else { 13954 ps.oldCodePaths = null; 13955 } 13956 if (ps.childPackageNames != null) { 13957 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13958 final String childPkgName = ps.childPackageNames.get(i); 13959 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13960 childPs.oldCodePaths = ps.oldCodePaths; 13961 } 13962 } 13963 prepareAppDataAfterInstallLIF(newPackage); 13964 addedPkg = true; 13965 } catch (PackageManagerException e) { 13966 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13967 } 13968 } 13969 13970 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13971 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13972 13973 // Revert all internal state mutations and added folders for the failed install 13974 if (addedPkg) { 13975 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13976 res.removedInfo, true, null); 13977 } 13978 13979 // Restore the old package 13980 if (deletedPkg) { 13981 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13982 File restoreFile = new File(deletedPackage.codePath); 13983 // Parse old package 13984 boolean oldExternal = isExternal(deletedPackage); 13985 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13986 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13987 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13988 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13989 try { 13990 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13991 null); 13992 } catch (PackageManagerException e) { 13993 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13994 + e.getMessage()); 13995 return; 13996 } 13997 13998 synchronized (mPackages) { 13999 // Ensure the installer package name up to date 14000 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14001 14002 // Update permissions for restored package 14003 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14004 14005 mSettings.writeLPr(); 14006 } 14007 14008 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14009 } 14010 } else { 14011 synchronized (mPackages) { 14012 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14013 if (ps != null) { 14014 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14015 if (res.removedInfo.removedChildPackages != null) { 14016 final int childCount = res.removedInfo.removedChildPackages.size(); 14017 // Iterate in reverse as we may modify the collection 14018 for (int i = childCount - 1; i >= 0; i--) { 14019 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14020 if (res.addedChildPackages.containsKey(childPackageName)) { 14021 res.removedInfo.removedChildPackages.removeAt(i); 14022 } else { 14023 PackageRemovedInfo childInfo = res.removedInfo 14024 .removedChildPackages.valueAt(i); 14025 childInfo.removedForAllUsers = mPackages.get( 14026 childInfo.removedPackage) == null; 14027 } 14028 } 14029 } 14030 } 14031 } 14032 } 14033 } 14034 14035 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14036 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14037 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14038 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14039 + ", old=" + deletedPackage); 14040 14041 final boolean disabledSystem; 14042 14043 // Remove existing system package 14044 removePackageLI(deletedPackage, true); 14045 14046 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14047 if (!disabledSystem) { 14048 // We didn't need to disable the .apk as a current system package, 14049 // which means we are replacing another update that is already 14050 // installed. We need to make sure to delete the older one's .apk. 14051 res.removedInfo.args = createInstallArgsForExisting(0, 14052 deletedPackage.applicationInfo.getCodePath(), 14053 deletedPackage.applicationInfo.getResourcePath(), 14054 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14055 } else { 14056 res.removedInfo.args = null; 14057 } 14058 14059 // Successfully disabled the old package. Now proceed with re-installation 14060 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14061 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14062 clearAppProfilesLIF(pkg); 14063 14064 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14065 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14066 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14067 14068 PackageParser.Package newPackage = null; 14069 try { 14070 // Add the package to the internal data structures 14071 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14072 14073 // Set the update and install times 14074 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14075 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14076 System.currentTimeMillis()); 14077 14078 // Update the package dynamic state if succeeded 14079 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14080 // Now that the install succeeded make sure we remove data 14081 // directories for any child package the update removed. 14082 final int deletedChildCount = (deletedPackage.childPackages != null) 14083 ? deletedPackage.childPackages.size() : 0; 14084 final int newChildCount = (newPackage.childPackages != null) 14085 ? newPackage.childPackages.size() : 0; 14086 for (int i = 0; i < deletedChildCount; i++) { 14087 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14088 boolean childPackageDeleted = true; 14089 for (int j = 0; j < newChildCount; j++) { 14090 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14091 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14092 childPackageDeleted = false; 14093 break; 14094 } 14095 } 14096 if (childPackageDeleted) { 14097 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14098 deletedChildPkg.packageName); 14099 if (ps != null && res.removedInfo.removedChildPackages != null) { 14100 PackageRemovedInfo removedChildRes = res.removedInfo 14101 .removedChildPackages.get(deletedChildPkg.packageName); 14102 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14103 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14104 } 14105 } 14106 } 14107 14108 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14109 prepareAppDataAfterInstallLIF(newPackage); 14110 } 14111 } catch (PackageManagerException e) { 14112 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14113 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14114 } 14115 14116 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14117 // Re installation failed. Restore old information 14118 // Remove new pkg information 14119 if (newPackage != null) { 14120 removeInstalledPackageLI(newPackage, true); 14121 } 14122 // Add back the old system package 14123 try { 14124 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14125 } catch (PackageManagerException e) { 14126 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14127 } 14128 14129 synchronized (mPackages) { 14130 if (disabledSystem) { 14131 enableSystemPackageLPw(deletedPackage); 14132 } 14133 14134 // Ensure the installer package name up to date 14135 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14136 14137 // Update permissions for restored package 14138 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14139 14140 mSettings.writeLPr(); 14141 } 14142 14143 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14144 + " after failed upgrade"); 14145 } 14146 } 14147 14148 /** 14149 * Checks whether the parent or any of the child packages have a change shared 14150 * user. For a package to be a valid update the shred users of the parent and 14151 * the children should match. We may later support changing child shared users. 14152 * @param oldPkg The updated package. 14153 * @param newPkg The update package. 14154 * @return The shared user that change between the versions. 14155 */ 14156 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14157 PackageParser.Package newPkg) { 14158 // Check parent shared user 14159 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14160 return newPkg.packageName; 14161 } 14162 // Check child shared users 14163 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14164 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14165 for (int i = 0; i < newChildCount; i++) { 14166 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14167 // If this child was present, did it have the same shared user? 14168 for (int j = 0; j < oldChildCount; j++) { 14169 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14170 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14171 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14172 return newChildPkg.packageName; 14173 } 14174 } 14175 } 14176 return null; 14177 } 14178 14179 private void removeNativeBinariesLI(PackageSetting ps) { 14180 // Remove the lib path for the parent package 14181 if (ps != null) { 14182 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14183 // Remove the lib path for the child packages 14184 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14185 for (int i = 0; i < childCount; i++) { 14186 PackageSetting childPs = null; 14187 synchronized (mPackages) { 14188 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14189 } 14190 if (childPs != null) { 14191 NativeLibraryHelper.removeNativeBinariesLI(childPs 14192 .legacyNativeLibraryPathString); 14193 } 14194 } 14195 } 14196 } 14197 14198 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14199 // Enable the parent package 14200 mSettings.enableSystemPackageLPw(pkg.packageName); 14201 // Enable the child packages 14202 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14203 for (int i = 0; i < childCount; i++) { 14204 PackageParser.Package childPkg = pkg.childPackages.get(i); 14205 mSettings.enableSystemPackageLPw(childPkg.packageName); 14206 } 14207 } 14208 14209 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14210 PackageParser.Package newPkg) { 14211 // Disable the parent package (parent always replaced) 14212 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14213 // Disable the child packages 14214 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14215 for (int i = 0; i < childCount; i++) { 14216 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14217 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14218 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14219 } 14220 return disabled; 14221 } 14222 14223 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14224 String installerPackageName) { 14225 // Enable the parent package 14226 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14227 // Enable the child packages 14228 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14229 for (int i = 0; i < childCount; i++) { 14230 PackageParser.Package childPkg = pkg.childPackages.get(i); 14231 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14232 } 14233 } 14234 14235 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14236 // Collect all used permissions in the UID 14237 ArraySet<String> usedPermissions = new ArraySet<>(); 14238 final int packageCount = su.packages.size(); 14239 for (int i = 0; i < packageCount; i++) { 14240 PackageSetting ps = su.packages.valueAt(i); 14241 if (ps.pkg == null) { 14242 continue; 14243 } 14244 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14245 for (int j = 0; j < requestedPermCount; j++) { 14246 String permission = ps.pkg.requestedPermissions.get(j); 14247 BasePermission bp = mSettings.mPermissions.get(permission); 14248 if (bp != null) { 14249 usedPermissions.add(permission); 14250 } 14251 } 14252 } 14253 14254 PermissionsState permissionsState = su.getPermissionsState(); 14255 // Prune install permissions 14256 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14257 final int installPermCount = installPermStates.size(); 14258 for (int i = installPermCount - 1; i >= 0; i--) { 14259 PermissionState permissionState = installPermStates.get(i); 14260 if (!usedPermissions.contains(permissionState.getName())) { 14261 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14262 if (bp != null) { 14263 permissionsState.revokeInstallPermission(bp); 14264 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14265 PackageManager.MASK_PERMISSION_FLAGS, 0); 14266 } 14267 } 14268 } 14269 14270 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14271 14272 // Prune runtime permissions 14273 for (int userId : allUserIds) { 14274 List<PermissionState> runtimePermStates = permissionsState 14275 .getRuntimePermissionStates(userId); 14276 final int runtimePermCount = runtimePermStates.size(); 14277 for (int i = runtimePermCount - 1; i >= 0; i--) { 14278 PermissionState permissionState = runtimePermStates.get(i); 14279 if (!usedPermissions.contains(permissionState.getName())) { 14280 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14281 if (bp != null) { 14282 permissionsState.revokeRuntimePermission(bp, userId); 14283 permissionsState.updatePermissionFlags(bp, userId, 14284 PackageManager.MASK_PERMISSION_FLAGS, 0); 14285 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14286 runtimePermissionChangedUserIds, userId); 14287 } 14288 } 14289 } 14290 } 14291 14292 return runtimePermissionChangedUserIds; 14293 } 14294 14295 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14296 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14297 // Update the parent package setting 14298 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14299 res, user); 14300 // Update the child packages setting 14301 final int childCount = (newPackage.childPackages != null) 14302 ? newPackage.childPackages.size() : 0; 14303 for (int i = 0; i < childCount; i++) { 14304 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14305 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14306 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14307 childRes.origUsers, childRes, user); 14308 } 14309 } 14310 14311 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14312 String installerPackageName, int[] allUsers, int[] installedForUsers, 14313 PackageInstalledInfo res, UserHandle user) { 14314 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14315 14316 String pkgName = newPackage.packageName; 14317 synchronized (mPackages) { 14318 //write settings. the installStatus will be incomplete at this stage. 14319 //note that the new package setting would have already been 14320 //added to mPackages. It hasn't been persisted yet. 14321 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14322 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14323 mSettings.writeLPr(); 14324 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14325 } 14326 14327 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14328 synchronized (mPackages) { 14329 updatePermissionsLPw(newPackage.packageName, newPackage, 14330 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14331 ? UPDATE_PERMISSIONS_ALL : 0)); 14332 // For system-bundled packages, we assume that installing an upgraded version 14333 // of the package implies that the user actually wants to run that new code, 14334 // so we enable the package. 14335 PackageSetting ps = mSettings.mPackages.get(pkgName); 14336 final int userId = user.getIdentifier(); 14337 if (ps != null) { 14338 if (isSystemApp(newPackage)) { 14339 if (DEBUG_INSTALL) { 14340 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14341 } 14342 // Enable system package for requested users 14343 if (res.origUsers != null) { 14344 for (int origUserId : res.origUsers) { 14345 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14346 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14347 origUserId, installerPackageName); 14348 } 14349 } 14350 } 14351 // Also convey the prior install/uninstall state 14352 if (allUsers != null && installedForUsers != null) { 14353 for (int currentUserId : allUsers) { 14354 final boolean installed = ArrayUtils.contains( 14355 installedForUsers, currentUserId); 14356 if (DEBUG_INSTALL) { 14357 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14358 } 14359 ps.setInstalled(installed, currentUserId); 14360 } 14361 // these install state changes will be persisted in the 14362 // upcoming call to mSettings.writeLPr(). 14363 } 14364 } 14365 // It's implied that when a user requests installation, they want the app to be 14366 // installed and enabled. 14367 if (userId != UserHandle.USER_ALL) { 14368 ps.setInstalled(true, userId); 14369 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14370 } 14371 } 14372 res.name = pkgName; 14373 res.uid = newPackage.applicationInfo.uid; 14374 res.pkg = newPackage; 14375 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14376 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14377 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14378 //to update install status 14379 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14380 mSettings.writeLPr(); 14381 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14382 } 14383 14384 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14385 } 14386 14387 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14388 try { 14389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14390 installPackageLI(args, res); 14391 } finally { 14392 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14393 } 14394 } 14395 14396 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14397 final int installFlags = args.installFlags; 14398 final String installerPackageName = args.installerPackageName; 14399 final String volumeUuid = args.volumeUuid; 14400 final File tmpPackageFile = new File(args.getCodePath()); 14401 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14402 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14403 || (args.volumeUuid != null)); 14404 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14405 boolean replace = false; 14406 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14407 if (args.move != null) { 14408 // moving a complete application; perform an initial scan on the new install location 14409 scanFlags |= SCAN_INITIAL; 14410 } 14411 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14412 scanFlags |= SCAN_DONT_KILL_APP; 14413 } 14414 14415 // Result object to be returned 14416 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14417 14418 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14419 14420 // Sanity check 14421 if (ephemeral && (forwardLocked || onExternal)) { 14422 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14423 + " external=" + onExternal); 14424 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14425 return; 14426 } 14427 14428 // Retrieve PackageSettings and parse package 14429 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14430 | PackageParser.PARSE_ENFORCE_CODE 14431 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14432 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14433 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14434 PackageParser pp = new PackageParser(); 14435 pp.setSeparateProcesses(mSeparateProcesses); 14436 pp.setDisplayMetrics(mMetrics); 14437 14438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14439 final PackageParser.Package pkg; 14440 try { 14441 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14442 } catch (PackageParserException e) { 14443 res.setError("Failed parse during installPackageLI", e); 14444 return; 14445 } finally { 14446 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14447 } 14448 14449 // If we are installing a clustered package add results for the children 14450 if (pkg.childPackages != null) { 14451 synchronized (mPackages) { 14452 final int childCount = pkg.childPackages.size(); 14453 for (int i = 0; i < childCount; i++) { 14454 PackageParser.Package childPkg = pkg.childPackages.get(i); 14455 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14456 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14457 childRes.pkg = childPkg; 14458 childRes.name = childPkg.packageName; 14459 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14460 if (childPs != null) { 14461 childRes.origUsers = childPs.queryInstalledUsers( 14462 sUserManager.getUserIds(), true); 14463 } 14464 if ((mPackages.containsKey(childPkg.packageName))) { 14465 childRes.removedInfo = new PackageRemovedInfo(); 14466 childRes.removedInfo.removedPackage = childPkg.packageName; 14467 } 14468 if (res.addedChildPackages == null) { 14469 res.addedChildPackages = new ArrayMap<>(); 14470 } 14471 res.addedChildPackages.put(childPkg.packageName, childRes); 14472 } 14473 } 14474 } 14475 14476 // If package doesn't declare API override, mark that we have an install 14477 // time CPU ABI override. 14478 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14479 pkg.cpuAbiOverride = args.abiOverride; 14480 } 14481 14482 String pkgName = res.name = pkg.packageName; 14483 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14484 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14485 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14486 return; 14487 } 14488 } 14489 14490 try { 14491 // either use what we've been given or parse directly from the APK 14492 if (args.certificates != null) { 14493 try { 14494 PackageParser.populateCertificates(pkg, args.certificates); 14495 } catch (PackageParserException e) { 14496 // there was something wrong with the certificates we were given; 14497 // try to pull them from the APK 14498 PackageParser.collectCertificates(pkg, parseFlags); 14499 } 14500 } else { 14501 PackageParser.collectCertificates(pkg, parseFlags); 14502 } 14503 } catch (PackageParserException e) { 14504 res.setError("Failed collect during installPackageLI", e); 14505 return; 14506 } 14507 14508 // Get rid of all references to package scan path via parser. 14509 pp = null; 14510 String oldCodePath = null; 14511 boolean systemApp = false; 14512 synchronized (mPackages) { 14513 // Check if installing already existing package 14514 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14515 String oldName = mSettings.mRenamedPackages.get(pkgName); 14516 if (pkg.mOriginalPackages != null 14517 && pkg.mOriginalPackages.contains(oldName) 14518 && mPackages.containsKey(oldName)) { 14519 // This package is derived from an original package, 14520 // and this device has been updating from that original 14521 // name. We must continue using the original name, so 14522 // rename the new package here. 14523 pkg.setPackageName(oldName); 14524 pkgName = pkg.packageName; 14525 replace = true; 14526 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14527 + oldName + " pkgName=" + pkgName); 14528 } else if (mPackages.containsKey(pkgName)) { 14529 // This package, under its official name, already exists 14530 // on the device; we should replace it. 14531 replace = true; 14532 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14533 } 14534 14535 // Child packages are installed through the parent package 14536 if (pkg.parentPackage != null) { 14537 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14538 "Package " + pkg.packageName + " is child of package " 14539 + pkg.parentPackage.parentPackage + ". Child packages " 14540 + "can be updated only through the parent package."); 14541 return; 14542 } 14543 14544 if (replace) { 14545 // Prevent apps opting out from runtime permissions 14546 PackageParser.Package oldPackage = mPackages.get(pkgName); 14547 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14548 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14549 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14550 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14551 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14552 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14553 + " doesn't support runtime permissions but the old" 14554 + " target SDK " + oldTargetSdk + " does."); 14555 return; 14556 } 14557 14558 // Prevent installing of child packages 14559 if (oldPackage.parentPackage != null) { 14560 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14561 "Package " + pkg.packageName + " is child of package " 14562 + oldPackage.parentPackage + ". Child packages " 14563 + "can be updated only through the parent package."); 14564 return; 14565 } 14566 } 14567 } 14568 14569 PackageSetting ps = mSettings.mPackages.get(pkgName); 14570 if (ps != null) { 14571 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14572 14573 // Quick sanity check that we're signed correctly if updating; 14574 // we'll check this again later when scanning, but we want to 14575 // bail early here before tripping over redefined permissions. 14576 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14577 if (!checkUpgradeKeySetLP(ps, pkg)) { 14578 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14579 + pkg.packageName + " upgrade keys do not match the " 14580 + "previously installed version"); 14581 return; 14582 } 14583 } else { 14584 try { 14585 verifySignaturesLP(ps, pkg); 14586 } catch (PackageManagerException e) { 14587 res.setError(e.error, e.getMessage()); 14588 return; 14589 } 14590 } 14591 14592 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14593 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14594 systemApp = (ps.pkg.applicationInfo.flags & 14595 ApplicationInfo.FLAG_SYSTEM) != 0; 14596 } 14597 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14598 } 14599 14600 // Check whether the newly-scanned package wants to define an already-defined perm 14601 int N = pkg.permissions.size(); 14602 for (int i = N-1; i >= 0; i--) { 14603 PackageParser.Permission perm = pkg.permissions.get(i); 14604 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14605 if (bp != null) { 14606 // If the defining package is signed with our cert, it's okay. This 14607 // also includes the "updating the same package" case, of course. 14608 // "updating same package" could also involve key-rotation. 14609 final boolean sigsOk; 14610 if (bp.sourcePackage.equals(pkg.packageName) 14611 && (bp.packageSetting instanceof PackageSetting) 14612 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14613 scanFlags))) { 14614 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14615 } else { 14616 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14617 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14618 } 14619 if (!sigsOk) { 14620 // If the owning package is the system itself, we log but allow 14621 // install to proceed; we fail the install on all other permission 14622 // redefinitions. 14623 if (!bp.sourcePackage.equals("android")) { 14624 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14625 + pkg.packageName + " attempting to redeclare permission " 14626 + perm.info.name + " already owned by " + bp.sourcePackage); 14627 res.origPermission = perm.info.name; 14628 res.origPackage = bp.sourcePackage; 14629 return; 14630 } else { 14631 Slog.w(TAG, "Package " + pkg.packageName 14632 + " attempting to redeclare system permission " 14633 + perm.info.name + "; ignoring new declaration"); 14634 pkg.permissions.remove(i); 14635 } 14636 } 14637 } 14638 } 14639 } 14640 14641 if (systemApp) { 14642 if (onExternal) { 14643 // Abort update; system app can't be replaced with app on sdcard 14644 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14645 "Cannot install updates to system apps on sdcard"); 14646 return; 14647 } else if (ephemeral) { 14648 // Abort update; system app can't be replaced with an ephemeral app 14649 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14650 "Cannot update a system app with an ephemeral app"); 14651 return; 14652 } 14653 } 14654 14655 if (args.move != null) { 14656 // We did an in-place move, so dex is ready to roll 14657 scanFlags |= SCAN_NO_DEX; 14658 scanFlags |= SCAN_MOVE; 14659 14660 synchronized (mPackages) { 14661 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14662 if (ps == null) { 14663 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14664 "Missing settings for moved package " + pkgName); 14665 } 14666 14667 // We moved the entire application as-is, so bring over the 14668 // previously derived ABI information. 14669 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14670 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14671 } 14672 14673 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14674 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14675 scanFlags |= SCAN_NO_DEX; 14676 14677 try { 14678 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14679 args.abiOverride : pkg.cpuAbiOverride); 14680 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14681 true /* extract libs */); 14682 } catch (PackageManagerException pme) { 14683 Slog.e(TAG, "Error deriving application ABI", pme); 14684 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14685 return; 14686 } 14687 14688 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14689 // Do not run PackageDexOptimizer through the local performDexOpt 14690 // method because `pkg` is not in `mPackages` yet. 14691 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14692 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14693 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14694 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14695 String msg = "Extracting package failed for " + pkgName; 14696 res.setError(INSTALL_FAILED_DEXOPT, msg); 14697 return; 14698 } 14699 14700 // Notify BackgroundDexOptService that the package has been changed. 14701 // If this is an update of a package which used to fail to compile, 14702 // BDOS will remove it from its blacklist. 14703 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14704 } 14705 14706 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14707 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14708 return; 14709 } 14710 14711 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14712 14713 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14714 "installPackageLI")) { 14715 if (replace) { 14716 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14717 installerPackageName, res); 14718 } else { 14719 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14720 args.user, installerPackageName, volumeUuid, res); 14721 } 14722 } 14723 synchronized (mPackages) { 14724 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14725 if (ps != null) { 14726 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14727 } 14728 14729 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14730 for (int i = 0; i < childCount; i++) { 14731 PackageParser.Package childPkg = pkg.childPackages.get(i); 14732 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14733 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14734 if (childPs != null) { 14735 childRes.newUsers = childPs.queryInstalledUsers( 14736 sUserManager.getUserIds(), true); 14737 } 14738 } 14739 } 14740 } 14741 14742 private void startIntentFilterVerifications(int userId, boolean replacing, 14743 PackageParser.Package pkg) { 14744 if (mIntentFilterVerifierComponent == null) { 14745 Slog.w(TAG, "No IntentFilter verification will not be done as " 14746 + "there is no IntentFilterVerifier available!"); 14747 return; 14748 } 14749 14750 final int verifierUid = getPackageUid( 14751 mIntentFilterVerifierComponent.getPackageName(), 14752 MATCH_DEBUG_TRIAGED_MISSING, 14753 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14754 14755 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14756 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14757 mHandler.sendMessage(msg); 14758 14759 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14760 for (int i = 0; i < childCount; i++) { 14761 PackageParser.Package childPkg = pkg.childPackages.get(i); 14762 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14763 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14764 mHandler.sendMessage(msg); 14765 } 14766 } 14767 14768 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14769 PackageParser.Package pkg) { 14770 int size = pkg.activities.size(); 14771 if (size == 0) { 14772 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14773 "No activity, so no need to verify any IntentFilter!"); 14774 return; 14775 } 14776 14777 final boolean hasDomainURLs = hasDomainURLs(pkg); 14778 if (!hasDomainURLs) { 14779 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14780 "No domain URLs, so no need to verify any IntentFilter!"); 14781 return; 14782 } 14783 14784 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14785 + " if any IntentFilter from the " + size 14786 + " Activities needs verification ..."); 14787 14788 int count = 0; 14789 final String packageName = pkg.packageName; 14790 14791 synchronized (mPackages) { 14792 // If this is a new install and we see that we've already run verification for this 14793 // package, we have nothing to do: it means the state was restored from backup. 14794 if (!replacing) { 14795 IntentFilterVerificationInfo ivi = 14796 mSettings.getIntentFilterVerificationLPr(packageName); 14797 if (ivi != null) { 14798 if (DEBUG_DOMAIN_VERIFICATION) { 14799 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14800 + ivi.getStatusString()); 14801 } 14802 return; 14803 } 14804 } 14805 14806 // If any filters need to be verified, then all need to be. 14807 boolean needToVerify = false; 14808 for (PackageParser.Activity a : pkg.activities) { 14809 for (ActivityIntentInfo filter : a.intents) { 14810 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14811 if (DEBUG_DOMAIN_VERIFICATION) { 14812 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14813 } 14814 needToVerify = true; 14815 break; 14816 } 14817 } 14818 } 14819 14820 if (needToVerify) { 14821 final int verificationId = mIntentFilterVerificationToken++; 14822 for (PackageParser.Activity a : pkg.activities) { 14823 for (ActivityIntentInfo filter : a.intents) { 14824 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14825 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14826 "Verification needed for IntentFilter:" + filter.toString()); 14827 mIntentFilterVerifier.addOneIntentFilterVerification( 14828 verifierUid, userId, verificationId, filter, packageName); 14829 count++; 14830 } 14831 } 14832 } 14833 } 14834 } 14835 14836 if (count > 0) { 14837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14838 + " IntentFilter verification" + (count > 1 ? "s" : "") 14839 + " for userId:" + userId); 14840 mIntentFilterVerifier.startVerifications(userId); 14841 } else { 14842 if (DEBUG_DOMAIN_VERIFICATION) { 14843 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14844 } 14845 } 14846 } 14847 14848 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14849 final ComponentName cn = filter.activity.getComponentName(); 14850 final String packageName = cn.getPackageName(); 14851 14852 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14853 packageName); 14854 if (ivi == null) { 14855 return true; 14856 } 14857 int status = ivi.getStatus(); 14858 switch (status) { 14859 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14860 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14861 return true; 14862 14863 default: 14864 // Nothing to do 14865 return false; 14866 } 14867 } 14868 14869 private static boolean isMultiArch(ApplicationInfo info) { 14870 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14871 } 14872 14873 private static boolean isExternal(PackageParser.Package pkg) { 14874 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14875 } 14876 14877 private static boolean isExternal(PackageSetting ps) { 14878 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14879 } 14880 14881 private static boolean isEphemeral(PackageParser.Package pkg) { 14882 return pkg.applicationInfo.isEphemeralApp(); 14883 } 14884 14885 private static boolean isEphemeral(PackageSetting ps) { 14886 return ps.pkg != null && isEphemeral(ps.pkg); 14887 } 14888 14889 private static boolean isSystemApp(PackageParser.Package pkg) { 14890 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14891 } 14892 14893 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14894 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14895 } 14896 14897 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14898 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14899 } 14900 14901 private static boolean isSystemApp(PackageSetting ps) { 14902 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14903 } 14904 14905 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14906 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14907 } 14908 14909 private int packageFlagsToInstallFlags(PackageSetting ps) { 14910 int installFlags = 0; 14911 if (isEphemeral(ps)) { 14912 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14913 } 14914 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14915 // This existing package was an external ASEC install when we have 14916 // the external flag without a UUID 14917 installFlags |= PackageManager.INSTALL_EXTERNAL; 14918 } 14919 if (ps.isForwardLocked()) { 14920 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14921 } 14922 return installFlags; 14923 } 14924 14925 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14926 if (isExternal(pkg)) { 14927 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14928 return StorageManager.UUID_PRIMARY_PHYSICAL; 14929 } else { 14930 return pkg.volumeUuid; 14931 } 14932 } else { 14933 return StorageManager.UUID_PRIVATE_INTERNAL; 14934 } 14935 } 14936 14937 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14938 if (isExternal(pkg)) { 14939 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14940 return mSettings.getExternalVersion(); 14941 } else { 14942 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14943 } 14944 } else { 14945 return mSettings.getInternalVersion(); 14946 } 14947 } 14948 14949 private void deleteTempPackageFiles() { 14950 final FilenameFilter filter = new FilenameFilter() { 14951 public boolean accept(File dir, String name) { 14952 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14953 } 14954 }; 14955 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14956 file.delete(); 14957 } 14958 } 14959 14960 @Override 14961 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14962 int flags) { 14963 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14964 flags); 14965 } 14966 14967 @Override 14968 public void deletePackage(final String packageName, 14969 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14970 mContext.enforceCallingOrSelfPermission( 14971 android.Manifest.permission.DELETE_PACKAGES, null); 14972 Preconditions.checkNotNull(packageName); 14973 Preconditions.checkNotNull(observer); 14974 final int uid = Binder.getCallingUid(); 14975 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14976 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14977 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14978 mContext.enforceCallingOrSelfPermission( 14979 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14980 "deletePackage for user " + userId); 14981 } 14982 14983 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14984 try { 14985 observer.onPackageDeleted(packageName, 14986 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14987 } catch (RemoteException re) { 14988 } 14989 return; 14990 } 14991 14992 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14993 try { 14994 observer.onPackageDeleted(packageName, 14995 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14996 } catch (RemoteException re) { 14997 } 14998 return; 14999 } 15000 15001 if (DEBUG_REMOVE) { 15002 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15003 + " deleteAllUsers: " + deleteAllUsers ); 15004 } 15005 // Queue up an async operation since the package deletion may take a little while. 15006 mHandler.post(new Runnable() { 15007 public void run() { 15008 mHandler.removeCallbacks(this); 15009 int returnCode; 15010 if (!deleteAllUsers) { 15011 returnCode = deletePackageX(packageName, userId, deleteFlags); 15012 } else { 15013 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15014 // If nobody is blocking uninstall, proceed with delete for all users 15015 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15016 returnCode = deletePackageX(packageName, userId, deleteFlags); 15017 } else { 15018 // Otherwise uninstall individually for users with blockUninstalls=false 15019 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15020 for (int userId : users) { 15021 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15022 returnCode = deletePackageX(packageName, userId, userFlags); 15023 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15024 Slog.w(TAG, "Package delete failed for user " + userId 15025 + ", returnCode " + returnCode); 15026 } 15027 } 15028 } 15029 // The app has only been marked uninstalled for certain users. 15030 // We still need to report that delete was blocked 15031 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15032 } 15033 } 15034 try { 15035 observer.onPackageDeleted(packageName, returnCode, null); 15036 } catch (RemoteException e) { 15037 Log.i(TAG, "Observer no longer exists."); 15038 } //end catch 15039 } //end run 15040 }); 15041 } 15042 15043 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15044 int[] result = EMPTY_INT_ARRAY; 15045 for (int userId : userIds) { 15046 if (getBlockUninstallForUser(packageName, userId)) { 15047 result = ArrayUtils.appendInt(result, userId); 15048 } 15049 } 15050 return result; 15051 } 15052 15053 @Override 15054 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15055 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15056 } 15057 15058 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15059 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15060 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15061 try { 15062 if (dpm != null) { 15063 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15064 /* callingUserOnly =*/ false); 15065 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15066 : deviceOwnerComponentName.getPackageName(); 15067 // Does the package contains the device owner? 15068 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15069 // this check is probably not needed, since DO should be registered as a device 15070 // admin on some user too. (Original bug for this: b/17657954) 15071 if (packageName.equals(deviceOwnerPackageName)) { 15072 return true; 15073 } 15074 // Does it contain a device admin for any user? 15075 int[] users; 15076 if (userId == UserHandle.USER_ALL) { 15077 users = sUserManager.getUserIds(); 15078 } else { 15079 users = new int[]{userId}; 15080 } 15081 for (int i = 0; i < users.length; ++i) { 15082 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15083 return true; 15084 } 15085 } 15086 } 15087 } catch (RemoteException e) { 15088 } 15089 return false; 15090 } 15091 15092 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15093 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15094 } 15095 15096 /** 15097 * This method is an internal method that could be get invoked either 15098 * to delete an installed package or to clean up a failed installation. 15099 * After deleting an installed package, a broadcast is sent to notify any 15100 * listeners that the package has been removed. For cleaning up a failed 15101 * installation, the broadcast is not necessary since the package's 15102 * installation wouldn't have sent the initial broadcast either 15103 * The key steps in deleting a package are 15104 * deleting the package information in internal structures like mPackages, 15105 * deleting the packages base directories through installd 15106 * updating mSettings to reflect current status 15107 * persisting settings for later use 15108 * sending a broadcast if necessary 15109 */ 15110 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15111 final PackageRemovedInfo info = new PackageRemovedInfo(); 15112 final boolean res; 15113 15114 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15115 ? UserHandle.ALL : new UserHandle(userId); 15116 15117 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15118 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15119 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15120 } 15121 15122 PackageSetting uninstalledPs = null; 15123 15124 // for the uninstall-updates case and restricted profiles, remember the per- 15125 // user handle installed state 15126 int[] allUsers; 15127 synchronized (mPackages) { 15128 uninstalledPs = mSettings.mPackages.get(packageName); 15129 if (uninstalledPs == null) { 15130 Slog.w(TAG, "Not removing non-existent package " + packageName); 15131 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15132 } 15133 allUsers = sUserManager.getUserIds(); 15134 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15135 } 15136 15137 synchronized (mInstallLock) { 15138 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15139 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15140 "deletePackageX")) { 15141 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15142 deleteFlags | REMOVE_CHATTY, info, true, null); 15143 } 15144 synchronized (mPackages) { 15145 if (res) { 15146 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15147 } 15148 } 15149 } 15150 15151 if (res) { 15152 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15153 info.sendPackageRemovedBroadcasts(killApp); 15154 info.sendSystemPackageUpdatedBroadcasts(); 15155 info.sendSystemPackageAppearedBroadcasts(); 15156 } 15157 // Force a gc here. 15158 Runtime.getRuntime().gc(); 15159 // Delete the resources here after sending the broadcast to let 15160 // other processes clean up before deleting resources. 15161 if (info.args != null) { 15162 synchronized (mInstallLock) { 15163 info.args.doPostDeleteLI(true); 15164 } 15165 } 15166 15167 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15168 } 15169 15170 class PackageRemovedInfo { 15171 String removedPackage; 15172 int uid = -1; 15173 int removedAppId = -1; 15174 int[] origUsers; 15175 int[] removedUsers = null; 15176 boolean isRemovedPackageSystemUpdate = false; 15177 boolean isUpdate; 15178 boolean dataRemoved; 15179 boolean removedForAllUsers; 15180 // Clean up resources deleted packages. 15181 InstallArgs args = null; 15182 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15183 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15184 15185 void sendPackageRemovedBroadcasts(boolean killApp) { 15186 sendPackageRemovedBroadcastInternal(killApp); 15187 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15188 for (int i = 0; i < childCount; i++) { 15189 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15190 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15191 } 15192 } 15193 15194 void sendSystemPackageUpdatedBroadcasts() { 15195 if (isRemovedPackageSystemUpdate) { 15196 sendSystemPackageUpdatedBroadcastsInternal(); 15197 final int childCount = (removedChildPackages != null) 15198 ? removedChildPackages.size() : 0; 15199 for (int i = 0; i < childCount; i++) { 15200 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15201 if (childInfo.isRemovedPackageSystemUpdate) { 15202 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15203 } 15204 } 15205 } 15206 } 15207 15208 void sendSystemPackageAppearedBroadcasts() { 15209 final int packageCount = (appearedChildPackages != null) 15210 ? appearedChildPackages.size() : 0; 15211 for (int i = 0; i < packageCount; i++) { 15212 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15213 for (int userId : installedInfo.newUsers) { 15214 sendPackageAddedForUser(installedInfo.name, true, 15215 UserHandle.getAppId(installedInfo.uid), userId); 15216 } 15217 } 15218 } 15219 15220 private void sendSystemPackageUpdatedBroadcastsInternal() { 15221 Bundle extras = new Bundle(2); 15222 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15223 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15224 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15225 extras, 0, null, null, null); 15226 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15227 extras, 0, null, null, null); 15228 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15229 null, 0, removedPackage, null, null); 15230 } 15231 15232 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15233 Bundle extras = new Bundle(2); 15234 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15235 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15236 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15237 if (isUpdate || isRemovedPackageSystemUpdate) { 15238 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15239 } 15240 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15241 if (removedPackage != null) { 15242 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15243 extras, 0, null, null, removedUsers); 15244 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15245 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15246 removedPackage, extras, 0, null, null, removedUsers); 15247 } 15248 } 15249 if (removedAppId >= 0) { 15250 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15251 removedUsers); 15252 } 15253 } 15254 } 15255 15256 /* 15257 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15258 * flag is not set, the data directory is removed as well. 15259 * make sure this flag is set for partially installed apps. If not its meaningless to 15260 * delete a partially installed application. 15261 */ 15262 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15263 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15264 String packageName = ps.name; 15265 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15266 // Retrieve object to delete permissions for shared user later on 15267 final PackageParser.Package deletedPkg; 15268 final PackageSetting deletedPs; 15269 // reader 15270 synchronized (mPackages) { 15271 deletedPkg = mPackages.get(packageName); 15272 deletedPs = mSettings.mPackages.get(packageName); 15273 if (outInfo != null) { 15274 outInfo.removedPackage = packageName; 15275 outInfo.removedUsers = deletedPs != null 15276 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15277 : null; 15278 } 15279 } 15280 15281 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15282 15283 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15284 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15285 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15286 destroyAppProfilesLIF(deletedPkg); 15287 if (outInfo != null) { 15288 outInfo.dataRemoved = true; 15289 } 15290 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15291 } 15292 15293 // writer 15294 synchronized (mPackages) { 15295 if (deletedPs != null) { 15296 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15297 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15298 clearDefaultBrowserIfNeeded(packageName); 15299 if (outInfo != null) { 15300 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15301 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15302 } 15303 updatePermissionsLPw(deletedPs.name, null, 0); 15304 if (deletedPs.sharedUser != null) { 15305 // Remove permissions associated with package. Since runtime 15306 // permissions are per user we have to kill the removed package 15307 // or packages running under the shared user of the removed 15308 // package if revoking the permissions requested only by the removed 15309 // package is successful and this causes a change in gids. 15310 for (int userId : UserManagerService.getInstance().getUserIds()) { 15311 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15312 userId); 15313 if (userIdToKill == UserHandle.USER_ALL 15314 || userIdToKill >= UserHandle.USER_SYSTEM) { 15315 // If gids changed for this user, kill all affected packages. 15316 mHandler.post(new Runnable() { 15317 @Override 15318 public void run() { 15319 // This has to happen with no lock held. 15320 killApplication(deletedPs.name, deletedPs.appId, 15321 KILL_APP_REASON_GIDS_CHANGED); 15322 } 15323 }); 15324 break; 15325 } 15326 } 15327 } 15328 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15329 } 15330 // make sure to preserve per-user disabled state if this removal was just 15331 // a downgrade of a system app to the factory package 15332 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15333 if (DEBUG_REMOVE) { 15334 Slog.d(TAG, "Propagating install state across downgrade"); 15335 } 15336 for (int userId : allUserHandles) { 15337 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15338 if (DEBUG_REMOVE) { 15339 Slog.d(TAG, " user " + userId + " => " + installed); 15340 } 15341 ps.setInstalled(installed, userId); 15342 } 15343 } 15344 } 15345 // can downgrade to reader 15346 if (writeSettings) { 15347 // Save settings now 15348 mSettings.writeLPr(); 15349 } 15350 } 15351 if (outInfo != null) { 15352 // A user ID was deleted here. Go through all users and remove it 15353 // from KeyStore. 15354 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15355 } 15356 } 15357 15358 static boolean locationIsPrivileged(File path) { 15359 try { 15360 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15361 .getCanonicalPath(); 15362 return path.getCanonicalPath().startsWith(privilegedAppDir); 15363 } catch (IOException e) { 15364 Slog.e(TAG, "Unable to access code path " + path); 15365 } 15366 return false; 15367 } 15368 15369 /* 15370 * Tries to delete system package. 15371 */ 15372 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15373 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15374 boolean writeSettings) { 15375 if (deletedPs.parentPackageName != null) { 15376 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15377 return false; 15378 } 15379 15380 final boolean applyUserRestrictions 15381 = (allUserHandles != null) && (outInfo.origUsers != null); 15382 final PackageSetting disabledPs; 15383 // Confirm if the system package has been updated 15384 // An updated system app can be deleted. This will also have to restore 15385 // the system pkg from system partition 15386 // reader 15387 synchronized (mPackages) { 15388 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15389 } 15390 15391 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15392 + " disabledPs=" + disabledPs); 15393 15394 if (disabledPs == null) { 15395 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15396 return false; 15397 } else if (DEBUG_REMOVE) { 15398 Slog.d(TAG, "Deleting system pkg from data partition"); 15399 } 15400 15401 if (DEBUG_REMOVE) { 15402 if (applyUserRestrictions) { 15403 Slog.d(TAG, "Remembering install states:"); 15404 for (int userId : allUserHandles) { 15405 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15406 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15407 } 15408 } 15409 } 15410 15411 // Delete the updated package 15412 outInfo.isRemovedPackageSystemUpdate = true; 15413 if (outInfo.removedChildPackages != null) { 15414 final int childCount = (deletedPs.childPackageNames != null) 15415 ? deletedPs.childPackageNames.size() : 0; 15416 for (int i = 0; i < childCount; i++) { 15417 String childPackageName = deletedPs.childPackageNames.get(i); 15418 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15419 .contains(childPackageName)) { 15420 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15421 childPackageName); 15422 if (childInfo != null) { 15423 childInfo.isRemovedPackageSystemUpdate = true; 15424 } 15425 } 15426 } 15427 } 15428 15429 if (disabledPs.versionCode < deletedPs.versionCode) { 15430 // Delete data for downgrades 15431 flags &= ~PackageManager.DELETE_KEEP_DATA; 15432 } else { 15433 // Preserve data by setting flag 15434 flags |= PackageManager.DELETE_KEEP_DATA; 15435 } 15436 15437 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15438 outInfo, writeSettings, disabledPs.pkg); 15439 if (!ret) { 15440 return false; 15441 } 15442 15443 // writer 15444 synchronized (mPackages) { 15445 // Reinstate the old system package 15446 enableSystemPackageLPw(disabledPs.pkg); 15447 // Remove any native libraries from the upgraded package. 15448 removeNativeBinariesLI(deletedPs); 15449 } 15450 15451 // Install the system package 15452 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15453 int parseFlags = mDefParseFlags 15454 | PackageParser.PARSE_MUST_BE_APK 15455 | PackageParser.PARSE_IS_SYSTEM 15456 | PackageParser.PARSE_IS_SYSTEM_DIR; 15457 if (locationIsPrivileged(disabledPs.codePath)) { 15458 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15459 } 15460 15461 final PackageParser.Package newPkg; 15462 try { 15463 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15464 } catch (PackageManagerException e) { 15465 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15466 + e.getMessage()); 15467 return false; 15468 } 15469 15470 prepareAppDataAfterInstallLIF(newPkg); 15471 15472 // writer 15473 synchronized (mPackages) { 15474 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15475 15476 // Propagate the permissions state as we do not want to drop on the floor 15477 // runtime permissions. The update permissions method below will take 15478 // care of removing obsolete permissions and grant install permissions. 15479 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15480 updatePermissionsLPw(newPkg.packageName, newPkg, 15481 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15482 15483 if (applyUserRestrictions) { 15484 if (DEBUG_REMOVE) { 15485 Slog.d(TAG, "Propagating install state across reinstall"); 15486 } 15487 for (int userId : allUserHandles) { 15488 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15489 if (DEBUG_REMOVE) { 15490 Slog.d(TAG, " user " + userId + " => " + installed); 15491 } 15492 ps.setInstalled(installed, userId); 15493 15494 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15495 } 15496 // Regardless of writeSettings we need to ensure that this restriction 15497 // state propagation is persisted 15498 mSettings.writeAllUsersPackageRestrictionsLPr(); 15499 } 15500 // can downgrade to reader here 15501 if (writeSettings) { 15502 mSettings.writeLPr(); 15503 } 15504 } 15505 return true; 15506 } 15507 15508 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15509 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15510 PackageRemovedInfo outInfo, boolean writeSettings, 15511 PackageParser.Package replacingPackage) { 15512 synchronized (mPackages) { 15513 if (outInfo != null) { 15514 outInfo.uid = ps.appId; 15515 } 15516 15517 if (outInfo != null && outInfo.removedChildPackages != null) { 15518 final int childCount = (ps.childPackageNames != null) 15519 ? ps.childPackageNames.size() : 0; 15520 for (int i = 0; i < childCount; i++) { 15521 String childPackageName = ps.childPackageNames.get(i); 15522 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15523 if (childPs == null) { 15524 return false; 15525 } 15526 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15527 childPackageName); 15528 if (childInfo != null) { 15529 childInfo.uid = childPs.appId; 15530 } 15531 } 15532 } 15533 } 15534 15535 // Delete package data from internal structures and also remove data if flag is set 15536 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15537 15538 // Delete the child packages data 15539 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15540 for (int i = 0; i < childCount; i++) { 15541 PackageSetting childPs; 15542 synchronized (mPackages) { 15543 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15544 } 15545 if (childPs != null) { 15546 PackageRemovedInfo childOutInfo = (outInfo != null 15547 && outInfo.removedChildPackages != null) 15548 ? outInfo.removedChildPackages.get(childPs.name) : null; 15549 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15550 && (replacingPackage != null 15551 && !replacingPackage.hasChildPackage(childPs.name)) 15552 ? flags & ~DELETE_KEEP_DATA : flags; 15553 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15554 deleteFlags, writeSettings); 15555 } 15556 } 15557 15558 // Delete application code and resources only for parent packages 15559 if (ps.parentPackageName == null) { 15560 if (deleteCodeAndResources && (outInfo != null)) { 15561 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15562 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15563 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15564 } 15565 } 15566 15567 return true; 15568 } 15569 15570 @Override 15571 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15572 int userId) { 15573 mContext.enforceCallingOrSelfPermission( 15574 android.Manifest.permission.DELETE_PACKAGES, null); 15575 synchronized (mPackages) { 15576 PackageSetting ps = mSettings.mPackages.get(packageName); 15577 if (ps == null) { 15578 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15579 return false; 15580 } 15581 if (!ps.getInstalled(userId)) { 15582 // Can't block uninstall for an app that is not installed or enabled. 15583 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15584 return false; 15585 } 15586 ps.setBlockUninstall(blockUninstall, userId); 15587 mSettings.writePackageRestrictionsLPr(userId); 15588 } 15589 return true; 15590 } 15591 15592 @Override 15593 public boolean getBlockUninstallForUser(String packageName, int userId) { 15594 synchronized (mPackages) { 15595 PackageSetting ps = mSettings.mPackages.get(packageName); 15596 if (ps == null) { 15597 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15598 return false; 15599 } 15600 return ps.getBlockUninstall(userId); 15601 } 15602 } 15603 15604 @Override 15605 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15606 int callingUid = Binder.getCallingUid(); 15607 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15608 throw new SecurityException( 15609 "setRequiredForSystemUser can only be run by the system or root"); 15610 } 15611 synchronized (mPackages) { 15612 PackageSetting ps = mSettings.mPackages.get(packageName); 15613 if (ps == null) { 15614 Log.w(TAG, "Package doesn't exist: " + packageName); 15615 return false; 15616 } 15617 if (systemUserApp) { 15618 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15619 } else { 15620 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15621 } 15622 mSettings.writeLPr(); 15623 } 15624 return true; 15625 } 15626 15627 /* 15628 * This method handles package deletion in general 15629 */ 15630 private boolean deletePackageLIF(String packageName, UserHandle user, 15631 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15632 PackageRemovedInfo outInfo, boolean writeSettings, 15633 PackageParser.Package replacingPackage) { 15634 if (packageName == null) { 15635 Slog.w(TAG, "Attempt to delete null packageName."); 15636 return false; 15637 } 15638 15639 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15640 15641 PackageSetting ps; 15642 15643 synchronized (mPackages) { 15644 ps = mSettings.mPackages.get(packageName); 15645 if (ps == null) { 15646 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15647 return false; 15648 } 15649 15650 if (ps.parentPackageName != null && (!isSystemApp(ps) 15651 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15652 if (DEBUG_REMOVE) { 15653 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15654 + ((user == null) ? UserHandle.USER_ALL : user)); 15655 } 15656 final int removedUserId = (user != null) ? user.getIdentifier() 15657 : UserHandle.USER_ALL; 15658 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15659 return false; 15660 } 15661 markPackageUninstalledForUserLPw(ps, user); 15662 scheduleWritePackageRestrictionsLocked(user); 15663 return true; 15664 } 15665 } 15666 15667 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15668 && user.getIdentifier() != UserHandle.USER_ALL)) { 15669 // The caller is asking that the package only be deleted for a single 15670 // user. To do this, we just mark its uninstalled state and delete 15671 // its data. If this is a system app, we only allow this to happen if 15672 // they have set the special DELETE_SYSTEM_APP which requests different 15673 // semantics than normal for uninstalling system apps. 15674 markPackageUninstalledForUserLPw(ps, user); 15675 15676 if (!isSystemApp(ps)) { 15677 // Do not uninstall the APK if an app should be cached 15678 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15679 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15680 // Other user still have this package installed, so all 15681 // we need to do is clear this user's data and save that 15682 // it is uninstalled. 15683 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15684 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15685 return false; 15686 } 15687 scheduleWritePackageRestrictionsLocked(user); 15688 return true; 15689 } else { 15690 // We need to set it back to 'installed' so the uninstall 15691 // broadcasts will be sent correctly. 15692 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15693 ps.setInstalled(true, user.getIdentifier()); 15694 } 15695 } else { 15696 // This is a system app, so we assume that the 15697 // other users still have this package installed, so all 15698 // we need to do is clear this user's data and save that 15699 // it is uninstalled. 15700 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15701 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15702 return false; 15703 } 15704 scheduleWritePackageRestrictionsLocked(user); 15705 return true; 15706 } 15707 } 15708 15709 // If we are deleting a composite package for all users, keep track 15710 // of result for each child. 15711 if (ps.childPackageNames != null && outInfo != null) { 15712 synchronized (mPackages) { 15713 final int childCount = ps.childPackageNames.size(); 15714 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15715 for (int i = 0; i < childCount; i++) { 15716 String childPackageName = ps.childPackageNames.get(i); 15717 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15718 childInfo.removedPackage = childPackageName; 15719 outInfo.removedChildPackages.put(childPackageName, childInfo); 15720 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15721 if (childPs != null) { 15722 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15723 } 15724 } 15725 } 15726 } 15727 15728 boolean ret = false; 15729 if (isSystemApp(ps)) { 15730 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15731 // When an updated system application is deleted we delete the existing resources 15732 // as well and fall back to existing code in system partition 15733 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15734 } else { 15735 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15736 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15737 outInfo, writeSettings, replacingPackage); 15738 } 15739 15740 // Take a note whether we deleted the package for all users 15741 if (outInfo != null) { 15742 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15743 if (outInfo.removedChildPackages != null) { 15744 synchronized (mPackages) { 15745 final int childCount = outInfo.removedChildPackages.size(); 15746 for (int i = 0; i < childCount; i++) { 15747 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15748 if (childInfo != null) { 15749 childInfo.removedForAllUsers = mPackages.get( 15750 childInfo.removedPackage) == null; 15751 } 15752 } 15753 } 15754 } 15755 // If we uninstalled an update to a system app there may be some 15756 // child packages that appeared as they are declared in the system 15757 // app but were not declared in the update. 15758 if (isSystemApp(ps)) { 15759 synchronized (mPackages) { 15760 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15761 final int childCount = (updatedPs.childPackageNames != null) 15762 ? updatedPs.childPackageNames.size() : 0; 15763 for (int i = 0; i < childCount; i++) { 15764 String childPackageName = updatedPs.childPackageNames.get(i); 15765 if (outInfo.removedChildPackages == null 15766 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15767 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15768 if (childPs == null) { 15769 continue; 15770 } 15771 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15772 installRes.name = childPackageName; 15773 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15774 installRes.pkg = mPackages.get(childPackageName); 15775 installRes.uid = childPs.pkg.applicationInfo.uid; 15776 if (outInfo.appearedChildPackages == null) { 15777 outInfo.appearedChildPackages = new ArrayMap<>(); 15778 } 15779 outInfo.appearedChildPackages.put(childPackageName, installRes); 15780 } 15781 } 15782 } 15783 } 15784 } 15785 15786 return ret; 15787 } 15788 15789 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15790 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15791 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15792 for (int nextUserId : userIds) { 15793 if (DEBUG_REMOVE) { 15794 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15795 } 15796 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15797 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15798 false /*hidden*/, false /*suspended*/, null, null, null, 15799 false /*blockUninstall*/, 15800 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15801 } 15802 } 15803 15804 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15805 PackageRemovedInfo outInfo) { 15806 final PackageParser.Package pkg; 15807 synchronized (mPackages) { 15808 pkg = mPackages.get(ps.name); 15809 } 15810 15811 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15812 : new int[] {userId}; 15813 for (int nextUserId : userIds) { 15814 if (DEBUG_REMOVE) { 15815 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15816 + nextUserId); 15817 } 15818 15819 destroyAppDataLIF(pkg, userId, 15820 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15821 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15822 schedulePackageCleaning(ps.name, nextUserId, false); 15823 synchronized (mPackages) { 15824 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15825 scheduleWritePackageRestrictionsLocked(nextUserId); 15826 } 15827 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15828 } 15829 } 15830 15831 if (outInfo != null) { 15832 outInfo.removedPackage = ps.name; 15833 outInfo.removedAppId = ps.appId; 15834 outInfo.removedUsers = userIds; 15835 } 15836 15837 return true; 15838 } 15839 15840 private final class ClearStorageConnection implements ServiceConnection { 15841 IMediaContainerService mContainerService; 15842 15843 @Override 15844 public void onServiceConnected(ComponentName name, IBinder service) { 15845 synchronized (this) { 15846 mContainerService = IMediaContainerService.Stub.asInterface(service); 15847 notifyAll(); 15848 } 15849 } 15850 15851 @Override 15852 public void onServiceDisconnected(ComponentName name) { 15853 } 15854 } 15855 15856 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15857 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15858 15859 final boolean mounted; 15860 if (Environment.isExternalStorageEmulated()) { 15861 mounted = true; 15862 } else { 15863 final String status = Environment.getExternalStorageState(); 15864 15865 mounted = status.equals(Environment.MEDIA_MOUNTED) 15866 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15867 } 15868 15869 if (!mounted) { 15870 return; 15871 } 15872 15873 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15874 int[] users; 15875 if (userId == UserHandle.USER_ALL) { 15876 users = sUserManager.getUserIds(); 15877 } else { 15878 users = new int[] { userId }; 15879 } 15880 final ClearStorageConnection conn = new ClearStorageConnection(); 15881 if (mContext.bindServiceAsUser( 15882 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15883 try { 15884 for (int curUser : users) { 15885 long timeout = SystemClock.uptimeMillis() + 5000; 15886 synchronized (conn) { 15887 long now = SystemClock.uptimeMillis(); 15888 while (conn.mContainerService == null && now < timeout) { 15889 try { 15890 conn.wait(timeout - now); 15891 } catch (InterruptedException e) { 15892 } 15893 } 15894 } 15895 if (conn.mContainerService == null) { 15896 return; 15897 } 15898 15899 final UserEnvironment userEnv = new UserEnvironment(curUser); 15900 clearDirectory(conn.mContainerService, 15901 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15902 if (allData) { 15903 clearDirectory(conn.mContainerService, 15904 userEnv.buildExternalStorageAppDataDirs(packageName)); 15905 clearDirectory(conn.mContainerService, 15906 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15907 } 15908 } 15909 } finally { 15910 mContext.unbindService(conn); 15911 } 15912 } 15913 } 15914 15915 @Override 15916 public void clearApplicationProfileData(String packageName) { 15917 enforceSystemOrRoot("Only the system can clear all profile data"); 15918 15919 final PackageParser.Package pkg; 15920 synchronized (mPackages) { 15921 pkg = mPackages.get(packageName); 15922 } 15923 15924 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15925 synchronized (mInstallLock) { 15926 clearAppProfilesLIF(pkg); 15927 } 15928 } 15929 } 15930 15931 @Override 15932 public void clearApplicationUserData(final String packageName, 15933 final IPackageDataObserver observer, final int userId) { 15934 mContext.enforceCallingOrSelfPermission( 15935 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15936 15937 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15938 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15939 15940 final DevicePolicyManagerInternal dpmi = LocalServices 15941 .getService(DevicePolicyManagerInternal.class); 15942 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15943 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15944 } 15945 // Queue up an async operation since the package deletion may take a little while. 15946 mHandler.post(new Runnable() { 15947 public void run() { 15948 mHandler.removeCallbacks(this); 15949 final boolean succeeded; 15950 try (PackageFreezer freezer = freezePackage(packageName, 15951 "clearApplicationUserData")) { 15952 synchronized (mInstallLock) { 15953 succeeded = clearApplicationUserDataLIF(packageName, userId); 15954 } 15955 clearExternalStorageDataSync(packageName, userId, true); 15956 } 15957 if (succeeded) { 15958 // invoke DeviceStorageMonitor's update method to clear any notifications 15959 DeviceStorageMonitorInternal dsm = LocalServices 15960 .getService(DeviceStorageMonitorInternal.class); 15961 if (dsm != null) { 15962 dsm.checkMemory(); 15963 } 15964 } 15965 if(observer != null) { 15966 try { 15967 observer.onRemoveCompleted(packageName, succeeded); 15968 } catch (RemoteException e) { 15969 Log.i(TAG, "Observer no longer exists."); 15970 } 15971 } //end if observer 15972 } //end run 15973 }); 15974 } 15975 15976 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15977 if (packageName == null) { 15978 Slog.w(TAG, "Attempt to delete null packageName."); 15979 return false; 15980 } 15981 15982 // Try finding details about the requested package 15983 PackageParser.Package pkg; 15984 synchronized (mPackages) { 15985 pkg = mPackages.get(packageName); 15986 if (pkg == null) { 15987 final PackageSetting ps = mSettings.mPackages.get(packageName); 15988 if (ps != null) { 15989 pkg = ps.pkg; 15990 } 15991 } 15992 15993 if (pkg == null) { 15994 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15995 return false; 15996 } 15997 15998 PackageSetting ps = (PackageSetting) pkg.mExtras; 15999 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16000 } 16001 16002 clearAppDataLIF(pkg, userId, 16003 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16004 16005 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16006 removeKeystoreDataIfNeeded(userId, appId); 16007 16008 final UserManager um = mContext.getSystemService(UserManager.class); 16009 final int flags; 16010 if (um.isUserUnlocked(userId)) { 16011 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16012 } else if (um.isUserRunning(userId)) { 16013 flags = StorageManager.FLAG_STORAGE_DE; 16014 } else { 16015 flags = 0; 16016 } 16017 prepareAppDataContentsLIF(pkg, userId, flags); 16018 16019 return true; 16020 } 16021 16022 /** 16023 * Reverts user permission state changes (permissions and flags) in 16024 * all packages for a given user. 16025 * 16026 * @param userId The device user for which to do a reset. 16027 */ 16028 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16029 final int packageCount = mPackages.size(); 16030 for (int i = 0; i < packageCount; i++) { 16031 PackageParser.Package pkg = mPackages.valueAt(i); 16032 PackageSetting ps = (PackageSetting) pkg.mExtras; 16033 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16034 } 16035 } 16036 16037 /** 16038 * Reverts user permission state changes (permissions and flags). 16039 * 16040 * @param ps The package for which to reset. 16041 * @param userId The device user for which to do a reset. 16042 */ 16043 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16044 final PackageSetting ps, final int userId) { 16045 if (ps.pkg == null) { 16046 return; 16047 } 16048 16049 // These are flags that can change base on user actions. 16050 final int userSettableMask = FLAG_PERMISSION_USER_SET 16051 | FLAG_PERMISSION_USER_FIXED 16052 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16053 | FLAG_PERMISSION_REVIEW_REQUIRED; 16054 16055 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16056 | FLAG_PERMISSION_POLICY_FIXED; 16057 16058 boolean writeInstallPermissions = false; 16059 boolean writeRuntimePermissions = false; 16060 16061 final int permissionCount = ps.pkg.requestedPermissions.size(); 16062 for (int i = 0; i < permissionCount; i++) { 16063 String permission = ps.pkg.requestedPermissions.get(i); 16064 16065 BasePermission bp = mSettings.mPermissions.get(permission); 16066 if (bp == null) { 16067 continue; 16068 } 16069 16070 // If shared user we just reset the state to which only this app contributed. 16071 if (ps.sharedUser != null) { 16072 boolean used = false; 16073 final int packageCount = ps.sharedUser.packages.size(); 16074 for (int j = 0; j < packageCount; j++) { 16075 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16076 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16077 && pkg.pkg.requestedPermissions.contains(permission)) { 16078 used = true; 16079 break; 16080 } 16081 } 16082 if (used) { 16083 continue; 16084 } 16085 } 16086 16087 PermissionsState permissionsState = ps.getPermissionsState(); 16088 16089 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16090 16091 // Always clear the user settable flags. 16092 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16093 bp.name) != null; 16094 // If permission review is enabled and this is a legacy app, mark the 16095 // permission as requiring a review as this is the initial state. 16096 int flags = 0; 16097 if (Build.PERMISSIONS_REVIEW_REQUIRED 16098 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16099 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16100 } 16101 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16102 if (hasInstallState) { 16103 writeInstallPermissions = true; 16104 } else { 16105 writeRuntimePermissions = true; 16106 } 16107 } 16108 16109 // Below is only runtime permission handling. 16110 if (!bp.isRuntime()) { 16111 continue; 16112 } 16113 16114 // Never clobber system or policy. 16115 if ((oldFlags & policyOrSystemFlags) != 0) { 16116 continue; 16117 } 16118 16119 // If this permission was granted by default, make sure it is. 16120 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16121 if (permissionsState.grantRuntimePermission(bp, userId) 16122 != PERMISSION_OPERATION_FAILURE) { 16123 writeRuntimePermissions = true; 16124 } 16125 // If permission review is enabled the permissions for a legacy apps 16126 // are represented as constantly granted runtime ones, so don't revoke. 16127 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16128 // Otherwise, reset the permission. 16129 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16130 switch (revokeResult) { 16131 case PERMISSION_OPERATION_SUCCESS: 16132 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16133 writeRuntimePermissions = true; 16134 final int appId = ps.appId; 16135 mHandler.post(new Runnable() { 16136 @Override 16137 public void run() { 16138 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16139 } 16140 }); 16141 } break; 16142 } 16143 } 16144 } 16145 16146 // Synchronously write as we are taking permissions away. 16147 if (writeRuntimePermissions) { 16148 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16149 } 16150 16151 // Synchronously write as we are taking permissions away. 16152 if (writeInstallPermissions) { 16153 mSettings.writeLPr(); 16154 } 16155 } 16156 16157 /** 16158 * Remove entries from the keystore daemon. Will only remove it if the 16159 * {@code appId} is valid. 16160 */ 16161 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16162 if (appId < 0) { 16163 return; 16164 } 16165 16166 final KeyStore keyStore = KeyStore.getInstance(); 16167 if (keyStore != null) { 16168 if (userId == UserHandle.USER_ALL) { 16169 for (final int individual : sUserManager.getUserIds()) { 16170 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16171 } 16172 } else { 16173 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16174 } 16175 } else { 16176 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16177 } 16178 } 16179 16180 @Override 16181 public void deleteApplicationCacheFiles(final String packageName, 16182 final IPackageDataObserver observer) { 16183 final int userId = UserHandle.getCallingUserId(); 16184 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16185 } 16186 16187 @Override 16188 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16189 final IPackageDataObserver observer) { 16190 mContext.enforceCallingOrSelfPermission( 16191 android.Manifest.permission.DELETE_CACHE_FILES, null); 16192 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16193 /* requireFullPermission= */ true, /* checkShell= */ false, 16194 "delete application cache files"); 16195 16196 final PackageParser.Package pkg; 16197 synchronized (mPackages) { 16198 pkg = mPackages.get(packageName); 16199 } 16200 16201 // Queue up an async operation since the package deletion may take a little while. 16202 mHandler.post(new Runnable() { 16203 public void run() { 16204 synchronized (mInstallLock) { 16205 final int flags = StorageManager.FLAG_STORAGE_DE 16206 | StorageManager.FLAG_STORAGE_CE; 16207 // We're only clearing cache files, so we don't care if the 16208 // app is unfrozen and still able to run 16209 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16210 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16211 } 16212 clearExternalStorageDataSync(packageName, userId, false); 16213 if (observer != null) { 16214 try { 16215 observer.onRemoveCompleted(packageName, true); 16216 } catch (RemoteException e) { 16217 Log.i(TAG, "Observer no longer exists."); 16218 } 16219 } 16220 } 16221 }); 16222 } 16223 16224 @Override 16225 public void getPackageSizeInfo(final String packageName, int userHandle, 16226 final IPackageStatsObserver observer) { 16227 mContext.enforceCallingOrSelfPermission( 16228 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16229 if (packageName == null) { 16230 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16231 } 16232 16233 PackageStats stats = new PackageStats(packageName, userHandle); 16234 16235 /* 16236 * Queue up an async operation since the package measurement may take a 16237 * little while. 16238 */ 16239 Message msg = mHandler.obtainMessage(INIT_COPY); 16240 msg.obj = new MeasureParams(stats, observer); 16241 mHandler.sendMessage(msg); 16242 } 16243 16244 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16245 final PackageSetting ps; 16246 synchronized (mPackages) { 16247 ps = mSettings.mPackages.get(packageName); 16248 if (ps == null) { 16249 Slog.w(TAG, "Failed to find settings for " + packageName); 16250 return false; 16251 } 16252 } 16253 try { 16254 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16255 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16256 ps.getCeDataInode(userId), ps.codePathString, stats); 16257 } catch (InstallerException e) { 16258 Slog.w(TAG, String.valueOf(e)); 16259 return false; 16260 } 16261 16262 // For now, ignore code size of packages on system partition 16263 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16264 stats.codeSize = 0; 16265 } 16266 16267 return true; 16268 } 16269 16270 private int getUidTargetSdkVersionLockedLPr(int uid) { 16271 Object obj = mSettings.getUserIdLPr(uid); 16272 if (obj instanceof SharedUserSetting) { 16273 final SharedUserSetting sus = (SharedUserSetting) obj; 16274 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16275 final Iterator<PackageSetting> it = sus.packages.iterator(); 16276 while (it.hasNext()) { 16277 final PackageSetting ps = it.next(); 16278 if (ps.pkg != null) { 16279 int v = ps.pkg.applicationInfo.targetSdkVersion; 16280 if (v < vers) vers = v; 16281 } 16282 } 16283 return vers; 16284 } else if (obj instanceof PackageSetting) { 16285 final PackageSetting ps = (PackageSetting) obj; 16286 if (ps.pkg != null) { 16287 return ps.pkg.applicationInfo.targetSdkVersion; 16288 } 16289 } 16290 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16291 } 16292 16293 @Override 16294 public void addPreferredActivity(IntentFilter filter, int match, 16295 ComponentName[] set, ComponentName activity, int userId) { 16296 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16297 "Adding preferred"); 16298 } 16299 16300 private void addPreferredActivityInternal(IntentFilter filter, int match, 16301 ComponentName[] set, ComponentName activity, boolean always, int userId, 16302 String opname) { 16303 // writer 16304 int callingUid = Binder.getCallingUid(); 16305 enforceCrossUserPermission(callingUid, userId, 16306 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16307 if (filter.countActions() == 0) { 16308 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16309 return; 16310 } 16311 synchronized (mPackages) { 16312 if (mContext.checkCallingOrSelfPermission( 16313 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16314 != PackageManager.PERMISSION_GRANTED) { 16315 if (getUidTargetSdkVersionLockedLPr(callingUid) 16316 < Build.VERSION_CODES.FROYO) { 16317 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16318 + callingUid); 16319 return; 16320 } 16321 mContext.enforceCallingOrSelfPermission( 16322 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16323 } 16324 16325 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16326 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16327 + userId + ":"); 16328 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16329 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16330 scheduleWritePackageRestrictionsLocked(userId); 16331 } 16332 } 16333 16334 @Override 16335 public void replacePreferredActivity(IntentFilter filter, int match, 16336 ComponentName[] set, ComponentName activity, int userId) { 16337 if (filter.countActions() != 1) { 16338 throw new IllegalArgumentException( 16339 "replacePreferredActivity expects filter to have only 1 action."); 16340 } 16341 if (filter.countDataAuthorities() != 0 16342 || filter.countDataPaths() != 0 16343 || filter.countDataSchemes() > 1 16344 || filter.countDataTypes() != 0) { 16345 throw new IllegalArgumentException( 16346 "replacePreferredActivity expects filter to have no data authorities, " + 16347 "paths, or types; and at most one scheme."); 16348 } 16349 16350 final int callingUid = Binder.getCallingUid(); 16351 enforceCrossUserPermission(callingUid, userId, 16352 true /* requireFullPermission */, false /* checkShell */, 16353 "replace preferred activity"); 16354 synchronized (mPackages) { 16355 if (mContext.checkCallingOrSelfPermission( 16356 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16357 != PackageManager.PERMISSION_GRANTED) { 16358 if (getUidTargetSdkVersionLockedLPr(callingUid) 16359 < Build.VERSION_CODES.FROYO) { 16360 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16361 + Binder.getCallingUid()); 16362 return; 16363 } 16364 mContext.enforceCallingOrSelfPermission( 16365 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16366 } 16367 16368 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16369 if (pir != null) { 16370 // Get all of the existing entries that exactly match this filter. 16371 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16372 if (existing != null && existing.size() == 1) { 16373 PreferredActivity cur = existing.get(0); 16374 if (DEBUG_PREFERRED) { 16375 Slog.i(TAG, "Checking replace of preferred:"); 16376 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16377 if (!cur.mPref.mAlways) { 16378 Slog.i(TAG, " -- CUR; not mAlways!"); 16379 } else { 16380 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16381 Slog.i(TAG, " -- CUR: mSet=" 16382 + Arrays.toString(cur.mPref.mSetComponents)); 16383 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16384 Slog.i(TAG, " -- NEW: mMatch=" 16385 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16386 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16387 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16388 } 16389 } 16390 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16391 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16392 && cur.mPref.sameSet(set)) { 16393 // Setting the preferred activity to what it happens to be already 16394 if (DEBUG_PREFERRED) { 16395 Slog.i(TAG, "Replacing with same preferred activity " 16396 + cur.mPref.mShortComponent + " for user " 16397 + userId + ":"); 16398 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16399 } 16400 return; 16401 } 16402 } 16403 16404 if (existing != null) { 16405 if (DEBUG_PREFERRED) { 16406 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16407 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16408 } 16409 for (int i = 0; i < existing.size(); i++) { 16410 PreferredActivity pa = existing.get(i); 16411 if (DEBUG_PREFERRED) { 16412 Slog.i(TAG, "Removing existing preferred activity " 16413 + pa.mPref.mComponent + ":"); 16414 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16415 } 16416 pir.removeFilter(pa); 16417 } 16418 } 16419 } 16420 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16421 "Replacing preferred"); 16422 } 16423 } 16424 16425 @Override 16426 public void clearPackagePreferredActivities(String packageName) { 16427 final int uid = Binder.getCallingUid(); 16428 // writer 16429 synchronized (mPackages) { 16430 PackageParser.Package pkg = mPackages.get(packageName); 16431 if (pkg == null || pkg.applicationInfo.uid != uid) { 16432 if (mContext.checkCallingOrSelfPermission( 16433 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16434 != PackageManager.PERMISSION_GRANTED) { 16435 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16436 < Build.VERSION_CODES.FROYO) { 16437 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16438 + Binder.getCallingUid()); 16439 return; 16440 } 16441 mContext.enforceCallingOrSelfPermission( 16442 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16443 } 16444 } 16445 16446 int user = UserHandle.getCallingUserId(); 16447 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16448 scheduleWritePackageRestrictionsLocked(user); 16449 } 16450 } 16451 } 16452 16453 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16454 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16455 ArrayList<PreferredActivity> removed = null; 16456 boolean changed = false; 16457 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16458 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16459 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16460 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16461 continue; 16462 } 16463 Iterator<PreferredActivity> it = pir.filterIterator(); 16464 while (it.hasNext()) { 16465 PreferredActivity pa = it.next(); 16466 // Mark entry for removal only if it matches the package name 16467 // and the entry is of type "always". 16468 if (packageName == null || 16469 (pa.mPref.mComponent.getPackageName().equals(packageName) 16470 && pa.mPref.mAlways)) { 16471 if (removed == null) { 16472 removed = new ArrayList<PreferredActivity>(); 16473 } 16474 removed.add(pa); 16475 } 16476 } 16477 if (removed != null) { 16478 for (int j=0; j<removed.size(); j++) { 16479 PreferredActivity pa = removed.get(j); 16480 pir.removeFilter(pa); 16481 } 16482 changed = true; 16483 } 16484 } 16485 return changed; 16486 } 16487 16488 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16489 private void clearIntentFilterVerificationsLPw(int userId) { 16490 final int packageCount = mPackages.size(); 16491 for (int i = 0; i < packageCount; i++) { 16492 PackageParser.Package pkg = mPackages.valueAt(i); 16493 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16494 } 16495 } 16496 16497 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16498 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16499 if (userId == UserHandle.USER_ALL) { 16500 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16501 sUserManager.getUserIds())) { 16502 for (int oneUserId : sUserManager.getUserIds()) { 16503 scheduleWritePackageRestrictionsLocked(oneUserId); 16504 } 16505 } 16506 } else { 16507 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16508 scheduleWritePackageRestrictionsLocked(userId); 16509 } 16510 } 16511 } 16512 16513 void clearDefaultBrowserIfNeeded(String packageName) { 16514 for (int oneUserId : sUserManager.getUserIds()) { 16515 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16516 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16517 if (packageName.equals(defaultBrowserPackageName)) { 16518 setDefaultBrowserPackageName(null, oneUserId); 16519 } 16520 } 16521 } 16522 16523 @Override 16524 public void resetApplicationPreferences(int userId) { 16525 mContext.enforceCallingOrSelfPermission( 16526 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16527 // writer 16528 synchronized (mPackages) { 16529 final long identity = Binder.clearCallingIdentity(); 16530 try { 16531 clearPackagePreferredActivitiesLPw(null, userId); 16532 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16533 // TODO: We have to reset the default SMS and Phone. This requires 16534 // significant refactoring to keep all default apps in the package 16535 // manager (cleaner but more work) or have the services provide 16536 // callbacks to the package manager to request a default app reset. 16537 applyFactoryDefaultBrowserLPw(userId); 16538 clearIntentFilterVerificationsLPw(userId); 16539 primeDomainVerificationsLPw(userId); 16540 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16541 scheduleWritePackageRestrictionsLocked(userId); 16542 } finally { 16543 Binder.restoreCallingIdentity(identity); 16544 } 16545 } 16546 } 16547 16548 @Override 16549 public int getPreferredActivities(List<IntentFilter> outFilters, 16550 List<ComponentName> outActivities, String packageName) { 16551 16552 int num = 0; 16553 final int userId = UserHandle.getCallingUserId(); 16554 // reader 16555 synchronized (mPackages) { 16556 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16557 if (pir != null) { 16558 final Iterator<PreferredActivity> it = pir.filterIterator(); 16559 while (it.hasNext()) { 16560 final PreferredActivity pa = it.next(); 16561 if (packageName == null 16562 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16563 && pa.mPref.mAlways)) { 16564 if (outFilters != null) { 16565 outFilters.add(new IntentFilter(pa)); 16566 } 16567 if (outActivities != null) { 16568 outActivities.add(pa.mPref.mComponent); 16569 } 16570 } 16571 } 16572 } 16573 } 16574 16575 return num; 16576 } 16577 16578 @Override 16579 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16580 int userId) { 16581 int callingUid = Binder.getCallingUid(); 16582 if (callingUid != Process.SYSTEM_UID) { 16583 throw new SecurityException( 16584 "addPersistentPreferredActivity can only be run by the system"); 16585 } 16586 if (filter.countActions() == 0) { 16587 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16588 return; 16589 } 16590 synchronized (mPackages) { 16591 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16592 ":"); 16593 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16594 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16595 new PersistentPreferredActivity(filter, activity)); 16596 scheduleWritePackageRestrictionsLocked(userId); 16597 } 16598 } 16599 16600 @Override 16601 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16602 int callingUid = Binder.getCallingUid(); 16603 if (callingUid != Process.SYSTEM_UID) { 16604 throw new SecurityException( 16605 "clearPackagePersistentPreferredActivities can only be run by the system"); 16606 } 16607 ArrayList<PersistentPreferredActivity> removed = null; 16608 boolean changed = false; 16609 synchronized (mPackages) { 16610 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16611 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16612 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16613 .valueAt(i); 16614 if (userId != thisUserId) { 16615 continue; 16616 } 16617 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16618 while (it.hasNext()) { 16619 PersistentPreferredActivity ppa = it.next(); 16620 // Mark entry for removal only if it matches the package name. 16621 if (ppa.mComponent.getPackageName().equals(packageName)) { 16622 if (removed == null) { 16623 removed = new ArrayList<PersistentPreferredActivity>(); 16624 } 16625 removed.add(ppa); 16626 } 16627 } 16628 if (removed != null) { 16629 for (int j=0; j<removed.size(); j++) { 16630 PersistentPreferredActivity ppa = removed.get(j); 16631 ppir.removeFilter(ppa); 16632 } 16633 changed = true; 16634 } 16635 } 16636 16637 if (changed) { 16638 scheduleWritePackageRestrictionsLocked(userId); 16639 } 16640 } 16641 } 16642 16643 /** 16644 * Common machinery for picking apart a restored XML blob and passing 16645 * it to a caller-supplied functor to be applied to the running system. 16646 */ 16647 private void restoreFromXml(XmlPullParser parser, int userId, 16648 String expectedStartTag, BlobXmlRestorer functor) 16649 throws IOException, XmlPullParserException { 16650 int type; 16651 while ((type = parser.next()) != XmlPullParser.START_TAG 16652 && type != XmlPullParser.END_DOCUMENT) { 16653 } 16654 if (type != XmlPullParser.START_TAG) { 16655 // oops didn't find a start tag?! 16656 if (DEBUG_BACKUP) { 16657 Slog.e(TAG, "Didn't find start tag during restore"); 16658 } 16659 return; 16660 } 16661Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16662 // this is supposed to be TAG_PREFERRED_BACKUP 16663 if (!expectedStartTag.equals(parser.getName())) { 16664 if (DEBUG_BACKUP) { 16665 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16666 } 16667 return; 16668 } 16669 16670 // skip interfering stuff, then we're aligned with the backing implementation 16671 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16672Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16673 functor.apply(parser, userId); 16674 } 16675 16676 private interface BlobXmlRestorer { 16677 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16678 } 16679 16680 /** 16681 * Non-Binder method, support for the backup/restore mechanism: write the 16682 * full set of preferred activities in its canonical XML format. Returns the 16683 * XML output as a byte array, or null if there is none. 16684 */ 16685 @Override 16686 public byte[] getPreferredActivityBackup(int userId) { 16687 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16688 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16689 } 16690 16691 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16692 try { 16693 final XmlSerializer serializer = new FastXmlSerializer(); 16694 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16695 serializer.startDocument(null, true); 16696 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16697 16698 synchronized (mPackages) { 16699 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16700 } 16701 16702 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16703 serializer.endDocument(); 16704 serializer.flush(); 16705 } catch (Exception e) { 16706 if (DEBUG_BACKUP) { 16707 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16708 } 16709 return null; 16710 } 16711 16712 return dataStream.toByteArray(); 16713 } 16714 16715 @Override 16716 public void restorePreferredActivities(byte[] backup, int userId) { 16717 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16718 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16719 } 16720 16721 try { 16722 final XmlPullParser parser = Xml.newPullParser(); 16723 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16724 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16725 new BlobXmlRestorer() { 16726 @Override 16727 public void apply(XmlPullParser parser, int userId) 16728 throws XmlPullParserException, IOException { 16729 synchronized (mPackages) { 16730 mSettings.readPreferredActivitiesLPw(parser, userId); 16731 } 16732 } 16733 } ); 16734 } catch (Exception e) { 16735 if (DEBUG_BACKUP) { 16736 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16737 } 16738 } 16739 } 16740 16741 /** 16742 * Non-Binder method, support for the backup/restore mechanism: write the 16743 * default browser (etc) settings in its canonical XML format. Returns the default 16744 * browser XML representation as a byte array, or null if there is none. 16745 */ 16746 @Override 16747 public byte[] getDefaultAppsBackup(int userId) { 16748 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16749 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16750 } 16751 16752 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16753 try { 16754 final XmlSerializer serializer = new FastXmlSerializer(); 16755 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16756 serializer.startDocument(null, true); 16757 serializer.startTag(null, TAG_DEFAULT_APPS); 16758 16759 synchronized (mPackages) { 16760 mSettings.writeDefaultAppsLPr(serializer, userId); 16761 } 16762 16763 serializer.endTag(null, TAG_DEFAULT_APPS); 16764 serializer.endDocument(); 16765 serializer.flush(); 16766 } catch (Exception e) { 16767 if (DEBUG_BACKUP) { 16768 Slog.e(TAG, "Unable to write default apps for backup", e); 16769 } 16770 return null; 16771 } 16772 16773 return dataStream.toByteArray(); 16774 } 16775 16776 @Override 16777 public void restoreDefaultApps(byte[] backup, int userId) { 16778 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16779 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16780 } 16781 16782 try { 16783 final XmlPullParser parser = Xml.newPullParser(); 16784 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16785 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16786 new BlobXmlRestorer() { 16787 @Override 16788 public void apply(XmlPullParser parser, int userId) 16789 throws XmlPullParserException, IOException { 16790 synchronized (mPackages) { 16791 mSettings.readDefaultAppsLPw(parser, userId); 16792 } 16793 } 16794 } ); 16795 } catch (Exception e) { 16796 if (DEBUG_BACKUP) { 16797 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16798 } 16799 } 16800 } 16801 16802 @Override 16803 public byte[] getIntentFilterVerificationBackup(int userId) { 16804 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16805 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16806 } 16807 16808 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16809 try { 16810 final XmlSerializer serializer = new FastXmlSerializer(); 16811 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16812 serializer.startDocument(null, true); 16813 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16814 16815 synchronized (mPackages) { 16816 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16817 } 16818 16819 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16820 serializer.endDocument(); 16821 serializer.flush(); 16822 } catch (Exception e) { 16823 if (DEBUG_BACKUP) { 16824 Slog.e(TAG, "Unable to write default apps for backup", e); 16825 } 16826 return null; 16827 } 16828 16829 return dataStream.toByteArray(); 16830 } 16831 16832 @Override 16833 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16834 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16835 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16836 } 16837 16838 try { 16839 final XmlPullParser parser = Xml.newPullParser(); 16840 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16841 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16842 new BlobXmlRestorer() { 16843 @Override 16844 public void apply(XmlPullParser parser, int userId) 16845 throws XmlPullParserException, IOException { 16846 synchronized (mPackages) { 16847 mSettings.readAllDomainVerificationsLPr(parser, userId); 16848 mSettings.writeLPr(); 16849 } 16850 } 16851 } ); 16852 } catch (Exception e) { 16853 if (DEBUG_BACKUP) { 16854 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16855 } 16856 } 16857 } 16858 16859 @Override 16860 public byte[] getPermissionGrantBackup(int userId) { 16861 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16862 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16863 } 16864 16865 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16866 try { 16867 final XmlSerializer serializer = new FastXmlSerializer(); 16868 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16869 serializer.startDocument(null, true); 16870 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16871 16872 synchronized (mPackages) { 16873 serializeRuntimePermissionGrantsLPr(serializer, userId); 16874 } 16875 16876 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16877 serializer.endDocument(); 16878 serializer.flush(); 16879 } catch (Exception e) { 16880 if (DEBUG_BACKUP) { 16881 Slog.e(TAG, "Unable to write default apps for backup", e); 16882 } 16883 return null; 16884 } 16885 16886 return dataStream.toByteArray(); 16887 } 16888 16889 @Override 16890 public void restorePermissionGrants(byte[] backup, int userId) { 16891 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16892 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16893 } 16894 16895 try { 16896 final XmlPullParser parser = Xml.newPullParser(); 16897 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16898 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16899 new BlobXmlRestorer() { 16900 @Override 16901 public void apply(XmlPullParser parser, int userId) 16902 throws XmlPullParserException, IOException { 16903 synchronized (mPackages) { 16904 processRestoredPermissionGrantsLPr(parser, userId); 16905 } 16906 } 16907 } ); 16908 } catch (Exception e) { 16909 if (DEBUG_BACKUP) { 16910 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16911 } 16912 } 16913 } 16914 16915 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16916 throws IOException { 16917 serializer.startTag(null, TAG_ALL_GRANTS); 16918 16919 final int N = mSettings.mPackages.size(); 16920 for (int i = 0; i < N; i++) { 16921 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16922 boolean pkgGrantsKnown = false; 16923 16924 PermissionsState packagePerms = ps.getPermissionsState(); 16925 16926 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16927 final int grantFlags = state.getFlags(); 16928 // only look at grants that are not system/policy fixed 16929 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16930 final boolean isGranted = state.isGranted(); 16931 // And only back up the user-twiddled state bits 16932 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16933 final String packageName = mSettings.mPackages.keyAt(i); 16934 if (!pkgGrantsKnown) { 16935 serializer.startTag(null, TAG_GRANT); 16936 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16937 pkgGrantsKnown = true; 16938 } 16939 16940 final boolean userSet = 16941 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16942 final boolean userFixed = 16943 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16944 final boolean revoke = 16945 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16946 16947 serializer.startTag(null, TAG_PERMISSION); 16948 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16949 if (isGranted) { 16950 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16951 } 16952 if (userSet) { 16953 serializer.attribute(null, ATTR_USER_SET, "true"); 16954 } 16955 if (userFixed) { 16956 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16957 } 16958 if (revoke) { 16959 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16960 } 16961 serializer.endTag(null, TAG_PERMISSION); 16962 } 16963 } 16964 } 16965 16966 if (pkgGrantsKnown) { 16967 serializer.endTag(null, TAG_GRANT); 16968 } 16969 } 16970 16971 serializer.endTag(null, TAG_ALL_GRANTS); 16972 } 16973 16974 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16975 throws XmlPullParserException, IOException { 16976 String pkgName = null; 16977 int outerDepth = parser.getDepth(); 16978 int type; 16979 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16980 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16981 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16982 continue; 16983 } 16984 16985 final String tagName = parser.getName(); 16986 if (tagName.equals(TAG_GRANT)) { 16987 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16988 if (DEBUG_BACKUP) { 16989 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16990 } 16991 } else if (tagName.equals(TAG_PERMISSION)) { 16992 16993 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16994 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16995 16996 int newFlagSet = 0; 16997 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16998 newFlagSet |= FLAG_PERMISSION_USER_SET; 16999 } 17000 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17001 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17002 } 17003 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17004 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17005 } 17006 if (DEBUG_BACKUP) { 17007 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17008 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17009 } 17010 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17011 if (ps != null) { 17012 // Already installed so we apply the grant immediately 17013 if (DEBUG_BACKUP) { 17014 Slog.v(TAG, " + already installed; applying"); 17015 } 17016 PermissionsState perms = ps.getPermissionsState(); 17017 BasePermission bp = mSettings.mPermissions.get(permName); 17018 if (bp != null) { 17019 if (isGranted) { 17020 perms.grantRuntimePermission(bp, userId); 17021 } 17022 if (newFlagSet != 0) { 17023 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17024 } 17025 } 17026 } else { 17027 // Need to wait for post-restore install to apply the grant 17028 if (DEBUG_BACKUP) { 17029 Slog.v(TAG, " - not yet installed; saving for later"); 17030 } 17031 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17032 isGranted, newFlagSet, userId); 17033 } 17034 } else { 17035 PackageManagerService.reportSettingsProblem(Log.WARN, 17036 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17037 XmlUtils.skipCurrentTag(parser); 17038 } 17039 } 17040 17041 scheduleWriteSettingsLocked(); 17042 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17043 } 17044 17045 @Override 17046 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17047 int sourceUserId, int targetUserId, int flags) { 17048 mContext.enforceCallingOrSelfPermission( 17049 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17050 int callingUid = Binder.getCallingUid(); 17051 enforceOwnerRights(ownerPackage, callingUid); 17052 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17053 if (intentFilter.countActions() == 0) { 17054 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17055 return; 17056 } 17057 synchronized (mPackages) { 17058 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17059 ownerPackage, targetUserId, flags); 17060 CrossProfileIntentResolver resolver = 17061 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17062 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17063 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17064 if (existing != null) { 17065 int size = existing.size(); 17066 for (int i = 0; i < size; i++) { 17067 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17068 return; 17069 } 17070 } 17071 } 17072 resolver.addFilter(newFilter); 17073 scheduleWritePackageRestrictionsLocked(sourceUserId); 17074 } 17075 } 17076 17077 @Override 17078 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17079 mContext.enforceCallingOrSelfPermission( 17080 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17081 int callingUid = Binder.getCallingUid(); 17082 enforceOwnerRights(ownerPackage, callingUid); 17083 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17084 synchronized (mPackages) { 17085 CrossProfileIntentResolver resolver = 17086 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17087 ArraySet<CrossProfileIntentFilter> set = 17088 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17089 for (CrossProfileIntentFilter filter : set) { 17090 if (filter.getOwnerPackage().equals(ownerPackage)) { 17091 resolver.removeFilter(filter); 17092 } 17093 } 17094 scheduleWritePackageRestrictionsLocked(sourceUserId); 17095 } 17096 } 17097 17098 // Enforcing that callingUid is owning pkg on userId 17099 private void enforceOwnerRights(String pkg, int callingUid) { 17100 // The system owns everything. 17101 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17102 return; 17103 } 17104 int callingUserId = UserHandle.getUserId(callingUid); 17105 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17106 if (pi == null) { 17107 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17108 + callingUserId); 17109 } 17110 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17111 throw new SecurityException("Calling uid " + callingUid 17112 + " does not own package " + pkg); 17113 } 17114 } 17115 17116 @Override 17117 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17118 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17119 } 17120 17121 private Intent getHomeIntent() { 17122 Intent intent = new Intent(Intent.ACTION_MAIN); 17123 intent.addCategory(Intent.CATEGORY_HOME); 17124 return intent; 17125 } 17126 17127 private IntentFilter getHomeFilter() { 17128 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17129 filter.addCategory(Intent.CATEGORY_HOME); 17130 filter.addCategory(Intent.CATEGORY_DEFAULT); 17131 return filter; 17132 } 17133 17134 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17135 int userId) { 17136 Intent intent = getHomeIntent(); 17137 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17138 PackageManager.GET_META_DATA, userId); 17139 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17140 true, false, false, userId); 17141 17142 allHomeCandidates.clear(); 17143 if (list != null) { 17144 for (ResolveInfo ri : list) { 17145 allHomeCandidates.add(ri); 17146 } 17147 } 17148 return (preferred == null || preferred.activityInfo == null) 17149 ? null 17150 : new ComponentName(preferred.activityInfo.packageName, 17151 preferred.activityInfo.name); 17152 } 17153 17154 @Override 17155 public void setHomeActivity(ComponentName comp, int userId) { 17156 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17157 getHomeActivitiesAsUser(homeActivities, userId); 17158 17159 boolean found = false; 17160 17161 final int size = homeActivities.size(); 17162 final ComponentName[] set = new ComponentName[size]; 17163 for (int i = 0; i < size; i++) { 17164 final ResolveInfo candidate = homeActivities.get(i); 17165 final ActivityInfo info = candidate.activityInfo; 17166 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17167 set[i] = activityName; 17168 if (!found && activityName.equals(comp)) { 17169 found = true; 17170 } 17171 } 17172 if (!found) { 17173 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17174 + userId); 17175 } 17176 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17177 set, comp, userId); 17178 } 17179 17180 private @Nullable String getSetupWizardPackageName() { 17181 final Intent intent = new Intent(Intent.ACTION_MAIN); 17182 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17183 17184 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17185 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17186 | MATCH_DISABLED_COMPONENTS, 17187 UserHandle.myUserId()); 17188 if (matches.size() == 1) { 17189 return matches.get(0).getComponentInfo().packageName; 17190 } else { 17191 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17192 + ": matches=" + matches); 17193 return null; 17194 } 17195 } 17196 17197 @Override 17198 public void setApplicationEnabledSetting(String appPackageName, 17199 int newState, int flags, int userId, String callingPackage) { 17200 if (!sUserManager.exists(userId)) return; 17201 if (callingPackage == null) { 17202 callingPackage = Integer.toString(Binder.getCallingUid()); 17203 } 17204 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17205 } 17206 17207 @Override 17208 public void setComponentEnabledSetting(ComponentName componentName, 17209 int newState, int flags, int userId) { 17210 if (!sUserManager.exists(userId)) return; 17211 setEnabledSetting(componentName.getPackageName(), 17212 componentName.getClassName(), newState, flags, userId, null); 17213 } 17214 17215 private void setEnabledSetting(final String packageName, String className, int newState, 17216 final int flags, int userId, String callingPackage) { 17217 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17218 || newState == COMPONENT_ENABLED_STATE_ENABLED 17219 || newState == COMPONENT_ENABLED_STATE_DISABLED 17220 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17221 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17222 throw new IllegalArgumentException("Invalid new component state: " 17223 + newState); 17224 } 17225 PackageSetting pkgSetting; 17226 final int uid = Binder.getCallingUid(); 17227 final int permission; 17228 if (uid == Process.SYSTEM_UID) { 17229 permission = PackageManager.PERMISSION_GRANTED; 17230 } else { 17231 permission = mContext.checkCallingOrSelfPermission( 17232 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17233 } 17234 enforceCrossUserPermission(uid, userId, 17235 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17236 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17237 boolean sendNow = false; 17238 boolean isApp = (className == null); 17239 String componentName = isApp ? packageName : className; 17240 int packageUid = -1; 17241 ArrayList<String> components; 17242 17243 // writer 17244 synchronized (mPackages) { 17245 pkgSetting = mSettings.mPackages.get(packageName); 17246 if (pkgSetting == null) { 17247 if (className == null) { 17248 throw new IllegalArgumentException("Unknown package: " + packageName); 17249 } 17250 throw new IllegalArgumentException( 17251 "Unknown component: " + packageName + "/" + className); 17252 } 17253 // Allow root and verify that userId is not being specified by a different user 17254 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17255 throw new SecurityException( 17256 "Permission Denial: attempt to change component state from pid=" 17257 + Binder.getCallingPid() 17258 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17259 } 17260 if (className == null) { 17261 // We're dealing with an application/package level state change 17262 if (pkgSetting.getEnabled(userId) == newState) { 17263 // Nothing to do 17264 return; 17265 } 17266 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17267 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17268 // Don't care about who enables an app. 17269 callingPackage = null; 17270 } 17271 pkgSetting.setEnabled(newState, userId, callingPackage); 17272 // pkgSetting.pkg.mSetEnabled = newState; 17273 } else { 17274 // We're dealing with a component level state change 17275 // First, verify that this is a valid class name. 17276 PackageParser.Package pkg = pkgSetting.pkg; 17277 if (pkg == null || !pkg.hasComponentClassName(className)) { 17278 if (pkg != null && 17279 pkg.applicationInfo.targetSdkVersion >= 17280 Build.VERSION_CODES.JELLY_BEAN) { 17281 throw new IllegalArgumentException("Component class " + className 17282 + " does not exist in " + packageName); 17283 } else { 17284 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17285 + className + " does not exist in " + packageName); 17286 } 17287 } 17288 switch (newState) { 17289 case COMPONENT_ENABLED_STATE_ENABLED: 17290 if (!pkgSetting.enableComponentLPw(className, userId)) { 17291 return; 17292 } 17293 break; 17294 case COMPONENT_ENABLED_STATE_DISABLED: 17295 if (!pkgSetting.disableComponentLPw(className, userId)) { 17296 return; 17297 } 17298 break; 17299 case COMPONENT_ENABLED_STATE_DEFAULT: 17300 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17301 return; 17302 } 17303 break; 17304 default: 17305 Slog.e(TAG, "Invalid new component state: " + newState); 17306 return; 17307 } 17308 } 17309 scheduleWritePackageRestrictionsLocked(userId); 17310 components = mPendingBroadcasts.get(userId, packageName); 17311 final boolean newPackage = components == null; 17312 if (newPackage) { 17313 components = new ArrayList<String>(); 17314 } 17315 if (!components.contains(componentName)) { 17316 components.add(componentName); 17317 } 17318 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17319 sendNow = true; 17320 // Purge entry from pending broadcast list if another one exists already 17321 // since we are sending one right away. 17322 mPendingBroadcasts.remove(userId, packageName); 17323 } else { 17324 if (newPackage) { 17325 mPendingBroadcasts.put(userId, packageName, components); 17326 } 17327 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17328 // Schedule a message 17329 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17330 } 17331 } 17332 } 17333 17334 long callingId = Binder.clearCallingIdentity(); 17335 try { 17336 if (sendNow) { 17337 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17338 sendPackageChangedBroadcast(packageName, 17339 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17340 } 17341 } finally { 17342 Binder.restoreCallingIdentity(callingId); 17343 } 17344 } 17345 17346 @Override 17347 public void flushPackageRestrictionsAsUser(int userId) { 17348 if (!sUserManager.exists(userId)) { 17349 return; 17350 } 17351 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17352 false /* checkShell */, "flushPackageRestrictions"); 17353 synchronized (mPackages) { 17354 mSettings.writePackageRestrictionsLPr(userId); 17355 mDirtyUsers.remove(userId); 17356 if (mDirtyUsers.isEmpty()) { 17357 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17358 } 17359 } 17360 } 17361 17362 private void sendPackageChangedBroadcast(String packageName, 17363 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17364 if (DEBUG_INSTALL) 17365 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17366 + componentNames); 17367 Bundle extras = new Bundle(4); 17368 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17369 String nameList[] = new String[componentNames.size()]; 17370 componentNames.toArray(nameList); 17371 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17372 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17373 extras.putInt(Intent.EXTRA_UID, packageUid); 17374 // If this is not reporting a change of the overall package, then only send it 17375 // to registered receivers. We don't want to launch a swath of apps for every 17376 // little component state change. 17377 final int flags = !componentNames.contains(packageName) 17378 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17379 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17380 new int[] {UserHandle.getUserId(packageUid)}); 17381 } 17382 17383 @Override 17384 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17385 if (!sUserManager.exists(userId)) return; 17386 final int uid = Binder.getCallingUid(); 17387 final int permission = mContext.checkCallingOrSelfPermission( 17388 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17389 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17390 enforceCrossUserPermission(uid, userId, 17391 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17392 // writer 17393 synchronized (mPackages) { 17394 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17395 allowedByPermission, uid, userId)) { 17396 scheduleWritePackageRestrictionsLocked(userId); 17397 } 17398 } 17399 } 17400 17401 @Override 17402 public String getInstallerPackageName(String packageName) { 17403 // reader 17404 synchronized (mPackages) { 17405 return mSettings.getInstallerPackageNameLPr(packageName); 17406 } 17407 } 17408 17409 @Override 17410 public int getApplicationEnabledSetting(String packageName, int userId) { 17411 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17412 int uid = Binder.getCallingUid(); 17413 enforceCrossUserPermission(uid, userId, 17414 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17415 // reader 17416 synchronized (mPackages) { 17417 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17418 } 17419 } 17420 17421 @Override 17422 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17423 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17424 int uid = Binder.getCallingUid(); 17425 enforceCrossUserPermission(uid, userId, 17426 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17427 // reader 17428 synchronized (mPackages) { 17429 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17430 } 17431 } 17432 17433 @Override 17434 public void enterSafeMode() { 17435 enforceSystemOrRoot("Only the system can request entering safe mode"); 17436 17437 if (!mSystemReady) { 17438 mSafeMode = true; 17439 } 17440 } 17441 17442 @Override 17443 public void systemReady() { 17444 mSystemReady = true; 17445 17446 // Read the compatibilty setting when the system is ready. 17447 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17448 mContext.getContentResolver(), 17449 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17450 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17451 if (DEBUG_SETTINGS) { 17452 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17453 } 17454 17455 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17456 17457 synchronized (mPackages) { 17458 // Verify that all of the preferred activity components actually 17459 // exist. It is possible for applications to be updated and at 17460 // that point remove a previously declared activity component that 17461 // had been set as a preferred activity. We try to clean this up 17462 // the next time we encounter that preferred activity, but it is 17463 // possible for the user flow to never be able to return to that 17464 // situation so here we do a sanity check to make sure we haven't 17465 // left any junk around. 17466 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17467 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17468 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17469 removed.clear(); 17470 for (PreferredActivity pa : pir.filterSet()) { 17471 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17472 removed.add(pa); 17473 } 17474 } 17475 if (removed.size() > 0) { 17476 for (int r=0; r<removed.size(); r++) { 17477 PreferredActivity pa = removed.get(r); 17478 Slog.w(TAG, "Removing dangling preferred activity: " 17479 + pa.mPref.mComponent); 17480 pir.removeFilter(pa); 17481 } 17482 mSettings.writePackageRestrictionsLPr( 17483 mSettings.mPreferredActivities.keyAt(i)); 17484 } 17485 } 17486 17487 for (int userId : UserManagerService.getInstance().getUserIds()) { 17488 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17489 grantPermissionsUserIds = ArrayUtils.appendInt( 17490 grantPermissionsUserIds, userId); 17491 } 17492 } 17493 } 17494 sUserManager.systemReady(); 17495 17496 // If we upgraded grant all default permissions before kicking off. 17497 for (int userId : grantPermissionsUserIds) { 17498 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17499 } 17500 17501 // Kick off any messages waiting for system ready 17502 if (mPostSystemReadyMessages != null) { 17503 for (Message msg : mPostSystemReadyMessages) { 17504 msg.sendToTarget(); 17505 } 17506 mPostSystemReadyMessages = null; 17507 } 17508 17509 // Watch for external volumes that come and go over time 17510 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17511 storage.registerListener(mStorageListener); 17512 17513 mInstallerService.systemReady(); 17514 mPackageDexOptimizer.systemReady(); 17515 17516 MountServiceInternal mountServiceInternal = LocalServices.getService( 17517 MountServiceInternal.class); 17518 mountServiceInternal.addExternalStoragePolicy( 17519 new MountServiceInternal.ExternalStorageMountPolicy() { 17520 @Override 17521 public int getMountMode(int uid, String packageName) { 17522 if (Process.isIsolated(uid)) { 17523 return Zygote.MOUNT_EXTERNAL_NONE; 17524 } 17525 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17526 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17527 } 17528 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17529 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17530 } 17531 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17532 return Zygote.MOUNT_EXTERNAL_READ; 17533 } 17534 return Zygote.MOUNT_EXTERNAL_WRITE; 17535 } 17536 17537 @Override 17538 public boolean hasExternalStorage(int uid, String packageName) { 17539 return true; 17540 } 17541 }); 17542 17543 // Now that we're mostly running, clean up stale users and apps 17544 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17545 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17546 } 17547 17548 @Override 17549 public boolean isSafeMode() { 17550 return mSafeMode; 17551 } 17552 17553 @Override 17554 public boolean hasSystemUidErrors() { 17555 return mHasSystemUidErrors; 17556 } 17557 17558 static String arrayToString(int[] array) { 17559 StringBuffer buf = new StringBuffer(128); 17560 buf.append('['); 17561 if (array != null) { 17562 for (int i=0; i<array.length; i++) { 17563 if (i > 0) buf.append(", "); 17564 buf.append(array[i]); 17565 } 17566 } 17567 buf.append(']'); 17568 return buf.toString(); 17569 } 17570 17571 static class DumpState { 17572 public static final int DUMP_LIBS = 1 << 0; 17573 public static final int DUMP_FEATURES = 1 << 1; 17574 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17575 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17576 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17577 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17578 public static final int DUMP_PERMISSIONS = 1 << 6; 17579 public static final int DUMP_PACKAGES = 1 << 7; 17580 public static final int DUMP_SHARED_USERS = 1 << 8; 17581 public static final int DUMP_MESSAGES = 1 << 9; 17582 public static final int DUMP_PROVIDERS = 1 << 10; 17583 public static final int DUMP_VERIFIERS = 1 << 11; 17584 public static final int DUMP_PREFERRED = 1 << 12; 17585 public static final int DUMP_PREFERRED_XML = 1 << 13; 17586 public static final int DUMP_KEYSETS = 1 << 14; 17587 public static final int DUMP_VERSION = 1 << 15; 17588 public static final int DUMP_INSTALLS = 1 << 16; 17589 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17590 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17591 public static final int DUMP_FROZEN = 1 << 19; 17592 17593 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17594 17595 private int mTypes; 17596 17597 private int mOptions; 17598 17599 private boolean mTitlePrinted; 17600 17601 private SharedUserSetting mSharedUser; 17602 17603 public boolean isDumping(int type) { 17604 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17605 return true; 17606 } 17607 17608 return (mTypes & type) != 0; 17609 } 17610 17611 public void setDump(int type) { 17612 mTypes |= type; 17613 } 17614 17615 public boolean isOptionEnabled(int option) { 17616 return (mOptions & option) != 0; 17617 } 17618 17619 public void setOptionEnabled(int option) { 17620 mOptions |= option; 17621 } 17622 17623 public boolean onTitlePrinted() { 17624 final boolean printed = mTitlePrinted; 17625 mTitlePrinted = true; 17626 return printed; 17627 } 17628 17629 public boolean getTitlePrinted() { 17630 return mTitlePrinted; 17631 } 17632 17633 public void setTitlePrinted(boolean enabled) { 17634 mTitlePrinted = enabled; 17635 } 17636 17637 public SharedUserSetting getSharedUser() { 17638 return mSharedUser; 17639 } 17640 17641 public void setSharedUser(SharedUserSetting user) { 17642 mSharedUser = user; 17643 } 17644 } 17645 17646 @Override 17647 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17648 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17649 (new PackageManagerShellCommand(this)).exec( 17650 this, in, out, err, args, resultReceiver); 17651 } 17652 17653 @Override 17654 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17655 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17656 != PackageManager.PERMISSION_GRANTED) { 17657 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17658 + Binder.getCallingPid() 17659 + ", uid=" + Binder.getCallingUid() 17660 + " without permission " 17661 + android.Manifest.permission.DUMP); 17662 return; 17663 } 17664 17665 DumpState dumpState = new DumpState(); 17666 boolean fullPreferred = false; 17667 boolean checkin = false; 17668 17669 String packageName = null; 17670 ArraySet<String> permissionNames = null; 17671 17672 int opti = 0; 17673 while (opti < args.length) { 17674 String opt = args[opti]; 17675 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17676 break; 17677 } 17678 opti++; 17679 17680 if ("-a".equals(opt)) { 17681 // Right now we only know how to print all. 17682 } else if ("-h".equals(opt)) { 17683 pw.println("Package manager dump options:"); 17684 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17685 pw.println(" --checkin: dump for a checkin"); 17686 pw.println(" -f: print details of intent filters"); 17687 pw.println(" -h: print this help"); 17688 pw.println(" cmd may be one of:"); 17689 pw.println(" l[ibraries]: list known shared libraries"); 17690 pw.println(" f[eatures]: list device features"); 17691 pw.println(" k[eysets]: print known keysets"); 17692 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17693 pw.println(" perm[issions]: dump permissions"); 17694 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17695 pw.println(" pref[erred]: print preferred package settings"); 17696 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17697 pw.println(" prov[iders]: dump content providers"); 17698 pw.println(" p[ackages]: dump installed packages"); 17699 pw.println(" s[hared-users]: dump shared user IDs"); 17700 pw.println(" m[essages]: print collected runtime messages"); 17701 pw.println(" v[erifiers]: print package verifier info"); 17702 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17703 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17704 pw.println(" version: print database version info"); 17705 pw.println(" write: write current settings now"); 17706 pw.println(" installs: details about install sessions"); 17707 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17708 pw.println(" <package.name>: info about given package"); 17709 return; 17710 } else if ("--checkin".equals(opt)) { 17711 checkin = true; 17712 } else if ("-f".equals(opt)) { 17713 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17714 } else { 17715 pw.println("Unknown argument: " + opt + "; use -h for help"); 17716 } 17717 } 17718 17719 // Is the caller requesting to dump a particular piece of data? 17720 if (opti < args.length) { 17721 String cmd = args[opti]; 17722 opti++; 17723 // Is this a package name? 17724 if ("android".equals(cmd) || cmd.contains(".")) { 17725 packageName = cmd; 17726 // When dumping a single package, we always dump all of its 17727 // filter information since the amount of data will be reasonable. 17728 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17729 } else if ("check-permission".equals(cmd)) { 17730 if (opti >= args.length) { 17731 pw.println("Error: check-permission missing permission argument"); 17732 return; 17733 } 17734 String perm = args[opti]; 17735 opti++; 17736 if (opti >= args.length) { 17737 pw.println("Error: check-permission missing package argument"); 17738 return; 17739 } 17740 String pkg = args[opti]; 17741 opti++; 17742 int user = UserHandle.getUserId(Binder.getCallingUid()); 17743 if (opti < args.length) { 17744 try { 17745 user = Integer.parseInt(args[opti]); 17746 } catch (NumberFormatException e) { 17747 pw.println("Error: check-permission user argument is not a number: " 17748 + args[opti]); 17749 return; 17750 } 17751 } 17752 pw.println(checkPermission(perm, pkg, user)); 17753 return; 17754 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17755 dumpState.setDump(DumpState.DUMP_LIBS); 17756 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17757 dumpState.setDump(DumpState.DUMP_FEATURES); 17758 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17759 if (opti >= args.length) { 17760 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17761 | DumpState.DUMP_SERVICE_RESOLVERS 17762 | DumpState.DUMP_RECEIVER_RESOLVERS 17763 | DumpState.DUMP_CONTENT_RESOLVERS); 17764 } else { 17765 while (opti < args.length) { 17766 String name = args[opti]; 17767 if ("a".equals(name) || "activity".equals(name)) { 17768 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17769 } else if ("s".equals(name) || "service".equals(name)) { 17770 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17771 } else if ("r".equals(name) || "receiver".equals(name)) { 17772 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17773 } else if ("c".equals(name) || "content".equals(name)) { 17774 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17775 } else { 17776 pw.println("Error: unknown resolver table type: " + name); 17777 return; 17778 } 17779 opti++; 17780 } 17781 } 17782 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17783 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17784 } else if ("permission".equals(cmd)) { 17785 if (opti >= args.length) { 17786 pw.println("Error: permission requires permission name"); 17787 return; 17788 } 17789 permissionNames = new ArraySet<>(); 17790 while (opti < args.length) { 17791 permissionNames.add(args[opti]); 17792 opti++; 17793 } 17794 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17795 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17796 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17797 dumpState.setDump(DumpState.DUMP_PREFERRED); 17798 } else if ("preferred-xml".equals(cmd)) { 17799 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17800 if (opti < args.length && "--full".equals(args[opti])) { 17801 fullPreferred = true; 17802 opti++; 17803 } 17804 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17805 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17806 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17807 dumpState.setDump(DumpState.DUMP_PACKAGES); 17808 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17809 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17810 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17811 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17812 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17813 dumpState.setDump(DumpState.DUMP_MESSAGES); 17814 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17815 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17816 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17817 || "intent-filter-verifiers".equals(cmd)) { 17818 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17819 } else if ("version".equals(cmd)) { 17820 dumpState.setDump(DumpState.DUMP_VERSION); 17821 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17822 dumpState.setDump(DumpState.DUMP_KEYSETS); 17823 } else if ("installs".equals(cmd)) { 17824 dumpState.setDump(DumpState.DUMP_INSTALLS); 17825 } else if ("frozen".equals(cmd)) { 17826 dumpState.setDump(DumpState.DUMP_FROZEN); 17827 } else if ("write".equals(cmd)) { 17828 synchronized (mPackages) { 17829 mSettings.writeLPr(); 17830 pw.println("Settings written."); 17831 return; 17832 } 17833 } 17834 } 17835 17836 if (checkin) { 17837 pw.println("vers,1"); 17838 } 17839 17840 // reader 17841 synchronized (mPackages) { 17842 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17843 if (!checkin) { 17844 if (dumpState.onTitlePrinted()) 17845 pw.println(); 17846 pw.println("Database versions:"); 17847 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17848 } 17849 } 17850 17851 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17852 if (!checkin) { 17853 if (dumpState.onTitlePrinted()) 17854 pw.println(); 17855 pw.println("Verifiers:"); 17856 pw.print(" Required: "); 17857 pw.print(mRequiredVerifierPackage); 17858 pw.print(" (uid="); 17859 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17860 UserHandle.USER_SYSTEM)); 17861 pw.println(")"); 17862 } else if (mRequiredVerifierPackage != null) { 17863 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17864 pw.print(","); 17865 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17866 UserHandle.USER_SYSTEM)); 17867 } 17868 } 17869 17870 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17871 packageName == null) { 17872 if (mIntentFilterVerifierComponent != null) { 17873 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17874 if (!checkin) { 17875 if (dumpState.onTitlePrinted()) 17876 pw.println(); 17877 pw.println("Intent Filter Verifier:"); 17878 pw.print(" Using: "); 17879 pw.print(verifierPackageName); 17880 pw.print(" (uid="); 17881 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17882 UserHandle.USER_SYSTEM)); 17883 pw.println(")"); 17884 } else if (verifierPackageName != null) { 17885 pw.print("ifv,"); pw.print(verifierPackageName); 17886 pw.print(","); 17887 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17888 UserHandle.USER_SYSTEM)); 17889 } 17890 } else { 17891 pw.println(); 17892 pw.println("No Intent Filter Verifier available!"); 17893 } 17894 } 17895 17896 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17897 boolean printedHeader = false; 17898 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17899 while (it.hasNext()) { 17900 String name = it.next(); 17901 SharedLibraryEntry ent = mSharedLibraries.get(name); 17902 if (!checkin) { 17903 if (!printedHeader) { 17904 if (dumpState.onTitlePrinted()) 17905 pw.println(); 17906 pw.println("Libraries:"); 17907 printedHeader = true; 17908 } 17909 pw.print(" "); 17910 } else { 17911 pw.print("lib,"); 17912 } 17913 pw.print(name); 17914 if (!checkin) { 17915 pw.print(" -> "); 17916 } 17917 if (ent.path != null) { 17918 if (!checkin) { 17919 pw.print("(jar) "); 17920 pw.print(ent.path); 17921 } else { 17922 pw.print(",jar,"); 17923 pw.print(ent.path); 17924 } 17925 } else { 17926 if (!checkin) { 17927 pw.print("(apk) "); 17928 pw.print(ent.apk); 17929 } else { 17930 pw.print(",apk,"); 17931 pw.print(ent.apk); 17932 } 17933 } 17934 pw.println(); 17935 } 17936 } 17937 17938 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17939 if (dumpState.onTitlePrinted()) 17940 pw.println(); 17941 if (!checkin) { 17942 pw.println("Features:"); 17943 } 17944 17945 for (FeatureInfo feat : mAvailableFeatures.values()) { 17946 if (checkin) { 17947 pw.print("feat,"); 17948 pw.print(feat.name); 17949 pw.print(","); 17950 pw.println(feat.version); 17951 } else { 17952 pw.print(" "); 17953 pw.print(feat.name); 17954 if (feat.version > 0) { 17955 pw.print(" version="); 17956 pw.print(feat.version); 17957 } 17958 pw.println(); 17959 } 17960 } 17961 } 17962 17963 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17964 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17965 : "Activity Resolver Table:", " ", packageName, 17966 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17967 dumpState.setTitlePrinted(true); 17968 } 17969 } 17970 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17971 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17972 : "Receiver Resolver Table:", " ", packageName, 17973 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17974 dumpState.setTitlePrinted(true); 17975 } 17976 } 17977 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17978 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17979 : "Service Resolver Table:", " ", packageName, 17980 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17981 dumpState.setTitlePrinted(true); 17982 } 17983 } 17984 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17985 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17986 : "Provider Resolver Table:", " ", packageName, 17987 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17988 dumpState.setTitlePrinted(true); 17989 } 17990 } 17991 17992 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17993 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17994 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17995 int user = mSettings.mPreferredActivities.keyAt(i); 17996 if (pir.dump(pw, 17997 dumpState.getTitlePrinted() 17998 ? "\nPreferred Activities User " + user + ":" 17999 : "Preferred Activities User " + user + ":", " ", 18000 packageName, true, false)) { 18001 dumpState.setTitlePrinted(true); 18002 } 18003 } 18004 } 18005 18006 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18007 pw.flush(); 18008 FileOutputStream fout = new FileOutputStream(fd); 18009 BufferedOutputStream str = new BufferedOutputStream(fout); 18010 XmlSerializer serializer = new FastXmlSerializer(); 18011 try { 18012 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18013 serializer.startDocument(null, true); 18014 serializer.setFeature( 18015 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18016 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18017 serializer.endDocument(); 18018 serializer.flush(); 18019 } catch (IllegalArgumentException e) { 18020 pw.println("Failed writing: " + e); 18021 } catch (IllegalStateException e) { 18022 pw.println("Failed writing: " + e); 18023 } catch (IOException e) { 18024 pw.println("Failed writing: " + e); 18025 } 18026 } 18027 18028 if (!checkin 18029 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18030 && packageName == null) { 18031 pw.println(); 18032 int count = mSettings.mPackages.size(); 18033 if (count == 0) { 18034 pw.println("No applications!"); 18035 pw.println(); 18036 } else { 18037 final String prefix = " "; 18038 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18039 if (allPackageSettings.size() == 0) { 18040 pw.println("No domain preferred apps!"); 18041 pw.println(); 18042 } else { 18043 pw.println("App verification status:"); 18044 pw.println(); 18045 count = 0; 18046 for (PackageSetting ps : allPackageSettings) { 18047 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18048 if (ivi == null || ivi.getPackageName() == null) continue; 18049 pw.println(prefix + "Package: " + ivi.getPackageName()); 18050 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18051 pw.println(prefix + "Status: " + ivi.getStatusString()); 18052 pw.println(); 18053 count++; 18054 } 18055 if (count == 0) { 18056 pw.println(prefix + "No app verification established."); 18057 pw.println(); 18058 } 18059 for (int userId : sUserManager.getUserIds()) { 18060 pw.println("App linkages for user " + userId + ":"); 18061 pw.println(); 18062 count = 0; 18063 for (PackageSetting ps : allPackageSettings) { 18064 final long status = ps.getDomainVerificationStatusForUser(userId); 18065 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18066 continue; 18067 } 18068 pw.println(prefix + "Package: " + ps.name); 18069 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18070 String statusStr = IntentFilterVerificationInfo. 18071 getStatusStringFromValue(status); 18072 pw.println(prefix + "Status: " + statusStr); 18073 pw.println(); 18074 count++; 18075 } 18076 if (count == 0) { 18077 pw.println(prefix + "No configured app linkages."); 18078 pw.println(); 18079 } 18080 } 18081 } 18082 } 18083 } 18084 18085 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18086 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18087 if (packageName == null && permissionNames == null) { 18088 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18089 if (iperm == 0) { 18090 if (dumpState.onTitlePrinted()) 18091 pw.println(); 18092 pw.println("AppOp Permissions:"); 18093 } 18094 pw.print(" AppOp Permission "); 18095 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18096 pw.println(":"); 18097 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18098 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18099 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18100 } 18101 } 18102 } 18103 } 18104 18105 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18106 boolean printedSomething = false; 18107 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18108 if (packageName != null && !packageName.equals(p.info.packageName)) { 18109 continue; 18110 } 18111 if (!printedSomething) { 18112 if (dumpState.onTitlePrinted()) 18113 pw.println(); 18114 pw.println("Registered ContentProviders:"); 18115 printedSomething = true; 18116 } 18117 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18118 pw.print(" "); pw.println(p.toString()); 18119 } 18120 printedSomething = false; 18121 for (Map.Entry<String, PackageParser.Provider> entry : 18122 mProvidersByAuthority.entrySet()) { 18123 PackageParser.Provider p = entry.getValue(); 18124 if (packageName != null && !packageName.equals(p.info.packageName)) { 18125 continue; 18126 } 18127 if (!printedSomething) { 18128 if (dumpState.onTitlePrinted()) 18129 pw.println(); 18130 pw.println("ContentProvider Authorities:"); 18131 printedSomething = true; 18132 } 18133 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18134 pw.print(" "); pw.println(p.toString()); 18135 if (p.info != null && p.info.applicationInfo != null) { 18136 final String appInfo = p.info.applicationInfo.toString(); 18137 pw.print(" applicationInfo="); pw.println(appInfo); 18138 } 18139 } 18140 } 18141 18142 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18143 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18144 } 18145 18146 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18147 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18148 } 18149 18150 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18151 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18152 } 18153 18154 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18155 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18156 } 18157 18158 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18159 // XXX should handle packageName != null by dumping only install data that 18160 // the given package is involved with. 18161 if (dumpState.onTitlePrinted()) pw.println(); 18162 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18163 } 18164 18165 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18166 // XXX should handle packageName != null by dumping only install data that 18167 // the given package is involved with. 18168 if (dumpState.onTitlePrinted()) pw.println(); 18169 18170 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18171 ipw.println(); 18172 ipw.println("Frozen packages:"); 18173 ipw.increaseIndent(); 18174 if (mFrozenPackages.size() == 0) { 18175 ipw.println("(none)"); 18176 } else { 18177 for (int i = 0; i < mFrozenPackages.size(); i++) { 18178 ipw.println(mFrozenPackages.valueAt(i)); 18179 } 18180 } 18181 ipw.decreaseIndent(); 18182 } 18183 18184 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18185 if (dumpState.onTitlePrinted()) pw.println(); 18186 mSettings.dumpReadMessagesLPr(pw, dumpState); 18187 18188 pw.println(); 18189 pw.println("Package warning messages:"); 18190 BufferedReader in = null; 18191 String line = null; 18192 try { 18193 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18194 while ((line = in.readLine()) != null) { 18195 if (line.contains("ignored: updated version")) continue; 18196 pw.println(line); 18197 } 18198 } catch (IOException ignored) { 18199 } finally { 18200 IoUtils.closeQuietly(in); 18201 } 18202 } 18203 18204 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18205 BufferedReader in = null; 18206 String line = null; 18207 try { 18208 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18209 while ((line = in.readLine()) != null) { 18210 if (line.contains("ignored: updated version")) continue; 18211 pw.print("msg,"); 18212 pw.println(line); 18213 } 18214 } catch (IOException ignored) { 18215 } finally { 18216 IoUtils.closeQuietly(in); 18217 } 18218 } 18219 } 18220 } 18221 18222 private String dumpDomainString(String packageName) { 18223 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18224 .getList(); 18225 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18226 18227 ArraySet<String> result = new ArraySet<>(); 18228 if (iviList.size() > 0) { 18229 for (IntentFilterVerificationInfo ivi : iviList) { 18230 for (String host : ivi.getDomains()) { 18231 result.add(host); 18232 } 18233 } 18234 } 18235 if (filters != null && filters.size() > 0) { 18236 for (IntentFilter filter : filters) { 18237 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18238 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18239 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18240 result.addAll(filter.getHostsList()); 18241 } 18242 } 18243 } 18244 18245 StringBuilder sb = new StringBuilder(result.size() * 16); 18246 for (String domain : result) { 18247 if (sb.length() > 0) sb.append(" "); 18248 sb.append(domain); 18249 } 18250 return sb.toString(); 18251 } 18252 18253 // ------- apps on sdcard specific code ------- 18254 static final boolean DEBUG_SD_INSTALL = false; 18255 18256 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18257 18258 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18259 18260 private boolean mMediaMounted = false; 18261 18262 static String getEncryptKey() { 18263 try { 18264 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18265 SD_ENCRYPTION_KEYSTORE_NAME); 18266 if (sdEncKey == null) { 18267 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18268 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18269 if (sdEncKey == null) { 18270 Slog.e(TAG, "Failed to create encryption keys"); 18271 return null; 18272 } 18273 } 18274 return sdEncKey; 18275 } catch (NoSuchAlgorithmException nsae) { 18276 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18277 return null; 18278 } catch (IOException ioe) { 18279 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18280 return null; 18281 } 18282 } 18283 18284 /* 18285 * Update media status on PackageManager. 18286 */ 18287 @Override 18288 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18289 int callingUid = Binder.getCallingUid(); 18290 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18291 throw new SecurityException("Media status can only be updated by the system"); 18292 } 18293 // reader; this apparently protects mMediaMounted, but should probably 18294 // be a different lock in that case. 18295 synchronized (mPackages) { 18296 Log.i(TAG, "Updating external media status from " 18297 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18298 + (mediaStatus ? "mounted" : "unmounted")); 18299 if (DEBUG_SD_INSTALL) 18300 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18301 + ", mMediaMounted=" + mMediaMounted); 18302 if (mediaStatus == mMediaMounted) { 18303 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18304 : 0, -1); 18305 mHandler.sendMessage(msg); 18306 return; 18307 } 18308 mMediaMounted = mediaStatus; 18309 } 18310 // Queue up an async operation since the package installation may take a 18311 // little while. 18312 mHandler.post(new Runnable() { 18313 public void run() { 18314 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18315 } 18316 }); 18317 } 18318 18319 /** 18320 * Called by MountService when the initial ASECs to scan are available. 18321 * Should block until all the ASEC containers are finished being scanned. 18322 */ 18323 public void scanAvailableAsecs() { 18324 updateExternalMediaStatusInner(true, false, false); 18325 } 18326 18327 /* 18328 * Collect information of applications on external media, map them against 18329 * existing containers and update information based on current mount status. 18330 * Please note that we always have to report status if reportStatus has been 18331 * set to true especially when unloading packages. 18332 */ 18333 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18334 boolean externalStorage) { 18335 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18336 int[] uidArr = EmptyArray.INT; 18337 18338 final String[] list = PackageHelper.getSecureContainerList(); 18339 if (ArrayUtils.isEmpty(list)) { 18340 Log.i(TAG, "No secure containers found"); 18341 } else { 18342 // Process list of secure containers and categorize them 18343 // as active or stale based on their package internal state. 18344 18345 // reader 18346 synchronized (mPackages) { 18347 for (String cid : list) { 18348 // Leave stages untouched for now; installer service owns them 18349 if (PackageInstallerService.isStageName(cid)) continue; 18350 18351 if (DEBUG_SD_INSTALL) 18352 Log.i(TAG, "Processing container " + cid); 18353 String pkgName = getAsecPackageName(cid); 18354 if (pkgName == null) { 18355 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18356 continue; 18357 } 18358 if (DEBUG_SD_INSTALL) 18359 Log.i(TAG, "Looking for pkg : " + pkgName); 18360 18361 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18362 if (ps == null) { 18363 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18364 continue; 18365 } 18366 18367 /* 18368 * Skip packages that are not external if we're unmounting 18369 * external storage. 18370 */ 18371 if (externalStorage && !isMounted && !isExternal(ps)) { 18372 continue; 18373 } 18374 18375 final AsecInstallArgs args = new AsecInstallArgs(cid, 18376 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18377 // The package status is changed only if the code path 18378 // matches between settings and the container id. 18379 if (ps.codePathString != null 18380 && ps.codePathString.startsWith(args.getCodePath())) { 18381 if (DEBUG_SD_INSTALL) { 18382 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18383 + " at code path: " + ps.codePathString); 18384 } 18385 18386 // We do have a valid package installed on sdcard 18387 processCids.put(args, ps.codePathString); 18388 final int uid = ps.appId; 18389 if (uid != -1) { 18390 uidArr = ArrayUtils.appendInt(uidArr, uid); 18391 } 18392 } else { 18393 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18394 + ps.codePathString); 18395 } 18396 } 18397 } 18398 18399 Arrays.sort(uidArr); 18400 } 18401 18402 // Process packages with valid entries. 18403 if (isMounted) { 18404 if (DEBUG_SD_INSTALL) 18405 Log.i(TAG, "Loading packages"); 18406 loadMediaPackages(processCids, uidArr, externalStorage); 18407 startCleaningPackages(); 18408 mInstallerService.onSecureContainersAvailable(); 18409 } else { 18410 if (DEBUG_SD_INSTALL) 18411 Log.i(TAG, "Unloading packages"); 18412 unloadMediaPackages(processCids, uidArr, reportStatus); 18413 } 18414 } 18415 18416 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18417 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18418 final int size = infos.size(); 18419 final String[] packageNames = new String[size]; 18420 final int[] packageUids = new int[size]; 18421 for (int i = 0; i < size; i++) { 18422 final ApplicationInfo info = infos.get(i); 18423 packageNames[i] = info.packageName; 18424 packageUids[i] = info.uid; 18425 } 18426 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18427 finishedReceiver); 18428 } 18429 18430 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18431 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18432 sendResourcesChangedBroadcast(mediaStatus, replacing, 18433 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18434 } 18435 18436 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18437 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18438 int size = pkgList.length; 18439 if (size > 0) { 18440 // Send broadcasts here 18441 Bundle extras = new Bundle(); 18442 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18443 if (uidArr != null) { 18444 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18445 } 18446 if (replacing) { 18447 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18448 } 18449 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18450 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18451 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18452 } 18453 } 18454 18455 /* 18456 * Look at potentially valid container ids from processCids If package 18457 * information doesn't match the one on record or package scanning fails, 18458 * the cid is added to list of removeCids. We currently don't delete stale 18459 * containers. 18460 */ 18461 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18462 boolean externalStorage) { 18463 ArrayList<String> pkgList = new ArrayList<String>(); 18464 Set<AsecInstallArgs> keys = processCids.keySet(); 18465 18466 for (AsecInstallArgs args : keys) { 18467 String codePath = processCids.get(args); 18468 if (DEBUG_SD_INSTALL) 18469 Log.i(TAG, "Loading container : " + args.cid); 18470 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18471 try { 18472 // Make sure there are no container errors first. 18473 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18474 Slog.e(TAG, "Failed to mount cid : " + args.cid 18475 + " when installing from sdcard"); 18476 continue; 18477 } 18478 // Check code path here. 18479 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18480 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18481 + " does not match one in settings " + codePath); 18482 continue; 18483 } 18484 // Parse package 18485 int parseFlags = mDefParseFlags; 18486 if (args.isExternalAsec()) { 18487 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18488 } 18489 if (args.isFwdLocked()) { 18490 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18491 } 18492 18493 synchronized (mInstallLock) { 18494 PackageParser.Package pkg = null; 18495 try { 18496 // Sadly we don't know the package name yet to freeze it 18497 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18498 SCAN_IGNORE_FROZEN, 0, null); 18499 } catch (PackageManagerException e) { 18500 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18501 } 18502 // Scan the package 18503 if (pkg != null) { 18504 /* 18505 * TODO why is the lock being held? doPostInstall is 18506 * called in other places without the lock. This needs 18507 * to be straightened out. 18508 */ 18509 // writer 18510 synchronized (mPackages) { 18511 retCode = PackageManager.INSTALL_SUCCEEDED; 18512 pkgList.add(pkg.packageName); 18513 // Post process args 18514 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18515 pkg.applicationInfo.uid); 18516 } 18517 } else { 18518 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18519 } 18520 } 18521 18522 } finally { 18523 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18524 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18525 } 18526 } 18527 } 18528 // writer 18529 synchronized (mPackages) { 18530 // If the platform SDK has changed since the last time we booted, 18531 // we need to re-grant app permission to catch any new ones that 18532 // appear. This is really a hack, and means that apps can in some 18533 // cases get permissions that the user didn't initially explicitly 18534 // allow... it would be nice to have some better way to handle 18535 // this situation. 18536 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18537 : mSettings.getInternalVersion(); 18538 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18539 : StorageManager.UUID_PRIVATE_INTERNAL; 18540 18541 int updateFlags = UPDATE_PERMISSIONS_ALL; 18542 if (ver.sdkVersion != mSdkVersion) { 18543 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18544 + mSdkVersion + "; regranting permissions for external"); 18545 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18546 } 18547 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18548 18549 // Yay, everything is now upgraded 18550 ver.forceCurrent(); 18551 18552 // can downgrade to reader 18553 // Persist settings 18554 mSettings.writeLPr(); 18555 } 18556 // Send a broadcast to let everyone know we are done processing 18557 if (pkgList.size() > 0) { 18558 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18559 } 18560 } 18561 18562 /* 18563 * Utility method to unload a list of specified containers 18564 */ 18565 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18566 // Just unmount all valid containers. 18567 for (AsecInstallArgs arg : cidArgs) { 18568 synchronized (mInstallLock) { 18569 arg.doPostDeleteLI(false); 18570 } 18571 } 18572 } 18573 18574 /* 18575 * Unload packages mounted on external media. This involves deleting package 18576 * data from internal structures, sending broadcasts about disabled packages, 18577 * gc'ing to free up references, unmounting all secure containers 18578 * corresponding to packages on external media, and posting a 18579 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18580 * that we always have to post this message if status has been requested no 18581 * matter what. 18582 */ 18583 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18584 final boolean reportStatus) { 18585 if (DEBUG_SD_INSTALL) 18586 Log.i(TAG, "unloading media packages"); 18587 ArrayList<String> pkgList = new ArrayList<String>(); 18588 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18589 final Set<AsecInstallArgs> keys = processCids.keySet(); 18590 for (AsecInstallArgs args : keys) { 18591 String pkgName = args.getPackageName(); 18592 if (DEBUG_SD_INSTALL) 18593 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18594 // Delete package internally 18595 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18596 synchronized (mInstallLock) { 18597 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18598 final boolean res; 18599 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18600 "unloadMediaPackages")) { 18601 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18602 null); 18603 } 18604 if (res) { 18605 pkgList.add(pkgName); 18606 } else { 18607 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18608 failedList.add(args); 18609 } 18610 } 18611 } 18612 18613 // reader 18614 synchronized (mPackages) { 18615 // We didn't update the settings after removing each package; 18616 // write them now for all packages. 18617 mSettings.writeLPr(); 18618 } 18619 18620 // We have to absolutely send UPDATED_MEDIA_STATUS only 18621 // after confirming that all the receivers processed the ordered 18622 // broadcast when packages get disabled, force a gc to clean things up. 18623 // and unload all the containers. 18624 if (pkgList.size() > 0) { 18625 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18626 new IIntentReceiver.Stub() { 18627 public void performReceive(Intent intent, int resultCode, String data, 18628 Bundle extras, boolean ordered, boolean sticky, 18629 int sendingUser) throws RemoteException { 18630 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18631 reportStatus ? 1 : 0, 1, keys); 18632 mHandler.sendMessage(msg); 18633 } 18634 }); 18635 } else { 18636 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18637 keys); 18638 mHandler.sendMessage(msg); 18639 } 18640 } 18641 18642 private void loadPrivatePackages(final VolumeInfo vol) { 18643 mHandler.post(new Runnable() { 18644 @Override 18645 public void run() { 18646 loadPrivatePackagesInner(vol); 18647 } 18648 }); 18649 } 18650 18651 private void loadPrivatePackagesInner(VolumeInfo vol) { 18652 final String volumeUuid = vol.fsUuid; 18653 if (TextUtils.isEmpty(volumeUuid)) { 18654 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18655 return; 18656 } 18657 18658 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18659 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18660 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18661 18662 final VersionInfo ver; 18663 final List<PackageSetting> packages; 18664 synchronized (mPackages) { 18665 ver = mSettings.findOrCreateVersion(volumeUuid); 18666 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18667 } 18668 18669 for (PackageSetting ps : packages) { 18670 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18671 synchronized (mInstallLock) { 18672 final PackageParser.Package pkg; 18673 try { 18674 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18675 loaded.add(pkg.applicationInfo); 18676 18677 } catch (PackageManagerException e) { 18678 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18679 } 18680 18681 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18682 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18683 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18684 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18685 } 18686 } 18687 } 18688 18689 // Reconcile app data for all started/unlocked users 18690 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18691 final UserManager um = mContext.getSystemService(UserManager.class); 18692 for (UserInfo user : um.getUsers()) { 18693 final int flags; 18694 if (um.isUserUnlocked(user.id)) { 18695 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18696 } else if (um.isUserRunning(user.id)) { 18697 flags = StorageManager.FLAG_STORAGE_DE; 18698 } else { 18699 continue; 18700 } 18701 18702 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18703 synchronized (mInstallLock) { 18704 reconcileAppsDataLI(volumeUuid, user.id, flags); 18705 } 18706 } 18707 18708 synchronized (mPackages) { 18709 int updateFlags = UPDATE_PERMISSIONS_ALL; 18710 if (ver.sdkVersion != mSdkVersion) { 18711 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18712 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18713 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18714 } 18715 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18716 18717 // Yay, everything is now upgraded 18718 ver.forceCurrent(); 18719 18720 mSettings.writeLPr(); 18721 } 18722 18723 for (PackageFreezer freezer : freezers) { 18724 freezer.close(); 18725 } 18726 18727 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18728 sendResourcesChangedBroadcast(true, false, loaded, null); 18729 } 18730 18731 private void unloadPrivatePackages(final VolumeInfo vol) { 18732 mHandler.post(new Runnable() { 18733 @Override 18734 public void run() { 18735 unloadPrivatePackagesInner(vol); 18736 } 18737 }); 18738 } 18739 18740 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18741 final String volumeUuid = vol.fsUuid; 18742 if (TextUtils.isEmpty(volumeUuid)) { 18743 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18744 return; 18745 } 18746 18747 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18748 synchronized (mInstallLock) { 18749 synchronized (mPackages) { 18750 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18751 for (PackageSetting ps : packages) { 18752 if (ps.pkg == null) continue; 18753 18754 final ApplicationInfo info = ps.pkg.applicationInfo; 18755 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18756 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18757 18758 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18759 "unloadPrivatePackagesInner")) { 18760 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18761 false, null)) { 18762 unloaded.add(info); 18763 } else { 18764 Slog.w(TAG, "Failed to unload " + ps.codePath); 18765 } 18766 } 18767 } 18768 18769 mSettings.writeLPr(); 18770 } 18771 } 18772 18773 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18774 sendResourcesChangedBroadcast(false, false, unloaded, null); 18775 } 18776 18777 /** 18778 * Prepare storage areas for given user on all mounted devices. 18779 */ 18780 void prepareUserData(int userId, int userSerial, int flags) { 18781 synchronized (mInstallLock) { 18782 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18783 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18784 final String volumeUuid = vol.getFsUuid(); 18785 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18786 } 18787 } 18788 } 18789 18790 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18791 boolean allowRecover) { 18792 // Prepare storage and verify that serial numbers are consistent; if 18793 // there's a mismatch we need to destroy to avoid leaking data 18794 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18795 try { 18796 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18797 18798 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18799 UserManagerService.enforceSerialNumber( 18800 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18801 } 18802 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18803 UserManagerService.enforceSerialNumber( 18804 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18805 } 18806 18807 synchronized (mInstallLock) { 18808 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18809 } 18810 } catch (Exception e) { 18811 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18812 + " because we failed to prepare: " + e); 18813 destroyUserDataLI(volumeUuid, userId, flags); 18814 18815 if (allowRecover) { 18816 // Try one last time; if we fail again we're really in trouble 18817 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18818 } 18819 } 18820 } 18821 18822 /** 18823 * Destroy storage areas for given user on all mounted devices. 18824 */ 18825 void destroyUserData(int userId, int flags) { 18826 synchronized (mInstallLock) { 18827 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18828 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18829 final String volumeUuid = vol.getFsUuid(); 18830 destroyUserDataLI(volumeUuid, userId, flags); 18831 } 18832 } 18833 } 18834 18835 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18836 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18837 try { 18838 // Clean up app data, profile data, and media data 18839 mInstaller.destroyUserData(volumeUuid, userId, flags); 18840 18841 // Clean up system data 18842 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18843 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18844 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18845 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18846 } 18847 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18848 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18849 } 18850 } 18851 18852 // Data with special labels is now gone, so finish the job 18853 storage.destroyUserStorage(volumeUuid, userId, flags); 18854 18855 } catch (Exception e) { 18856 logCriticalInfo(Log.WARN, 18857 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18858 } 18859 } 18860 18861 /** 18862 * Examine all users present on given mounted volume, and destroy data 18863 * belonging to users that are no longer valid, or whose user ID has been 18864 * recycled. 18865 */ 18866 private void reconcileUsers(String volumeUuid) { 18867 final List<File> files = new ArrayList<>(); 18868 Collections.addAll(files, FileUtils 18869 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18870 Collections.addAll(files, FileUtils 18871 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18872 for (File file : files) { 18873 if (!file.isDirectory()) continue; 18874 18875 final int userId; 18876 final UserInfo info; 18877 try { 18878 userId = Integer.parseInt(file.getName()); 18879 info = sUserManager.getUserInfo(userId); 18880 } catch (NumberFormatException e) { 18881 Slog.w(TAG, "Invalid user directory " + file); 18882 continue; 18883 } 18884 18885 boolean destroyUser = false; 18886 if (info == null) { 18887 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18888 + " because no matching user was found"); 18889 destroyUser = true; 18890 } else if (!mOnlyCore) { 18891 try { 18892 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18893 } catch (IOException e) { 18894 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18895 + " because we failed to enforce serial number: " + e); 18896 destroyUser = true; 18897 } 18898 } 18899 18900 if (destroyUser) { 18901 synchronized (mInstallLock) { 18902 destroyUserDataLI(volumeUuid, userId, 18903 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18904 } 18905 } 18906 } 18907 } 18908 18909 private void assertPackageKnown(String volumeUuid, String packageName) 18910 throws PackageManagerException { 18911 synchronized (mPackages) { 18912 final PackageSetting ps = mSettings.mPackages.get(packageName); 18913 if (ps == null) { 18914 throw new PackageManagerException("Package " + packageName + " is unknown"); 18915 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18916 throw new PackageManagerException( 18917 "Package " + packageName + " found on unknown volume " + volumeUuid 18918 + "; expected volume " + ps.volumeUuid); 18919 } 18920 } 18921 } 18922 18923 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18924 throws PackageManagerException { 18925 synchronized (mPackages) { 18926 final PackageSetting ps = mSettings.mPackages.get(packageName); 18927 if (ps == null) { 18928 throw new PackageManagerException("Package " + packageName + " is unknown"); 18929 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18930 throw new PackageManagerException( 18931 "Package " + packageName + " found on unknown volume " + volumeUuid 18932 + "; expected volume " + ps.volumeUuid); 18933 } else if (!ps.getInstalled(userId)) { 18934 throw new PackageManagerException( 18935 "Package " + packageName + " not installed for user " + userId); 18936 } 18937 } 18938 } 18939 18940 /** 18941 * Examine all apps present on given mounted volume, and destroy apps that 18942 * aren't expected, either due to uninstallation or reinstallation on 18943 * another volume. 18944 */ 18945 private void reconcileApps(String volumeUuid) { 18946 final File[] files = FileUtils 18947 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18948 for (File file : files) { 18949 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18950 && !PackageInstallerService.isStageName(file.getName()); 18951 if (!isPackage) { 18952 // Ignore entries which are not packages 18953 continue; 18954 } 18955 18956 try { 18957 final PackageLite pkg = PackageParser.parsePackageLite(file, 18958 PackageParser.PARSE_MUST_BE_APK); 18959 assertPackageKnown(volumeUuid, pkg.packageName); 18960 18961 } catch (PackageParserException | PackageManagerException e) { 18962 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18963 synchronized (mInstallLock) { 18964 removeCodePathLI(file); 18965 } 18966 } 18967 } 18968 } 18969 18970 /** 18971 * Reconcile all app data for the given user. 18972 * <p> 18973 * Verifies that directories exist and that ownership and labeling is 18974 * correct for all installed apps on all mounted volumes. 18975 */ 18976 void reconcileAppsData(int userId, int flags) { 18977 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18978 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18979 final String volumeUuid = vol.getFsUuid(); 18980 synchronized (mInstallLock) { 18981 reconcileAppsDataLI(volumeUuid, userId, flags); 18982 } 18983 } 18984 } 18985 18986 /** 18987 * Reconcile all app data on given mounted volume. 18988 * <p> 18989 * Destroys app data that isn't expected, either due to uninstallation or 18990 * reinstallation on another volume. 18991 * <p> 18992 * Verifies that directories exist and that ownership and labeling is 18993 * correct for all installed apps. 18994 */ 18995 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18996 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18997 + Integer.toHexString(flags)); 18998 18999 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19000 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19001 19002 boolean restoreconNeeded = false; 19003 19004 // First look for stale data that doesn't belong, and check if things 19005 // have changed since we did our last restorecon 19006 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19007 if (!isUserKeyUnlocked(userId)) { 19008 throw new RuntimeException( 19009 "Yikes, someone asked us to reconcile CE storage while " + userId 19010 + " was still locked; this would have caused massive data loss!"); 19011 } 19012 19013 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19014 19015 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19016 for (File file : files) { 19017 final String packageName = file.getName(); 19018 try { 19019 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19020 } catch (PackageManagerException e) { 19021 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19022 try { 19023 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19024 StorageManager.FLAG_STORAGE_CE, 0); 19025 } catch (InstallerException e2) { 19026 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19027 } 19028 } 19029 } 19030 } 19031 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19032 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19033 19034 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19035 for (File file : files) { 19036 final String packageName = file.getName(); 19037 try { 19038 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19039 } catch (PackageManagerException e) { 19040 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19041 try { 19042 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19043 StorageManager.FLAG_STORAGE_DE, 0); 19044 } catch (InstallerException e2) { 19045 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19046 } 19047 } 19048 } 19049 } 19050 19051 // Ensure that data directories are ready to roll for all packages 19052 // installed for this volume and user 19053 final List<PackageSetting> packages; 19054 synchronized (mPackages) { 19055 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19056 } 19057 int preparedCount = 0; 19058 for (PackageSetting ps : packages) { 19059 final String packageName = ps.name; 19060 if (ps.pkg == null) { 19061 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19062 // TODO: might be due to legacy ASEC apps; we should circle back 19063 // and reconcile again once they're scanned 19064 continue; 19065 } 19066 19067 if (ps.getInstalled(userId)) { 19068 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19069 19070 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19071 // We may have just shuffled around app data directories, so 19072 // prepare them one more time 19073 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19074 } 19075 19076 preparedCount++; 19077 } 19078 } 19079 19080 if (restoreconNeeded) { 19081 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19082 SELinuxMMAC.setRestoreconDone(ceDir); 19083 } 19084 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19085 SELinuxMMAC.setRestoreconDone(deDir); 19086 } 19087 } 19088 19089 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19090 + " packages; restoreconNeeded was " + restoreconNeeded); 19091 } 19092 19093 /** 19094 * Prepare app data for the given app just after it was installed or 19095 * upgraded. This method carefully only touches users that it's installed 19096 * for, and it forces a restorecon to handle any seinfo changes. 19097 * <p> 19098 * Verifies that directories exist and that ownership and labeling is 19099 * correct for all installed apps. If there is an ownership mismatch, it 19100 * will try recovering system apps by wiping data; third-party app data is 19101 * left intact. 19102 * <p> 19103 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19104 */ 19105 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19106 final PackageSetting ps; 19107 synchronized (mPackages) { 19108 ps = mSettings.mPackages.get(pkg.packageName); 19109 mSettings.writeKernelMappingLPr(ps); 19110 } 19111 19112 final UserManager um = mContext.getSystemService(UserManager.class); 19113 for (UserInfo user : um.getUsers()) { 19114 final int flags; 19115 if (um.isUserUnlocked(user.id)) { 19116 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19117 } else if (um.isUserRunning(user.id)) { 19118 flags = StorageManager.FLAG_STORAGE_DE; 19119 } else { 19120 continue; 19121 } 19122 19123 if (ps.getInstalled(user.id)) { 19124 // Whenever an app changes, force a restorecon of its data 19125 // TODO: when user data is locked, mark that we're still dirty 19126 prepareAppDataLIF(pkg, user.id, flags, true); 19127 } 19128 } 19129 } 19130 19131 /** 19132 * Prepare app data for the given app. 19133 * <p> 19134 * Verifies that directories exist and that ownership and labeling is 19135 * correct for all installed apps. If there is an ownership mismatch, this 19136 * will try recovering system apps by wiping data; third-party app data is 19137 * left intact. 19138 */ 19139 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19140 boolean restoreconNeeded) { 19141 if (pkg == null) { 19142 Slog.wtf(TAG, "Package was null!", new Throwable()); 19143 return; 19144 } 19145 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19146 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19147 for (int i = 0; i < childCount; i++) { 19148 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19149 } 19150 } 19151 19152 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19153 boolean restoreconNeeded) { 19154 if (DEBUG_APP_DATA) { 19155 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19156 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19157 } 19158 19159 final String volumeUuid = pkg.volumeUuid; 19160 final String packageName = pkg.packageName; 19161 final ApplicationInfo app = pkg.applicationInfo; 19162 final int appId = UserHandle.getAppId(app.uid); 19163 19164 Preconditions.checkNotNull(app.seinfo); 19165 19166 try { 19167 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19168 appId, app.seinfo, app.targetSdkVersion); 19169 } catch (InstallerException e) { 19170 if (app.isSystemApp()) { 19171 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19172 + ", but trying to recover: " + e); 19173 destroyAppDataLeafLIF(pkg, userId, flags); 19174 try { 19175 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19176 appId, app.seinfo, app.targetSdkVersion); 19177 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19178 } catch (InstallerException e2) { 19179 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19180 } 19181 } else { 19182 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19183 } 19184 } 19185 19186 if (restoreconNeeded) { 19187 try { 19188 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19189 app.seinfo); 19190 } catch (InstallerException e) { 19191 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19192 } 19193 } 19194 19195 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19196 try { 19197 // CE storage is unlocked right now, so read out the inode and 19198 // remember for use later when it's locked 19199 // TODO: mark this structure as dirty so we persist it! 19200 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19201 StorageManager.FLAG_STORAGE_CE); 19202 synchronized (mPackages) { 19203 final PackageSetting ps = mSettings.mPackages.get(packageName); 19204 if (ps != null) { 19205 ps.setCeDataInode(ceDataInode, userId); 19206 } 19207 } 19208 } catch (InstallerException e) { 19209 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19210 } 19211 } 19212 19213 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19214 } 19215 19216 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19217 if (pkg == null) { 19218 Slog.wtf(TAG, "Package was null!", new Throwable()); 19219 return; 19220 } 19221 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19222 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19223 for (int i = 0; i < childCount; i++) { 19224 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19225 } 19226 } 19227 19228 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19229 final String volumeUuid = pkg.volumeUuid; 19230 final String packageName = pkg.packageName; 19231 final ApplicationInfo app = pkg.applicationInfo; 19232 19233 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19234 // Create a native library symlink only if we have native libraries 19235 // and if the native libraries are 32 bit libraries. We do not provide 19236 // this symlink for 64 bit libraries. 19237 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19238 final String nativeLibPath = app.nativeLibraryDir; 19239 try { 19240 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19241 nativeLibPath, userId); 19242 } catch (InstallerException e) { 19243 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19244 } 19245 } 19246 } 19247 } 19248 19249 /** 19250 * For system apps on non-FBE devices, this method migrates any existing 19251 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19252 * requested by the app. 19253 */ 19254 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19255 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19256 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19257 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19258 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19259 try { 19260 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19261 storageTarget); 19262 } catch (InstallerException e) { 19263 logCriticalInfo(Log.WARN, 19264 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19265 } 19266 return true; 19267 } else { 19268 return false; 19269 } 19270 } 19271 19272 public PackageFreezer freezePackage(String packageName, String killReason) { 19273 return new PackageFreezer(packageName, killReason); 19274 } 19275 19276 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19277 String killReason) { 19278 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19279 return new PackageFreezer(); 19280 } else { 19281 return freezePackage(packageName, killReason); 19282 } 19283 } 19284 19285 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19286 String killReason) { 19287 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19288 return new PackageFreezer(); 19289 } else { 19290 return freezePackage(packageName, killReason); 19291 } 19292 } 19293 19294 /** 19295 * Class that freezes and kills the given package upon creation, and 19296 * unfreezes it upon closing. This is typically used when doing surgery on 19297 * app code/data to prevent the app from running while you're working. 19298 */ 19299 private class PackageFreezer implements AutoCloseable { 19300 private final String mPackageName; 19301 private final PackageFreezer[] mChildren; 19302 19303 private final boolean mWeFroze; 19304 19305 private final AtomicBoolean mClosed = new AtomicBoolean(); 19306 private final CloseGuard mCloseGuard = CloseGuard.get(); 19307 19308 /** 19309 * Create and return a stub freezer that doesn't actually do anything, 19310 * typically used when someone requested 19311 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19312 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19313 */ 19314 public PackageFreezer() { 19315 mPackageName = null; 19316 mChildren = null; 19317 mWeFroze = false; 19318 mCloseGuard.open("close"); 19319 } 19320 19321 public PackageFreezer(String packageName, String killReason) { 19322 synchronized (mPackages) { 19323 mPackageName = packageName; 19324 mWeFroze = mFrozenPackages.add(mPackageName); 19325 19326 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19327 if (ps != null) { 19328 killApplication(ps.name, ps.appId, killReason); 19329 } 19330 19331 final PackageParser.Package p = mPackages.get(packageName); 19332 if (p != null && p.childPackages != null) { 19333 final int N = p.childPackages.size(); 19334 mChildren = new PackageFreezer[N]; 19335 for (int i = 0; i < N; i++) { 19336 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19337 killReason); 19338 } 19339 } else { 19340 mChildren = null; 19341 } 19342 } 19343 mCloseGuard.open("close"); 19344 } 19345 19346 @Override 19347 protected void finalize() throws Throwable { 19348 try { 19349 mCloseGuard.warnIfOpen(); 19350 close(); 19351 } finally { 19352 super.finalize(); 19353 } 19354 } 19355 19356 @Override 19357 public void close() { 19358 mCloseGuard.close(); 19359 if (mClosed.compareAndSet(false, true)) { 19360 synchronized (mPackages) { 19361 if (mWeFroze) { 19362 mFrozenPackages.remove(mPackageName); 19363 } 19364 19365 if (mChildren != null) { 19366 for (PackageFreezer freezer : mChildren) { 19367 freezer.close(); 19368 } 19369 } 19370 } 19371 } 19372 } 19373 } 19374 19375 /** 19376 * Verify that given package is currently frozen. 19377 */ 19378 private void checkPackageFrozen(String packageName) { 19379 synchronized (mPackages) { 19380 if (!mFrozenPackages.contains(packageName)) { 19381 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19382 } 19383 } 19384 } 19385 19386 @Override 19387 public int movePackage(final String packageName, final String volumeUuid) { 19388 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19389 19390 final int moveId = mNextMoveId.getAndIncrement(); 19391 mHandler.post(new Runnable() { 19392 @Override 19393 public void run() { 19394 try { 19395 movePackageInternal(packageName, volumeUuid, moveId); 19396 } catch (PackageManagerException e) { 19397 Slog.w(TAG, "Failed to move " + packageName, e); 19398 mMoveCallbacks.notifyStatusChanged(moveId, 19399 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19400 } 19401 } 19402 }); 19403 return moveId; 19404 } 19405 19406 private void movePackageInternal(final String packageName, final String volumeUuid, 19407 final int moveId) throws PackageManagerException { 19408 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19409 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19410 final PackageManager pm = mContext.getPackageManager(); 19411 19412 final boolean currentAsec; 19413 final String currentVolumeUuid; 19414 final File codeFile; 19415 final String installerPackageName; 19416 final String packageAbiOverride; 19417 final int appId; 19418 final String seinfo; 19419 final String label; 19420 final int targetSdkVersion; 19421 final PackageFreezer freezer; 19422 19423 // reader 19424 synchronized (mPackages) { 19425 final PackageParser.Package pkg = mPackages.get(packageName); 19426 final PackageSetting ps = mSettings.mPackages.get(packageName); 19427 if (pkg == null || ps == null) { 19428 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19429 } 19430 19431 if (pkg.applicationInfo.isSystemApp()) { 19432 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19433 "Cannot move system application"); 19434 } 19435 19436 if (pkg.applicationInfo.isExternalAsec()) { 19437 currentAsec = true; 19438 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19439 } else if (pkg.applicationInfo.isForwardLocked()) { 19440 currentAsec = true; 19441 currentVolumeUuid = "forward_locked"; 19442 } else { 19443 currentAsec = false; 19444 currentVolumeUuid = ps.volumeUuid; 19445 19446 final File probe = new File(pkg.codePath); 19447 final File probeOat = new File(probe, "oat"); 19448 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19449 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19450 "Move only supported for modern cluster style installs"); 19451 } 19452 } 19453 19454 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19455 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19456 "Package already moved to " + volumeUuid); 19457 } 19458 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19459 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19460 "Device admin cannot be moved"); 19461 } 19462 19463 if (mFrozenPackages.contains(packageName)) { 19464 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19465 "Failed to move already frozen package"); 19466 } 19467 19468 codeFile = new File(pkg.codePath); 19469 installerPackageName = ps.installerPackageName; 19470 packageAbiOverride = ps.cpuAbiOverrideString; 19471 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19472 seinfo = pkg.applicationInfo.seinfo; 19473 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19474 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19475 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19476 } 19477 19478 final Bundle extras = new Bundle(); 19479 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19480 extras.putString(Intent.EXTRA_TITLE, label); 19481 mMoveCallbacks.notifyCreated(moveId, extras); 19482 19483 int installFlags; 19484 final boolean moveCompleteApp; 19485 final File measurePath; 19486 19487 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19488 installFlags = INSTALL_INTERNAL; 19489 moveCompleteApp = !currentAsec; 19490 measurePath = Environment.getDataAppDirectory(volumeUuid); 19491 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19492 installFlags = INSTALL_EXTERNAL; 19493 moveCompleteApp = false; 19494 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19495 } else { 19496 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19497 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19498 || !volume.isMountedWritable()) { 19499 freezer.close(); 19500 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19501 "Move location not mounted private volume"); 19502 } 19503 19504 Preconditions.checkState(!currentAsec); 19505 19506 installFlags = INSTALL_INTERNAL; 19507 moveCompleteApp = true; 19508 measurePath = Environment.getDataAppDirectory(volumeUuid); 19509 } 19510 19511 final PackageStats stats = new PackageStats(null, -1); 19512 synchronized (mInstaller) { 19513 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19514 freezer.close(); 19515 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19516 "Failed to measure package size"); 19517 } 19518 } 19519 19520 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19521 + stats.dataSize); 19522 19523 final long startFreeBytes = measurePath.getFreeSpace(); 19524 final long sizeBytes; 19525 if (moveCompleteApp) { 19526 sizeBytes = stats.codeSize + stats.dataSize; 19527 } else { 19528 sizeBytes = stats.codeSize; 19529 } 19530 19531 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19532 freezer.close(); 19533 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19534 "Not enough free space to move"); 19535 } 19536 19537 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19538 19539 final CountDownLatch installedLatch = new CountDownLatch(1); 19540 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19541 @Override 19542 public void onUserActionRequired(Intent intent) throws RemoteException { 19543 throw new IllegalStateException(); 19544 } 19545 19546 @Override 19547 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19548 Bundle extras) throws RemoteException { 19549 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19550 + PackageManager.installStatusToString(returnCode, msg)); 19551 19552 installedLatch.countDown(); 19553 freezer.close(); 19554 19555 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19556 switch (status) { 19557 case PackageInstaller.STATUS_SUCCESS: 19558 mMoveCallbacks.notifyStatusChanged(moveId, 19559 PackageManager.MOVE_SUCCEEDED); 19560 break; 19561 case PackageInstaller.STATUS_FAILURE_STORAGE: 19562 mMoveCallbacks.notifyStatusChanged(moveId, 19563 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19564 break; 19565 default: 19566 mMoveCallbacks.notifyStatusChanged(moveId, 19567 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19568 break; 19569 } 19570 } 19571 }; 19572 19573 final MoveInfo move; 19574 if (moveCompleteApp) { 19575 // Kick off a thread to report progress estimates 19576 new Thread() { 19577 @Override 19578 public void run() { 19579 while (true) { 19580 try { 19581 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19582 break; 19583 } 19584 } catch (InterruptedException ignored) { 19585 } 19586 19587 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19588 final int progress = 10 + (int) MathUtils.constrain( 19589 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19590 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19591 } 19592 } 19593 }.start(); 19594 19595 final String dataAppName = codeFile.getName(); 19596 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19597 dataAppName, appId, seinfo, targetSdkVersion); 19598 } else { 19599 move = null; 19600 } 19601 19602 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19603 19604 final Message msg = mHandler.obtainMessage(INIT_COPY); 19605 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19606 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19607 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19608 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19609 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19610 msg.obj = params; 19611 19612 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19613 System.identityHashCode(msg.obj)); 19614 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19615 System.identityHashCode(msg.obj)); 19616 19617 mHandler.sendMessage(msg); 19618 } 19619 19620 @Override 19621 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19622 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19623 19624 final int realMoveId = mNextMoveId.getAndIncrement(); 19625 final Bundle extras = new Bundle(); 19626 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19627 mMoveCallbacks.notifyCreated(realMoveId, extras); 19628 19629 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19630 @Override 19631 public void onCreated(int moveId, Bundle extras) { 19632 // Ignored 19633 } 19634 19635 @Override 19636 public void onStatusChanged(int moveId, int status, long estMillis) { 19637 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19638 } 19639 }; 19640 19641 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19642 storage.setPrimaryStorageUuid(volumeUuid, callback); 19643 return realMoveId; 19644 } 19645 19646 @Override 19647 public int getMoveStatus(int moveId) { 19648 mContext.enforceCallingOrSelfPermission( 19649 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19650 return mMoveCallbacks.mLastStatus.get(moveId); 19651 } 19652 19653 @Override 19654 public void registerMoveCallback(IPackageMoveObserver callback) { 19655 mContext.enforceCallingOrSelfPermission( 19656 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19657 mMoveCallbacks.register(callback); 19658 } 19659 19660 @Override 19661 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19662 mContext.enforceCallingOrSelfPermission( 19663 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19664 mMoveCallbacks.unregister(callback); 19665 } 19666 19667 @Override 19668 public boolean setInstallLocation(int loc) { 19669 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19670 null); 19671 if (getInstallLocation() == loc) { 19672 return true; 19673 } 19674 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19675 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19676 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19677 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19678 return true; 19679 } 19680 return false; 19681 } 19682 19683 @Override 19684 public int getInstallLocation() { 19685 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19686 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19687 PackageHelper.APP_INSTALL_AUTO); 19688 } 19689 19690 /** Called by UserManagerService */ 19691 void cleanUpUser(UserManagerService userManager, int userHandle) { 19692 synchronized (mPackages) { 19693 mDirtyUsers.remove(userHandle); 19694 mUserNeedsBadging.delete(userHandle); 19695 mSettings.removeUserLPw(userHandle); 19696 mPendingBroadcasts.remove(userHandle); 19697 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19698 removeUnusedPackagesLPw(userManager, userHandle); 19699 } 19700 } 19701 19702 /** 19703 * We're removing userHandle and would like to remove any downloaded packages 19704 * that are no longer in use by any other user. 19705 * @param userHandle the user being removed 19706 */ 19707 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19708 final boolean DEBUG_CLEAN_APKS = false; 19709 int [] users = userManager.getUserIds(); 19710 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19711 while (psit.hasNext()) { 19712 PackageSetting ps = psit.next(); 19713 if (ps.pkg == null) { 19714 continue; 19715 } 19716 final String packageName = ps.pkg.packageName; 19717 // Skip over if system app 19718 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19719 continue; 19720 } 19721 if (DEBUG_CLEAN_APKS) { 19722 Slog.i(TAG, "Checking package " + packageName); 19723 } 19724 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19725 if (keep) { 19726 if (DEBUG_CLEAN_APKS) { 19727 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19728 } 19729 } else { 19730 for (int i = 0; i < users.length; i++) { 19731 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19732 keep = true; 19733 if (DEBUG_CLEAN_APKS) { 19734 Slog.i(TAG, " Keeping package " + packageName + " for user " 19735 + users[i]); 19736 } 19737 break; 19738 } 19739 } 19740 } 19741 if (!keep) { 19742 if (DEBUG_CLEAN_APKS) { 19743 Slog.i(TAG, " Removing package " + packageName); 19744 } 19745 mHandler.post(new Runnable() { 19746 public void run() { 19747 deletePackageX(packageName, userHandle, 0); 19748 } //end run 19749 }); 19750 } 19751 } 19752 } 19753 19754 /** Called by UserManagerService */ 19755 void createNewUser(int userHandle) { 19756 synchronized (mInstallLock) { 19757 mSettings.createNewUserLI(this, mInstaller, userHandle); 19758 } 19759 synchronized (mPackages) { 19760 applyFactoryDefaultBrowserLPw(userHandle); 19761 primeDomainVerificationsLPw(userHandle); 19762 } 19763 } 19764 19765 void newUserCreated(final int userHandle) { 19766 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19767 // If permission review for legacy apps is required, we represent 19768 // dagerous permissions for such apps as always granted runtime 19769 // permissions to keep per user flag state whether review is needed. 19770 // Hence, if a new user is added we have to propagate dangerous 19771 // permission grants for these legacy apps. 19772 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19773 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19774 | UPDATE_PERMISSIONS_REPLACE_ALL); 19775 } 19776 } 19777 19778 @Override 19779 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19780 mContext.enforceCallingOrSelfPermission( 19781 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19782 "Only package verification agents can read the verifier device identity"); 19783 19784 synchronized (mPackages) { 19785 return mSettings.getVerifierDeviceIdentityLPw(); 19786 } 19787 } 19788 19789 @Override 19790 public void setPermissionEnforced(String permission, boolean enforced) { 19791 // TODO: Now that we no longer change GID for storage, this should to away. 19792 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19793 "setPermissionEnforced"); 19794 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19795 synchronized (mPackages) { 19796 if (mSettings.mReadExternalStorageEnforced == null 19797 || mSettings.mReadExternalStorageEnforced != enforced) { 19798 mSettings.mReadExternalStorageEnforced = enforced; 19799 mSettings.writeLPr(); 19800 } 19801 } 19802 // kill any non-foreground processes so we restart them and 19803 // grant/revoke the GID. 19804 final IActivityManager am = ActivityManagerNative.getDefault(); 19805 if (am != null) { 19806 final long token = Binder.clearCallingIdentity(); 19807 try { 19808 am.killProcessesBelowForeground("setPermissionEnforcement"); 19809 } catch (RemoteException e) { 19810 } finally { 19811 Binder.restoreCallingIdentity(token); 19812 } 19813 } 19814 } else { 19815 throw new IllegalArgumentException("No selective enforcement for " + permission); 19816 } 19817 } 19818 19819 @Override 19820 @Deprecated 19821 public boolean isPermissionEnforced(String permission) { 19822 return true; 19823 } 19824 19825 @Override 19826 public boolean isStorageLow() { 19827 final long token = Binder.clearCallingIdentity(); 19828 try { 19829 final DeviceStorageMonitorInternal 19830 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19831 if (dsm != null) { 19832 return dsm.isMemoryLow(); 19833 } else { 19834 return false; 19835 } 19836 } finally { 19837 Binder.restoreCallingIdentity(token); 19838 } 19839 } 19840 19841 @Override 19842 public IPackageInstaller getPackageInstaller() { 19843 return mInstallerService; 19844 } 19845 19846 private boolean userNeedsBadging(int userId) { 19847 int index = mUserNeedsBadging.indexOfKey(userId); 19848 if (index < 0) { 19849 final UserInfo userInfo; 19850 final long token = Binder.clearCallingIdentity(); 19851 try { 19852 userInfo = sUserManager.getUserInfo(userId); 19853 } finally { 19854 Binder.restoreCallingIdentity(token); 19855 } 19856 final boolean b; 19857 if (userInfo != null && userInfo.isManagedProfile()) { 19858 b = true; 19859 } else { 19860 b = false; 19861 } 19862 mUserNeedsBadging.put(userId, b); 19863 return b; 19864 } 19865 return mUserNeedsBadging.valueAt(index); 19866 } 19867 19868 @Override 19869 public KeySet getKeySetByAlias(String packageName, String alias) { 19870 if (packageName == null || alias == null) { 19871 return null; 19872 } 19873 synchronized(mPackages) { 19874 final PackageParser.Package pkg = mPackages.get(packageName); 19875 if (pkg == null) { 19876 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19877 throw new IllegalArgumentException("Unknown package: " + packageName); 19878 } 19879 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19880 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19881 } 19882 } 19883 19884 @Override 19885 public KeySet getSigningKeySet(String packageName) { 19886 if (packageName == null) { 19887 return null; 19888 } 19889 synchronized(mPackages) { 19890 final PackageParser.Package pkg = mPackages.get(packageName); 19891 if (pkg == null) { 19892 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19893 throw new IllegalArgumentException("Unknown package: " + packageName); 19894 } 19895 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19896 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19897 throw new SecurityException("May not access signing KeySet of other apps."); 19898 } 19899 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19900 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19901 } 19902 } 19903 19904 @Override 19905 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19906 if (packageName == null || ks == null) { 19907 return false; 19908 } 19909 synchronized(mPackages) { 19910 final PackageParser.Package pkg = mPackages.get(packageName); 19911 if (pkg == null) { 19912 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19913 throw new IllegalArgumentException("Unknown package: " + packageName); 19914 } 19915 IBinder ksh = ks.getToken(); 19916 if (ksh instanceof KeySetHandle) { 19917 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19918 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19919 } 19920 return false; 19921 } 19922 } 19923 19924 @Override 19925 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19926 if (packageName == null || ks == null) { 19927 return false; 19928 } 19929 synchronized(mPackages) { 19930 final PackageParser.Package pkg = mPackages.get(packageName); 19931 if (pkg == null) { 19932 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19933 throw new IllegalArgumentException("Unknown package: " + packageName); 19934 } 19935 IBinder ksh = ks.getToken(); 19936 if (ksh instanceof KeySetHandle) { 19937 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19938 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19939 } 19940 return false; 19941 } 19942 } 19943 19944 private void deletePackageIfUnusedLPr(final String packageName) { 19945 PackageSetting ps = mSettings.mPackages.get(packageName); 19946 if (ps == null) { 19947 return; 19948 } 19949 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19950 // TODO Implement atomic delete if package is unused 19951 // It is currently possible that the package will be deleted even if it is installed 19952 // after this method returns. 19953 mHandler.post(new Runnable() { 19954 public void run() { 19955 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19956 } 19957 }); 19958 } 19959 } 19960 19961 /** 19962 * Check and throw if the given before/after packages would be considered a 19963 * downgrade. 19964 */ 19965 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19966 throws PackageManagerException { 19967 if (after.versionCode < before.mVersionCode) { 19968 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19969 "Update version code " + after.versionCode + " is older than current " 19970 + before.mVersionCode); 19971 } else if (after.versionCode == before.mVersionCode) { 19972 if (after.baseRevisionCode < before.baseRevisionCode) { 19973 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19974 "Update base revision code " + after.baseRevisionCode 19975 + " is older than current " + before.baseRevisionCode); 19976 } 19977 19978 if (!ArrayUtils.isEmpty(after.splitNames)) { 19979 for (int i = 0; i < after.splitNames.length; i++) { 19980 final String splitName = after.splitNames[i]; 19981 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19982 if (j != -1) { 19983 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19984 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19985 "Update split " + splitName + " revision code " 19986 + after.splitRevisionCodes[i] + " is older than current " 19987 + before.splitRevisionCodes[j]); 19988 } 19989 } 19990 } 19991 } 19992 } 19993 } 19994 19995 private static class MoveCallbacks extends Handler { 19996 private static final int MSG_CREATED = 1; 19997 private static final int MSG_STATUS_CHANGED = 2; 19998 19999 private final RemoteCallbackList<IPackageMoveObserver> 20000 mCallbacks = new RemoteCallbackList<>(); 20001 20002 private final SparseIntArray mLastStatus = new SparseIntArray(); 20003 20004 public MoveCallbacks(Looper looper) { 20005 super(looper); 20006 } 20007 20008 public void register(IPackageMoveObserver callback) { 20009 mCallbacks.register(callback); 20010 } 20011 20012 public void unregister(IPackageMoveObserver callback) { 20013 mCallbacks.unregister(callback); 20014 } 20015 20016 @Override 20017 public void handleMessage(Message msg) { 20018 final SomeArgs args = (SomeArgs) msg.obj; 20019 final int n = mCallbacks.beginBroadcast(); 20020 for (int i = 0; i < n; i++) { 20021 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20022 try { 20023 invokeCallback(callback, msg.what, args); 20024 } catch (RemoteException ignored) { 20025 } 20026 } 20027 mCallbacks.finishBroadcast(); 20028 args.recycle(); 20029 } 20030 20031 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20032 throws RemoteException { 20033 switch (what) { 20034 case MSG_CREATED: { 20035 callback.onCreated(args.argi1, (Bundle) args.arg2); 20036 break; 20037 } 20038 case MSG_STATUS_CHANGED: { 20039 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20040 break; 20041 } 20042 } 20043 } 20044 20045 private void notifyCreated(int moveId, Bundle extras) { 20046 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20047 20048 final SomeArgs args = SomeArgs.obtain(); 20049 args.argi1 = moveId; 20050 args.arg2 = extras; 20051 obtainMessage(MSG_CREATED, args).sendToTarget(); 20052 } 20053 20054 private void notifyStatusChanged(int moveId, int status) { 20055 notifyStatusChanged(moveId, status, -1); 20056 } 20057 20058 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20059 Slog.v(TAG, "Move " + moveId + " status " + status); 20060 20061 final SomeArgs args = SomeArgs.obtain(); 20062 args.argi1 = moveId; 20063 args.argi2 = status; 20064 args.arg3 = estMillis; 20065 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20066 20067 synchronized (mLastStatus) { 20068 mLastStatus.put(moveId, status); 20069 } 20070 } 20071 } 20072 20073 private final static class OnPermissionChangeListeners extends Handler { 20074 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20075 20076 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20077 new RemoteCallbackList<>(); 20078 20079 public OnPermissionChangeListeners(Looper looper) { 20080 super(looper); 20081 } 20082 20083 @Override 20084 public void handleMessage(Message msg) { 20085 switch (msg.what) { 20086 case MSG_ON_PERMISSIONS_CHANGED: { 20087 final int uid = msg.arg1; 20088 handleOnPermissionsChanged(uid); 20089 } break; 20090 } 20091 } 20092 20093 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20094 mPermissionListeners.register(listener); 20095 20096 } 20097 20098 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20099 mPermissionListeners.unregister(listener); 20100 } 20101 20102 public void onPermissionsChanged(int uid) { 20103 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20104 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20105 } 20106 } 20107 20108 private void handleOnPermissionsChanged(int uid) { 20109 final int count = mPermissionListeners.beginBroadcast(); 20110 try { 20111 for (int i = 0; i < count; i++) { 20112 IOnPermissionsChangeListener callback = mPermissionListeners 20113 .getBroadcastItem(i); 20114 try { 20115 callback.onPermissionsChanged(uid); 20116 } catch (RemoteException e) { 20117 Log.e(TAG, "Permission listener is dead", e); 20118 } 20119 } 20120 } finally { 20121 mPermissionListeners.finishBroadcast(); 20122 } 20123 } 20124 } 20125 20126 private class PackageManagerInternalImpl extends PackageManagerInternal { 20127 @Override 20128 public void setLocationPackagesProvider(PackagesProvider provider) { 20129 synchronized (mPackages) { 20130 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20131 } 20132 } 20133 20134 @Override 20135 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20136 synchronized (mPackages) { 20137 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20138 } 20139 } 20140 20141 @Override 20142 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20143 synchronized (mPackages) { 20144 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20145 } 20146 } 20147 20148 @Override 20149 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20150 synchronized (mPackages) { 20151 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20152 } 20153 } 20154 20155 @Override 20156 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20157 synchronized (mPackages) { 20158 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20159 } 20160 } 20161 20162 @Override 20163 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20164 synchronized (mPackages) { 20165 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20166 } 20167 } 20168 20169 @Override 20170 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20171 synchronized (mPackages) { 20172 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20173 packageName, userId); 20174 } 20175 } 20176 20177 @Override 20178 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20179 synchronized (mPackages) { 20180 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20181 packageName, userId); 20182 } 20183 } 20184 20185 @Override 20186 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20187 synchronized (mPackages) { 20188 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20189 packageName, userId); 20190 } 20191 } 20192 20193 @Override 20194 public void setKeepUninstalledPackages(final List<String> packageList) { 20195 Preconditions.checkNotNull(packageList); 20196 List<String> removedFromList = null; 20197 synchronized (mPackages) { 20198 if (mKeepUninstalledPackages != null) { 20199 final int packagesCount = mKeepUninstalledPackages.size(); 20200 for (int i = 0; i < packagesCount; i++) { 20201 String oldPackage = mKeepUninstalledPackages.get(i); 20202 if (packageList != null && packageList.contains(oldPackage)) { 20203 continue; 20204 } 20205 if (removedFromList == null) { 20206 removedFromList = new ArrayList<>(); 20207 } 20208 removedFromList.add(oldPackage); 20209 } 20210 } 20211 mKeepUninstalledPackages = new ArrayList<>(packageList); 20212 if (removedFromList != null) { 20213 final int removedCount = removedFromList.size(); 20214 for (int i = 0; i < removedCount; i++) { 20215 deletePackageIfUnusedLPr(removedFromList.get(i)); 20216 } 20217 } 20218 } 20219 } 20220 20221 @Override 20222 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20223 synchronized (mPackages) { 20224 // If we do not support permission review, done. 20225 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20226 return false; 20227 } 20228 20229 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20230 if (packageSetting == null) { 20231 return false; 20232 } 20233 20234 // Permission review applies only to apps not supporting the new permission model. 20235 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20236 return false; 20237 } 20238 20239 // Legacy apps have the permission and get user consent on launch. 20240 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20241 return permissionsState.isPermissionReviewRequired(userId); 20242 } 20243 } 20244 20245 @Override 20246 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20247 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20248 } 20249 20250 @Override 20251 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20252 int userId) { 20253 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20254 } 20255 } 20256 20257 @Override 20258 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20259 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20260 synchronized (mPackages) { 20261 final long identity = Binder.clearCallingIdentity(); 20262 try { 20263 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20264 packageNames, userId); 20265 } finally { 20266 Binder.restoreCallingIdentity(identity); 20267 } 20268 } 20269 } 20270 20271 private static void enforceSystemOrPhoneCaller(String tag) { 20272 int callingUid = Binder.getCallingUid(); 20273 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20274 throw new SecurityException( 20275 "Cannot call " + tag + " from UID " + callingUid); 20276 } 20277 } 20278 20279 boolean isHistoricalPackageUsageAvailable() { 20280 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20281 } 20282 20283 /** 20284 * Return a <b>copy</b> of the collection of packages known to the package manager. 20285 * @return A copy of the values of mPackages. 20286 */ 20287 Collection<PackageParser.Package> getPackages() { 20288 synchronized (mPackages) { 20289 return new ArrayList<>(mPackages.values()); 20290 } 20291 } 20292 20293 /** 20294 * Logs process start information (including base APK hash) to the security log. 20295 * @hide 20296 */ 20297 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20298 String apkFile, int pid) { 20299 if (!SecurityLog.isLoggingEnabled()) { 20300 return; 20301 } 20302 Bundle data = new Bundle(); 20303 data.putLong("startTimestamp", System.currentTimeMillis()); 20304 data.putString("processName", processName); 20305 data.putInt("uid", uid); 20306 data.putString("seinfo", seinfo); 20307 data.putString("apkFile", apkFile); 20308 data.putInt("pid", pid); 20309 Message msg = mProcessLoggingHandler.obtainMessage( 20310 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20311 msg.setData(data); 20312 mProcessLoggingHandler.sendMessage(msg); 20313 } 20314} 20315