PackageManagerService.java revision 97ef0e77afa3be6255b70c8567843ac298386251
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 final @NonNull String mSharedSystemSharedLibraryPackageName; 1108 1109 private final PackageUsage mPackageUsage = new PackageUsage(); 1110 1111 private class PackageUsage { 1112 private static final int WRITE_INTERVAL 1113 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1114 1115 private final Object mFileLock = new Object(); 1116 private final AtomicLong mLastWritten = new AtomicLong(0); 1117 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1118 1119 private boolean mIsHistoricalPackageUsageAvailable = true; 1120 1121 boolean isHistoricalPackageUsageAvailable() { 1122 return mIsHistoricalPackageUsageAvailable; 1123 } 1124 1125 void write(boolean force) { 1126 if (force) { 1127 writeInternal(); 1128 return; 1129 } 1130 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1131 && !DEBUG_DEXOPT) { 1132 return; 1133 } 1134 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1135 new Thread("PackageUsage_DiskWriter") { 1136 @Override 1137 public void run() { 1138 try { 1139 writeInternal(); 1140 } finally { 1141 mBackgroundWriteRunning.set(false); 1142 } 1143 } 1144 }.start(); 1145 } 1146 } 1147 1148 private void writeInternal() { 1149 synchronized (mPackages) { 1150 synchronized (mFileLock) { 1151 AtomicFile file = getFile(); 1152 FileOutputStream f = null; 1153 try { 1154 f = file.startWrite(); 1155 BufferedOutputStream out = new BufferedOutputStream(f); 1156 FileUtils.setPermissions(file.getBaseFile().getPath(), 1157 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1158 StringBuilder sb = new StringBuilder(); 1159 1160 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1161 sb.append('\n'); 1162 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1163 1164 for (PackageParser.Package pkg : mPackages.values()) { 1165 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1166 continue; 1167 } 1168 sb.setLength(0); 1169 sb.append(pkg.packageName); 1170 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1171 sb.append(' '); 1172 sb.append(usageTimeInMillis); 1173 } 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 } 1177 out.flush(); 1178 file.finishWrite(f); 1179 } catch (IOException e) { 1180 if (f != null) { 1181 file.failWrite(f); 1182 } 1183 Log.e(TAG, "Failed to write package usage times", e); 1184 } 1185 } 1186 } 1187 mLastWritten.set(SystemClock.elapsedRealtime()); 1188 } 1189 1190 void readLP() { 1191 synchronized (mFileLock) { 1192 AtomicFile file = getFile(); 1193 BufferedInputStream in = null; 1194 try { 1195 in = new BufferedInputStream(file.openRead()); 1196 StringBuffer sb = new StringBuffer(); 1197 1198 String firstLine = readLine(in, sb); 1199 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1200 readVersion1LP(in, sb); 1201 } else { 1202 readVersion0LP(in, sb, firstLine); 1203 } 1204 } catch (FileNotFoundException expected) { 1205 mIsHistoricalPackageUsageAvailable = false; 1206 } catch (IOException e) { 1207 Log.w(TAG, "Failed to read package usage times", e); 1208 } finally { 1209 IoUtils.closeQuietly(in); 1210 } 1211 } 1212 mLastWritten.set(SystemClock.elapsedRealtime()); 1213 } 1214 1215 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1216 throws IOException { 1217 // Initial version of the file had no version number and stored one 1218 // package-timestamp pair per line. 1219 // Note that the first line has already been read from the InputStream. 1220 String line = firstLine; 1221 while (true) { 1222 if (line == null) { 1223 break; 1224 } 1225 1226 String[] tokens = line.split(" "); 1227 if (tokens.length != 2) { 1228 throw new IOException("Failed to parse " + line + 1229 " as package-timestamp pair."); 1230 } 1231 1232 String packageName = tokens[0]; 1233 PackageParser.Package pkg = mPackages.get(packageName); 1234 if (pkg == null) { 1235 continue; 1236 } 1237 1238 long timestamp = parseAsLong(tokens[1]); 1239 for (int reason = 0; 1240 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1241 reason++) { 1242 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1243 } 1244 1245 line = readLine(in, sb); 1246 } 1247 } 1248 1249 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1250 // Version 1 of the file started with the corresponding version 1251 // number and then stored a package name and eight timestamps per line. 1252 String line; 1253 while ((line = readLine(in, sb)) != null) { 1254 String[] tokens = line.split(" "); 1255 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1256 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1257 } 1258 1259 String packageName = tokens[0]; 1260 PackageParser.Package pkg = mPackages.get(packageName); 1261 if (pkg == null) { 1262 continue; 1263 } 1264 1265 for (int reason = 0; 1266 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1267 reason++) { 1268 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1269 } 1270 } 1271 } 1272 1273 private long parseAsLong(String token) throws IOException { 1274 try { 1275 return Long.parseLong(token); 1276 } catch (NumberFormatException e) { 1277 throw new IOException("Failed to parse " + token + " as a long.", e); 1278 } 1279 } 1280 1281 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1282 return readToken(in, sb, '\n'); 1283 } 1284 1285 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1286 throws IOException { 1287 sb.setLength(0); 1288 while (true) { 1289 int ch = in.read(); 1290 if (ch == -1) { 1291 if (sb.length() == 0) { 1292 return null; 1293 } 1294 throw new IOException("Unexpected EOF"); 1295 } 1296 if (ch == endOfToken) { 1297 return sb.toString(); 1298 } 1299 sb.append((char)ch); 1300 } 1301 } 1302 1303 private AtomicFile getFile() { 1304 File dataDir = Environment.getDataDirectory(); 1305 File systemDir = new File(dataDir, "system"); 1306 File fname = new File(systemDir, "package-usage.list"); 1307 return new AtomicFile(fname); 1308 } 1309 1310 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1311 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1312 } 1313 1314 class PackageHandler extends Handler { 1315 private boolean mBound = false; 1316 final ArrayList<HandlerParams> mPendingInstalls = 1317 new ArrayList<HandlerParams>(); 1318 1319 private boolean connectToService() { 1320 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1321 " DefaultContainerService"); 1322 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1323 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1324 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1325 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1326 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1327 mBound = true; 1328 return true; 1329 } 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 return false; 1332 } 1333 1334 private void disconnectService() { 1335 mContainerService = null; 1336 mBound = false; 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1338 mContext.unbindService(mDefContainerConn); 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1340 } 1341 1342 PackageHandler(Looper looper) { 1343 super(looper); 1344 } 1345 1346 public void handleMessage(Message msg) { 1347 try { 1348 doHandleMessage(msg); 1349 } finally { 1350 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1351 } 1352 } 1353 1354 void doHandleMessage(Message msg) { 1355 switch (msg.what) { 1356 case INIT_COPY: { 1357 HandlerParams params = (HandlerParams) msg.obj; 1358 int idx = mPendingInstalls.size(); 1359 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1360 // If a bind was already initiated we dont really 1361 // need to do anything. The pending install 1362 // will be processed later on. 1363 if (!mBound) { 1364 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1365 System.identityHashCode(mHandler)); 1366 // If this is the only one pending we might 1367 // have to bind to the service again. 1368 if (!connectToService()) { 1369 Slog.e(TAG, "Failed to bind to media container service"); 1370 params.serviceError(); 1371 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1372 System.identityHashCode(mHandler)); 1373 if (params.traceMethod != null) { 1374 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1375 params.traceCookie); 1376 } 1377 return; 1378 } else { 1379 // Once we bind to the service, the first 1380 // pending request will be processed. 1381 mPendingInstalls.add(idx, params); 1382 } 1383 } else { 1384 mPendingInstalls.add(idx, params); 1385 // Already bound to the service. Just make 1386 // sure we trigger off processing the first request. 1387 if (idx == 0) { 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 } 1391 break; 1392 } 1393 case MCS_BOUND: { 1394 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1395 if (msg.obj != null) { 1396 mContainerService = (IMediaContainerService) msg.obj; 1397 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1398 System.identityHashCode(mHandler)); 1399 } 1400 if (mContainerService == null) { 1401 if (!mBound) { 1402 // Something seriously wrong since we are not bound and we are not 1403 // waiting for connection. Bail out. 1404 Slog.e(TAG, "Cannot bind to media container service"); 1405 for (HandlerParams params : mPendingInstalls) { 1406 // Indicate service bind error 1407 params.serviceError(); 1408 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1409 System.identityHashCode(params)); 1410 if (params.traceMethod != null) { 1411 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1412 params.traceMethod, params.traceCookie); 1413 } 1414 return; 1415 } 1416 mPendingInstalls.clear(); 1417 } else { 1418 Slog.w(TAG, "Waiting to connect to media container service"); 1419 } 1420 } else if (mPendingInstalls.size() > 0) { 1421 HandlerParams params = mPendingInstalls.get(0); 1422 if (params != null) { 1423 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1424 System.identityHashCode(params)); 1425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1426 if (params.startCopy()) { 1427 // We are done... look for more work or to 1428 // go idle. 1429 if (DEBUG_SD_INSTALL) Log.i(TAG, 1430 "Checking for more work or unbind..."); 1431 // Delete pending install 1432 if (mPendingInstalls.size() > 0) { 1433 mPendingInstalls.remove(0); 1434 } 1435 if (mPendingInstalls.size() == 0) { 1436 if (mBound) { 1437 if (DEBUG_SD_INSTALL) Log.i(TAG, 1438 "Posting delayed MCS_UNBIND"); 1439 removeMessages(MCS_UNBIND); 1440 Message ubmsg = obtainMessage(MCS_UNBIND); 1441 // Unbind after a little delay, to avoid 1442 // continual thrashing. 1443 sendMessageDelayed(ubmsg, 10000); 1444 } 1445 } else { 1446 // There are more pending requests in queue. 1447 // Just post MCS_BOUND message to trigger processing 1448 // of next pending install. 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, 1450 "Posting MCS_BOUND for next work"); 1451 mHandler.sendEmptyMessage(MCS_BOUND); 1452 } 1453 } 1454 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1455 } 1456 } else { 1457 // Should never happen ideally. 1458 Slog.w(TAG, "Empty queue"); 1459 } 1460 break; 1461 } 1462 case MCS_RECONNECT: { 1463 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1464 if (mPendingInstalls.size() > 0) { 1465 if (mBound) { 1466 disconnectService(); 1467 } 1468 if (!connectToService()) { 1469 Slog.e(TAG, "Failed to bind to media container service"); 1470 for (HandlerParams params : mPendingInstalls) { 1471 // Indicate service bind error 1472 params.serviceError(); 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1474 System.identityHashCode(params)); 1475 } 1476 mPendingInstalls.clear(); 1477 } 1478 } 1479 break; 1480 } 1481 case MCS_UNBIND: { 1482 // If there is no actual work left, then time to unbind. 1483 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1484 1485 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1486 if (mBound) { 1487 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1488 1489 disconnectService(); 1490 } 1491 } else if (mPendingInstalls.size() > 0) { 1492 // There are more pending requests in queue. 1493 // Just post MCS_BOUND message to trigger processing 1494 // of next pending install. 1495 mHandler.sendEmptyMessage(MCS_BOUND); 1496 } 1497 1498 break; 1499 } 1500 case MCS_GIVE_UP: { 1501 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1502 HandlerParams params = mPendingInstalls.remove(0); 1503 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1504 System.identityHashCode(params)); 1505 break; 1506 } 1507 case SEND_PENDING_BROADCAST: { 1508 String packages[]; 1509 ArrayList<String> components[]; 1510 int size = 0; 1511 int uids[]; 1512 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1513 synchronized (mPackages) { 1514 if (mPendingBroadcasts == null) { 1515 return; 1516 } 1517 size = mPendingBroadcasts.size(); 1518 if (size <= 0) { 1519 // Nothing to be done. Just return 1520 return; 1521 } 1522 packages = new String[size]; 1523 components = new ArrayList[size]; 1524 uids = new int[size]; 1525 int i = 0; // filling out the above arrays 1526 1527 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1528 int packageUserId = mPendingBroadcasts.userIdAt(n); 1529 Iterator<Map.Entry<String, ArrayList<String>>> it 1530 = mPendingBroadcasts.packagesForUserId(packageUserId) 1531 .entrySet().iterator(); 1532 while (it.hasNext() && i < size) { 1533 Map.Entry<String, ArrayList<String>> ent = it.next(); 1534 packages[i] = ent.getKey(); 1535 components[i] = ent.getValue(); 1536 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1537 uids[i] = (ps != null) 1538 ? UserHandle.getUid(packageUserId, ps.appId) 1539 : -1; 1540 i++; 1541 } 1542 } 1543 size = i; 1544 mPendingBroadcasts.clear(); 1545 } 1546 // Send broadcasts 1547 for (int i = 0; i < size; i++) { 1548 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1549 } 1550 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1551 break; 1552 } 1553 case START_CLEANING_PACKAGE: { 1554 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1555 final String packageName = (String)msg.obj; 1556 final int userId = msg.arg1; 1557 final boolean andCode = msg.arg2 != 0; 1558 synchronized (mPackages) { 1559 if (userId == UserHandle.USER_ALL) { 1560 int[] users = sUserManager.getUserIds(); 1561 for (int user : users) { 1562 mSettings.addPackageToCleanLPw( 1563 new PackageCleanItem(user, packageName, andCode)); 1564 } 1565 } else { 1566 mSettings.addPackageToCleanLPw( 1567 new PackageCleanItem(userId, packageName, andCode)); 1568 } 1569 } 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1571 startCleaningPackages(); 1572 } break; 1573 case POST_INSTALL: { 1574 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1575 1576 PostInstallData data = mRunningInstalls.get(msg.arg1); 1577 mRunningInstalls.delete(msg.arg1); 1578 1579 if (data != null) { 1580 InstallArgs args = data.args; 1581 PackageInstalledInfo parentRes = data.res; 1582 1583 final boolean grantPermissions = (args.installFlags 1584 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1585 final boolean killApp = (args.installFlags 1586 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1587 final String[] grantedPermissions = args.installGrantPermissions; 1588 1589 // Handle the parent package 1590 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1591 grantedPermissions, args.observer); 1592 1593 // Handle the child packages 1594 final int childCount = (parentRes.addedChildPackages != null) 1595 ? parentRes.addedChildPackages.size() : 0; 1596 for (int i = 0; i < childCount; i++) { 1597 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1598 handlePackagePostInstall(childRes, grantPermissions, killApp, 1599 grantedPermissions, args.observer); 1600 } 1601 1602 // Log tracing if needed 1603 if (args.traceMethod != null) { 1604 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1605 args.traceCookie); 1606 } 1607 } else { 1608 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1609 } 1610 1611 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1612 } break; 1613 case UPDATED_MEDIA_STATUS: { 1614 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1615 boolean reportStatus = msg.arg1 == 1; 1616 boolean doGc = msg.arg2 == 1; 1617 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1618 if (doGc) { 1619 // Force a gc to clear up stale containers. 1620 Runtime.getRuntime().gc(); 1621 } 1622 if (msg.obj != null) { 1623 @SuppressWarnings("unchecked") 1624 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1625 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1626 // Unload containers 1627 unloadAllContainers(args); 1628 } 1629 if (reportStatus) { 1630 try { 1631 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1632 PackageHelper.getMountService().finishMediaUpdate(); 1633 } catch (RemoteException e) { 1634 Log.e(TAG, "MountService not running?"); 1635 } 1636 } 1637 } break; 1638 case WRITE_SETTINGS: { 1639 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1640 synchronized (mPackages) { 1641 removeMessages(WRITE_SETTINGS); 1642 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1643 mSettings.writeLPr(); 1644 mDirtyUsers.clear(); 1645 } 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1647 } break; 1648 case WRITE_PACKAGE_RESTRICTIONS: { 1649 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1650 synchronized (mPackages) { 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 for (int userId : mDirtyUsers) { 1653 mSettings.writePackageRestrictionsLPr(userId); 1654 } 1655 mDirtyUsers.clear(); 1656 } 1657 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1658 } break; 1659 case CHECK_PENDING_VERIFICATION: { 1660 final int verificationId = msg.arg1; 1661 final PackageVerificationState state = mPendingVerification.get(verificationId); 1662 1663 if ((state != null) && !state.timeoutExtended()) { 1664 final InstallArgs args = state.getInstallArgs(); 1665 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1666 1667 Slog.i(TAG, "Verification timed out for " + originUri); 1668 mPendingVerification.remove(verificationId); 1669 1670 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1671 1672 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1673 Slog.i(TAG, "Continuing with installation of " + originUri); 1674 state.setVerifierResponse(Binder.getCallingUid(), 1675 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1676 broadcastPackageVerified(verificationId, originUri, 1677 PackageManager.VERIFICATION_ALLOW, 1678 state.getInstallArgs().getUser()); 1679 try { 1680 ret = args.copyApk(mContainerService, true); 1681 } catch (RemoteException e) { 1682 Slog.e(TAG, "Could not contact the ContainerService"); 1683 } 1684 } else { 1685 broadcastPackageVerified(verificationId, originUri, 1686 PackageManager.VERIFICATION_REJECT, 1687 state.getInstallArgs().getUser()); 1688 } 1689 1690 Trace.asyncTraceEnd( 1691 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1692 1693 processPendingInstall(args, ret); 1694 mHandler.sendEmptyMessage(MCS_UNBIND); 1695 } 1696 break; 1697 } 1698 case PACKAGE_VERIFIED: { 1699 final int verificationId = msg.arg1; 1700 1701 final PackageVerificationState state = mPendingVerification.get(verificationId); 1702 if (state == null) { 1703 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1704 break; 1705 } 1706 1707 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1708 1709 state.setVerifierResponse(response.callerUid, response.code); 1710 1711 if (state.isVerificationComplete()) { 1712 mPendingVerification.remove(verificationId); 1713 1714 final InstallArgs args = state.getInstallArgs(); 1715 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1716 1717 int ret; 1718 if (state.isInstallAllowed()) { 1719 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1720 broadcastPackageVerified(verificationId, originUri, 1721 response.code, state.getInstallArgs().getUser()); 1722 try { 1723 ret = args.copyApk(mContainerService, true); 1724 } catch (RemoteException e) { 1725 Slog.e(TAG, "Could not contact the ContainerService"); 1726 } 1727 } else { 1728 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1729 } 1730 1731 Trace.asyncTraceEnd( 1732 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1733 1734 processPendingInstall(args, ret); 1735 mHandler.sendEmptyMessage(MCS_UNBIND); 1736 } 1737 1738 break; 1739 } 1740 case START_INTENT_FILTER_VERIFICATIONS: { 1741 IFVerificationParams params = (IFVerificationParams) msg.obj; 1742 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1743 params.replacing, params.pkg); 1744 break; 1745 } 1746 case INTENT_FILTER_VERIFIED: { 1747 final int verificationId = msg.arg1; 1748 1749 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1750 verificationId); 1751 if (state == null) { 1752 Slog.w(TAG, "Invalid IntentFilter verification token " 1753 + verificationId + " received"); 1754 break; 1755 } 1756 1757 final int userId = state.getUserId(); 1758 1759 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1760 "Processing IntentFilter verification with token:" 1761 + verificationId + " and userId:" + userId); 1762 1763 final IntentFilterVerificationResponse response = 1764 (IntentFilterVerificationResponse) msg.obj; 1765 1766 state.setVerifierResponse(response.callerUid, response.code); 1767 1768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1769 "IntentFilter verification with token:" + verificationId 1770 + " and userId:" + userId 1771 + " is settings verifier response with response code:" 1772 + response.code); 1773 1774 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1775 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1776 + response.getFailedDomainsString()); 1777 } 1778 1779 if (state.isVerificationComplete()) { 1780 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1781 } else { 1782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1783 "IntentFilter verification with token:" + verificationId 1784 + " was not said to be complete"); 1785 } 1786 1787 break; 1788 } 1789 } 1790 } 1791 } 1792 1793 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1794 boolean killApp, String[] grantedPermissions, 1795 IPackageInstallObserver2 installObserver) { 1796 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1797 // Send the removed broadcasts 1798 if (res.removedInfo != null) { 1799 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1800 } 1801 1802 // Now that we successfully installed the package, grant runtime 1803 // permissions if requested before broadcasting the install. 1804 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1805 >= Build.VERSION_CODES.M) { 1806 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1807 } 1808 1809 final boolean update = res.removedInfo != null 1810 && res.removedInfo.removedPackage != null; 1811 1812 // If this is the first time we have child packages for a disabled privileged 1813 // app that had no children, we grant requested runtime permissions to the new 1814 // children if the parent on the system image had them already granted. 1815 if (res.pkg.parentPackage != null) { 1816 synchronized (mPackages) { 1817 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1818 } 1819 } 1820 1821 synchronized (mPackages) { 1822 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1823 } 1824 1825 final String packageName = res.pkg.applicationInfo.packageName; 1826 Bundle extras = new Bundle(1); 1827 extras.putInt(Intent.EXTRA_UID, res.uid); 1828 1829 // Determine the set of users who are adding this package for 1830 // the first time vs. those who are seeing an update. 1831 int[] firstUsers = EMPTY_INT_ARRAY; 1832 int[] updateUsers = EMPTY_INT_ARRAY; 1833 if (res.origUsers == null || res.origUsers.length == 0) { 1834 firstUsers = res.newUsers; 1835 } else { 1836 for (int newUser : res.newUsers) { 1837 boolean isNew = true; 1838 for (int origUser : res.origUsers) { 1839 if (origUser == newUser) { 1840 isNew = false; 1841 break; 1842 } 1843 } 1844 if (isNew) { 1845 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1846 } else { 1847 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1848 } 1849 } 1850 } 1851 1852 // Send installed broadcasts if the install/update is not ephemeral 1853 if (!isEphemeral(res.pkg)) { 1854 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1855 1856 // Send added for users that see the package for the first time 1857 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1858 extras, 0 /*flags*/, null /*targetPackage*/, 1859 null /*finishedReceiver*/, firstUsers); 1860 1861 // Send added for users that don't see the package for the first time 1862 if (update) { 1863 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1864 } 1865 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1866 extras, 0 /*flags*/, null /*targetPackage*/, 1867 null /*finishedReceiver*/, updateUsers); 1868 1869 // Send replaced for users that don't see the package for the first time 1870 if (update) { 1871 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1872 packageName, extras, 0 /*flags*/, 1873 null /*targetPackage*/, null /*finishedReceiver*/, 1874 updateUsers); 1875 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1876 null /*package*/, null /*extras*/, 0 /*flags*/, 1877 packageName /*targetPackage*/, 1878 null /*finishedReceiver*/, updateUsers); 1879 } 1880 1881 // Send broadcast package appeared if forward locked/external for all users 1882 // treat asec-hosted packages like removable media on upgrade 1883 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1884 if (DEBUG_INSTALL) { 1885 Slog.i(TAG, "upgrading pkg " + res.pkg 1886 + " is ASEC-hosted -> AVAILABLE"); 1887 } 1888 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1889 ArrayList<String> pkgList = new ArrayList<>(1); 1890 pkgList.add(packageName); 1891 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1892 } 1893 } 1894 1895 // Work that needs to happen on first install within each user 1896 if (firstUsers != null && firstUsers.length > 0) { 1897 synchronized (mPackages) { 1898 for (int userId : firstUsers) { 1899 // If this app is a browser and it's newly-installed for some 1900 // users, clear any default-browser state in those users. The 1901 // app's nature doesn't depend on the user, so we can just check 1902 // its browser nature in any user and generalize. 1903 if (packageIsBrowser(packageName, userId)) { 1904 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1905 } 1906 1907 // We may also need to apply pending (restored) runtime 1908 // permission grants within these users. 1909 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1910 } 1911 } 1912 } 1913 1914 // Log current value of "unknown sources" setting 1915 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1916 getUnknownSourcesSettings()); 1917 1918 // Force a gc to clear up things 1919 Runtime.getRuntime().gc(); 1920 1921 // Remove the replaced package's older resources safely now 1922 // We delete after a gc for applications on sdcard. 1923 if (res.removedInfo != null && res.removedInfo.args != null) { 1924 synchronized (mInstallLock) { 1925 res.removedInfo.args.doPostDeleteLI(true); 1926 } 1927 } 1928 } 1929 1930 // If someone is watching installs - notify them 1931 if (installObserver != null) { 1932 try { 1933 Bundle extras = extrasForInstallResult(res); 1934 installObserver.onPackageInstalled(res.name, res.returnCode, 1935 res.returnMsg, extras); 1936 } catch (RemoteException e) { 1937 Slog.i(TAG, "Observer no longer exists."); 1938 } 1939 } 1940 } 1941 1942 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1943 PackageParser.Package pkg) { 1944 if (pkg.parentPackage == null) { 1945 return; 1946 } 1947 if (pkg.requestedPermissions == null) { 1948 return; 1949 } 1950 final PackageSetting disabledSysParentPs = mSettings 1951 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1952 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1953 || !disabledSysParentPs.isPrivileged() 1954 || (disabledSysParentPs.childPackageNames != null 1955 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1956 return; 1957 } 1958 final int[] allUserIds = sUserManager.getUserIds(); 1959 final int permCount = pkg.requestedPermissions.size(); 1960 for (int i = 0; i < permCount; i++) { 1961 String permission = pkg.requestedPermissions.get(i); 1962 BasePermission bp = mSettings.mPermissions.get(permission); 1963 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1964 continue; 1965 } 1966 for (int userId : allUserIds) { 1967 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1968 permission, userId)) { 1969 grantRuntimePermission(pkg.packageName, permission, userId); 1970 } 1971 } 1972 } 1973 } 1974 1975 private StorageEventListener mStorageListener = new StorageEventListener() { 1976 @Override 1977 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1978 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1979 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1980 final String volumeUuid = vol.getFsUuid(); 1981 1982 // Clean up any users or apps that were removed or recreated 1983 // while this volume was missing 1984 reconcileUsers(volumeUuid); 1985 reconcileApps(volumeUuid); 1986 1987 // Clean up any install sessions that expired or were 1988 // cancelled while this volume was missing 1989 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1990 1991 loadPrivatePackages(vol); 1992 1993 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1994 unloadPrivatePackages(vol); 1995 } 1996 } 1997 1998 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1999 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2000 updateExternalMediaStatus(true, false); 2001 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2002 updateExternalMediaStatus(false, false); 2003 } 2004 } 2005 } 2006 2007 @Override 2008 public void onVolumeForgotten(String fsUuid) { 2009 if (TextUtils.isEmpty(fsUuid)) { 2010 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2011 return; 2012 } 2013 2014 // Remove any apps installed on the forgotten volume 2015 synchronized (mPackages) { 2016 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2017 for (PackageSetting ps : packages) { 2018 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2019 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2020 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2021 } 2022 2023 mSettings.onVolumeForgotten(fsUuid); 2024 mSettings.writeLPr(); 2025 } 2026 } 2027 }; 2028 2029 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2030 String[] grantedPermissions) { 2031 for (int userId : userIds) { 2032 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2033 } 2034 2035 // We could have touched GID membership, so flush out packages.list 2036 synchronized (mPackages) { 2037 mSettings.writePackageListLPr(); 2038 } 2039 } 2040 2041 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2042 String[] grantedPermissions) { 2043 SettingBase sb = (SettingBase) pkg.mExtras; 2044 if (sb == null) { 2045 return; 2046 } 2047 2048 PermissionsState permissionsState = sb.getPermissionsState(); 2049 2050 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2051 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2052 2053 synchronized (mPackages) { 2054 for (String permission : pkg.requestedPermissions) { 2055 BasePermission bp = mSettings.mPermissions.get(permission); 2056 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2057 && (grantedPermissions == null 2058 || ArrayUtils.contains(grantedPermissions, permission))) { 2059 final int flags = permissionsState.getPermissionFlags(permission, userId); 2060 // Installer cannot change immutable permissions. 2061 if ((flags & immutableFlags) == 0) { 2062 grantRuntimePermission(pkg.packageName, permission, userId); 2063 } 2064 } 2065 } 2066 } 2067 } 2068 2069 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2070 Bundle extras = null; 2071 switch (res.returnCode) { 2072 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2073 extras = new Bundle(); 2074 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2075 res.origPermission); 2076 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2077 res.origPackage); 2078 break; 2079 } 2080 case PackageManager.INSTALL_SUCCEEDED: { 2081 extras = new Bundle(); 2082 extras.putBoolean(Intent.EXTRA_REPLACING, 2083 res.removedInfo != null && res.removedInfo.removedPackage != null); 2084 break; 2085 } 2086 } 2087 return extras; 2088 } 2089 2090 void scheduleWriteSettingsLocked() { 2091 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2092 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2093 } 2094 } 2095 2096 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2097 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2098 scheduleWritePackageRestrictionsLocked(userId); 2099 } 2100 2101 void scheduleWritePackageRestrictionsLocked(int userId) { 2102 final int[] userIds = (userId == UserHandle.USER_ALL) 2103 ? sUserManager.getUserIds() : new int[]{userId}; 2104 for (int nextUserId : userIds) { 2105 if (!sUserManager.exists(nextUserId)) return; 2106 mDirtyUsers.add(nextUserId); 2107 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2108 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2109 } 2110 } 2111 } 2112 2113 public static PackageManagerService main(Context context, Installer installer, 2114 boolean factoryTest, boolean onlyCore) { 2115 // Self-check for initial settings. 2116 PackageManagerServiceCompilerMapping.checkProperties(); 2117 2118 PackageManagerService m = new PackageManagerService(context, installer, 2119 factoryTest, onlyCore); 2120 m.enableSystemUserPackages(); 2121 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2122 // disabled after already being started. 2123 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2124 UserHandle.USER_SYSTEM); 2125 ServiceManager.addService("package", m); 2126 return m; 2127 } 2128 2129 private void enableSystemUserPackages() { 2130 if (!UserManager.isSplitSystemUser()) { 2131 return; 2132 } 2133 // For system user, enable apps based on the following conditions: 2134 // - app is whitelisted or belong to one of these groups: 2135 // -- system app which has no launcher icons 2136 // -- system app which has INTERACT_ACROSS_USERS permission 2137 // -- system IME app 2138 // - app is not in the blacklist 2139 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2140 Set<String> enableApps = new ArraySet<>(); 2141 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2142 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2143 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2144 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2145 enableApps.addAll(wlApps); 2146 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2147 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2148 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2149 enableApps.removeAll(blApps); 2150 Log.i(TAG, "Applications installed for system user: " + enableApps); 2151 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2152 UserHandle.SYSTEM); 2153 final int allAppsSize = allAps.size(); 2154 synchronized (mPackages) { 2155 for (int i = 0; i < allAppsSize; i++) { 2156 String pName = allAps.get(i); 2157 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2158 // Should not happen, but we shouldn't be failing if it does 2159 if (pkgSetting == null) { 2160 continue; 2161 } 2162 boolean install = enableApps.contains(pName); 2163 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2164 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2165 + " for system user"); 2166 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2167 } 2168 } 2169 } 2170 } 2171 2172 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2173 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2174 Context.DISPLAY_SERVICE); 2175 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2176 } 2177 2178 public PackageManagerService(Context context, Installer installer, 2179 boolean factoryTest, boolean onlyCore) { 2180 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2181 SystemClock.uptimeMillis()); 2182 2183 if (mSdkVersion <= 0) { 2184 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2185 } 2186 2187 mContext = context; 2188 mFactoryTest = factoryTest; 2189 mOnlyCore = onlyCore; 2190 mMetrics = new DisplayMetrics(); 2191 mSettings = new Settings(mPackages); 2192 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2193 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2194 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2195 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2196 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2197 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2198 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2199 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2200 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2201 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2202 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2203 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2204 2205 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2206 if (separateProcesses != null && separateProcesses.length() > 0) { 2207 if ("*".equals(separateProcesses)) { 2208 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2209 mSeparateProcesses = null; 2210 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2211 } else { 2212 mDefParseFlags = 0; 2213 mSeparateProcesses = separateProcesses.split(","); 2214 Slog.w(TAG, "Running with debug.separate_processes: " 2215 + separateProcesses); 2216 } 2217 } else { 2218 mDefParseFlags = 0; 2219 mSeparateProcesses = null; 2220 } 2221 2222 mInstaller = installer; 2223 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2224 "*dexopt*"); 2225 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2226 2227 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2228 FgThread.get().getLooper()); 2229 2230 getDefaultDisplayMetrics(context, mMetrics); 2231 2232 SystemConfig systemConfig = SystemConfig.getInstance(); 2233 mGlobalGids = systemConfig.getGlobalGids(); 2234 mSystemPermissions = systemConfig.getSystemPermissions(); 2235 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2236 2237 synchronized (mInstallLock) { 2238 // writer 2239 synchronized (mPackages) { 2240 mHandlerThread = new ServiceThread(TAG, 2241 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2242 mHandlerThread.start(); 2243 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2244 mProcessLoggingHandler = new ProcessLoggingHandler(); 2245 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2246 2247 File dataDir = Environment.getDataDirectory(); 2248 mAppInstallDir = new File(dataDir, "app"); 2249 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2250 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2251 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2252 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2253 2254 sUserManager = new UserManagerService(context, this, mPackages); 2255 2256 // Propagate permission configuration in to package manager. 2257 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2258 = systemConfig.getPermissions(); 2259 for (int i=0; i<permConfig.size(); i++) { 2260 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2261 BasePermission bp = mSettings.mPermissions.get(perm.name); 2262 if (bp == null) { 2263 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2264 mSettings.mPermissions.put(perm.name, bp); 2265 } 2266 if (perm.gids != null) { 2267 bp.setGids(perm.gids, perm.perUser); 2268 } 2269 } 2270 2271 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2272 for (int i=0; i<libConfig.size(); i++) { 2273 mSharedLibraries.put(libConfig.keyAt(i), 2274 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2275 } 2276 2277 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2278 2279 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2280 2281 String customResolverActivity = Resources.getSystem().getString( 2282 R.string.config_customResolverActivity); 2283 if (TextUtils.isEmpty(customResolverActivity)) { 2284 customResolverActivity = null; 2285 } else { 2286 mCustomResolverComponentName = ComponentName.unflattenFromString( 2287 customResolverActivity); 2288 } 2289 2290 long startTime = SystemClock.uptimeMillis(); 2291 2292 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2293 startTime); 2294 2295 // Set flag to monitor and not change apk file paths when 2296 // scanning install directories. 2297 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2298 2299 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2300 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2301 2302 if (bootClassPath == null) { 2303 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2304 } 2305 2306 if (systemServerClassPath == null) { 2307 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2308 } 2309 2310 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2311 final String[] dexCodeInstructionSets = 2312 getDexCodeInstructionSets( 2313 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2314 2315 /** 2316 * Ensure all external libraries have had dexopt run on them. 2317 */ 2318 if (mSharedLibraries.size() > 0) { 2319 // NOTE: For now, we're compiling these system "shared libraries" 2320 // (and framework jars) into all available architectures. It's possible 2321 // to compile them only when we come across an app that uses them (there's 2322 // already logic for that in scanPackageLI) but that adds some complexity. 2323 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2324 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2325 final String lib = libEntry.path; 2326 if (lib == null) { 2327 continue; 2328 } 2329 2330 try { 2331 // Shared libraries do not have profiles so we perform a full 2332 // AOT compilation (if needed). 2333 int dexoptNeeded = DexFile.getDexOptNeeded( 2334 lib, dexCodeInstructionSet, 2335 getCompilerFilterForReason(REASON_SHARED_APK), 2336 false /* newProfile */); 2337 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2338 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2339 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2340 getCompilerFilterForReason(REASON_SHARED_APK), 2341 StorageManager.UUID_PRIVATE_INTERNAL); 2342 } 2343 } catch (FileNotFoundException e) { 2344 Slog.w(TAG, "Library not found: " + lib); 2345 } catch (IOException | InstallerException e) { 2346 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2347 + e.getMessage()); 2348 } 2349 } 2350 } 2351 } 2352 2353 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2354 2355 final VersionInfo ver = mSettings.getInternalVersion(); 2356 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2357 2358 // when upgrading from pre-M, promote system app permissions from install to runtime 2359 mPromoteSystemApps = 2360 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2361 2362 // save off the names of pre-existing system packages prior to scanning; we don't 2363 // want to automatically grant runtime permissions for new system apps 2364 if (mPromoteSystemApps) { 2365 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2366 while (pkgSettingIter.hasNext()) { 2367 PackageSetting ps = pkgSettingIter.next(); 2368 if (isSystemApp(ps)) { 2369 mExistingSystemPackages.add(ps.name); 2370 } 2371 } 2372 } 2373 2374 // When upgrading from pre-N, we need to handle package extraction like first boot, 2375 // as there is no profiling data available. 2376 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2377 mSettings.setNWorkDone(); 2378 2379 // Collect vendor overlay packages. 2380 // (Do this before scanning any apps.) 2381 // For security and version matching reason, only consider 2382 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2383 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2384 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2385 | PackageParser.PARSE_IS_SYSTEM 2386 | PackageParser.PARSE_IS_SYSTEM_DIR 2387 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2388 2389 // Find base frameworks (resource packages without code). 2390 scanDirTracedLI(frameworkDir, mDefParseFlags 2391 | PackageParser.PARSE_IS_SYSTEM 2392 | PackageParser.PARSE_IS_SYSTEM_DIR 2393 | PackageParser.PARSE_IS_PRIVILEGED, 2394 scanFlags | SCAN_NO_DEX, 0); 2395 2396 // Collected privileged system packages. 2397 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2398 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2399 | PackageParser.PARSE_IS_SYSTEM 2400 | PackageParser.PARSE_IS_SYSTEM_DIR 2401 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2402 2403 // Collect ordinary system packages. 2404 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2405 scanDirTracedLI(systemAppDir, mDefParseFlags 2406 | PackageParser.PARSE_IS_SYSTEM 2407 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2408 2409 // Collect all vendor packages. 2410 File vendorAppDir = new File("/vendor/app"); 2411 try { 2412 vendorAppDir = vendorAppDir.getCanonicalFile(); 2413 } catch (IOException e) { 2414 // failed to look up canonical path, continue with original one 2415 } 2416 scanDirTracedLI(vendorAppDir, mDefParseFlags 2417 | PackageParser.PARSE_IS_SYSTEM 2418 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2419 2420 // Collect all OEM packages. 2421 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2422 scanDirTracedLI(oemAppDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2425 2426 // Prune any system packages that no longer exist. 2427 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2428 if (!mOnlyCore) { 2429 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2430 while (psit.hasNext()) { 2431 PackageSetting ps = psit.next(); 2432 2433 /* 2434 * If this is not a system app, it can't be a 2435 * disable system app. 2436 */ 2437 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2438 continue; 2439 } 2440 2441 /* 2442 * If the package is scanned, it's not erased. 2443 */ 2444 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2445 if (scannedPkg != null) { 2446 /* 2447 * If the system app is both scanned and in the 2448 * disabled packages list, then it must have been 2449 * added via OTA. Remove it from the currently 2450 * scanned package so the previously user-installed 2451 * application can be scanned. 2452 */ 2453 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2454 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2455 + ps.name + "; removing system app. Last known codePath=" 2456 + ps.codePathString + ", installStatus=" + ps.installStatus 2457 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2458 + scannedPkg.mVersionCode); 2459 removePackageLI(scannedPkg, true); 2460 mExpectingBetter.put(ps.name, ps.codePath); 2461 } 2462 2463 continue; 2464 } 2465 2466 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2467 psit.remove(); 2468 logCriticalInfo(Log.WARN, "System package " + ps.name 2469 + " no longer exists; it's data will be wiped"); 2470 // Actual deletion of code and data will be handled by later 2471 // reconciliation step 2472 } else { 2473 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2474 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2475 possiblyDeletedUpdatedSystemApps.add(ps.name); 2476 } 2477 } 2478 } 2479 } 2480 2481 //look for any incomplete package installations 2482 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2483 for (int i = 0; i < deletePkgsList.size(); i++) { 2484 // Actual deletion of code and data will be handled by later 2485 // reconciliation step 2486 final String packageName = deletePkgsList.get(i).name; 2487 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2488 synchronized (mPackages) { 2489 mSettings.removePackageLPw(packageName); 2490 } 2491 } 2492 2493 //delete tmp files 2494 deleteTempPackageFiles(); 2495 2496 // Remove any shared userIDs that have no associated packages 2497 mSettings.pruneSharedUsersLPw(); 2498 2499 if (!mOnlyCore) { 2500 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2501 SystemClock.uptimeMillis()); 2502 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2503 2504 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2505 | PackageParser.PARSE_FORWARD_LOCK, 2506 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2507 2508 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2509 | PackageParser.PARSE_IS_EPHEMERAL, 2510 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2511 2512 /** 2513 * Remove disable package settings for any updated system 2514 * apps that were removed via an OTA. If they're not a 2515 * previously-updated app, remove them completely. 2516 * Otherwise, just revoke their system-level permissions. 2517 */ 2518 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2519 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2520 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2521 2522 String msg; 2523 if (deletedPkg == null) { 2524 msg = "Updated system package " + deletedAppName 2525 + " no longer exists; it's data will be wiped"; 2526 // Actual deletion of code and data will be handled by later 2527 // reconciliation step 2528 } else { 2529 msg = "Updated system app + " + deletedAppName 2530 + " no longer present; removing system privileges for " 2531 + deletedAppName; 2532 2533 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2534 2535 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2536 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2537 } 2538 logCriticalInfo(Log.WARN, msg); 2539 } 2540 2541 /** 2542 * Make sure all system apps that we expected to appear on 2543 * the userdata partition actually showed up. If they never 2544 * appeared, crawl back and revive the system version. 2545 */ 2546 for (int i = 0; i < mExpectingBetter.size(); i++) { 2547 final String packageName = mExpectingBetter.keyAt(i); 2548 if (!mPackages.containsKey(packageName)) { 2549 final File scanFile = mExpectingBetter.valueAt(i); 2550 2551 logCriticalInfo(Log.WARN, "Expected better " + packageName 2552 + " but never showed up; reverting to system"); 2553 2554 int reparseFlags = mDefParseFlags; 2555 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2556 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2557 | PackageParser.PARSE_IS_SYSTEM_DIR 2558 | PackageParser.PARSE_IS_PRIVILEGED; 2559 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2560 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2561 | PackageParser.PARSE_IS_SYSTEM_DIR; 2562 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2563 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2564 | PackageParser.PARSE_IS_SYSTEM_DIR; 2565 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2566 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2567 | PackageParser.PARSE_IS_SYSTEM_DIR; 2568 } else { 2569 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2570 continue; 2571 } 2572 2573 mSettings.enableSystemPackageLPw(packageName); 2574 2575 try { 2576 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2577 } catch (PackageManagerException e) { 2578 Slog.e(TAG, "Failed to parse original system package: " 2579 + e.getMessage()); 2580 } 2581 } 2582 } 2583 } 2584 mExpectingBetter.clear(); 2585 2586 // Resolve protected action filters. Only the setup wizard is allowed to 2587 // have a high priority filter for these actions. 2588 mSetupWizardPackage = getSetupWizardPackageName(); 2589 if (mProtectedFilters.size() > 0) { 2590 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2591 Slog.i(TAG, "No setup wizard;" 2592 + " All protected intents capped to priority 0"); 2593 } 2594 for (ActivityIntentInfo filter : mProtectedFilters) { 2595 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2596 if (DEBUG_FILTERS) { 2597 Slog.i(TAG, "Found setup wizard;" 2598 + " allow priority " + filter.getPriority() + ";" 2599 + " package: " + filter.activity.info.packageName 2600 + " activity: " + filter.activity.className 2601 + " priority: " + filter.getPriority()); 2602 } 2603 // skip setup wizard; allow it to keep the high priority filter 2604 continue; 2605 } 2606 Slog.w(TAG, "Protected action; cap priority to 0;" 2607 + " package: " + filter.activity.info.packageName 2608 + " activity: " + filter.activity.className 2609 + " origPrio: " + filter.getPriority()); 2610 filter.setPriority(0); 2611 } 2612 } 2613 mDeferProtectedFilters = false; 2614 mProtectedFilters.clear(); 2615 2616 // Now that we know all of the shared libraries, update all clients to have 2617 // the correct library paths. 2618 updateAllSharedLibrariesLPw(); 2619 2620 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2621 // NOTE: We ignore potential failures here during a system scan (like 2622 // the rest of the commands above) because there's precious little we 2623 // can do about it. A settings error is reported, though. 2624 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2625 false /* boot complete */); 2626 } 2627 2628 // Now that we know all the packages we are keeping, 2629 // read and update their last usage times. 2630 mPackageUsage.readLP(); 2631 2632 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2633 SystemClock.uptimeMillis()); 2634 Slog.i(TAG, "Time to scan packages: " 2635 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2636 + " seconds"); 2637 2638 // If the platform SDK has changed since the last time we booted, 2639 // we need to re-grant app permission to catch any new ones that 2640 // appear. This is really a hack, and means that apps can in some 2641 // cases get permissions that the user didn't initially explicitly 2642 // allow... it would be nice to have some better way to handle 2643 // this situation. 2644 int updateFlags = UPDATE_PERMISSIONS_ALL; 2645 if (ver.sdkVersion != mSdkVersion) { 2646 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2647 + mSdkVersion + "; regranting permissions for internal storage"); 2648 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2649 } 2650 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2651 ver.sdkVersion = mSdkVersion; 2652 2653 // If this is the first boot or an update from pre-M, and it is a normal 2654 // boot, then we need to initialize the default preferred apps across 2655 // all defined users. 2656 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2657 for (UserInfo user : sUserManager.getUsers(true)) { 2658 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2659 applyFactoryDefaultBrowserLPw(user.id); 2660 primeDomainVerificationsLPw(user.id); 2661 } 2662 } 2663 2664 // Prepare storage for system user really early during boot, 2665 // since core system apps like SettingsProvider and SystemUI 2666 // can't wait for user to start 2667 final int storageFlags; 2668 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2669 storageFlags = StorageManager.FLAG_STORAGE_DE; 2670 } else { 2671 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2672 } 2673 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2674 storageFlags); 2675 2676 // If this is first boot after an OTA, and a normal boot, then 2677 // we need to clear code cache directories. 2678 if (mIsUpgrade && !onlyCore) { 2679 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2680 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2681 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2682 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2683 // No apps are running this early, so no need to freeze 2684 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2685 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2686 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2687 } 2688 clearAppProfilesLIF(ps.pkg); 2689 } 2690 ver.fingerprint = Build.FINGERPRINT; 2691 } 2692 2693 checkDefaultBrowser(); 2694 2695 // clear only after permissions and other defaults have been updated 2696 mExistingSystemPackages.clear(); 2697 mPromoteSystemApps = false; 2698 2699 // All the changes are done during package scanning. 2700 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2701 2702 // can downgrade to reader 2703 mSettings.writeLPr(); 2704 2705 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2706 SystemClock.uptimeMillis()); 2707 2708 if (!mOnlyCore) { 2709 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2710 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2711 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2712 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2713 mIntentFilterVerifierComponent); 2714 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2715 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2716 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2717 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2718 } else { 2719 mRequiredVerifierPackage = null; 2720 mRequiredInstallerPackage = null; 2721 mIntentFilterVerifierComponent = null; 2722 mIntentFilterVerifier = null; 2723 mServicesSystemSharedLibraryPackageName = null; 2724 mSharedSystemSharedLibraryPackageName = null; 2725 } 2726 2727 mInstallerService = new PackageInstallerService(context, this); 2728 2729 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2730 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2731 // both the installer and resolver must be present to enable ephemeral 2732 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2733 if (DEBUG_EPHEMERAL) { 2734 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2735 + " installer:" + ephemeralInstallerComponent); 2736 } 2737 mEphemeralResolverComponent = ephemeralResolverComponent; 2738 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2739 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2740 mEphemeralResolverConnection = 2741 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2742 } else { 2743 if (DEBUG_EPHEMERAL) { 2744 final String missingComponent = 2745 (ephemeralResolverComponent == null) 2746 ? (ephemeralInstallerComponent == null) 2747 ? "resolver and installer" 2748 : "resolver" 2749 : "installer"; 2750 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2751 } 2752 mEphemeralResolverComponent = null; 2753 mEphemeralInstallerComponent = null; 2754 mEphemeralResolverConnection = null; 2755 } 2756 2757 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2758 } // synchronized (mPackages) 2759 } // synchronized (mInstallLock) 2760 2761 // Now after opening every single application zip, make sure they 2762 // are all flushed. Not really needed, but keeps things nice and 2763 // tidy. 2764 Runtime.getRuntime().gc(); 2765 2766 // The initial scanning above does many calls into installd while 2767 // holding the mPackages lock, but we're mostly interested in yelling 2768 // once we have a booted system. 2769 mInstaller.setWarnIfHeld(mPackages); 2770 2771 // Expose private service for system components to use. 2772 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2773 } 2774 2775 @Override 2776 public boolean isFirstBoot() { 2777 return !mRestoredSettings; 2778 } 2779 2780 @Override 2781 public boolean isOnlyCoreApps() { 2782 return mOnlyCore; 2783 } 2784 2785 @Override 2786 public boolean isUpgrade() { 2787 return mIsUpgrade; 2788 } 2789 2790 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2791 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2792 2793 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2794 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2795 UserHandle.USER_SYSTEM); 2796 if (matches.size() == 1) { 2797 return matches.get(0).getComponentInfo().packageName; 2798 } else { 2799 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2800 return null; 2801 } 2802 } 2803 2804 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2805 synchronized (mPackages) { 2806 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2807 if (libraryEntry == null) { 2808 throw new IllegalStateException("Missing required shared library:" + libraryName); 2809 } 2810 return libraryEntry.apk; 2811 } 2812 } 2813 2814 private @NonNull String getRequiredInstallerLPr() { 2815 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2816 intent.addCategory(Intent.CATEGORY_DEFAULT); 2817 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2818 2819 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2820 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2821 UserHandle.USER_SYSTEM); 2822 if (matches.size() == 1) { 2823 ResolveInfo resolveInfo = matches.get(0); 2824 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2825 throw new RuntimeException("The installer must be a privileged app"); 2826 } 2827 return matches.get(0).getComponentInfo().packageName; 2828 } else { 2829 throw new RuntimeException("There must be exactly one installer; found " + matches); 2830 } 2831 } 2832 2833 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2834 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2835 2836 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2837 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2838 UserHandle.USER_SYSTEM); 2839 ResolveInfo best = null; 2840 final int N = matches.size(); 2841 for (int i = 0; i < N; i++) { 2842 final ResolveInfo cur = matches.get(i); 2843 final String packageName = cur.getComponentInfo().packageName; 2844 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2845 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2846 continue; 2847 } 2848 2849 if (best == null || cur.priority > best.priority) { 2850 best = cur; 2851 } 2852 } 2853 2854 if (best != null) { 2855 return best.getComponentInfo().getComponentName(); 2856 } else { 2857 throw new RuntimeException("There must be at least one intent filter verifier"); 2858 } 2859 } 2860 2861 private @Nullable ComponentName getEphemeralResolverLPr() { 2862 final String[] packageArray = 2863 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2864 if (packageArray.length == 0) { 2865 if (DEBUG_EPHEMERAL) { 2866 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2867 } 2868 return null; 2869 } 2870 2871 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2872 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2873 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2874 UserHandle.USER_SYSTEM); 2875 2876 final int N = resolvers.size(); 2877 if (N == 0) { 2878 if (DEBUG_EPHEMERAL) { 2879 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2880 } 2881 return null; 2882 } 2883 2884 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2885 for (int i = 0; i < N; i++) { 2886 final ResolveInfo info = resolvers.get(i); 2887 2888 if (info.serviceInfo == null) { 2889 continue; 2890 } 2891 2892 final String packageName = info.serviceInfo.packageName; 2893 if (!possiblePackages.contains(packageName)) { 2894 if (DEBUG_EPHEMERAL) { 2895 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2896 + " pkg: " + packageName + ", info:" + info); 2897 } 2898 continue; 2899 } 2900 2901 if (DEBUG_EPHEMERAL) { 2902 Slog.v(TAG, "Ephemeral resolver found;" 2903 + " pkg: " + packageName + ", info:" + info); 2904 } 2905 return new ComponentName(packageName, info.serviceInfo.name); 2906 } 2907 if (DEBUG_EPHEMERAL) { 2908 Slog.v(TAG, "Ephemeral resolver NOT found"); 2909 } 2910 return null; 2911 } 2912 2913 private @Nullable ComponentName getEphemeralInstallerLPr() { 2914 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2915 intent.addCategory(Intent.CATEGORY_DEFAULT); 2916 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2917 2918 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2919 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2920 UserHandle.USER_SYSTEM); 2921 if (matches.size() == 0) { 2922 return null; 2923 } else if (matches.size() == 1) { 2924 return matches.get(0).getComponentInfo().getComponentName(); 2925 } else { 2926 throw new RuntimeException( 2927 "There must be at most one ephemeral installer; found " + matches); 2928 } 2929 } 2930 2931 private void primeDomainVerificationsLPw(int userId) { 2932 if (DEBUG_DOMAIN_VERIFICATION) { 2933 Slog.d(TAG, "Priming domain verifications in user " + userId); 2934 } 2935 2936 SystemConfig systemConfig = SystemConfig.getInstance(); 2937 ArraySet<String> packages = systemConfig.getLinkedApps(); 2938 ArraySet<String> domains = new ArraySet<String>(); 2939 2940 for (String packageName : packages) { 2941 PackageParser.Package pkg = mPackages.get(packageName); 2942 if (pkg != null) { 2943 if (!pkg.isSystemApp()) { 2944 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2945 continue; 2946 } 2947 2948 domains.clear(); 2949 for (PackageParser.Activity a : pkg.activities) { 2950 for (ActivityIntentInfo filter : a.intents) { 2951 if (hasValidDomains(filter)) { 2952 domains.addAll(filter.getHostsList()); 2953 } 2954 } 2955 } 2956 2957 if (domains.size() > 0) { 2958 if (DEBUG_DOMAIN_VERIFICATION) { 2959 Slog.v(TAG, " + " + packageName); 2960 } 2961 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2962 // state w.r.t. the formal app-linkage "no verification attempted" state; 2963 // and then 'always' in the per-user state actually used for intent resolution. 2964 final IntentFilterVerificationInfo ivi; 2965 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2966 new ArrayList<String>(domains)); 2967 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2968 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2969 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2970 } else { 2971 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2972 + "' does not handle web links"); 2973 } 2974 } else { 2975 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2976 } 2977 } 2978 2979 scheduleWritePackageRestrictionsLocked(userId); 2980 scheduleWriteSettingsLocked(); 2981 } 2982 2983 private void applyFactoryDefaultBrowserLPw(int userId) { 2984 // The default browser app's package name is stored in a string resource, 2985 // with a product-specific overlay used for vendor customization. 2986 String browserPkg = mContext.getResources().getString( 2987 com.android.internal.R.string.default_browser); 2988 if (!TextUtils.isEmpty(browserPkg)) { 2989 // non-empty string => required to be a known package 2990 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2991 if (ps == null) { 2992 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2993 browserPkg = null; 2994 } else { 2995 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2996 } 2997 } 2998 2999 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3000 // default. If there's more than one, just leave everything alone. 3001 if (browserPkg == null) { 3002 calculateDefaultBrowserLPw(userId); 3003 } 3004 } 3005 3006 private void calculateDefaultBrowserLPw(int userId) { 3007 List<String> allBrowsers = resolveAllBrowserApps(userId); 3008 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3009 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3010 } 3011 3012 private List<String> resolveAllBrowserApps(int userId) { 3013 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3014 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3015 PackageManager.MATCH_ALL, userId); 3016 3017 final int count = list.size(); 3018 List<String> result = new ArrayList<String>(count); 3019 for (int i=0; i<count; i++) { 3020 ResolveInfo info = list.get(i); 3021 if (info.activityInfo == null 3022 || !info.handleAllWebDataURI 3023 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3024 || result.contains(info.activityInfo.packageName)) { 3025 continue; 3026 } 3027 result.add(info.activityInfo.packageName); 3028 } 3029 3030 return result; 3031 } 3032 3033 private boolean packageIsBrowser(String packageName, int userId) { 3034 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3035 PackageManager.MATCH_ALL, userId); 3036 final int N = list.size(); 3037 for (int i = 0; i < N; i++) { 3038 ResolveInfo info = list.get(i); 3039 if (packageName.equals(info.activityInfo.packageName)) { 3040 return true; 3041 } 3042 } 3043 return false; 3044 } 3045 3046 private void checkDefaultBrowser() { 3047 final int myUserId = UserHandle.myUserId(); 3048 final String packageName = getDefaultBrowserPackageName(myUserId); 3049 if (packageName != null) { 3050 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3051 if (info == null) { 3052 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3053 synchronized (mPackages) { 3054 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3055 } 3056 } 3057 } 3058 } 3059 3060 @Override 3061 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3062 throws RemoteException { 3063 try { 3064 return super.onTransact(code, data, reply, flags); 3065 } catch (RuntimeException e) { 3066 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3067 Slog.wtf(TAG, "Package Manager Crash", e); 3068 } 3069 throw e; 3070 } 3071 } 3072 3073 static int[] appendInts(int[] cur, int[] add) { 3074 if (add == null) return cur; 3075 if (cur == null) return add; 3076 final int N = add.length; 3077 for (int i=0; i<N; i++) { 3078 cur = appendInt(cur, add[i]); 3079 } 3080 return cur; 3081 } 3082 3083 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3084 if (!sUserManager.exists(userId)) return null; 3085 if (ps == null) { 3086 return null; 3087 } 3088 final PackageParser.Package p = ps.pkg; 3089 if (p == null) { 3090 return null; 3091 } 3092 3093 final PermissionsState permissionsState = ps.getPermissionsState(); 3094 3095 final int[] gids = permissionsState.computeGids(userId); 3096 final Set<String> permissions = permissionsState.getPermissions(userId); 3097 final PackageUserState state = ps.readUserState(userId); 3098 3099 return PackageParser.generatePackageInfo(p, gids, flags, 3100 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3101 } 3102 3103 @Override 3104 public void checkPackageStartable(String packageName, int userId) { 3105 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3106 3107 synchronized (mPackages) { 3108 final PackageSetting ps = mSettings.mPackages.get(packageName); 3109 if (ps == null) { 3110 throw new SecurityException("Package " + packageName + " was not found!"); 3111 } 3112 3113 if (!ps.getInstalled(userId)) { 3114 throw new SecurityException( 3115 "Package " + packageName + " was not installed for user " + userId + "!"); 3116 } 3117 3118 if (mSafeMode && !ps.isSystem()) { 3119 throw new SecurityException("Package " + packageName + " not a system app!"); 3120 } 3121 3122 if (mFrozenPackages.contains(packageName)) { 3123 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3124 } 3125 3126 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3127 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3128 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3129 } 3130 } 3131 } 3132 3133 @Override 3134 public boolean isPackageAvailable(String packageName, int userId) { 3135 if (!sUserManager.exists(userId)) return false; 3136 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3137 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3138 synchronized (mPackages) { 3139 PackageParser.Package p = mPackages.get(packageName); 3140 if (p != null) { 3141 final PackageSetting ps = (PackageSetting) p.mExtras; 3142 if (ps != null) { 3143 final PackageUserState state = ps.readUserState(userId); 3144 if (state != null) { 3145 return PackageParser.isAvailable(state); 3146 } 3147 } 3148 } 3149 } 3150 return false; 3151 } 3152 3153 @Override 3154 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3155 if (!sUserManager.exists(userId)) return null; 3156 flags = updateFlagsForPackage(flags, userId, packageName); 3157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3158 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3159 // reader 3160 synchronized (mPackages) { 3161 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3162 PackageParser.Package p = null; 3163 if (matchFactoryOnly) { 3164 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3165 if (ps != null) { 3166 return generatePackageInfo(ps, flags, userId); 3167 } 3168 } 3169 if (p == null) { 3170 p = mPackages.get(packageName); 3171 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3172 return null; 3173 } 3174 } 3175 if (DEBUG_PACKAGE_INFO) 3176 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3177 if (p != null) { 3178 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3179 } 3180 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3181 final PackageSetting ps = mSettings.mPackages.get(packageName); 3182 return generatePackageInfo(ps, flags, userId); 3183 } 3184 } 3185 return null; 3186 } 3187 3188 @Override 3189 public String[] currentToCanonicalPackageNames(String[] names) { 3190 String[] out = new String[names.length]; 3191 // reader 3192 synchronized (mPackages) { 3193 for (int i=names.length-1; i>=0; i--) { 3194 PackageSetting ps = mSettings.mPackages.get(names[i]); 3195 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3196 } 3197 } 3198 return out; 3199 } 3200 3201 @Override 3202 public String[] canonicalToCurrentPackageNames(String[] names) { 3203 String[] out = new String[names.length]; 3204 // reader 3205 synchronized (mPackages) { 3206 for (int i=names.length-1; i>=0; i--) { 3207 String cur = mSettings.mRenamedPackages.get(names[i]); 3208 out[i] = cur != null ? cur : names[i]; 3209 } 3210 } 3211 return out; 3212 } 3213 3214 @Override 3215 public int getPackageUid(String packageName, int flags, int userId) { 3216 if (!sUserManager.exists(userId)) return -1; 3217 flags = updateFlagsForPackage(flags, userId, packageName); 3218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3219 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3220 3221 // reader 3222 synchronized (mPackages) { 3223 final PackageParser.Package p = mPackages.get(packageName); 3224 if (p != null && p.isMatch(flags)) { 3225 return UserHandle.getUid(userId, p.applicationInfo.uid); 3226 } 3227 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3228 final PackageSetting ps = mSettings.mPackages.get(packageName); 3229 if (ps != null && ps.isMatch(flags)) { 3230 return UserHandle.getUid(userId, ps.appId); 3231 } 3232 } 3233 } 3234 3235 return -1; 3236 } 3237 3238 @Override 3239 public int[] getPackageGids(String packageName, int flags, int userId) { 3240 if (!sUserManager.exists(userId)) return null; 3241 flags = updateFlagsForPackage(flags, userId, packageName); 3242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3243 false /* requireFullPermission */, false /* checkShell */, 3244 "getPackageGids"); 3245 3246 // reader 3247 synchronized (mPackages) { 3248 final PackageParser.Package p = mPackages.get(packageName); 3249 if (p != null && p.isMatch(flags)) { 3250 PackageSetting ps = (PackageSetting) p.mExtras; 3251 return ps.getPermissionsState().computeGids(userId); 3252 } 3253 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3254 final PackageSetting ps = mSettings.mPackages.get(packageName); 3255 if (ps != null && ps.isMatch(flags)) { 3256 return ps.getPermissionsState().computeGids(userId); 3257 } 3258 } 3259 } 3260 3261 return null; 3262 } 3263 3264 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3265 if (bp.perm != null) { 3266 return PackageParser.generatePermissionInfo(bp.perm, flags); 3267 } 3268 PermissionInfo pi = new PermissionInfo(); 3269 pi.name = bp.name; 3270 pi.packageName = bp.sourcePackage; 3271 pi.nonLocalizedLabel = bp.name; 3272 pi.protectionLevel = bp.protectionLevel; 3273 return pi; 3274 } 3275 3276 @Override 3277 public PermissionInfo getPermissionInfo(String name, int flags) { 3278 // reader 3279 synchronized (mPackages) { 3280 final BasePermission p = mSettings.mPermissions.get(name); 3281 if (p != null) { 3282 return generatePermissionInfo(p, flags); 3283 } 3284 return null; 3285 } 3286 } 3287 3288 @Override 3289 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3290 int flags) { 3291 // reader 3292 synchronized (mPackages) { 3293 if (group != null && !mPermissionGroups.containsKey(group)) { 3294 // This is thrown as NameNotFoundException 3295 return null; 3296 } 3297 3298 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3299 for (BasePermission p : mSettings.mPermissions.values()) { 3300 if (group == null) { 3301 if (p.perm == null || p.perm.info.group == null) { 3302 out.add(generatePermissionInfo(p, flags)); 3303 } 3304 } else { 3305 if (p.perm != null && group.equals(p.perm.info.group)) { 3306 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3307 } 3308 } 3309 } 3310 return new ParceledListSlice<>(out); 3311 } 3312 } 3313 3314 @Override 3315 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3316 // reader 3317 synchronized (mPackages) { 3318 return PackageParser.generatePermissionGroupInfo( 3319 mPermissionGroups.get(name), flags); 3320 } 3321 } 3322 3323 @Override 3324 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3325 // reader 3326 synchronized (mPackages) { 3327 final int N = mPermissionGroups.size(); 3328 ArrayList<PermissionGroupInfo> out 3329 = new ArrayList<PermissionGroupInfo>(N); 3330 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3331 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3332 } 3333 return new ParceledListSlice<>(out); 3334 } 3335 } 3336 3337 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3338 int userId) { 3339 if (!sUserManager.exists(userId)) return null; 3340 PackageSetting ps = mSettings.mPackages.get(packageName); 3341 if (ps != null) { 3342 if (ps.pkg == null) { 3343 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3344 if (pInfo != null) { 3345 return pInfo.applicationInfo; 3346 } 3347 return null; 3348 } 3349 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3350 ps.readUserState(userId), userId); 3351 } 3352 return null; 3353 } 3354 3355 @Override 3356 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3357 if (!sUserManager.exists(userId)) return null; 3358 flags = updateFlagsForApplication(flags, userId, packageName); 3359 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3360 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3361 // writer 3362 synchronized (mPackages) { 3363 PackageParser.Package p = mPackages.get(packageName); 3364 if (DEBUG_PACKAGE_INFO) Log.v( 3365 TAG, "getApplicationInfo " + packageName 3366 + ": " + p); 3367 if (p != null) { 3368 PackageSetting ps = mSettings.mPackages.get(packageName); 3369 if (ps == null) return null; 3370 // Note: isEnabledLP() does not apply here - always return info 3371 return PackageParser.generateApplicationInfo( 3372 p, flags, ps.readUserState(userId), userId); 3373 } 3374 if ("android".equals(packageName)||"system".equals(packageName)) { 3375 return mAndroidApplication; 3376 } 3377 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3378 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3379 } 3380 } 3381 return null; 3382 } 3383 3384 @Override 3385 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3386 final IPackageDataObserver observer) { 3387 mContext.enforceCallingOrSelfPermission( 3388 android.Manifest.permission.CLEAR_APP_CACHE, null); 3389 // Queue up an async operation since clearing cache may take a little while. 3390 mHandler.post(new Runnable() { 3391 public void run() { 3392 mHandler.removeCallbacks(this); 3393 boolean success = true; 3394 synchronized (mInstallLock) { 3395 try { 3396 mInstaller.freeCache(volumeUuid, freeStorageSize); 3397 } catch (InstallerException e) { 3398 Slog.w(TAG, "Couldn't clear application caches: " + e); 3399 success = false; 3400 } 3401 } 3402 if (observer != null) { 3403 try { 3404 observer.onRemoveCompleted(null, success); 3405 } catch (RemoteException e) { 3406 Slog.w(TAG, "RemoveException when invoking call back"); 3407 } 3408 } 3409 } 3410 }); 3411 } 3412 3413 @Override 3414 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3415 final IntentSender pi) { 3416 mContext.enforceCallingOrSelfPermission( 3417 android.Manifest.permission.CLEAR_APP_CACHE, null); 3418 // Queue up an async operation since clearing cache may take a little while. 3419 mHandler.post(new Runnable() { 3420 public void run() { 3421 mHandler.removeCallbacks(this); 3422 boolean success = true; 3423 synchronized (mInstallLock) { 3424 try { 3425 mInstaller.freeCache(volumeUuid, freeStorageSize); 3426 } catch (InstallerException e) { 3427 Slog.w(TAG, "Couldn't clear application caches: " + e); 3428 success = false; 3429 } 3430 } 3431 if(pi != null) { 3432 try { 3433 // Callback via pending intent 3434 int code = success ? 1 : 0; 3435 pi.sendIntent(null, code, null, 3436 null, null); 3437 } catch (SendIntentException e1) { 3438 Slog.i(TAG, "Failed to send pending intent"); 3439 } 3440 } 3441 } 3442 }); 3443 } 3444 3445 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3446 synchronized (mInstallLock) { 3447 try { 3448 mInstaller.freeCache(volumeUuid, freeStorageSize); 3449 } catch (InstallerException e) { 3450 throw new IOException("Failed to free enough space", e); 3451 } 3452 } 3453 } 3454 3455 /** 3456 * Return if the user key is currently unlocked. 3457 */ 3458 private boolean isUserKeyUnlocked(int userId) { 3459 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3460 final IMountService mount = IMountService.Stub 3461 .asInterface(ServiceManager.getService("mount")); 3462 if (mount == null) { 3463 Slog.w(TAG, "Early during boot, assuming locked"); 3464 return false; 3465 } 3466 final long token = Binder.clearCallingIdentity(); 3467 try { 3468 return mount.isUserKeyUnlocked(userId); 3469 } catch (RemoteException e) { 3470 throw e.rethrowAsRuntimeException(); 3471 } finally { 3472 Binder.restoreCallingIdentity(token); 3473 } 3474 } else { 3475 return true; 3476 } 3477 } 3478 3479 /** 3480 * Update given flags based on encryption status of current user. 3481 */ 3482 private int updateFlags(int flags, int userId) { 3483 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3484 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3485 // Caller expressed an explicit opinion about what encryption 3486 // aware/unaware components they want to see, so fall through and 3487 // give them what they want 3488 } else { 3489 // Caller expressed no opinion, so match based on user state 3490 if (isUserKeyUnlocked(userId)) { 3491 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3492 } else { 3493 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3494 } 3495 } 3496 return flags; 3497 } 3498 3499 /** 3500 * Update given flags when being used to request {@link PackageInfo}. 3501 */ 3502 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3503 boolean triaged = true; 3504 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3505 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3506 // Caller is asking for component details, so they'd better be 3507 // asking for specific encryption matching behavior, or be triaged 3508 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3509 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3510 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3511 triaged = false; 3512 } 3513 } 3514 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3515 | PackageManager.MATCH_SYSTEM_ONLY 3516 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3517 triaged = false; 3518 } 3519 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3520 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3521 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3522 } 3523 return updateFlags(flags, userId); 3524 } 3525 3526 /** 3527 * Update given flags when being used to request {@link ApplicationInfo}. 3528 */ 3529 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3530 return updateFlagsForPackage(flags, userId, cookie); 3531 } 3532 3533 /** 3534 * Update given flags when being used to request {@link ComponentInfo}. 3535 */ 3536 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3537 if (cookie instanceof Intent) { 3538 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3539 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3540 } 3541 } 3542 3543 boolean triaged = true; 3544 // Caller is asking for component details, so they'd better be 3545 // asking for specific encryption matching behavior, or be triaged 3546 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3547 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3548 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3549 triaged = false; 3550 } 3551 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3552 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3553 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3554 } 3555 3556 return updateFlags(flags, userId); 3557 } 3558 3559 /** 3560 * Update given flags when being used to request {@link ResolveInfo}. 3561 */ 3562 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3563 // Safe mode means we shouldn't match any third-party components 3564 if (mSafeMode) { 3565 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3566 } 3567 3568 return updateFlagsForComponent(flags, userId, cookie); 3569 } 3570 3571 @Override 3572 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3573 if (!sUserManager.exists(userId)) return null; 3574 flags = updateFlagsForComponent(flags, userId, component); 3575 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3576 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3577 synchronized (mPackages) { 3578 PackageParser.Activity a = mActivities.mActivities.get(component); 3579 3580 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3581 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3582 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3583 if (ps == null) return null; 3584 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3585 userId); 3586 } 3587 if (mResolveComponentName.equals(component)) { 3588 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3589 new PackageUserState(), userId); 3590 } 3591 } 3592 return null; 3593 } 3594 3595 @Override 3596 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3597 String resolvedType) { 3598 synchronized (mPackages) { 3599 if (component.equals(mResolveComponentName)) { 3600 // The resolver supports EVERYTHING! 3601 return true; 3602 } 3603 PackageParser.Activity a = mActivities.mActivities.get(component); 3604 if (a == null) { 3605 return false; 3606 } 3607 for (int i=0; i<a.intents.size(); i++) { 3608 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3609 intent.getData(), intent.getCategories(), TAG) >= 0) { 3610 return true; 3611 } 3612 } 3613 return false; 3614 } 3615 } 3616 3617 @Override 3618 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3619 if (!sUserManager.exists(userId)) return null; 3620 flags = updateFlagsForComponent(flags, userId, component); 3621 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3622 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3623 synchronized (mPackages) { 3624 PackageParser.Activity a = mReceivers.mActivities.get(component); 3625 if (DEBUG_PACKAGE_INFO) Log.v( 3626 TAG, "getReceiverInfo " + component + ": " + a); 3627 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3628 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3629 if (ps == null) return null; 3630 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3631 userId); 3632 } 3633 } 3634 return null; 3635 } 3636 3637 @Override 3638 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3639 if (!sUserManager.exists(userId)) return null; 3640 flags = updateFlagsForComponent(flags, userId, component); 3641 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3642 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3643 synchronized (mPackages) { 3644 PackageParser.Service s = mServices.mServices.get(component); 3645 if (DEBUG_PACKAGE_INFO) Log.v( 3646 TAG, "getServiceInfo " + component + ": " + s); 3647 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3648 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3649 if (ps == null) return null; 3650 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3651 userId); 3652 } 3653 } 3654 return null; 3655 } 3656 3657 @Override 3658 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3659 if (!sUserManager.exists(userId)) return null; 3660 flags = updateFlagsForComponent(flags, userId, component); 3661 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3662 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3663 synchronized (mPackages) { 3664 PackageParser.Provider p = mProviders.mProviders.get(component); 3665 if (DEBUG_PACKAGE_INFO) Log.v( 3666 TAG, "getProviderInfo " + component + ": " + p); 3667 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3668 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3669 if (ps == null) return null; 3670 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3671 userId); 3672 } 3673 } 3674 return null; 3675 } 3676 3677 @Override 3678 public String[] getSystemSharedLibraryNames() { 3679 Set<String> libSet; 3680 synchronized (mPackages) { 3681 libSet = mSharedLibraries.keySet(); 3682 int size = libSet.size(); 3683 if (size > 0) { 3684 String[] libs = new String[size]; 3685 libSet.toArray(libs); 3686 return libs; 3687 } 3688 } 3689 return null; 3690 } 3691 3692 @Override 3693 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3694 synchronized (mPackages) { 3695 return mServicesSystemSharedLibraryPackageName; 3696 } 3697 } 3698 3699 @Override 3700 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3701 synchronized (mPackages) { 3702 return mSharedSystemSharedLibraryPackageName; 3703 } 3704 } 3705 3706 @Override 3707 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3708 synchronized (mPackages) { 3709 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3710 3711 final FeatureInfo fi = new FeatureInfo(); 3712 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3713 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3714 res.add(fi); 3715 3716 return new ParceledListSlice<>(res); 3717 } 3718 } 3719 3720 @Override 3721 public boolean hasSystemFeature(String name, int version) { 3722 synchronized (mPackages) { 3723 final FeatureInfo feat = mAvailableFeatures.get(name); 3724 if (feat == null) { 3725 return false; 3726 } else { 3727 return feat.version >= version; 3728 } 3729 } 3730 } 3731 3732 @Override 3733 public int checkPermission(String permName, String pkgName, int userId) { 3734 if (!sUserManager.exists(userId)) { 3735 return PackageManager.PERMISSION_DENIED; 3736 } 3737 3738 synchronized (mPackages) { 3739 final PackageParser.Package p = mPackages.get(pkgName); 3740 if (p != null && p.mExtras != null) { 3741 final PackageSetting ps = (PackageSetting) p.mExtras; 3742 final PermissionsState permissionsState = ps.getPermissionsState(); 3743 if (permissionsState.hasPermission(permName, userId)) { 3744 return PackageManager.PERMISSION_GRANTED; 3745 } 3746 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3747 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3748 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3749 return PackageManager.PERMISSION_GRANTED; 3750 } 3751 } 3752 } 3753 3754 return PackageManager.PERMISSION_DENIED; 3755 } 3756 3757 @Override 3758 public int checkUidPermission(String permName, int uid) { 3759 final int userId = UserHandle.getUserId(uid); 3760 3761 if (!sUserManager.exists(userId)) { 3762 return PackageManager.PERMISSION_DENIED; 3763 } 3764 3765 synchronized (mPackages) { 3766 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3767 if (obj != null) { 3768 final SettingBase ps = (SettingBase) obj; 3769 final PermissionsState permissionsState = ps.getPermissionsState(); 3770 if (permissionsState.hasPermission(permName, userId)) { 3771 return PackageManager.PERMISSION_GRANTED; 3772 } 3773 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3774 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3775 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3776 return PackageManager.PERMISSION_GRANTED; 3777 } 3778 } else { 3779 ArraySet<String> perms = mSystemPermissions.get(uid); 3780 if (perms != null) { 3781 if (perms.contains(permName)) { 3782 return PackageManager.PERMISSION_GRANTED; 3783 } 3784 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3785 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3786 return PackageManager.PERMISSION_GRANTED; 3787 } 3788 } 3789 } 3790 } 3791 3792 return PackageManager.PERMISSION_DENIED; 3793 } 3794 3795 @Override 3796 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3797 if (UserHandle.getCallingUserId() != userId) { 3798 mContext.enforceCallingPermission( 3799 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3800 "isPermissionRevokedByPolicy for user " + userId); 3801 } 3802 3803 if (checkPermission(permission, packageName, userId) 3804 == PackageManager.PERMISSION_GRANTED) { 3805 return false; 3806 } 3807 3808 final long identity = Binder.clearCallingIdentity(); 3809 try { 3810 final int flags = getPermissionFlags(permission, packageName, userId); 3811 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3812 } finally { 3813 Binder.restoreCallingIdentity(identity); 3814 } 3815 } 3816 3817 @Override 3818 public String getPermissionControllerPackageName() { 3819 synchronized (mPackages) { 3820 return mRequiredInstallerPackage; 3821 } 3822 } 3823 3824 /** 3825 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3826 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3827 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3828 * @param message the message to log on security exception 3829 */ 3830 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3831 boolean checkShell, String message) { 3832 if (userId < 0) { 3833 throw new IllegalArgumentException("Invalid userId " + userId); 3834 } 3835 if (checkShell) { 3836 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3837 } 3838 if (userId == UserHandle.getUserId(callingUid)) return; 3839 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3840 if (requireFullPermission) { 3841 mContext.enforceCallingOrSelfPermission( 3842 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3843 } else { 3844 try { 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3847 } catch (SecurityException se) { 3848 mContext.enforceCallingOrSelfPermission( 3849 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3850 } 3851 } 3852 } 3853 } 3854 3855 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3856 if (callingUid == Process.SHELL_UID) { 3857 if (userHandle >= 0 3858 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3859 throw new SecurityException("Shell does not have permission to access user " 3860 + userHandle); 3861 } else if (userHandle < 0) { 3862 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3863 + Debug.getCallers(3)); 3864 } 3865 } 3866 } 3867 3868 private BasePermission findPermissionTreeLP(String permName) { 3869 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3870 if (permName.startsWith(bp.name) && 3871 permName.length() > bp.name.length() && 3872 permName.charAt(bp.name.length()) == '.') { 3873 return bp; 3874 } 3875 } 3876 return null; 3877 } 3878 3879 private BasePermission checkPermissionTreeLP(String permName) { 3880 if (permName != null) { 3881 BasePermission bp = findPermissionTreeLP(permName); 3882 if (bp != null) { 3883 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3884 return bp; 3885 } 3886 throw new SecurityException("Calling uid " 3887 + Binder.getCallingUid() 3888 + " is not allowed to add to permission tree " 3889 + bp.name + " owned by uid " + bp.uid); 3890 } 3891 } 3892 throw new SecurityException("No permission tree found for " + permName); 3893 } 3894 3895 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3896 if (s1 == null) { 3897 return s2 == null; 3898 } 3899 if (s2 == null) { 3900 return false; 3901 } 3902 if (s1.getClass() != s2.getClass()) { 3903 return false; 3904 } 3905 return s1.equals(s2); 3906 } 3907 3908 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3909 if (pi1.icon != pi2.icon) return false; 3910 if (pi1.logo != pi2.logo) return false; 3911 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3912 if (!compareStrings(pi1.name, pi2.name)) return false; 3913 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3914 // We'll take care of setting this one. 3915 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3916 // These are not currently stored in settings. 3917 //if (!compareStrings(pi1.group, pi2.group)) return false; 3918 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3919 //if (pi1.labelRes != pi2.labelRes) return false; 3920 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3921 return true; 3922 } 3923 3924 int permissionInfoFootprint(PermissionInfo info) { 3925 int size = info.name.length(); 3926 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3927 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3928 return size; 3929 } 3930 3931 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3932 int size = 0; 3933 for (BasePermission perm : mSettings.mPermissions.values()) { 3934 if (perm.uid == tree.uid) { 3935 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3936 } 3937 } 3938 return size; 3939 } 3940 3941 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3942 // We calculate the max size of permissions defined by this uid and throw 3943 // if that plus the size of 'info' would exceed our stated maximum. 3944 if (tree.uid != Process.SYSTEM_UID) { 3945 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3946 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3947 throw new SecurityException("Permission tree size cap exceeded"); 3948 } 3949 } 3950 } 3951 3952 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3953 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3954 throw new SecurityException("Label must be specified in permission"); 3955 } 3956 BasePermission tree = checkPermissionTreeLP(info.name); 3957 BasePermission bp = mSettings.mPermissions.get(info.name); 3958 boolean added = bp == null; 3959 boolean changed = true; 3960 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3961 if (added) { 3962 enforcePermissionCapLocked(info, tree); 3963 bp = new BasePermission(info.name, tree.sourcePackage, 3964 BasePermission.TYPE_DYNAMIC); 3965 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3966 throw new SecurityException( 3967 "Not allowed to modify non-dynamic permission " 3968 + info.name); 3969 } else { 3970 if (bp.protectionLevel == fixedLevel 3971 && bp.perm.owner.equals(tree.perm.owner) 3972 && bp.uid == tree.uid 3973 && comparePermissionInfos(bp.perm.info, info)) { 3974 changed = false; 3975 } 3976 } 3977 bp.protectionLevel = fixedLevel; 3978 info = new PermissionInfo(info); 3979 info.protectionLevel = fixedLevel; 3980 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3981 bp.perm.info.packageName = tree.perm.info.packageName; 3982 bp.uid = tree.uid; 3983 if (added) { 3984 mSettings.mPermissions.put(info.name, bp); 3985 } 3986 if (changed) { 3987 if (!async) { 3988 mSettings.writeLPr(); 3989 } else { 3990 scheduleWriteSettingsLocked(); 3991 } 3992 } 3993 return added; 3994 } 3995 3996 @Override 3997 public boolean addPermission(PermissionInfo info) { 3998 synchronized (mPackages) { 3999 return addPermissionLocked(info, false); 4000 } 4001 } 4002 4003 @Override 4004 public boolean addPermissionAsync(PermissionInfo info) { 4005 synchronized (mPackages) { 4006 return addPermissionLocked(info, true); 4007 } 4008 } 4009 4010 @Override 4011 public void removePermission(String name) { 4012 synchronized (mPackages) { 4013 checkPermissionTreeLP(name); 4014 BasePermission bp = mSettings.mPermissions.get(name); 4015 if (bp != null) { 4016 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4017 throw new SecurityException( 4018 "Not allowed to modify non-dynamic permission " 4019 + name); 4020 } 4021 mSettings.mPermissions.remove(name); 4022 mSettings.writeLPr(); 4023 } 4024 } 4025 } 4026 4027 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4028 BasePermission bp) { 4029 int index = pkg.requestedPermissions.indexOf(bp.name); 4030 if (index == -1) { 4031 throw new SecurityException("Package " + pkg.packageName 4032 + " has not requested permission " + bp.name); 4033 } 4034 if (!bp.isRuntime() && !bp.isDevelopment()) { 4035 throw new SecurityException("Permission " + bp.name 4036 + " is not a changeable permission type"); 4037 } 4038 } 4039 4040 @Override 4041 public void grantRuntimePermission(String packageName, String name, final int userId) { 4042 if (!sUserManager.exists(userId)) { 4043 Log.e(TAG, "No such user:" + userId); 4044 return; 4045 } 4046 4047 mContext.enforceCallingOrSelfPermission( 4048 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4049 "grantRuntimePermission"); 4050 4051 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4052 true /* requireFullPermission */, true /* checkShell */, 4053 "grantRuntimePermission"); 4054 4055 final int uid; 4056 final SettingBase sb; 4057 4058 synchronized (mPackages) { 4059 final PackageParser.Package pkg = mPackages.get(packageName); 4060 if (pkg == null) { 4061 throw new IllegalArgumentException("Unknown package: " + packageName); 4062 } 4063 4064 final BasePermission bp = mSettings.mPermissions.get(name); 4065 if (bp == null) { 4066 throw new IllegalArgumentException("Unknown permission: " + name); 4067 } 4068 4069 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4070 4071 // If a permission review is required for legacy apps we represent 4072 // their permissions as always granted runtime ones since we need 4073 // to keep the review required permission flag per user while an 4074 // install permission's state is shared across all users. 4075 if (Build.PERMISSIONS_REVIEW_REQUIRED 4076 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4077 && bp.isRuntime()) { 4078 return; 4079 } 4080 4081 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4082 sb = (SettingBase) pkg.mExtras; 4083 if (sb == null) { 4084 throw new IllegalArgumentException("Unknown package: " + packageName); 4085 } 4086 4087 final PermissionsState permissionsState = sb.getPermissionsState(); 4088 4089 final int flags = permissionsState.getPermissionFlags(name, userId); 4090 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4091 throw new SecurityException("Cannot grant system fixed permission " 4092 + name + " for package " + packageName); 4093 } 4094 4095 if (bp.isDevelopment()) { 4096 // Development permissions must be handled specially, since they are not 4097 // normal runtime permissions. For now they apply to all users. 4098 if (permissionsState.grantInstallPermission(bp) != 4099 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4100 scheduleWriteSettingsLocked(); 4101 } 4102 return; 4103 } 4104 4105 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4106 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4107 return; 4108 } 4109 4110 final int result = permissionsState.grantRuntimePermission(bp, userId); 4111 switch (result) { 4112 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4113 return; 4114 } 4115 4116 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4117 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4118 mHandler.post(new Runnable() { 4119 @Override 4120 public void run() { 4121 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4122 } 4123 }); 4124 } 4125 break; 4126 } 4127 4128 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4129 4130 // Not critical if that is lost - app has to request again. 4131 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4132 } 4133 4134 // Only need to do this if user is initialized. Otherwise it's a new user 4135 // and there are no processes running as the user yet and there's no need 4136 // to make an expensive call to remount processes for the changed permissions. 4137 if (READ_EXTERNAL_STORAGE.equals(name) 4138 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4139 final long token = Binder.clearCallingIdentity(); 4140 try { 4141 if (sUserManager.isInitialized(userId)) { 4142 MountServiceInternal mountServiceInternal = LocalServices.getService( 4143 MountServiceInternal.class); 4144 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4145 } 4146 } finally { 4147 Binder.restoreCallingIdentity(token); 4148 } 4149 } 4150 } 4151 4152 @Override 4153 public void revokeRuntimePermission(String packageName, String name, int userId) { 4154 if (!sUserManager.exists(userId)) { 4155 Log.e(TAG, "No such user:" + userId); 4156 return; 4157 } 4158 4159 mContext.enforceCallingOrSelfPermission( 4160 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4161 "revokeRuntimePermission"); 4162 4163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4164 true /* requireFullPermission */, true /* checkShell */, 4165 "revokeRuntimePermission"); 4166 4167 final int appId; 4168 4169 synchronized (mPackages) { 4170 final PackageParser.Package pkg = mPackages.get(packageName); 4171 if (pkg == null) { 4172 throw new IllegalArgumentException("Unknown package: " + packageName); 4173 } 4174 4175 final BasePermission bp = mSettings.mPermissions.get(name); 4176 if (bp == null) { 4177 throw new IllegalArgumentException("Unknown permission: " + name); 4178 } 4179 4180 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4181 4182 // If a permission review is required for legacy apps we represent 4183 // their permissions as always granted runtime ones since we need 4184 // to keep the review required permission flag per user while an 4185 // install permission's state is shared across all users. 4186 if (Build.PERMISSIONS_REVIEW_REQUIRED 4187 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4188 && bp.isRuntime()) { 4189 return; 4190 } 4191 4192 SettingBase sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 final int flags = permissionsState.getPermissionFlags(name, userId); 4200 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4201 throw new SecurityException("Cannot revoke system fixed permission " 4202 + name + " for package " + packageName); 4203 } 4204 4205 if (bp.isDevelopment()) { 4206 // Development permissions must be handled specially, since they are not 4207 // normal runtime permissions. For now they apply to all users. 4208 if (permissionsState.revokeInstallPermission(bp) != 4209 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4210 scheduleWriteSettingsLocked(); 4211 } 4212 return; 4213 } 4214 4215 if (permissionsState.revokeRuntimePermission(bp, userId) == 4216 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4217 return; 4218 } 4219 4220 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4221 4222 // Critical, after this call app should never have the permission. 4223 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4224 4225 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4226 } 4227 4228 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4229 } 4230 4231 @Override 4232 public void resetRuntimePermissions() { 4233 mContext.enforceCallingOrSelfPermission( 4234 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4235 "revokeRuntimePermission"); 4236 4237 int callingUid = Binder.getCallingUid(); 4238 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4239 mContext.enforceCallingOrSelfPermission( 4240 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4241 "resetRuntimePermissions"); 4242 } 4243 4244 synchronized (mPackages) { 4245 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4246 for (int userId : UserManagerService.getInstance().getUserIds()) { 4247 final int packageCount = mPackages.size(); 4248 for (int i = 0; i < packageCount; i++) { 4249 PackageParser.Package pkg = mPackages.valueAt(i); 4250 if (!(pkg.mExtras instanceof PackageSetting)) { 4251 continue; 4252 } 4253 PackageSetting ps = (PackageSetting) pkg.mExtras; 4254 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4255 } 4256 } 4257 } 4258 } 4259 4260 @Override 4261 public int getPermissionFlags(String name, String packageName, int userId) { 4262 if (!sUserManager.exists(userId)) { 4263 return 0; 4264 } 4265 4266 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4267 4268 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4269 true /* requireFullPermission */, false /* checkShell */, 4270 "getPermissionFlags"); 4271 4272 synchronized (mPackages) { 4273 final PackageParser.Package pkg = mPackages.get(packageName); 4274 if (pkg == null) { 4275 throw new IllegalArgumentException("Unknown package: " + packageName); 4276 } 4277 4278 final BasePermission bp = mSettings.mPermissions.get(name); 4279 if (bp == null) { 4280 throw new IllegalArgumentException("Unknown permission: " + name); 4281 } 4282 4283 SettingBase sb = (SettingBase) pkg.mExtras; 4284 if (sb == null) { 4285 throw new IllegalArgumentException("Unknown package: " + packageName); 4286 } 4287 4288 PermissionsState permissionsState = sb.getPermissionsState(); 4289 return permissionsState.getPermissionFlags(name, userId); 4290 } 4291 } 4292 4293 @Override 4294 public void updatePermissionFlags(String name, String packageName, int flagMask, 4295 int flagValues, int userId) { 4296 if (!sUserManager.exists(userId)) { 4297 return; 4298 } 4299 4300 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4301 4302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4303 true /* requireFullPermission */, true /* checkShell */, 4304 "updatePermissionFlags"); 4305 4306 // Only the system can change these flags and nothing else. 4307 if (getCallingUid() != Process.SYSTEM_UID) { 4308 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4309 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4310 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4311 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4312 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4313 } 4314 4315 synchronized (mPackages) { 4316 final PackageParser.Package pkg = mPackages.get(packageName); 4317 if (pkg == null) { 4318 throw new IllegalArgumentException("Unknown package: " + packageName); 4319 } 4320 4321 final BasePermission bp = mSettings.mPermissions.get(name); 4322 if (bp == null) { 4323 throw new IllegalArgumentException("Unknown permission: " + name); 4324 } 4325 4326 SettingBase sb = (SettingBase) pkg.mExtras; 4327 if (sb == null) { 4328 throw new IllegalArgumentException("Unknown package: " + packageName); 4329 } 4330 4331 PermissionsState permissionsState = sb.getPermissionsState(); 4332 4333 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4334 4335 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4336 // Install and runtime permissions are stored in different places, 4337 // so figure out what permission changed and persist the change. 4338 if (permissionsState.getInstallPermissionState(name) != null) { 4339 scheduleWriteSettingsLocked(); 4340 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4341 || hadState) { 4342 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4343 } 4344 } 4345 } 4346 } 4347 4348 /** 4349 * Update the permission flags for all packages and runtime permissions of a user in order 4350 * to allow device or profile owner to remove POLICY_FIXED. 4351 */ 4352 @Override 4353 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4354 if (!sUserManager.exists(userId)) { 4355 return; 4356 } 4357 4358 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4359 4360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4361 true /* requireFullPermission */, true /* checkShell */, 4362 "updatePermissionFlagsForAllApps"); 4363 4364 // Only the system can change system fixed flags. 4365 if (getCallingUid() != Process.SYSTEM_UID) { 4366 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4367 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4368 } 4369 4370 synchronized (mPackages) { 4371 boolean changed = false; 4372 final int packageCount = mPackages.size(); 4373 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4374 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4375 SettingBase sb = (SettingBase) pkg.mExtras; 4376 if (sb == null) { 4377 continue; 4378 } 4379 PermissionsState permissionsState = sb.getPermissionsState(); 4380 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4381 userId, flagMask, flagValues); 4382 } 4383 if (changed) { 4384 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4385 } 4386 } 4387 } 4388 4389 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4390 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4391 != PackageManager.PERMISSION_GRANTED 4392 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4393 != PackageManager.PERMISSION_GRANTED) { 4394 throw new SecurityException(message + " requires " 4395 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4396 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4397 } 4398 } 4399 4400 @Override 4401 public boolean shouldShowRequestPermissionRationale(String permissionName, 4402 String packageName, int userId) { 4403 if (UserHandle.getCallingUserId() != userId) { 4404 mContext.enforceCallingPermission( 4405 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4406 "canShowRequestPermissionRationale for user " + userId); 4407 } 4408 4409 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4410 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4411 return false; 4412 } 4413 4414 if (checkPermission(permissionName, packageName, userId) 4415 == PackageManager.PERMISSION_GRANTED) { 4416 return false; 4417 } 4418 4419 final int flags; 4420 4421 final long identity = Binder.clearCallingIdentity(); 4422 try { 4423 flags = getPermissionFlags(permissionName, 4424 packageName, userId); 4425 } finally { 4426 Binder.restoreCallingIdentity(identity); 4427 } 4428 4429 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4430 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4431 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4432 4433 if ((flags & fixedFlags) != 0) { 4434 return false; 4435 } 4436 4437 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4438 } 4439 4440 @Override 4441 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4442 mContext.enforceCallingOrSelfPermission( 4443 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4444 "addOnPermissionsChangeListener"); 4445 4446 synchronized (mPackages) { 4447 mOnPermissionChangeListeners.addListenerLocked(listener); 4448 } 4449 } 4450 4451 @Override 4452 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4453 synchronized (mPackages) { 4454 mOnPermissionChangeListeners.removeListenerLocked(listener); 4455 } 4456 } 4457 4458 @Override 4459 public boolean isProtectedBroadcast(String actionName) { 4460 synchronized (mPackages) { 4461 if (mProtectedBroadcasts.contains(actionName)) { 4462 return true; 4463 } else if (actionName != null) { 4464 // TODO: remove these terrible hacks 4465 if (actionName.startsWith("android.net.netmon.lingerExpired") 4466 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4467 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4468 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4469 return true; 4470 } 4471 } 4472 } 4473 return false; 4474 } 4475 4476 @Override 4477 public int checkSignatures(String pkg1, String pkg2) { 4478 synchronized (mPackages) { 4479 final PackageParser.Package p1 = mPackages.get(pkg1); 4480 final PackageParser.Package p2 = mPackages.get(pkg2); 4481 if (p1 == null || p1.mExtras == null 4482 || p2 == null || p2.mExtras == null) { 4483 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4484 } 4485 return compareSignatures(p1.mSignatures, p2.mSignatures); 4486 } 4487 } 4488 4489 @Override 4490 public int checkUidSignatures(int uid1, int uid2) { 4491 // Map to base uids. 4492 uid1 = UserHandle.getAppId(uid1); 4493 uid2 = UserHandle.getAppId(uid2); 4494 // reader 4495 synchronized (mPackages) { 4496 Signature[] s1; 4497 Signature[] s2; 4498 Object obj = mSettings.getUserIdLPr(uid1); 4499 if (obj != null) { 4500 if (obj instanceof SharedUserSetting) { 4501 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4502 } else if (obj instanceof PackageSetting) { 4503 s1 = ((PackageSetting)obj).signatures.mSignatures; 4504 } else { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 } else { 4508 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4509 } 4510 obj = mSettings.getUserIdLPr(uid2); 4511 if (obj != null) { 4512 if (obj instanceof SharedUserSetting) { 4513 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4514 } else if (obj instanceof PackageSetting) { 4515 s2 = ((PackageSetting)obj).signatures.mSignatures; 4516 } else { 4517 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4518 } 4519 } else { 4520 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4521 } 4522 return compareSignatures(s1, s2); 4523 } 4524 } 4525 4526 /** 4527 * This method should typically only be used when granting or revoking 4528 * permissions, since the app may immediately restart after this call. 4529 * <p> 4530 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4531 * guard your work against the app being relaunched. 4532 */ 4533 private void killUid(int appId, int userId, String reason) { 4534 final long identity = Binder.clearCallingIdentity(); 4535 try { 4536 IActivityManager am = ActivityManagerNative.getDefault(); 4537 if (am != null) { 4538 try { 4539 am.killUid(appId, userId, reason); 4540 } catch (RemoteException e) { 4541 /* ignore - same process */ 4542 } 4543 } 4544 } finally { 4545 Binder.restoreCallingIdentity(identity); 4546 } 4547 } 4548 4549 /** 4550 * Compares two sets of signatures. Returns: 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4553 * <br /> 4554 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4555 * <br /> 4556 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4557 * <br /> 4558 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4559 * <br /> 4560 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4561 */ 4562 static int compareSignatures(Signature[] s1, Signature[] s2) { 4563 if (s1 == null) { 4564 return s2 == null 4565 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4566 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4567 } 4568 4569 if (s2 == null) { 4570 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4571 } 4572 4573 if (s1.length != s2.length) { 4574 return PackageManager.SIGNATURE_NO_MATCH; 4575 } 4576 4577 // Since both signature sets are of size 1, we can compare without HashSets. 4578 if (s1.length == 1) { 4579 return s1[0].equals(s2[0]) ? 4580 PackageManager.SIGNATURE_MATCH : 4581 PackageManager.SIGNATURE_NO_MATCH; 4582 } 4583 4584 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4585 for (Signature sig : s1) { 4586 set1.add(sig); 4587 } 4588 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4589 for (Signature sig : s2) { 4590 set2.add(sig); 4591 } 4592 // Make sure s2 contains all signatures in s1. 4593 if (set1.equals(set2)) { 4594 return PackageManager.SIGNATURE_MATCH; 4595 } 4596 return PackageManager.SIGNATURE_NO_MATCH; 4597 } 4598 4599 /** 4600 * If the database version for this type of package (internal storage or 4601 * external storage) is less than the version where package signatures 4602 * were updated, return true. 4603 */ 4604 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4605 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4606 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4607 } 4608 4609 /** 4610 * Used for backward compatibility to make sure any packages with 4611 * certificate chains get upgraded to the new style. {@code existingSigs} 4612 * will be in the old format (since they were stored on disk from before the 4613 * system upgrade) and {@code scannedSigs} will be in the newer format. 4614 */ 4615 private int compareSignaturesCompat(PackageSignatures existingSigs, 4616 PackageParser.Package scannedPkg) { 4617 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4618 return PackageManager.SIGNATURE_NO_MATCH; 4619 } 4620 4621 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4622 for (Signature sig : existingSigs.mSignatures) { 4623 existingSet.add(sig); 4624 } 4625 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4626 for (Signature sig : scannedPkg.mSignatures) { 4627 try { 4628 Signature[] chainSignatures = sig.getChainSignatures(); 4629 for (Signature chainSig : chainSignatures) { 4630 scannedCompatSet.add(chainSig); 4631 } 4632 } catch (CertificateEncodingException e) { 4633 scannedCompatSet.add(sig); 4634 } 4635 } 4636 /* 4637 * Make sure the expanded scanned set contains all signatures in the 4638 * existing one. 4639 */ 4640 if (scannedCompatSet.equals(existingSet)) { 4641 // Migrate the old signatures to the new scheme. 4642 existingSigs.assignSignatures(scannedPkg.mSignatures); 4643 // The new KeySets will be re-added later in the scanning process. 4644 synchronized (mPackages) { 4645 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4646 } 4647 return PackageManager.SIGNATURE_MATCH; 4648 } 4649 return PackageManager.SIGNATURE_NO_MATCH; 4650 } 4651 4652 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4653 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4654 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4655 } 4656 4657 private int compareSignaturesRecover(PackageSignatures existingSigs, 4658 PackageParser.Package scannedPkg) { 4659 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4660 return PackageManager.SIGNATURE_NO_MATCH; 4661 } 4662 4663 String msg = null; 4664 try { 4665 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4666 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4667 + scannedPkg.packageName); 4668 return PackageManager.SIGNATURE_MATCH; 4669 } 4670 } catch (CertificateException e) { 4671 msg = e.getMessage(); 4672 } 4673 4674 logCriticalInfo(Log.INFO, 4675 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4676 return PackageManager.SIGNATURE_NO_MATCH; 4677 } 4678 4679 @Override 4680 public List<String> getAllPackages() { 4681 synchronized (mPackages) { 4682 return new ArrayList<String>(mPackages.keySet()); 4683 } 4684 } 4685 4686 @Override 4687 public String[] getPackagesForUid(int uid) { 4688 uid = UserHandle.getAppId(uid); 4689 // reader 4690 synchronized (mPackages) { 4691 Object obj = mSettings.getUserIdLPr(uid); 4692 if (obj instanceof SharedUserSetting) { 4693 final SharedUserSetting sus = (SharedUserSetting) obj; 4694 final int N = sus.packages.size(); 4695 final String[] res = new String[N]; 4696 final Iterator<PackageSetting> it = sus.packages.iterator(); 4697 int i = 0; 4698 while (it.hasNext()) { 4699 res[i++] = it.next().name; 4700 } 4701 return res; 4702 } else if (obj instanceof PackageSetting) { 4703 final PackageSetting ps = (PackageSetting) obj; 4704 return new String[] { ps.name }; 4705 } 4706 } 4707 return null; 4708 } 4709 4710 @Override 4711 public String getNameForUid(int uid) { 4712 // reader 4713 synchronized (mPackages) { 4714 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4715 if (obj instanceof SharedUserSetting) { 4716 final SharedUserSetting sus = (SharedUserSetting) obj; 4717 return sus.name + ":" + sus.userId; 4718 } else if (obj instanceof PackageSetting) { 4719 final PackageSetting ps = (PackageSetting) obj; 4720 return ps.name; 4721 } 4722 } 4723 return null; 4724 } 4725 4726 @Override 4727 public int getUidForSharedUser(String sharedUserName) { 4728 if(sharedUserName == null) { 4729 return -1; 4730 } 4731 // reader 4732 synchronized (mPackages) { 4733 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4734 if (suid == null) { 4735 return -1; 4736 } 4737 return suid.userId; 4738 } 4739 } 4740 4741 @Override 4742 public int getFlagsForUid(int uid) { 4743 synchronized (mPackages) { 4744 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4745 if (obj instanceof SharedUserSetting) { 4746 final SharedUserSetting sus = (SharedUserSetting) obj; 4747 return sus.pkgFlags; 4748 } else if (obj instanceof PackageSetting) { 4749 final PackageSetting ps = (PackageSetting) obj; 4750 return ps.pkgFlags; 4751 } 4752 } 4753 return 0; 4754 } 4755 4756 @Override 4757 public int getPrivateFlagsForUid(int uid) { 4758 synchronized (mPackages) { 4759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4760 if (obj instanceof SharedUserSetting) { 4761 final SharedUserSetting sus = (SharedUserSetting) obj; 4762 return sus.pkgPrivateFlags; 4763 } else if (obj instanceof PackageSetting) { 4764 final PackageSetting ps = (PackageSetting) obj; 4765 return ps.pkgPrivateFlags; 4766 } 4767 } 4768 return 0; 4769 } 4770 4771 @Override 4772 public boolean isUidPrivileged(int uid) { 4773 uid = UserHandle.getAppId(uid); 4774 // reader 4775 synchronized (mPackages) { 4776 Object obj = mSettings.getUserIdLPr(uid); 4777 if (obj instanceof SharedUserSetting) { 4778 final SharedUserSetting sus = (SharedUserSetting) obj; 4779 final Iterator<PackageSetting> it = sus.packages.iterator(); 4780 while (it.hasNext()) { 4781 if (it.next().isPrivileged()) { 4782 return true; 4783 } 4784 } 4785 } else if (obj instanceof PackageSetting) { 4786 final PackageSetting ps = (PackageSetting) obj; 4787 return ps.isPrivileged(); 4788 } 4789 } 4790 return false; 4791 } 4792 4793 @Override 4794 public String[] getAppOpPermissionPackages(String permissionName) { 4795 synchronized (mPackages) { 4796 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4797 if (pkgs == null) { 4798 return null; 4799 } 4800 return pkgs.toArray(new String[pkgs.size()]); 4801 } 4802 } 4803 4804 @Override 4805 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4806 int flags, int userId) { 4807 try { 4808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4809 4810 if (!sUserManager.exists(userId)) return null; 4811 flags = updateFlagsForResolve(flags, userId, intent); 4812 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4813 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4814 4815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4816 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4817 flags, userId); 4818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4819 4820 final ResolveInfo bestChoice = 4821 chooseBestActivity(intent, resolvedType, flags, query, userId); 4822 4823 if (isEphemeralAllowed(intent, query, userId)) { 4824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4825 final EphemeralResolveInfo ai = 4826 getEphemeralResolveInfo(intent, resolvedType, userId); 4827 if (ai != null) { 4828 if (DEBUG_EPHEMERAL) { 4829 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4830 } 4831 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4832 bestChoice.ephemeralResolveInfo = ai; 4833 } 4834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4835 } 4836 return bestChoice; 4837 } finally { 4838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4839 } 4840 } 4841 4842 @Override 4843 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4844 IntentFilter filter, int match, ComponentName activity) { 4845 final int userId = UserHandle.getCallingUserId(); 4846 if (DEBUG_PREFERRED) { 4847 Log.v(TAG, "setLastChosenActivity intent=" + intent 4848 + " resolvedType=" + resolvedType 4849 + " flags=" + flags 4850 + " filter=" + filter 4851 + " match=" + match 4852 + " activity=" + activity); 4853 filter.dump(new PrintStreamPrinter(System.out), " "); 4854 } 4855 intent.setComponent(null); 4856 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4857 userId); 4858 // Find any earlier preferred or last chosen entries and nuke them 4859 findPreferredActivity(intent, resolvedType, 4860 flags, query, 0, false, true, false, userId); 4861 // Add the new activity as the last chosen for this filter 4862 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4863 "Setting last chosen"); 4864 } 4865 4866 @Override 4867 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4868 final int userId = UserHandle.getCallingUserId(); 4869 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4870 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4871 userId); 4872 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4873 false, false, false, userId); 4874 } 4875 4876 4877 private boolean isEphemeralAllowed( 4878 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4879 // Short circuit and return early if possible. 4880 if (DISABLE_EPHEMERAL_APPS) { 4881 return false; 4882 } 4883 final int callingUser = UserHandle.getCallingUserId(); 4884 if (callingUser != UserHandle.USER_SYSTEM) { 4885 return false; 4886 } 4887 if (mEphemeralResolverConnection == null) { 4888 return false; 4889 } 4890 if (intent.getComponent() != null) { 4891 return false; 4892 } 4893 if (intent.getPackage() != null) { 4894 return false; 4895 } 4896 final boolean isWebUri = hasWebURI(intent); 4897 if (!isWebUri) { 4898 return false; 4899 } 4900 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4901 synchronized (mPackages) { 4902 final int count = resolvedActivites.size(); 4903 for (int n = 0; n < count; n++) { 4904 ResolveInfo info = resolvedActivites.get(n); 4905 String packageName = info.activityInfo.packageName; 4906 PackageSetting ps = mSettings.mPackages.get(packageName); 4907 if (ps != null) { 4908 // Try to get the status from User settings first 4909 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4910 int status = (int) (packedStatus >> 32); 4911 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4912 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4913 if (DEBUG_EPHEMERAL) { 4914 Slog.v(TAG, "DENY ephemeral apps;" 4915 + " pkg: " + packageName + ", status: " + status); 4916 } 4917 return false; 4918 } 4919 } 4920 } 4921 } 4922 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4923 return true; 4924 } 4925 4926 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4927 int userId) { 4928 MessageDigest digest = null; 4929 try { 4930 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4931 } catch (NoSuchAlgorithmException e) { 4932 // If we can't create a digest, ignore ephemeral apps. 4933 return null; 4934 } 4935 4936 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4937 final byte[] digestBytes = digest.digest(hostBytes); 4938 int shaPrefix = 4939 digestBytes[0] << 24 4940 | digestBytes[1] << 16 4941 | digestBytes[2] << 8 4942 | digestBytes[3] << 0; 4943 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4944 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4945 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4946 // No hash prefix match; there are no ephemeral apps for this domain. 4947 return null; 4948 } 4949 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4950 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4951 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4952 continue; 4953 } 4954 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4955 // No filters; this should never happen. 4956 if (filters.isEmpty()) { 4957 continue; 4958 } 4959 // We have a domain match; resolve the filters to see if anything matches. 4960 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4961 for (int j = filters.size() - 1; j >= 0; --j) { 4962 final EphemeralResolveIntentInfo intentInfo = 4963 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4964 ephemeralResolver.addFilter(intentInfo); 4965 } 4966 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4967 intent, resolvedType, false /*defaultOnly*/, userId); 4968 if (!matchedResolveInfoList.isEmpty()) { 4969 return matchedResolveInfoList.get(0); 4970 } 4971 } 4972 // Hash or filter mis-match; no ephemeral apps for this domain. 4973 return null; 4974 } 4975 4976 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4977 int flags, List<ResolveInfo> query, int userId) { 4978 if (query != null) { 4979 final int N = query.size(); 4980 if (N == 1) { 4981 return query.get(0); 4982 } else if (N > 1) { 4983 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4984 // If there is more than one activity with the same priority, 4985 // then let the user decide between them. 4986 ResolveInfo r0 = query.get(0); 4987 ResolveInfo r1 = query.get(1); 4988 if (DEBUG_INTENT_MATCHING || debug) { 4989 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4990 + r1.activityInfo.name + "=" + r1.priority); 4991 } 4992 // If the first activity has a higher priority, or a different 4993 // default, then it is always desirable to pick it. 4994 if (r0.priority != r1.priority 4995 || r0.preferredOrder != r1.preferredOrder 4996 || r0.isDefault != r1.isDefault) { 4997 return query.get(0); 4998 } 4999 // If we have saved a preference for a preferred activity for 5000 // this Intent, use that. 5001 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5002 flags, query, r0.priority, true, false, debug, userId); 5003 if (ri != null) { 5004 return ri; 5005 } 5006 ri = new ResolveInfo(mResolveInfo); 5007 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5008 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5009 ri.activityInfo.applicationInfo = new ApplicationInfo( 5010 ri.activityInfo.applicationInfo); 5011 if (userId != 0) { 5012 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5013 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5014 } 5015 // Make sure that the resolver is displayable in car mode 5016 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5017 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5018 return ri; 5019 } 5020 } 5021 return null; 5022 } 5023 5024 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5025 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5026 final int N = query.size(); 5027 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5028 .get(userId); 5029 // Get the list of persistent preferred activities that handle the intent 5030 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5031 List<PersistentPreferredActivity> pprefs = ppir != null 5032 ? ppir.queryIntent(intent, resolvedType, 5033 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5034 : null; 5035 if (pprefs != null && pprefs.size() > 0) { 5036 final int M = pprefs.size(); 5037 for (int i=0; i<M; i++) { 5038 final PersistentPreferredActivity ppa = pprefs.get(i); 5039 if (DEBUG_PREFERRED || debug) { 5040 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5041 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5042 + "\n component=" + ppa.mComponent); 5043 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5044 } 5045 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5046 flags | MATCH_DISABLED_COMPONENTS, userId); 5047 if (DEBUG_PREFERRED || debug) { 5048 Slog.v(TAG, "Found persistent preferred activity:"); 5049 if (ai != null) { 5050 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5051 } else { 5052 Slog.v(TAG, " null"); 5053 } 5054 } 5055 if (ai == null) { 5056 // This previously registered persistent preferred activity 5057 // component is no longer known. Ignore it and do NOT remove it. 5058 continue; 5059 } 5060 for (int j=0; j<N; j++) { 5061 final ResolveInfo ri = query.get(j); 5062 if (!ri.activityInfo.applicationInfo.packageName 5063 .equals(ai.applicationInfo.packageName)) { 5064 continue; 5065 } 5066 if (!ri.activityInfo.name.equals(ai.name)) { 5067 continue; 5068 } 5069 // Found a persistent preference that can handle the intent. 5070 if (DEBUG_PREFERRED || debug) { 5071 Slog.v(TAG, "Returning persistent preferred activity: " + 5072 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5073 } 5074 return ri; 5075 } 5076 } 5077 } 5078 return null; 5079 } 5080 5081 // TODO: handle preferred activities missing while user has amnesia 5082 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5083 List<ResolveInfo> query, int priority, boolean always, 5084 boolean removeMatches, boolean debug, int userId) { 5085 if (!sUserManager.exists(userId)) return null; 5086 flags = updateFlagsForResolve(flags, userId, intent); 5087 // writer 5088 synchronized (mPackages) { 5089 if (intent.getSelector() != null) { 5090 intent = intent.getSelector(); 5091 } 5092 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5093 5094 // Try to find a matching persistent preferred activity. 5095 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5096 debug, userId); 5097 5098 // If a persistent preferred activity matched, use it. 5099 if (pri != null) { 5100 return pri; 5101 } 5102 5103 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5104 // Get the list of preferred activities that handle the intent 5105 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5106 List<PreferredActivity> prefs = pir != null 5107 ? pir.queryIntent(intent, resolvedType, 5108 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5109 : null; 5110 if (prefs != null && prefs.size() > 0) { 5111 boolean changed = false; 5112 try { 5113 // First figure out how good the original match set is. 5114 // We will only allow preferred activities that came 5115 // from the same match quality. 5116 int match = 0; 5117 5118 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5119 5120 final int N = query.size(); 5121 for (int j=0; j<N; j++) { 5122 final ResolveInfo ri = query.get(j); 5123 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5124 + ": 0x" + Integer.toHexString(match)); 5125 if (ri.match > match) { 5126 match = ri.match; 5127 } 5128 } 5129 5130 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5131 + Integer.toHexString(match)); 5132 5133 match &= IntentFilter.MATCH_CATEGORY_MASK; 5134 final int M = prefs.size(); 5135 for (int i=0; i<M; i++) { 5136 final PreferredActivity pa = prefs.get(i); 5137 if (DEBUG_PREFERRED || debug) { 5138 Slog.v(TAG, "Checking PreferredActivity ds=" 5139 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5140 + "\n component=" + pa.mPref.mComponent); 5141 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5142 } 5143 if (pa.mPref.mMatch != match) { 5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5145 + Integer.toHexString(pa.mPref.mMatch)); 5146 continue; 5147 } 5148 // If it's not an "always" type preferred activity and that's what we're 5149 // looking for, skip it. 5150 if (always && !pa.mPref.mAlways) { 5151 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5152 continue; 5153 } 5154 final ActivityInfo ai = getActivityInfo( 5155 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5156 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5157 userId); 5158 if (DEBUG_PREFERRED || debug) { 5159 Slog.v(TAG, "Found preferred activity:"); 5160 if (ai != null) { 5161 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5162 } else { 5163 Slog.v(TAG, " null"); 5164 } 5165 } 5166 if (ai == null) { 5167 // This previously registered preferred activity 5168 // component is no longer known. Most likely an update 5169 // to the app was installed and in the new version this 5170 // component no longer exists. Clean it up by removing 5171 // it from the preferred activities list, and skip it. 5172 Slog.w(TAG, "Removing dangling preferred activity: " 5173 + pa.mPref.mComponent); 5174 pir.removeFilter(pa); 5175 changed = true; 5176 continue; 5177 } 5178 for (int j=0; j<N; j++) { 5179 final ResolveInfo ri = query.get(j); 5180 if (!ri.activityInfo.applicationInfo.packageName 5181 .equals(ai.applicationInfo.packageName)) { 5182 continue; 5183 } 5184 if (!ri.activityInfo.name.equals(ai.name)) { 5185 continue; 5186 } 5187 5188 if (removeMatches) { 5189 pir.removeFilter(pa); 5190 changed = true; 5191 if (DEBUG_PREFERRED) { 5192 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5193 } 5194 break; 5195 } 5196 5197 // Okay we found a previously set preferred or last chosen app. 5198 // If the result set is different from when this 5199 // was created, we need to clear it and re-ask the 5200 // user their preference, if we're looking for an "always" type entry. 5201 if (always && !pa.mPref.sameSet(query)) { 5202 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5203 + intent + " type " + resolvedType); 5204 if (DEBUG_PREFERRED) { 5205 Slog.v(TAG, "Removing preferred activity since set changed " 5206 + pa.mPref.mComponent); 5207 } 5208 pir.removeFilter(pa); 5209 // Re-add the filter as a "last chosen" entry (!always) 5210 PreferredActivity lastChosen = new PreferredActivity( 5211 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5212 pir.addFilter(lastChosen); 5213 changed = true; 5214 return null; 5215 } 5216 5217 // Yay! Either the set matched or we're looking for the last chosen 5218 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5219 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5220 return ri; 5221 } 5222 } 5223 } finally { 5224 if (changed) { 5225 if (DEBUG_PREFERRED) { 5226 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5227 } 5228 scheduleWritePackageRestrictionsLocked(userId); 5229 } 5230 } 5231 } 5232 } 5233 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5234 return null; 5235 } 5236 5237 /* 5238 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5239 */ 5240 @Override 5241 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5242 int targetUserId) { 5243 mContext.enforceCallingOrSelfPermission( 5244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5245 List<CrossProfileIntentFilter> matches = 5246 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5247 if (matches != null) { 5248 int size = matches.size(); 5249 for (int i = 0; i < size; i++) { 5250 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5251 } 5252 } 5253 if (hasWebURI(intent)) { 5254 // cross-profile app linking works only towards the parent. 5255 final UserInfo parent = getProfileParent(sourceUserId); 5256 synchronized(mPackages) { 5257 int flags = updateFlagsForResolve(0, parent.id, intent); 5258 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5259 intent, resolvedType, flags, sourceUserId, parent.id); 5260 return xpDomainInfo != null; 5261 } 5262 } 5263 return false; 5264 } 5265 5266 private UserInfo getProfileParent(int userId) { 5267 final long identity = Binder.clearCallingIdentity(); 5268 try { 5269 return sUserManager.getProfileParent(userId); 5270 } finally { 5271 Binder.restoreCallingIdentity(identity); 5272 } 5273 } 5274 5275 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5276 String resolvedType, int userId) { 5277 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5278 if (resolver != null) { 5279 return resolver.queryIntent(intent, resolvedType, false, userId); 5280 } 5281 return null; 5282 } 5283 5284 @Override 5285 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5286 String resolvedType, int flags, int userId) { 5287 try { 5288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5289 5290 return new ParceledListSlice<>( 5291 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5292 } finally { 5293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5294 } 5295 } 5296 5297 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5298 String resolvedType, int flags, int userId) { 5299 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5300 flags = updateFlagsForResolve(flags, userId, intent); 5301 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5302 false /* requireFullPermission */, false /* checkShell */, 5303 "query intent activities"); 5304 ComponentName comp = intent.getComponent(); 5305 if (comp == null) { 5306 if (intent.getSelector() != null) { 5307 intent = intent.getSelector(); 5308 comp = intent.getComponent(); 5309 } 5310 } 5311 5312 if (comp != null) { 5313 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5314 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5315 if (ai != null) { 5316 final ResolveInfo ri = new ResolveInfo(); 5317 ri.activityInfo = ai; 5318 list.add(ri); 5319 } 5320 return list; 5321 } 5322 5323 // reader 5324 synchronized (mPackages) { 5325 final String pkgName = intent.getPackage(); 5326 if (pkgName == null) { 5327 List<CrossProfileIntentFilter> matchingFilters = 5328 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5329 // Check for results that need to skip the current profile. 5330 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5331 resolvedType, flags, userId); 5332 if (xpResolveInfo != null) { 5333 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5334 result.add(xpResolveInfo); 5335 return filterIfNotSystemUser(result, userId); 5336 } 5337 5338 // Check for results in the current profile. 5339 List<ResolveInfo> result = mActivities.queryIntent( 5340 intent, resolvedType, flags, userId); 5341 result = filterIfNotSystemUser(result, userId); 5342 5343 // Check for cross profile results. 5344 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5345 xpResolveInfo = queryCrossProfileIntents( 5346 matchingFilters, intent, resolvedType, flags, userId, 5347 hasNonNegativePriorityResult); 5348 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5349 boolean isVisibleToUser = filterIfNotSystemUser( 5350 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5351 if (isVisibleToUser) { 5352 result.add(xpResolveInfo); 5353 Collections.sort(result, mResolvePrioritySorter); 5354 } 5355 } 5356 if (hasWebURI(intent)) { 5357 CrossProfileDomainInfo xpDomainInfo = null; 5358 final UserInfo parent = getProfileParent(userId); 5359 if (parent != null) { 5360 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5361 flags, userId, parent.id); 5362 } 5363 if (xpDomainInfo != null) { 5364 if (xpResolveInfo != null) { 5365 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5366 // in the result. 5367 result.remove(xpResolveInfo); 5368 } 5369 if (result.size() == 0) { 5370 result.add(xpDomainInfo.resolveInfo); 5371 return result; 5372 } 5373 } else if (result.size() <= 1) { 5374 return result; 5375 } 5376 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5377 xpDomainInfo, userId); 5378 Collections.sort(result, mResolvePrioritySorter); 5379 } 5380 return result; 5381 } 5382 final PackageParser.Package pkg = mPackages.get(pkgName); 5383 if (pkg != null) { 5384 return filterIfNotSystemUser( 5385 mActivities.queryIntentForPackage( 5386 intent, resolvedType, flags, pkg.activities, userId), 5387 userId); 5388 } 5389 return new ArrayList<ResolveInfo>(); 5390 } 5391 } 5392 5393 private static class CrossProfileDomainInfo { 5394 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5395 ResolveInfo resolveInfo; 5396 /* Best domain verification status of the activities found in the other profile */ 5397 int bestDomainVerificationStatus; 5398 } 5399 5400 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5401 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5402 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5403 sourceUserId)) { 5404 return null; 5405 } 5406 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5407 resolvedType, flags, parentUserId); 5408 5409 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5410 return null; 5411 } 5412 CrossProfileDomainInfo result = null; 5413 int size = resultTargetUser.size(); 5414 for (int i = 0; i < size; i++) { 5415 ResolveInfo riTargetUser = resultTargetUser.get(i); 5416 // Intent filter verification is only for filters that specify a host. So don't return 5417 // those that handle all web uris. 5418 if (riTargetUser.handleAllWebDataURI) { 5419 continue; 5420 } 5421 String packageName = riTargetUser.activityInfo.packageName; 5422 PackageSetting ps = mSettings.mPackages.get(packageName); 5423 if (ps == null) { 5424 continue; 5425 } 5426 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5427 int status = (int)(verificationState >> 32); 5428 if (result == null) { 5429 result = new CrossProfileDomainInfo(); 5430 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5431 sourceUserId, parentUserId); 5432 result.bestDomainVerificationStatus = status; 5433 } else { 5434 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5435 result.bestDomainVerificationStatus); 5436 } 5437 } 5438 // Don't consider matches with status NEVER across profiles. 5439 if (result != null && result.bestDomainVerificationStatus 5440 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5441 return null; 5442 } 5443 return result; 5444 } 5445 5446 /** 5447 * Verification statuses are ordered from the worse to the best, except for 5448 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5449 */ 5450 private int bestDomainVerificationStatus(int status1, int status2) { 5451 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5452 return status2; 5453 } 5454 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5455 return status1; 5456 } 5457 return (int) MathUtils.max(status1, status2); 5458 } 5459 5460 private boolean isUserEnabled(int userId) { 5461 long callingId = Binder.clearCallingIdentity(); 5462 try { 5463 UserInfo userInfo = sUserManager.getUserInfo(userId); 5464 return userInfo != null && userInfo.isEnabled(); 5465 } finally { 5466 Binder.restoreCallingIdentity(callingId); 5467 } 5468 } 5469 5470 /** 5471 * Filter out activities with systemUserOnly flag set, when current user is not System. 5472 * 5473 * @return filtered list 5474 */ 5475 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5476 if (userId == UserHandle.USER_SYSTEM) { 5477 return resolveInfos; 5478 } 5479 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5480 ResolveInfo info = resolveInfos.get(i); 5481 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5482 resolveInfos.remove(i); 5483 } 5484 } 5485 return resolveInfos; 5486 } 5487 5488 /** 5489 * @param resolveInfos list of resolve infos in descending priority order 5490 * @return if the list contains a resolve info with non-negative priority 5491 */ 5492 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5493 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5494 } 5495 5496 private static boolean hasWebURI(Intent intent) { 5497 if (intent.getData() == null) { 5498 return false; 5499 } 5500 final String scheme = intent.getScheme(); 5501 if (TextUtils.isEmpty(scheme)) { 5502 return false; 5503 } 5504 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5505 } 5506 5507 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5508 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5509 int userId) { 5510 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5511 5512 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5513 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5514 candidates.size()); 5515 } 5516 5517 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5518 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5519 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5520 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5521 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5522 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5523 5524 synchronized (mPackages) { 5525 final int count = candidates.size(); 5526 // First, try to use linked apps. Partition the candidates into four lists: 5527 // one for the final results, one for the "do not use ever", one for "undefined status" 5528 // and finally one for "browser app type". 5529 for (int n=0; n<count; n++) { 5530 ResolveInfo info = candidates.get(n); 5531 String packageName = info.activityInfo.packageName; 5532 PackageSetting ps = mSettings.mPackages.get(packageName); 5533 if (ps != null) { 5534 // Add to the special match all list (Browser use case) 5535 if (info.handleAllWebDataURI) { 5536 matchAllList.add(info); 5537 continue; 5538 } 5539 // Try to get the status from User settings first 5540 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5541 int status = (int)(packedStatus >> 32); 5542 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5543 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5544 if (DEBUG_DOMAIN_VERIFICATION) { 5545 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5546 + " : linkgen=" + linkGeneration); 5547 } 5548 // Use link-enabled generation as preferredOrder, i.e. 5549 // prefer newly-enabled over earlier-enabled. 5550 info.preferredOrder = linkGeneration; 5551 alwaysList.add(info); 5552 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5553 if (DEBUG_DOMAIN_VERIFICATION) { 5554 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5555 } 5556 neverList.add(info); 5557 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5558 if (DEBUG_DOMAIN_VERIFICATION) { 5559 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5560 } 5561 alwaysAskList.add(info); 5562 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5563 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5564 if (DEBUG_DOMAIN_VERIFICATION) { 5565 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5566 } 5567 undefinedList.add(info); 5568 } 5569 } 5570 } 5571 5572 // We'll want to include browser possibilities in a few cases 5573 boolean includeBrowser = false; 5574 5575 // First try to add the "always" resolution(s) for the current user, if any 5576 if (alwaysList.size() > 0) { 5577 result.addAll(alwaysList); 5578 } else { 5579 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5580 result.addAll(undefinedList); 5581 // Maybe add one for the other profile. 5582 if (xpDomainInfo != null && ( 5583 xpDomainInfo.bestDomainVerificationStatus 5584 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5585 result.add(xpDomainInfo.resolveInfo); 5586 } 5587 includeBrowser = true; 5588 } 5589 5590 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5591 // If there were 'always' entries their preferred order has been set, so we also 5592 // back that off to make the alternatives equivalent 5593 if (alwaysAskList.size() > 0) { 5594 for (ResolveInfo i : result) { 5595 i.preferredOrder = 0; 5596 } 5597 result.addAll(alwaysAskList); 5598 includeBrowser = true; 5599 } 5600 5601 if (includeBrowser) { 5602 // Also add browsers (all of them or only the default one) 5603 if (DEBUG_DOMAIN_VERIFICATION) { 5604 Slog.v(TAG, " ...including browsers in candidate set"); 5605 } 5606 if ((matchFlags & MATCH_ALL) != 0) { 5607 result.addAll(matchAllList); 5608 } else { 5609 // Browser/generic handling case. If there's a default browser, go straight 5610 // to that (but only if there is no other higher-priority match). 5611 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5612 int maxMatchPrio = 0; 5613 ResolveInfo defaultBrowserMatch = null; 5614 final int numCandidates = matchAllList.size(); 5615 for (int n = 0; n < numCandidates; n++) { 5616 ResolveInfo info = matchAllList.get(n); 5617 // track the highest overall match priority... 5618 if (info.priority > maxMatchPrio) { 5619 maxMatchPrio = info.priority; 5620 } 5621 // ...and the highest-priority default browser match 5622 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5623 if (defaultBrowserMatch == null 5624 || (defaultBrowserMatch.priority < info.priority)) { 5625 if (debug) { 5626 Slog.v(TAG, "Considering default browser match " + info); 5627 } 5628 defaultBrowserMatch = info; 5629 } 5630 } 5631 } 5632 if (defaultBrowserMatch != null 5633 && defaultBrowserMatch.priority >= maxMatchPrio 5634 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5635 { 5636 if (debug) { 5637 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5638 } 5639 result.add(defaultBrowserMatch); 5640 } else { 5641 result.addAll(matchAllList); 5642 } 5643 } 5644 5645 // If there is nothing selected, add all candidates and remove the ones that the user 5646 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5647 if (result.size() == 0) { 5648 result.addAll(candidates); 5649 result.removeAll(neverList); 5650 } 5651 } 5652 } 5653 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5654 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5655 result.size()); 5656 for (ResolveInfo info : result) { 5657 Slog.v(TAG, " + " + info.activityInfo); 5658 } 5659 } 5660 return result; 5661 } 5662 5663 // Returns a packed value as a long: 5664 // 5665 // high 'int'-sized word: link status: undefined/ask/never/always. 5666 // low 'int'-sized word: relative priority among 'always' results. 5667 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5668 long result = ps.getDomainVerificationStatusForUser(userId); 5669 // if none available, get the master status 5670 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5671 if (ps.getIntentFilterVerificationInfo() != null) { 5672 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5673 } 5674 } 5675 return result; 5676 } 5677 5678 private ResolveInfo querySkipCurrentProfileIntents( 5679 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5680 int flags, int sourceUserId) { 5681 if (matchingFilters != null) { 5682 int size = matchingFilters.size(); 5683 for (int i = 0; i < size; i ++) { 5684 CrossProfileIntentFilter filter = matchingFilters.get(i); 5685 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5686 // Checking if there are activities in the target user that can handle the 5687 // intent. 5688 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5689 resolvedType, flags, sourceUserId); 5690 if (resolveInfo != null) { 5691 return resolveInfo; 5692 } 5693 } 5694 } 5695 } 5696 return null; 5697 } 5698 5699 // Return matching ResolveInfo in target user if any. 5700 private ResolveInfo queryCrossProfileIntents( 5701 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5702 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5703 if (matchingFilters != null) { 5704 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5705 // match the same intent. For performance reasons, it is better not to 5706 // run queryIntent twice for the same userId 5707 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5708 int size = matchingFilters.size(); 5709 for (int i = 0; i < size; i++) { 5710 CrossProfileIntentFilter filter = matchingFilters.get(i); 5711 int targetUserId = filter.getTargetUserId(); 5712 boolean skipCurrentProfile = 5713 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5714 boolean skipCurrentProfileIfNoMatchFound = 5715 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5716 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5717 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5718 // Checking if there are activities in the target user that can handle the 5719 // intent. 5720 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5721 resolvedType, flags, sourceUserId); 5722 if (resolveInfo != null) return resolveInfo; 5723 alreadyTriedUserIds.put(targetUserId, true); 5724 } 5725 } 5726 } 5727 return null; 5728 } 5729 5730 /** 5731 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5732 * will forward the intent to the filter's target user. 5733 * Otherwise, returns null. 5734 */ 5735 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5736 String resolvedType, int flags, int sourceUserId) { 5737 int targetUserId = filter.getTargetUserId(); 5738 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5739 resolvedType, flags, targetUserId); 5740 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5741 // If all the matches in the target profile are suspended, return null. 5742 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5743 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5744 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5745 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5746 targetUserId); 5747 } 5748 } 5749 } 5750 return null; 5751 } 5752 5753 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5754 int sourceUserId, int targetUserId) { 5755 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5756 long ident = Binder.clearCallingIdentity(); 5757 boolean targetIsProfile; 5758 try { 5759 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5760 } finally { 5761 Binder.restoreCallingIdentity(ident); 5762 } 5763 String className; 5764 if (targetIsProfile) { 5765 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5766 } else { 5767 className = FORWARD_INTENT_TO_PARENT; 5768 } 5769 ComponentName forwardingActivityComponentName = new ComponentName( 5770 mAndroidApplication.packageName, className); 5771 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5772 sourceUserId); 5773 if (!targetIsProfile) { 5774 forwardingActivityInfo.showUserIcon = targetUserId; 5775 forwardingResolveInfo.noResourceId = true; 5776 } 5777 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5778 forwardingResolveInfo.priority = 0; 5779 forwardingResolveInfo.preferredOrder = 0; 5780 forwardingResolveInfo.match = 0; 5781 forwardingResolveInfo.isDefault = true; 5782 forwardingResolveInfo.filter = filter; 5783 forwardingResolveInfo.targetUserId = targetUserId; 5784 return forwardingResolveInfo; 5785 } 5786 5787 @Override 5788 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5789 Intent[] specifics, String[] specificTypes, Intent intent, 5790 String resolvedType, int flags, int userId) { 5791 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5792 specificTypes, intent, resolvedType, flags, userId)); 5793 } 5794 5795 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5796 Intent[] specifics, String[] specificTypes, Intent intent, 5797 String resolvedType, int flags, int userId) { 5798 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5799 flags = updateFlagsForResolve(flags, userId, intent); 5800 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5801 false /* requireFullPermission */, false /* checkShell */, 5802 "query intent activity options"); 5803 final String resultsAction = intent.getAction(); 5804 5805 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5806 | PackageManager.GET_RESOLVED_FILTER, userId); 5807 5808 if (DEBUG_INTENT_MATCHING) { 5809 Log.v(TAG, "Query " + intent + ": " + results); 5810 } 5811 5812 int specificsPos = 0; 5813 int N; 5814 5815 // todo: note that the algorithm used here is O(N^2). This 5816 // isn't a problem in our current environment, but if we start running 5817 // into situations where we have more than 5 or 10 matches then this 5818 // should probably be changed to something smarter... 5819 5820 // First we go through and resolve each of the specific items 5821 // that were supplied, taking care of removing any corresponding 5822 // duplicate items in the generic resolve list. 5823 if (specifics != null) { 5824 for (int i=0; i<specifics.length; i++) { 5825 final Intent sintent = specifics[i]; 5826 if (sintent == null) { 5827 continue; 5828 } 5829 5830 if (DEBUG_INTENT_MATCHING) { 5831 Log.v(TAG, "Specific #" + i + ": " + sintent); 5832 } 5833 5834 String action = sintent.getAction(); 5835 if (resultsAction != null && resultsAction.equals(action)) { 5836 // If this action was explicitly requested, then don't 5837 // remove things that have it. 5838 action = null; 5839 } 5840 5841 ResolveInfo ri = null; 5842 ActivityInfo ai = null; 5843 5844 ComponentName comp = sintent.getComponent(); 5845 if (comp == null) { 5846 ri = resolveIntent( 5847 sintent, 5848 specificTypes != null ? specificTypes[i] : null, 5849 flags, userId); 5850 if (ri == null) { 5851 continue; 5852 } 5853 if (ri == mResolveInfo) { 5854 // ACK! Must do something better with this. 5855 } 5856 ai = ri.activityInfo; 5857 comp = new ComponentName(ai.applicationInfo.packageName, 5858 ai.name); 5859 } else { 5860 ai = getActivityInfo(comp, flags, userId); 5861 if (ai == null) { 5862 continue; 5863 } 5864 } 5865 5866 // Look for any generic query activities that are duplicates 5867 // of this specific one, and remove them from the results. 5868 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5869 N = results.size(); 5870 int j; 5871 for (j=specificsPos; j<N; j++) { 5872 ResolveInfo sri = results.get(j); 5873 if ((sri.activityInfo.name.equals(comp.getClassName()) 5874 && sri.activityInfo.applicationInfo.packageName.equals( 5875 comp.getPackageName())) 5876 || (action != null && sri.filter.matchAction(action))) { 5877 results.remove(j); 5878 if (DEBUG_INTENT_MATCHING) Log.v( 5879 TAG, "Removing duplicate item from " + j 5880 + " due to specific " + specificsPos); 5881 if (ri == null) { 5882 ri = sri; 5883 } 5884 j--; 5885 N--; 5886 } 5887 } 5888 5889 // Add this specific item to its proper place. 5890 if (ri == null) { 5891 ri = new ResolveInfo(); 5892 ri.activityInfo = ai; 5893 } 5894 results.add(specificsPos, ri); 5895 ri.specificIndex = i; 5896 specificsPos++; 5897 } 5898 } 5899 5900 // Now we go through the remaining generic results and remove any 5901 // duplicate actions that are found here. 5902 N = results.size(); 5903 for (int i=specificsPos; i<N-1; i++) { 5904 final ResolveInfo rii = results.get(i); 5905 if (rii.filter == null) { 5906 continue; 5907 } 5908 5909 // Iterate over all of the actions of this result's intent 5910 // filter... typically this should be just one. 5911 final Iterator<String> it = rii.filter.actionsIterator(); 5912 if (it == null) { 5913 continue; 5914 } 5915 while (it.hasNext()) { 5916 final String action = it.next(); 5917 if (resultsAction != null && resultsAction.equals(action)) { 5918 // If this action was explicitly requested, then don't 5919 // remove things that have it. 5920 continue; 5921 } 5922 for (int j=i+1; j<N; j++) { 5923 final ResolveInfo rij = results.get(j); 5924 if (rij.filter != null && rij.filter.hasAction(action)) { 5925 results.remove(j); 5926 if (DEBUG_INTENT_MATCHING) Log.v( 5927 TAG, "Removing duplicate item from " + j 5928 + " due to action " + action + " at " + i); 5929 j--; 5930 N--; 5931 } 5932 } 5933 } 5934 5935 // If the caller didn't request filter information, drop it now 5936 // so we don't have to marshall/unmarshall it. 5937 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5938 rii.filter = null; 5939 } 5940 } 5941 5942 // Filter out the caller activity if so requested. 5943 if (caller != null) { 5944 N = results.size(); 5945 for (int i=0; i<N; i++) { 5946 ActivityInfo ainfo = results.get(i).activityInfo; 5947 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5948 && caller.getClassName().equals(ainfo.name)) { 5949 results.remove(i); 5950 break; 5951 } 5952 } 5953 } 5954 5955 // If the caller didn't request filter information, 5956 // drop them now so we don't have to 5957 // marshall/unmarshall it. 5958 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5959 N = results.size(); 5960 for (int i=0; i<N; i++) { 5961 results.get(i).filter = null; 5962 } 5963 } 5964 5965 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5966 return results; 5967 } 5968 5969 @Override 5970 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5971 String resolvedType, int flags, int userId) { 5972 return new ParceledListSlice<>( 5973 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5974 } 5975 5976 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5977 String resolvedType, int flags, int userId) { 5978 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5979 flags = updateFlagsForResolve(flags, userId, intent); 5980 ComponentName comp = intent.getComponent(); 5981 if (comp == null) { 5982 if (intent.getSelector() != null) { 5983 intent = intent.getSelector(); 5984 comp = intent.getComponent(); 5985 } 5986 } 5987 if (comp != null) { 5988 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5989 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5990 if (ai != null) { 5991 ResolveInfo ri = new ResolveInfo(); 5992 ri.activityInfo = ai; 5993 list.add(ri); 5994 } 5995 return list; 5996 } 5997 5998 // reader 5999 synchronized (mPackages) { 6000 String pkgName = intent.getPackage(); 6001 if (pkgName == null) { 6002 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6003 } 6004 final PackageParser.Package pkg = mPackages.get(pkgName); 6005 if (pkg != null) { 6006 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6007 userId); 6008 } 6009 return Collections.emptyList(); 6010 } 6011 } 6012 6013 @Override 6014 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6015 if (!sUserManager.exists(userId)) return null; 6016 flags = updateFlagsForResolve(flags, userId, intent); 6017 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6018 if (query != null) { 6019 if (query.size() >= 1) { 6020 // If there is more than one service with the same priority, 6021 // just arbitrarily pick the first one. 6022 return query.get(0); 6023 } 6024 } 6025 return null; 6026 } 6027 6028 @Override 6029 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6030 String resolvedType, int flags, int userId) { 6031 return new ParceledListSlice<>( 6032 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6033 } 6034 6035 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6036 String resolvedType, int flags, int userId) { 6037 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6038 flags = updateFlagsForResolve(flags, userId, intent); 6039 ComponentName comp = intent.getComponent(); 6040 if (comp == null) { 6041 if (intent.getSelector() != null) { 6042 intent = intent.getSelector(); 6043 comp = intent.getComponent(); 6044 } 6045 } 6046 if (comp != null) { 6047 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6048 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6049 if (si != null) { 6050 final ResolveInfo ri = new ResolveInfo(); 6051 ri.serviceInfo = si; 6052 list.add(ri); 6053 } 6054 return list; 6055 } 6056 6057 // reader 6058 synchronized (mPackages) { 6059 String pkgName = intent.getPackage(); 6060 if (pkgName == null) { 6061 return mServices.queryIntent(intent, resolvedType, flags, userId); 6062 } 6063 final PackageParser.Package pkg = mPackages.get(pkgName); 6064 if (pkg != null) { 6065 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6066 userId); 6067 } 6068 return Collections.emptyList(); 6069 } 6070 } 6071 6072 @Override 6073 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6074 String resolvedType, int flags, int userId) { 6075 return new ParceledListSlice<>( 6076 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6077 } 6078 6079 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6080 Intent intent, String resolvedType, int flags, int userId) { 6081 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6082 flags = updateFlagsForResolve(flags, userId, intent); 6083 ComponentName comp = intent.getComponent(); 6084 if (comp == null) { 6085 if (intent.getSelector() != null) { 6086 intent = intent.getSelector(); 6087 comp = intent.getComponent(); 6088 } 6089 } 6090 if (comp != null) { 6091 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6092 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6093 if (pi != null) { 6094 final ResolveInfo ri = new ResolveInfo(); 6095 ri.providerInfo = pi; 6096 list.add(ri); 6097 } 6098 return list; 6099 } 6100 6101 // reader 6102 synchronized (mPackages) { 6103 String pkgName = intent.getPackage(); 6104 if (pkgName == null) { 6105 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6106 } 6107 final PackageParser.Package pkg = mPackages.get(pkgName); 6108 if (pkg != null) { 6109 return mProviders.queryIntentForPackage( 6110 intent, resolvedType, flags, pkg.providers, userId); 6111 } 6112 return Collections.emptyList(); 6113 } 6114 } 6115 6116 @Override 6117 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6118 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6119 flags = updateFlagsForPackage(flags, userId, null); 6120 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6121 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6122 true /* requireFullPermission */, false /* checkShell */, 6123 "get installed packages"); 6124 6125 // writer 6126 synchronized (mPackages) { 6127 ArrayList<PackageInfo> list; 6128 if (listUninstalled) { 6129 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6130 for (PackageSetting ps : mSettings.mPackages.values()) { 6131 final PackageInfo pi; 6132 if (ps.pkg != null) { 6133 pi = generatePackageInfo(ps, flags, userId); 6134 } else { 6135 pi = generatePackageInfo(ps, flags, userId); 6136 } 6137 if (pi != null) { 6138 list.add(pi); 6139 } 6140 } 6141 } else { 6142 list = new ArrayList<PackageInfo>(mPackages.size()); 6143 for (PackageParser.Package p : mPackages.values()) { 6144 final PackageInfo pi = 6145 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6146 if (pi != null) { 6147 list.add(pi); 6148 } 6149 } 6150 } 6151 6152 return new ParceledListSlice<PackageInfo>(list); 6153 } 6154 } 6155 6156 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6157 String[] permissions, boolean[] tmp, int flags, int userId) { 6158 int numMatch = 0; 6159 final PermissionsState permissionsState = ps.getPermissionsState(); 6160 for (int i=0; i<permissions.length; i++) { 6161 final String permission = permissions[i]; 6162 if (permissionsState.hasPermission(permission, userId)) { 6163 tmp[i] = true; 6164 numMatch++; 6165 } else { 6166 tmp[i] = false; 6167 } 6168 } 6169 if (numMatch == 0) { 6170 return; 6171 } 6172 final PackageInfo pi; 6173 if (ps.pkg != null) { 6174 pi = generatePackageInfo(ps, flags, userId); 6175 } else { 6176 pi = generatePackageInfo(ps, flags, userId); 6177 } 6178 // The above might return null in cases of uninstalled apps or install-state 6179 // skew across users/profiles. 6180 if (pi != null) { 6181 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6182 if (numMatch == permissions.length) { 6183 pi.requestedPermissions = permissions; 6184 } else { 6185 pi.requestedPermissions = new String[numMatch]; 6186 numMatch = 0; 6187 for (int i=0; i<permissions.length; i++) { 6188 if (tmp[i]) { 6189 pi.requestedPermissions[numMatch] = permissions[i]; 6190 numMatch++; 6191 } 6192 } 6193 } 6194 } 6195 list.add(pi); 6196 } 6197 } 6198 6199 @Override 6200 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6201 String[] permissions, int flags, int userId) { 6202 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6203 flags = updateFlagsForPackage(flags, userId, permissions); 6204 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6205 6206 // writer 6207 synchronized (mPackages) { 6208 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6209 boolean[] tmpBools = new boolean[permissions.length]; 6210 if (listUninstalled) { 6211 for (PackageSetting ps : mSettings.mPackages.values()) { 6212 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6213 } 6214 } else { 6215 for (PackageParser.Package pkg : mPackages.values()) { 6216 PackageSetting ps = (PackageSetting)pkg.mExtras; 6217 if (ps != null) { 6218 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6219 userId); 6220 } 6221 } 6222 } 6223 6224 return new ParceledListSlice<PackageInfo>(list); 6225 } 6226 } 6227 6228 @Override 6229 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6230 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6231 flags = updateFlagsForApplication(flags, userId, null); 6232 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6233 6234 // writer 6235 synchronized (mPackages) { 6236 ArrayList<ApplicationInfo> list; 6237 if (listUninstalled) { 6238 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6239 for (PackageSetting ps : mSettings.mPackages.values()) { 6240 ApplicationInfo ai; 6241 if (ps.pkg != null) { 6242 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6243 ps.readUserState(userId), userId); 6244 } else { 6245 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6246 } 6247 if (ai != null) { 6248 list.add(ai); 6249 } 6250 } 6251 } else { 6252 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6253 for (PackageParser.Package p : mPackages.values()) { 6254 if (p.mExtras != null) { 6255 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6256 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6257 if (ai != null) { 6258 list.add(ai); 6259 } 6260 } 6261 } 6262 } 6263 6264 return new ParceledListSlice<ApplicationInfo>(list); 6265 } 6266 } 6267 6268 @Override 6269 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6270 if (DISABLE_EPHEMERAL_APPS) { 6271 return null; 6272 } 6273 6274 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6275 "getEphemeralApplications"); 6276 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6277 true /* requireFullPermission */, false /* checkShell */, 6278 "getEphemeralApplications"); 6279 synchronized (mPackages) { 6280 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6281 .getEphemeralApplicationsLPw(userId); 6282 if (ephemeralApps != null) { 6283 return new ParceledListSlice<>(ephemeralApps); 6284 } 6285 } 6286 return null; 6287 } 6288 6289 @Override 6290 public boolean isEphemeralApplication(String packageName, int userId) { 6291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6292 true /* requireFullPermission */, false /* checkShell */, 6293 "isEphemeral"); 6294 if (DISABLE_EPHEMERAL_APPS) { 6295 return false; 6296 } 6297 6298 if (!isCallerSameApp(packageName)) { 6299 return false; 6300 } 6301 synchronized (mPackages) { 6302 PackageParser.Package pkg = mPackages.get(packageName); 6303 if (pkg != null) { 6304 return pkg.applicationInfo.isEphemeralApp(); 6305 } 6306 } 6307 return false; 6308 } 6309 6310 @Override 6311 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6312 if (DISABLE_EPHEMERAL_APPS) { 6313 return null; 6314 } 6315 6316 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6317 true /* requireFullPermission */, false /* checkShell */, 6318 "getCookie"); 6319 if (!isCallerSameApp(packageName)) { 6320 return null; 6321 } 6322 synchronized (mPackages) { 6323 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6324 packageName, userId); 6325 } 6326 } 6327 6328 @Override 6329 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6330 if (DISABLE_EPHEMERAL_APPS) { 6331 return true; 6332 } 6333 6334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6335 true /* requireFullPermission */, true /* checkShell */, 6336 "setCookie"); 6337 if (!isCallerSameApp(packageName)) { 6338 return false; 6339 } 6340 synchronized (mPackages) { 6341 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6342 packageName, cookie, userId); 6343 } 6344 } 6345 6346 @Override 6347 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6348 if (DISABLE_EPHEMERAL_APPS) { 6349 return null; 6350 } 6351 6352 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6353 "getEphemeralApplicationIcon"); 6354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6355 true /* requireFullPermission */, false /* checkShell */, 6356 "getEphemeralApplicationIcon"); 6357 synchronized (mPackages) { 6358 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6359 packageName, userId); 6360 } 6361 } 6362 6363 private boolean isCallerSameApp(String packageName) { 6364 PackageParser.Package pkg = mPackages.get(packageName); 6365 return pkg != null 6366 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6367 } 6368 6369 @Override 6370 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6371 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6372 } 6373 6374 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6375 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6376 6377 // reader 6378 synchronized (mPackages) { 6379 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6380 final int userId = UserHandle.getCallingUserId(); 6381 while (i.hasNext()) { 6382 final PackageParser.Package p = i.next(); 6383 if (p.applicationInfo == null) continue; 6384 6385 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6386 && !p.applicationInfo.isDirectBootAware(); 6387 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6388 && p.applicationInfo.isDirectBootAware(); 6389 6390 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6391 && (!mSafeMode || isSystemApp(p)) 6392 && (matchesUnaware || matchesAware)) { 6393 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6394 if (ps != null) { 6395 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6396 ps.readUserState(userId), userId); 6397 if (ai != null) { 6398 finalList.add(ai); 6399 } 6400 } 6401 } 6402 } 6403 } 6404 6405 return finalList; 6406 } 6407 6408 @Override 6409 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6410 if (!sUserManager.exists(userId)) return null; 6411 flags = updateFlagsForComponent(flags, userId, name); 6412 // reader 6413 synchronized (mPackages) { 6414 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6415 PackageSetting ps = provider != null 6416 ? mSettings.mPackages.get(provider.owner.packageName) 6417 : null; 6418 return ps != null 6419 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6420 ? PackageParser.generateProviderInfo(provider, flags, 6421 ps.readUserState(userId), userId) 6422 : null; 6423 } 6424 } 6425 6426 /** 6427 * @deprecated 6428 */ 6429 @Deprecated 6430 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6431 // reader 6432 synchronized (mPackages) { 6433 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6434 .entrySet().iterator(); 6435 final int userId = UserHandle.getCallingUserId(); 6436 while (i.hasNext()) { 6437 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6438 PackageParser.Provider p = entry.getValue(); 6439 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6440 6441 if (ps != null && p.syncable 6442 && (!mSafeMode || (p.info.applicationInfo.flags 6443 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6444 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6445 ps.readUserState(userId), userId); 6446 if (info != null) { 6447 outNames.add(entry.getKey()); 6448 outInfo.add(info); 6449 } 6450 } 6451 } 6452 } 6453 } 6454 6455 @Override 6456 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6457 int uid, int flags) { 6458 final int userId = processName != null ? UserHandle.getUserId(uid) 6459 : UserHandle.getCallingUserId(); 6460 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6461 flags = updateFlagsForComponent(flags, userId, processName); 6462 6463 ArrayList<ProviderInfo> finalList = null; 6464 // reader 6465 synchronized (mPackages) { 6466 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6467 while (i.hasNext()) { 6468 final PackageParser.Provider p = i.next(); 6469 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6470 if (ps != null && p.info.authority != null 6471 && (processName == null 6472 || (p.info.processName.equals(processName) 6473 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6474 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6475 if (finalList == null) { 6476 finalList = new ArrayList<ProviderInfo>(3); 6477 } 6478 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6479 ps.readUserState(userId), userId); 6480 if (info != null) { 6481 finalList.add(info); 6482 } 6483 } 6484 } 6485 } 6486 6487 if (finalList != null) { 6488 Collections.sort(finalList, mProviderInitOrderSorter); 6489 return new ParceledListSlice<ProviderInfo>(finalList); 6490 } 6491 6492 return ParceledListSlice.emptyList(); 6493 } 6494 6495 @Override 6496 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6497 // reader 6498 synchronized (mPackages) { 6499 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6500 return PackageParser.generateInstrumentationInfo(i, flags); 6501 } 6502 } 6503 6504 @Override 6505 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6506 String targetPackage, int flags) { 6507 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6508 } 6509 6510 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6511 int flags) { 6512 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6513 6514 // reader 6515 synchronized (mPackages) { 6516 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6517 while (i.hasNext()) { 6518 final PackageParser.Instrumentation p = i.next(); 6519 if (targetPackage == null 6520 || targetPackage.equals(p.info.targetPackage)) { 6521 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6522 flags); 6523 if (ii != null) { 6524 finalList.add(ii); 6525 } 6526 } 6527 } 6528 } 6529 6530 return finalList; 6531 } 6532 6533 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6534 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6535 if (overlays == null) { 6536 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6537 return; 6538 } 6539 for (PackageParser.Package opkg : overlays.values()) { 6540 // Not much to do if idmap fails: we already logged the error 6541 // and we certainly don't want to abort installation of pkg simply 6542 // because an overlay didn't fit properly. For these reasons, 6543 // ignore the return value of createIdmapForPackagePairLI. 6544 createIdmapForPackagePairLI(pkg, opkg); 6545 } 6546 } 6547 6548 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6549 PackageParser.Package opkg) { 6550 if (!opkg.mTrustedOverlay) { 6551 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6552 opkg.baseCodePath + ": overlay not trusted"); 6553 return false; 6554 } 6555 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6556 if (overlaySet == null) { 6557 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6558 opkg.baseCodePath + " but target package has no known overlays"); 6559 return false; 6560 } 6561 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6562 // TODO: generate idmap for split APKs 6563 try { 6564 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6565 } catch (InstallerException e) { 6566 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6567 + opkg.baseCodePath); 6568 return false; 6569 } 6570 PackageParser.Package[] overlayArray = 6571 overlaySet.values().toArray(new PackageParser.Package[0]); 6572 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6573 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6574 return p1.mOverlayPriority - p2.mOverlayPriority; 6575 } 6576 }; 6577 Arrays.sort(overlayArray, cmp); 6578 6579 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6580 int i = 0; 6581 for (PackageParser.Package p : overlayArray) { 6582 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6583 } 6584 return true; 6585 } 6586 6587 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6588 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6589 try { 6590 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6591 } finally { 6592 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6593 } 6594 } 6595 6596 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6597 final File[] files = dir.listFiles(); 6598 if (ArrayUtils.isEmpty(files)) { 6599 Log.d(TAG, "No files in app dir " + dir); 6600 return; 6601 } 6602 6603 if (DEBUG_PACKAGE_SCANNING) { 6604 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6605 + " flags=0x" + Integer.toHexString(parseFlags)); 6606 } 6607 6608 for (File file : files) { 6609 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6610 && !PackageInstallerService.isStageName(file.getName()); 6611 if (!isPackage) { 6612 // Ignore entries which are not packages 6613 continue; 6614 } 6615 try { 6616 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6617 scanFlags, currentTime, null); 6618 } catch (PackageManagerException e) { 6619 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6620 6621 // Delete invalid userdata apps 6622 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6623 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6624 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6625 removeCodePathLI(file); 6626 } 6627 } 6628 } 6629 } 6630 6631 private static File getSettingsProblemFile() { 6632 File dataDir = Environment.getDataDirectory(); 6633 File systemDir = new File(dataDir, "system"); 6634 File fname = new File(systemDir, "uiderrors.txt"); 6635 return fname; 6636 } 6637 6638 static void reportSettingsProblem(int priority, String msg) { 6639 logCriticalInfo(priority, msg); 6640 } 6641 6642 static void logCriticalInfo(int priority, String msg) { 6643 Slog.println(priority, TAG, msg); 6644 EventLogTags.writePmCriticalInfo(msg); 6645 try { 6646 File fname = getSettingsProblemFile(); 6647 FileOutputStream out = new FileOutputStream(fname, true); 6648 PrintWriter pw = new FastPrintWriter(out); 6649 SimpleDateFormat formatter = new SimpleDateFormat(); 6650 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6651 pw.println(dateString + ": " + msg); 6652 pw.close(); 6653 FileUtils.setPermissions( 6654 fname.toString(), 6655 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6656 -1, -1); 6657 } catch (java.io.IOException e) { 6658 } 6659 } 6660 6661 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6662 final int policyFlags) throws PackageManagerException { 6663 if (ps != null 6664 && ps.codePath.equals(srcFile) 6665 && ps.timeStamp == srcFile.lastModified() 6666 && !isCompatSignatureUpdateNeeded(pkg) 6667 && !isRecoverSignatureUpdateNeeded(pkg)) { 6668 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6669 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6670 ArraySet<PublicKey> signingKs; 6671 synchronized (mPackages) { 6672 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6673 } 6674 if (ps.signatures.mSignatures != null 6675 && ps.signatures.mSignatures.length != 0 6676 && signingKs != null) { 6677 // Optimization: reuse the existing cached certificates 6678 // if the package appears to be unchanged. 6679 pkg.mSignatures = ps.signatures.mSignatures; 6680 pkg.mSigningKeys = signingKs; 6681 return; 6682 } 6683 6684 Slog.w(TAG, "PackageSetting for " + ps.name 6685 + " is missing signatures. Collecting certs again to recover them."); 6686 } else { 6687 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6688 } 6689 6690 try { 6691 PackageParser.collectCertificates(pkg, policyFlags); 6692 } catch (PackageParserException e) { 6693 throw PackageManagerException.from(e); 6694 } 6695 } 6696 6697 /** 6698 * Traces a package scan. 6699 * @see #scanPackageLI(File, int, int, long, UserHandle) 6700 */ 6701 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6702 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6703 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6704 try { 6705 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6706 } finally { 6707 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6708 } 6709 } 6710 6711 /** 6712 * Scans a package and returns the newly parsed package. 6713 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6714 */ 6715 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6716 long currentTime, UserHandle user) throws PackageManagerException { 6717 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6718 PackageParser pp = new PackageParser(); 6719 pp.setSeparateProcesses(mSeparateProcesses); 6720 pp.setOnlyCoreApps(mOnlyCore); 6721 pp.setDisplayMetrics(mMetrics); 6722 6723 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6724 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6725 } 6726 6727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6728 final PackageParser.Package pkg; 6729 try { 6730 pkg = pp.parsePackage(scanFile, parseFlags); 6731 } catch (PackageParserException e) { 6732 throw PackageManagerException.from(e); 6733 } finally { 6734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6735 } 6736 6737 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6738 } 6739 6740 /** 6741 * Scans a package and returns the newly parsed package. 6742 * @throws PackageManagerException on a parse error. 6743 */ 6744 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6745 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6746 throws PackageManagerException { 6747 // If the package has children and this is the first dive in the function 6748 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6749 // packages (parent and children) would be successfully scanned before the 6750 // actual scan since scanning mutates internal state and we want to atomically 6751 // install the package and its children. 6752 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6753 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6754 scanFlags |= SCAN_CHECK_ONLY; 6755 } 6756 } else { 6757 scanFlags &= ~SCAN_CHECK_ONLY; 6758 } 6759 6760 // Scan the parent 6761 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6762 scanFlags, currentTime, user); 6763 6764 // Scan the children 6765 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6766 for (int i = 0; i < childCount; i++) { 6767 PackageParser.Package childPackage = pkg.childPackages.get(i); 6768 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6769 currentTime, user); 6770 } 6771 6772 6773 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6774 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6775 } 6776 6777 return scannedPkg; 6778 } 6779 6780 /** 6781 * Scans a package and returns the newly parsed package. 6782 * @throws PackageManagerException on a parse error. 6783 */ 6784 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6785 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6786 throws PackageManagerException { 6787 PackageSetting ps = null; 6788 PackageSetting updatedPkg; 6789 // reader 6790 synchronized (mPackages) { 6791 // Look to see if we already know about this package. 6792 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6793 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6794 // This package has been renamed to its original name. Let's 6795 // use that. 6796 ps = mSettings.peekPackageLPr(oldName); 6797 } 6798 // If there was no original package, see one for the real package name. 6799 if (ps == null) { 6800 ps = mSettings.peekPackageLPr(pkg.packageName); 6801 } 6802 // Check to see if this package could be hiding/updating a system 6803 // package. Must look for it either under the original or real 6804 // package name depending on our state. 6805 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6806 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6807 6808 // If this is a package we don't know about on the system partition, we 6809 // may need to remove disabled child packages on the system partition 6810 // or may need to not add child packages if the parent apk is updated 6811 // on the data partition and no longer defines this child package. 6812 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6813 // If this is a parent package for an updated system app and this system 6814 // app got an OTA update which no longer defines some of the child packages 6815 // we have to prune them from the disabled system packages. 6816 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6817 if (disabledPs != null) { 6818 final int scannedChildCount = (pkg.childPackages != null) 6819 ? pkg.childPackages.size() : 0; 6820 final int disabledChildCount = disabledPs.childPackageNames != null 6821 ? disabledPs.childPackageNames.size() : 0; 6822 for (int i = 0; i < disabledChildCount; i++) { 6823 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6824 boolean disabledPackageAvailable = false; 6825 for (int j = 0; j < scannedChildCount; j++) { 6826 PackageParser.Package childPkg = pkg.childPackages.get(j); 6827 if (childPkg.packageName.equals(disabledChildPackageName)) { 6828 disabledPackageAvailable = true; 6829 break; 6830 } 6831 } 6832 if (!disabledPackageAvailable) { 6833 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6834 } 6835 } 6836 } 6837 } 6838 } 6839 6840 boolean updatedPkgBetter = false; 6841 // First check if this is a system package that may involve an update 6842 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6843 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6844 // it needs to drop FLAG_PRIVILEGED. 6845 if (locationIsPrivileged(scanFile)) { 6846 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6847 } else { 6848 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6849 } 6850 6851 if (ps != null && !ps.codePath.equals(scanFile)) { 6852 // The path has changed from what was last scanned... check the 6853 // version of the new path against what we have stored to determine 6854 // what to do. 6855 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6856 if (pkg.mVersionCode <= ps.versionCode) { 6857 // The system package has been updated and the code path does not match 6858 // Ignore entry. Skip it. 6859 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6860 + " ignored: updated version " + ps.versionCode 6861 + " better than this " + pkg.mVersionCode); 6862 if (!updatedPkg.codePath.equals(scanFile)) { 6863 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6864 + ps.name + " changing from " + updatedPkg.codePathString 6865 + " to " + scanFile); 6866 updatedPkg.codePath = scanFile; 6867 updatedPkg.codePathString = scanFile.toString(); 6868 updatedPkg.resourcePath = scanFile; 6869 updatedPkg.resourcePathString = scanFile.toString(); 6870 } 6871 updatedPkg.pkg = pkg; 6872 updatedPkg.versionCode = pkg.mVersionCode; 6873 6874 // Update the disabled system child packages to point to the package too. 6875 final int childCount = updatedPkg.childPackageNames != null 6876 ? updatedPkg.childPackageNames.size() : 0; 6877 for (int i = 0; i < childCount; i++) { 6878 String childPackageName = updatedPkg.childPackageNames.get(i); 6879 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6880 childPackageName); 6881 if (updatedChildPkg != null) { 6882 updatedChildPkg.pkg = pkg; 6883 updatedChildPkg.versionCode = pkg.mVersionCode; 6884 } 6885 } 6886 6887 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6888 + scanFile + " ignored: updated version " + ps.versionCode 6889 + " better than this " + pkg.mVersionCode); 6890 } else { 6891 // The current app on the system partition is better than 6892 // what we have updated to on the data partition; switch 6893 // back to the system partition version. 6894 // At this point, its safely assumed that package installation for 6895 // apps in system partition will go through. If not there won't be a working 6896 // version of the app 6897 // writer 6898 synchronized (mPackages) { 6899 // Just remove the loaded entries from package lists. 6900 mPackages.remove(ps.name); 6901 } 6902 6903 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6904 + " reverting from " + ps.codePathString 6905 + ": new version " + pkg.mVersionCode 6906 + " better than installed " + ps.versionCode); 6907 6908 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6909 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6910 synchronized (mInstallLock) { 6911 args.cleanUpResourcesLI(); 6912 } 6913 synchronized (mPackages) { 6914 mSettings.enableSystemPackageLPw(ps.name); 6915 } 6916 updatedPkgBetter = true; 6917 } 6918 } 6919 } 6920 6921 if (updatedPkg != null) { 6922 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6923 // initially 6924 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6925 6926 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6927 // flag set initially 6928 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6929 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6930 } 6931 } 6932 6933 // Verify certificates against what was last scanned 6934 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6935 6936 /* 6937 * A new system app appeared, but we already had a non-system one of the 6938 * same name installed earlier. 6939 */ 6940 boolean shouldHideSystemApp = false; 6941 if (updatedPkg == null && ps != null 6942 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6943 /* 6944 * Check to make sure the signatures match first. If they don't, 6945 * wipe the installed application and its data. 6946 */ 6947 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6948 != PackageManager.SIGNATURE_MATCH) { 6949 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6950 + " signatures don't match existing userdata copy; removing"); 6951 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6952 "scanPackageInternalLI")) { 6953 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6954 } 6955 ps = null; 6956 } else { 6957 /* 6958 * If the newly-added system app is an older version than the 6959 * already installed version, hide it. It will be scanned later 6960 * and re-added like an update. 6961 */ 6962 if (pkg.mVersionCode <= ps.versionCode) { 6963 shouldHideSystemApp = true; 6964 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6965 + " but new version " + pkg.mVersionCode + " better than installed " 6966 + ps.versionCode + "; hiding system"); 6967 } else { 6968 /* 6969 * The newly found system app is a newer version that the 6970 * one previously installed. Simply remove the 6971 * already-installed application and replace it with our own 6972 * while keeping the application data. 6973 */ 6974 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6975 + " reverting from " + ps.codePathString + ": new version " 6976 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6977 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6978 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6979 synchronized (mInstallLock) { 6980 args.cleanUpResourcesLI(); 6981 } 6982 } 6983 } 6984 } 6985 6986 // The apk is forward locked (not public) if its code and resources 6987 // are kept in different files. (except for app in either system or 6988 // vendor path). 6989 // TODO grab this value from PackageSettings 6990 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6991 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6992 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6993 } 6994 } 6995 6996 // TODO: extend to support forward-locked splits 6997 String resourcePath = null; 6998 String baseResourcePath = null; 6999 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7000 if (ps != null && ps.resourcePathString != null) { 7001 resourcePath = ps.resourcePathString; 7002 baseResourcePath = ps.resourcePathString; 7003 } else { 7004 // Should not happen at all. Just log an error. 7005 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7006 } 7007 } else { 7008 resourcePath = pkg.codePath; 7009 baseResourcePath = pkg.baseCodePath; 7010 } 7011 7012 // Set application objects path explicitly. 7013 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7014 pkg.setApplicationInfoCodePath(pkg.codePath); 7015 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7016 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7017 pkg.setApplicationInfoResourcePath(resourcePath); 7018 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7019 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7020 7021 // Note that we invoke the following method only if we are about to unpack an application 7022 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7023 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7024 7025 /* 7026 * If the system app should be overridden by a previously installed 7027 * data, hide the system app now and let the /data/app scan pick it up 7028 * again. 7029 */ 7030 if (shouldHideSystemApp) { 7031 synchronized (mPackages) { 7032 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7033 } 7034 } 7035 7036 return scannedPkg; 7037 } 7038 7039 private static String fixProcessName(String defProcessName, 7040 String processName, int uid) { 7041 if (processName == null) { 7042 return defProcessName; 7043 } 7044 return processName; 7045 } 7046 7047 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7048 throws PackageManagerException { 7049 if (pkgSetting.signatures.mSignatures != null) { 7050 // Already existing package. Make sure signatures match 7051 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7052 == PackageManager.SIGNATURE_MATCH; 7053 if (!match) { 7054 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7055 == PackageManager.SIGNATURE_MATCH; 7056 } 7057 if (!match) { 7058 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7059 == PackageManager.SIGNATURE_MATCH; 7060 } 7061 if (!match) { 7062 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7063 + pkg.packageName + " signatures do not match the " 7064 + "previously installed version; ignoring!"); 7065 } 7066 } 7067 7068 // Check for shared user signatures 7069 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7070 // Already existing package. Make sure signatures match 7071 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7072 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7073 if (!match) { 7074 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7075 == PackageManager.SIGNATURE_MATCH; 7076 } 7077 if (!match) { 7078 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7079 == PackageManager.SIGNATURE_MATCH; 7080 } 7081 if (!match) { 7082 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7083 "Package " + pkg.packageName 7084 + " has no signatures that match those in shared user " 7085 + pkgSetting.sharedUser.name + "; ignoring!"); 7086 } 7087 } 7088 } 7089 7090 /** 7091 * Enforces that only the system UID or root's UID can call a method exposed 7092 * via Binder. 7093 * 7094 * @param message used as message if SecurityException is thrown 7095 * @throws SecurityException if the caller is not system or root 7096 */ 7097 private static final void enforceSystemOrRoot(String message) { 7098 final int uid = Binder.getCallingUid(); 7099 if (uid != Process.SYSTEM_UID && uid != 0) { 7100 throw new SecurityException(message); 7101 } 7102 } 7103 7104 @Override 7105 public void performFstrimIfNeeded() { 7106 enforceSystemOrRoot("Only the system can request fstrim"); 7107 7108 // Before everything else, see whether we need to fstrim. 7109 try { 7110 IMountService ms = PackageHelper.getMountService(); 7111 if (ms != null) { 7112 final boolean isUpgrade = isUpgrade(); 7113 boolean doTrim = isUpgrade; 7114 if (doTrim) { 7115 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7116 } else { 7117 final long interval = android.provider.Settings.Global.getLong( 7118 mContext.getContentResolver(), 7119 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7120 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7121 if (interval > 0) { 7122 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7123 if (timeSinceLast > interval) { 7124 doTrim = true; 7125 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7126 + "; running immediately"); 7127 } 7128 } 7129 } 7130 if (doTrim) { 7131 if (!isFirstBoot()) { 7132 try { 7133 ActivityManagerNative.getDefault().showBootMessage( 7134 mContext.getResources().getString( 7135 R.string.android_upgrading_fstrim), true); 7136 } catch (RemoteException e) { 7137 } 7138 } 7139 ms.runMaintenance(); 7140 } 7141 } else { 7142 Slog.e(TAG, "Mount service unavailable!"); 7143 } 7144 } catch (RemoteException e) { 7145 // Can't happen; MountService is local 7146 } 7147 } 7148 7149 @Override 7150 public void updatePackagesIfNeeded() { 7151 enforceSystemOrRoot("Only the system can request package update"); 7152 7153 // We need to re-extract after an OTA. 7154 boolean causeUpgrade = isUpgrade(); 7155 7156 // First boot or factory reset. 7157 // Note: we also handle devices that are upgrading to N right now as if it is their 7158 // first boot, as they do not have profile data. 7159 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7160 7161 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7162 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7163 7164 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7165 return; 7166 } 7167 7168 List<PackageParser.Package> pkgs; 7169 synchronized (mPackages) { 7170 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7171 } 7172 7173 int curr = 0; 7174 int total = pkgs.size(); 7175 for (PackageParser.Package pkg : pkgs) { 7176 curr++; 7177 7178 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7179 if (DEBUG_DEXOPT) { 7180 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7181 } 7182 continue; 7183 } 7184 7185 if (DEBUG_DEXOPT) { 7186 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7187 } 7188 7189 if (!isFirstBoot()) { 7190 try { 7191 ActivityManagerNative.getDefault().showBootMessage( 7192 mContext.getResources().getString(R.string.android_upgrading_apk, 7193 curr, total), true); 7194 } catch (RemoteException e) { 7195 } 7196 } 7197 7198 performDexOpt(pkg.packageName, 7199 null /* instructionSet */, 7200 true /* checkProfiles */, 7201 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7202 false /* force */); 7203 } 7204 } 7205 7206 @Override 7207 public void notifyPackageUse(String packageName, int reason) { 7208 synchronized (mPackages) { 7209 PackageParser.Package p = mPackages.get(packageName); 7210 if (p == null) { 7211 return; 7212 } 7213 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7214 } 7215 } 7216 7217 // TODO: this is not used nor needed. Delete it. 7218 @Override 7219 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7220 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7221 getFullCompilerFilter(), false /* force */); 7222 } 7223 7224 @Override 7225 public boolean performDexOpt(String packageName, String instructionSet, 7226 boolean checkProfiles, int compileReason, boolean force) { 7227 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7228 getCompilerFilterForReason(compileReason), force); 7229 } 7230 7231 @Override 7232 public boolean performDexOptMode(String packageName, String instructionSet, 7233 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7234 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7235 targetCompilerFilter, force); 7236 } 7237 7238 private boolean performDexOptTraced(String packageName, String instructionSet, 7239 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7240 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7241 try { 7242 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7243 targetCompilerFilter, force); 7244 } finally { 7245 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7246 } 7247 } 7248 7249 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7250 // if the package can now be considered up to date for the given filter. 7251 private boolean performDexOptInternal(String packageName, String instructionSet, 7252 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7253 PackageParser.Package p; 7254 final String targetInstructionSet; 7255 synchronized (mPackages) { 7256 p = mPackages.get(packageName); 7257 if (p == null) { 7258 return false; 7259 } 7260 mPackageUsage.write(false); 7261 7262 targetInstructionSet = instructionSet != null ? instructionSet : 7263 getPrimaryInstructionSet(p.applicationInfo); 7264 } 7265 long callingId = Binder.clearCallingIdentity(); 7266 try { 7267 synchronized (mInstallLock) { 7268 final String[] instructionSets = new String[] { targetInstructionSet }; 7269 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7270 checkProfiles, targetCompilerFilter, force); 7271 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7272 } 7273 } finally { 7274 Binder.restoreCallingIdentity(callingId); 7275 } 7276 } 7277 7278 public ArraySet<String> getOptimizablePackages() { 7279 ArraySet<String> pkgs = new ArraySet<String>(); 7280 synchronized (mPackages) { 7281 for (PackageParser.Package p : mPackages.values()) { 7282 if (PackageDexOptimizer.canOptimizePackage(p)) { 7283 pkgs.add(p.packageName); 7284 } 7285 } 7286 } 7287 return pkgs; 7288 } 7289 7290 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7291 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7292 boolean force) { 7293 // Select the dex optimizer based on the force parameter. 7294 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7295 // allocate an object here. 7296 PackageDexOptimizer pdo = force 7297 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7298 : mPackageDexOptimizer; 7299 7300 // Optimize all dependencies first. Note: we ignore the return value and march on 7301 // on errors. 7302 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7303 if (!deps.isEmpty()) { 7304 for (PackageParser.Package depPackage : deps) { 7305 // TODO: Analyze and investigate if we (should) profile libraries. 7306 // Currently this will do a full compilation of the library by default. 7307 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7308 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7309 } 7310 } 7311 7312 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7313 } 7314 7315 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7316 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7317 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7318 Set<String> collectedNames = new HashSet<>(); 7319 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7320 7321 retValue.remove(p); 7322 7323 return retValue; 7324 } else { 7325 return Collections.emptyList(); 7326 } 7327 } 7328 7329 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7330 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7331 if (!collectedNames.contains(p.packageName)) { 7332 collectedNames.add(p.packageName); 7333 collected.add(p); 7334 7335 if (p.usesLibraries != null) { 7336 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7337 } 7338 if (p.usesOptionalLibraries != null) { 7339 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7340 collectedNames); 7341 } 7342 } 7343 } 7344 7345 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7346 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7347 for (String libName : libs) { 7348 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7349 if (libPkg != null) { 7350 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7351 } 7352 } 7353 } 7354 7355 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7356 synchronized (mPackages) { 7357 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7358 if (lib != null && lib.apk != null) { 7359 return mPackages.get(lib.apk); 7360 } 7361 } 7362 return null; 7363 } 7364 7365 public void shutdown() { 7366 mPackageUsage.write(true); 7367 } 7368 7369 @Override 7370 public void forceDexOpt(String packageName) { 7371 enforceSystemOrRoot("forceDexOpt"); 7372 7373 PackageParser.Package pkg; 7374 synchronized (mPackages) { 7375 pkg = mPackages.get(packageName); 7376 if (pkg == null) { 7377 throw new IllegalArgumentException("Unknown package: " + packageName); 7378 } 7379 } 7380 7381 synchronized (mInstallLock) { 7382 final String[] instructionSets = new String[] { 7383 getPrimaryInstructionSet(pkg.applicationInfo) }; 7384 7385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7386 7387 // Whoever is calling forceDexOpt wants a fully compiled package. 7388 // Don't use profiles since that may cause compilation to be skipped. 7389 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7390 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7391 true /* force */); 7392 7393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7394 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7395 throw new IllegalStateException("Failed to dexopt: " + res); 7396 } 7397 } 7398 } 7399 7400 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7401 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7402 Slog.w(TAG, "Unable to update from " + oldPkg.name 7403 + " to " + newPkg.packageName 7404 + ": old package not in system partition"); 7405 return false; 7406 } else if (mPackages.get(oldPkg.name) != null) { 7407 Slog.w(TAG, "Unable to update from " + oldPkg.name 7408 + " to " + newPkg.packageName 7409 + ": old package still exists"); 7410 return false; 7411 } 7412 return true; 7413 } 7414 7415 void removeCodePathLI(File codePath) { 7416 if (codePath.isDirectory()) { 7417 try { 7418 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7419 } catch (InstallerException e) { 7420 Slog.w(TAG, "Failed to remove code path", e); 7421 } 7422 } else { 7423 codePath.delete(); 7424 } 7425 } 7426 7427 private int[] resolveUserIds(int userId) { 7428 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7429 } 7430 7431 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7432 if (pkg == null) { 7433 Slog.wtf(TAG, "Package was null!", new Throwable()); 7434 return; 7435 } 7436 clearAppDataLeafLIF(pkg, userId, flags); 7437 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7438 for (int i = 0; i < childCount; i++) { 7439 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7440 } 7441 } 7442 7443 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7444 final PackageSetting ps; 7445 synchronized (mPackages) { 7446 ps = mSettings.mPackages.get(pkg.packageName); 7447 } 7448 for (int realUserId : resolveUserIds(userId)) { 7449 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7450 try { 7451 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7452 ceDataInode); 7453 } catch (InstallerException e) { 7454 Slog.w(TAG, String.valueOf(e)); 7455 } 7456 } 7457 } 7458 7459 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7460 if (pkg == null) { 7461 Slog.wtf(TAG, "Package was null!", new Throwable()); 7462 return; 7463 } 7464 destroyAppDataLeafLIF(pkg, userId, flags); 7465 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7466 for (int i = 0; i < childCount; i++) { 7467 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7468 } 7469 } 7470 7471 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7472 final PackageSetting ps; 7473 synchronized (mPackages) { 7474 ps = mSettings.mPackages.get(pkg.packageName); 7475 } 7476 for (int realUserId : resolveUserIds(userId)) { 7477 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7478 try { 7479 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7480 ceDataInode); 7481 } catch (InstallerException e) { 7482 Slog.w(TAG, String.valueOf(e)); 7483 } 7484 } 7485 } 7486 7487 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7488 if (pkg == null) { 7489 Slog.wtf(TAG, "Package was null!", new Throwable()); 7490 return; 7491 } 7492 destroyAppProfilesLeafLIF(pkg); 7493 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7494 for (int i = 0; i < childCount; i++) { 7495 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7496 } 7497 } 7498 7499 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7500 try { 7501 mInstaller.destroyAppProfiles(pkg.packageName); 7502 } catch (InstallerException e) { 7503 Slog.w(TAG, String.valueOf(e)); 7504 } 7505 } 7506 7507 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7508 if (pkg == null) { 7509 Slog.wtf(TAG, "Package was null!", new Throwable()); 7510 return; 7511 } 7512 clearAppProfilesLeafLIF(pkg); 7513 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7514 for (int i = 0; i < childCount; i++) { 7515 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7516 } 7517 } 7518 7519 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7520 try { 7521 mInstaller.clearAppProfiles(pkg.packageName); 7522 } catch (InstallerException e) { 7523 Slog.w(TAG, String.valueOf(e)); 7524 } 7525 } 7526 7527 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7528 long lastUpdateTime) { 7529 // Set parent install/update time 7530 PackageSetting ps = (PackageSetting) pkg.mExtras; 7531 if (ps != null) { 7532 ps.firstInstallTime = firstInstallTime; 7533 ps.lastUpdateTime = lastUpdateTime; 7534 } 7535 // Set children install/update time 7536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7537 for (int i = 0; i < childCount; i++) { 7538 PackageParser.Package childPkg = pkg.childPackages.get(i); 7539 ps = (PackageSetting) childPkg.mExtras; 7540 if (ps != null) { 7541 ps.firstInstallTime = firstInstallTime; 7542 ps.lastUpdateTime = lastUpdateTime; 7543 } 7544 } 7545 } 7546 7547 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7548 PackageParser.Package changingLib) { 7549 if (file.path != null) { 7550 usesLibraryFiles.add(file.path); 7551 return; 7552 } 7553 PackageParser.Package p = mPackages.get(file.apk); 7554 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7555 // If we are doing this while in the middle of updating a library apk, 7556 // then we need to make sure to use that new apk for determining the 7557 // dependencies here. (We haven't yet finished committing the new apk 7558 // to the package manager state.) 7559 if (p == null || p.packageName.equals(changingLib.packageName)) { 7560 p = changingLib; 7561 } 7562 } 7563 if (p != null) { 7564 usesLibraryFiles.addAll(p.getAllCodePaths()); 7565 } 7566 } 7567 7568 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7569 PackageParser.Package changingLib) throws PackageManagerException { 7570 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7571 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7572 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7573 for (int i=0; i<N; i++) { 7574 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7575 if (file == null) { 7576 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7577 "Package " + pkg.packageName + " requires unavailable shared library " 7578 + pkg.usesLibraries.get(i) + "; failing!"); 7579 } 7580 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7581 } 7582 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7583 for (int i=0; i<N; i++) { 7584 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7585 if (file == null) { 7586 Slog.w(TAG, "Package " + pkg.packageName 7587 + " desires unavailable shared library " 7588 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7589 } else { 7590 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7591 } 7592 } 7593 N = usesLibraryFiles.size(); 7594 if (N > 0) { 7595 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7596 } else { 7597 pkg.usesLibraryFiles = null; 7598 } 7599 } 7600 } 7601 7602 private static boolean hasString(List<String> list, List<String> which) { 7603 if (list == null) { 7604 return false; 7605 } 7606 for (int i=list.size()-1; i>=0; i--) { 7607 for (int j=which.size()-1; j>=0; j--) { 7608 if (which.get(j).equals(list.get(i))) { 7609 return true; 7610 } 7611 } 7612 } 7613 return false; 7614 } 7615 7616 private void updateAllSharedLibrariesLPw() { 7617 for (PackageParser.Package pkg : mPackages.values()) { 7618 try { 7619 updateSharedLibrariesLPw(pkg, null); 7620 } catch (PackageManagerException e) { 7621 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7622 } 7623 } 7624 } 7625 7626 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7627 PackageParser.Package changingPkg) { 7628 ArrayList<PackageParser.Package> res = null; 7629 for (PackageParser.Package pkg : mPackages.values()) { 7630 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7631 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7632 if (res == null) { 7633 res = new ArrayList<PackageParser.Package>(); 7634 } 7635 res.add(pkg); 7636 try { 7637 updateSharedLibrariesLPw(pkg, changingPkg); 7638 } catch (PackageManagerException e) { 7639 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7640 } 7641 } 7642 } 7643 return res; 7644 } 7645 7646 /** 7647 * Derive the value of the {@code cpuAbiOverride} based on the provided 7648 * value and an optional stored value from the package settings. 7649 */ 7650 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7651 String cpuAbiOverride = null; 7652 7653 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7654 cpuAbiOverride = null; 7655 } else if (abiOverride != null) { 7656 cpuAbiOverride = abiOverride; 7657 } else if (settings != null) { 7658 cpuAbiOverride = settings.cpuAbiOverrideString; 7659 } 7660 7661 return cpuAbiOverride; 7662 } 7663 7664 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7665 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7666 throws PackageManagerException { 7667 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7668 // If the package has children and this is the first dive in the function 7669 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7670 // whether all packages (parent and children) would be successfully scanned 7671 // before the actual scan since scanning mutates internal state and we want 7672 // to atomically install the package and its children. 7673 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7674 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7675 scanFlags |= SCAN_CHECK_ONLY; 7676 } 7677 } else { 7678 scanFlags &= ~SCAN_CHECK_ONLY; 7679 } 7680 7681 final PackageParser.Package scannedPkg; 7682 try { 7683 // Scan the parent 7684 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7685 // Scan the children 7686 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7687 for (int i = 0; i < childCount; i++) { 7688 PackageParser.Package childPkg = pkg.childPackages.get(i); 7689 scanPackageLI(childPkg, policyFlags, 7690 scanFlags, currentTime, user); 7691 } 7692 } finally { 7693 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7694 } 7695 7696 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7697 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7698 } 7699 7700 return scannedPkg; 7701 } 7702 7703 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7704 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7705 boolean success = false; 7706 try { 7707 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7708 currentTime, user); 7709 success = true; 7710 return res; 7711 } finally { 7712 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7713 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7714 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7715 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7716 destroyAppProfilesLIF(pkg); 7717 } 7718 } 7719 } 7720 7721 /** 7722 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7723 */ 7724 private static boolean apkHasCode(String fileName) { 7725 StrictJarFile jarFile = null; 7726 try { 7727 jarFile = new StrictJarFile(fileName, 7728 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7729 return jarFile.findEntry("classes.dex") != null; 7730 } catch (IOException ignore) { 7731 } finally { 7732 try { 7733 jarFile.close(); 7734 } catch (IOException ignore) {} 7735 } 7736 return false; 7737 } 7738 7739 /** 7740 * Enforces code policy for the package. This ensures that if an APK has 7741 * declared hasCode="true" in its manifest that the APK actually contains 7742 * code. 7743 * 7744 * @throws PackageManagerException If bytecode could not be found when it should exist 7745 */ 7746 private static void enforceCodePolicy(PackageParser.Package pkg) 7747 throws PackageManagerException { 7748 final boolean shouldHaveCode = 7749 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7750 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7751 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7752 "Package " + pkg.baseCodePath + " code is missing"); 7753 } 7754 7755 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7756 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7757 final boolean splitShouldHaveCode = 7758 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7759 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7760 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7761 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7762 } 7763 } 7764 } 7765 } 7766 7767 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7768 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7769 throws PackageManagerException { 7770 final File scanFile = new File(pkg.codePath); 7771 if (pkg.applicationInfo.getCodePath() == null || 7772 pkg.applicationInfo.getResourcePath() == null) { 7773 // Bail out. The resource and code paths haven't been set. 7774 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7775 "Code and resource paths haven't been set correctly"); 7776 } 7777 7778 // Apply policy 7779 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7780 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7781 if (pkg.applicationInfo.isDirectBootAware()) { 7782 // we're direct boot aware; set for all components 7783 for (PackageParser.Service s : pkg.services) { 7784 s.info.encryptionAware = s.info.directBootAware = true; 7785 } 7786 for (PackageParser.Provider p : pkg.providers) { 7787 p.info.encryptionAware = p.info.directBootAware = true; 7788 } 7789 for (PackageParser.Activity a : pkg.activities) { 7790 a.info.encryptionAware = a.info.directBootAware = true; 7791 } 7792 for (PackageParser.Activity r : pkg.receivers) { 7793 r.info.encryptionAware = r.info.directBootAware = true; 7794 } 7795 } 7796 } else { 7797 // Only allow system apps to be flagged as core apps. 7798 pkg.coreApp = false; 7799 // clear flags not applicable to regular apps 7800 pkg.applicationInfo.privateFlags &= 7801 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7802 pkg.applicationInfo.privateFlags &= 7803 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7804 } 7805 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7806 7807 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7808 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7809 } 7810 7811 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7812 enforceCodePolicy(pkg); 7813 } 7814 7815 if (mCustomResolverComponentName != null && 7816 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7817 setUpCustomResolverActivity(pkg); 7818 } 7819 7820 if (pkg.packageName.equals("android")) { 7821 synchronized (mPackages) { 7822 if (mAndroidApplication != null) { 7823 Slog.w(TAG, "*************************************************"); 7824 Slog.w(TAG, "Core android package being redefined. Skipping."); 7825 Slog.w(TAG, " file=" + scanFile); 7826 Slog.w(TAG, "*************************************************"); 7827 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7828 "Core android package being redefined. Skipping."); 7829 } 7830 7831 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7832 // Set up information for our fall-back user intent resolution activity. 7833 mPlatformPackage = pkg; 7834 pkg.mVersionCode = mSdkVersion; 7835 mAndroidApplication = pkg.applicationInfo; 7836 7837 if (!mResolverReplaced) { 7838 mResolveActivity.applicationInfo = mAndroidApplication; 7839 mResolveActivity.name = ResolverActivity.class.getName(); 7840 mResolveActivity.packageName = mAndroidApplication.packageName; 7841 mResolveActivity.processName = "system:ui"; 7842 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7843 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7844 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7845 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7846 mResolveActivity.exported = true; 7847 mResolveActivity.enabled = true; 7848 mResolveInfo.activityInfo = mResolveActivity; 7849 mResolveInfo.priority = 0; 7850 mResolveInfo.preferredOrder = 0; 7851 mResolveInfo.match = 0; 7852 mResolveComponentName = new ComponentName( 7853 mAndroidApplication.packageName, mResolveActivity.name); 7854 } 7855 } 7856 } 7857 } 7858 7859 if (DEBUG_PACKAGE_SCANNING) { 7860 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7861 Log.d(TAG, "Scanning package " + pkg.packageName); 7862 } 7863 7864 synchronized (mPackages) { 7865 if (mPackages.containsKey(pkg.packageName) 7866 || mSharedLibraries.containsKey(pkg.packageName)) { 7867 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7868 "Application package " + pkg.packageName 7869 + " already installed. Skipping duplicate."); 7870 } 7871 7872 // If we're only installing presumed-existing packages, require that the 7873 // scanned APK is both already known and at the path previously established 7874 // for it. Previously unknown packages we pick up normally, but if we have an 7875 // a priori expectation about this package's install presence, enforce it. 7876 // With a singular exception for new system packages. When an OTA contains 7877 // a new system package, we allow the codepath to change from a system location 7878 // to the user-installed location. If we don't allow this change, any newer, 7879 // user-installed version of the application will be ignored. 7880 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7881 if (mExpectingBetter.containsKey(pkg.packageName)) { 7882 logCriticalInfo(Log.WARN, 7883 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7884 } else { 7885 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7886 if (known != null) { 7887 if (DEBUG_PACKAGE_SCANNING) { 7888 Log.d(TAG, "Examining " + pkg.codePath 7889 + " and requiring known paths " + known.codePathString 7890 + " & " + known.resourcePathString); 7891 } 7892 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7893 || !pkg.applicationInfo.getResourcePath().equals( 7894 known.resourcePathString)) { 7895 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7896 "Application package " + pkg.packageName 7897 + " found at " + pkg.applicationInfo.getCodePath() 7898 + " but expected at " + known.codePathString 7899 + "; ignoring."); 7900 } 7901 } 7902 } 7903 } 7904 } 7905 7906 // Initialize package source and resource directories 7907 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7908 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7909 7910 SharedUserSetting suid = null; 7911 PackageSetting pkgSetting = null; 7912 7913 if (!isSystemApp(pkg)) { 7914 // Only system apps can use these features. 7915 pkg.mOriginalPackages = null; 7916 pkg.mRealPackage = null; 7917 pkg.mAdoptPermissions = null; 7918 } 7919 7920 // Getting the package setting may have a side-effect, so if we 7921 // are only checking if scan would succeed, stash a copy of the 7922 // old setting to restore at the end. 7923 PackageSetting nonMutatedPs = null; 7924 7925 // writer 7926 synchronized (mPackages) { 7927 if (pkg.mSharedUserId != null) { 7928 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7929 if (suid == null) { 7930 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7931 "Creating application package " + pkg.packageName 7932 + " for shared user failed"); 7933 } 7934 if (DEBUG_PACKAGE_SCANNING) { 7935 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7936 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7937 + "): packages=" + suid.packages); 7938 } 7939 } 7940 7941 // Check if we are renaming from an original package name. 7942 PackageSetting origPackage = null; 7943 String realName = null; 7944 if (pkg.mOriginalPackages != null) { 7945 // This package may need to be renamed to a previously 7946 // installed name. Let's check on that... 7947 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7948 if (pkg.mOriginalPackages.contains(renamed)) { 7949 // This package had originally been installed as the 7950 // original name, and we have already taken care of 7951 // transitioning to the new one. Just update the new 7952 // one to continue using the old name. 7953 realName = pkg.mRealPackage; 7954 if (!pkg.packageName.equals(renamed)) { 7955 // Callers into this function may have already taken 7956 // care of renaming the package; only do it here if 7957 // it is not already done. 7958 pkg.setPackageName(renamed); 7959 } 7960 7961 } else { 7962 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7963 if ((origPackage = mSettings.peekPackageLPr( 7964 pkg.mOriginalPackages.get(i))) != null) { 7965 // We do have the package already installed under its 7966 // original name... should we use it? 7967 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7968 // New package is not compatible with original. 7969 origPackage = null; 7970 continue; 7971 } else if (origPackage.sharedUser != null) { 7972 // Make sure uid is compatible between packages. 7973 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7974 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7975 + " to " + pkg.packageName + ": old uid " 7976 + origPackage.sharedUser.name 7977 + " differs from " + pkg.mSharedUserId); 7978 origPackage = null; 7979 continue; 7980 } 7981 // TODO: Add case when shared user id is added [b/28144775] 7982 } else { 7983 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7984 + pkg.packageName + " to old name " + origPackage.name); 7985 } 7986 break; 7987 } 7988 } 7989 } 7990 } 7991 7992 if (mTransferedPackages.contains(pkg.packageName)) { 7993 Slog.w(TAG, "Package " + pkg.packageName 7994 + " was transferred to another, but its .apk remains"); 7995 } 7996 7997 // See comments in nonMutatedPs declaration 7998 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7999 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8000 if (foundPs != null) { 8001 nonMutatedPs = new PackageSetting(foundPs); 8002 } 8003 } 8004 8005 // Just create the setting, don't add it yet. For already existing packages 8006 // the PkgSetting exists already and doesn't have to be created. 8007 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8008 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8009 pkg.applicationInfo.primaryCpuAbi, 8010 pkg.applicationInfo.secondaryCpuAbi, 8011 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8012 user, false); 8013 if (pkgSetting == null) { 8014 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8015 "Creating application package " + pkg.packageName + " failed"); 8016 } 8017 8018 if (pkgSetting.origPackage != null) { 8019 // If we are first transitioning from an original package, 8020 // fix up the new package's name now. We need to do this after 8021 // looking up the package under its new name, so getPackageLP 8022 // can take care of fiddling things correctly. 8023 pkg.setPackageName(origPackage.name); 8024 8025 // File a report about this. 8026 String msg = "New package " + pkgSetting.realName 8027 + " renamed to replace old package " + pkgSetting.name; 8028 reportSettingsProblem(Log.WARN, msg); 8029 8030 // Make a note of it. 8031 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8032 mTransferedPackages.add(origPackage.name); 8033 } 8034 8035 // No longer need to retain this. 8036 pkgSetting.origPackage = null; 8037 } 8038 8039 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8040 // Make a note of it. 8041 mTransferedPackages.add(pkg.packageName); 8042 } 8043 8044 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8045 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8046 } 8047 8048 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8049 // Check all shared libraries and map to their actual file path. 8050 // We only do this here for apps not on a system dir, because those 8051 // are the only ones that can fail an install due to this. We 8052 // will take care of the system apps by updating all of their 8053 // library paths after the scan is done. 8054 updateSharedLibrariesLPw(pkg, null); 8055 } 8056 8057 if (mFoundPolicyFile) { 8058 SELinuxMMAC.assignSeinfoValue(pkg); 8059 } 8060 8061 pkg.applicationInfo.uid = pkgSetting.appId; 8062 pkg.mExtras = pkgSetting; 8063 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8064 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8065 // We just determined the app is signed correctly, so bring 8066 // over the latest parsed certs. 8067 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8068 } else { 8069 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8070 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8071 "Package " + pkg.packageName + " upgrade keys do not match the " 8072 + "previously installed version"); 8073 } else { 8074 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8075 String msg = "System package " + pkg.packageName 8076 + " signature changed; retaining data."; 8077 reportSettingsProblem(Log.WARN, msg); 8078 } 8079 } 8080 } else { 8081 try { 8082 verifySignaturesLP(pkgSetting, pkg); 8083 // We just determined the app is signed correctly, so bring 8084 // over the latest parsed certs. 8085 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8086 } catch (PackageManagerException e) { 8087 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8088 throw e; 8089 } 8090 // The signature has changed, but this package is in the system 8091 // image... let's recover! 8092 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8093 // However... if this package is part of a shared user, but it 8094 // doesn't match the signature of the shared user, let's fail. 8095 // What this means is that you can't change the signatures 8096 // associated with an overall shared user, which doesn't seem all 8097 // that unreasonable. 8098 if (pkgSetting.sharedUser != null) { 8099 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8100 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8101 throw new PackageManagerException( 8102 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8103 "Signature mismatch for shared user: " 8104 + pkgSetting.sharedUser); 8105 } 8106 } 8107 // File a report about this. 8108 String msg = "System package " + pkg.packageName 8109 + " signature changed; retaining data."; 8110 reportSettingsProblem(Log.WARN, msg); 8111 } 8112 } 8113 // Verify that this new package doesn't have any content providers 8114 // that conflict with existing packages. Only do this if the 8115 // package isn't already installed, since we don't want to break 8116 // things that are installed. 8117 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8118 final int N = pkg.providers.size(); 8119 int i; 8120 for (i=0; i<N; i++) { 8121 PackageParser.Provider p = pkg.providers.get(i); 8122 if (p.info.authority != null) { 8123 String names[] = p.info.authority.split(";"); 8124 for (int j = 0; j < names.length; j++) { 8125 if (mProvidersByAuthority.containsKey(names[j])) { 8126 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8127 final String otherPackageName = 8128 ((other != null && other.getComponentName() != null) ? 8129 other.getComponentName().getPackageName() : "?"); 8130 throw new PackageManagerException( 8131 INSTALL_FAILED_CONFLICTING_PROVIDER, 8132 "Can't install because provider name " + names[j] 8133 + " (in package " + pkg.applicationInfo.packageName 8134 + ") is already used by " + otherPackageName); 8135 } 8136 } 8137 } 8138 } 8139 } 8140 8141 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8142 // This package wants to adopt ownership of permissions from 8143 // another package. 8144 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8145 final String origName = pkg.mAdoptPermissions.get(i); 8146 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8147 if (orig != null) { 8148 if (verifyPackageUpdateLPr(orig, pkg)) { 8149 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8150 + pkg.packageName); 8151 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8152 } 8153 } 8154 } 8155 } 8156 } 8157 8158 final String pkgName = pkg.packageName; 8159 8160 final long scanFileTime = scanFile.lastModified(); 8161 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8162 pkg.applicationInfo.processName = fixProcessName( 8163 pkg.applicationInfo.packageName, 8164 pkg.applicationInfo.processName, 8165 pkg.applicationInfo.uid); 8166 8167 if (pkg != mPlatformPackage) { 8168 // Get all of our default paths setup 8169 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8170 } 8171 8172 final String path = scanFile.getPath(); 8173 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8174 8175 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8176 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8177 8178 // Some system apps still use directory structure for native libraries 8179 // in which case we might end up not detecting abi solely based on apk 8180 // structure. Try to detect abi based on directory structure. 8181 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8182 pkg.applicationInfo.primaryCpuAbi == null) { 8183 setBundledAppAbisAndRoots(pkg, pkgSetting); 8184 setNativeLibraryPaths(pkg); 8185 } 8186 8187 } else { 8188 if ((scanFlags & SCAN_MOVE) != 0) { 8189 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8190 // but we already have this packages package info in the PackageSetting. We just 8191 // use that and derive the native library path based on the new codepath. 8192 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8193 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8194 } 8195 8196 // Set native library paths again. For moves, the path will be updated based on the 8197 // ABIs we've determined above. For non-moves, the path will be updated based on the 8198 // ABIs we determined during compilation, but the path will depend on the final 8199 // package path (after the rename away from the stage path). 8200 setNativeLibraryPaths(pkg); 8201 } 8202 8203 // This is a special case for the "system" package, where the ABI is 8204 // dictated by the zygote configuration (and init.rc). We should keep track 8205 // of this ABI so that we can deal with "normal" applications that run under 8206 // the same UID correctly. 8207 if (mPlatformPackage == pkg) { 8208 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8209 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8210 } 8211 8212 // If there's a mismatch between the abi-override in the package setting 8213 // and the abiOverride specified for the install. Warn about this because we 8214 // would've already compiled the app without taking the package setting into 8215 // account. 8216 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8217 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8218 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8219 " for package " + pkg.packageName); 8220 } 8221 } 8222 8223 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8224 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8225 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8226 8227 // Copy the derived override back to the parsed package, so that we can 8228 // update the package settings accordingly. 8229 pkg.cpuAbiOverride = cpuAbiOverride; 8230 8231 if (DEBUG_ABI_SELECTION) { 8232 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8233 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8234 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8235 } 8236 8237 // Push the derived path down into PackageSettings so we know what to 8238 // clean up at uninstall time. 8239 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8240 8241 if (DEBUG_ABI_SELECTION) { 8242 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8243 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8244 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8245 } 8246 8247 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8248 // We don't do this here during boot because we can do it all 8249 // at once after scanning all existing packages. 8250 // 8251 // We also do this *before* we perform dexopt on this package, so that 8252 // we can avoid redundant dexopts, and also to make sure we've got the 8253 // code and package path correct. 8254 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8255 pkg, true /* boot complete */); 8256 } 8257 8258 if (mFactoryTest && pkg.requestedPermissions.contains( 8259 android.Manifest.permission.FACTORY_TEST)) { 8260 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8261 } 8262 8263 ArrayList<PackageParser.Package> clientLibPkgs = null; 8264 8265 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8266 if (nonMutatedPs != null) { 8267 synchronized (mPackages) { 8268 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8269 } 8270 } 8271 return pkg; 8272 } 8273 8274 // Only privileged apps and updated privileged apps can add child packages. 8275 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8276 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8277 throw new PackageManagerException("Only privileged apps and updated " 8278 + "privileged apps can add child packages. Ignoring package " 8279 + pkg.packageName); 8280 } 8281 final int childCount = pkg.childPackages.size(); 8282 for (int i = 0; i < childCount; i++) { 8283 PackageParser.Package childPkg = pkg.childPackages.get(i); 8284 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8285 childPkg.packageName)) { 8286 throw new PackageManagerException("Cannot override a child package of " 8287 + "another disabled system app. Ignoring package " + pkg.packageName); 8288 } 8289 } 8290 } 8291 8292 // writer 8293 synchronized (mPackages) { 8294 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8295 // Only system apps can add new shared libraries. 8296 if (pkg.libraryNames != null) { 8297 for (int i=0; i<pkg.libraryNames.size(); i++) { 8298 String name = pkg.libraryNames.get(i); 8299 boolean allowed = false; 8300 if (pkg.isUpdatedSystemApp()) { 8301 // New library entries can only be added through the 8302 // system image. This is important to get rid of a lot 8303 // of nasty edge cases: for example if we allowed a non- 8304 // system update of the app to add a library, then uninstalling 8305 // the update would make the library go away, and assumptions 8306 // we made such as through app install filtering would now 8307 // have allowed apps on the device which aren't compatible 8308 // with it. Better to just have the restriction here, be 8309 // conservative, and create many fewer cases that can negatively 8310 // impact the user experience. 8311 final PackageSetting sysPs = mSettings 8312 .getDisabledSystemPkgLPr(pkg.packageName); 8313 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8314 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8315 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8316 allowed = true; 8317 break; 8318 } 8319 } 8320 } 8321 } else { 8322 allowed = true; 8323 } 8324 if (allowed) { 8325 if (!mSharedLibraries.containsKey(name)) { 8326 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8327 } else if (!name.equals(pkg.packageName)) { 8328 Slog.w(TAG, "Package " + pkg.packageName + " library " 8329 + name + " already exists; skipping"); 8330 } 8331 } else { 8332 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8333 + name + " that is not declared on system image; skipping"); 8334 } 8335 } 8336 if ((scanFlags & SCAN_BOOTING) == 0) { 8337 // If we are not booting, we need to update any applications 8338 // that are clients of our shared library. If we are booting, 8339 // this will all be done once the scan is complete. 8340 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8341 } 8342 } 8343 } 8344 } 8345 8346 if ((scanFlags & SCAN_BOOTING) != 0) { 8347 // No apps can run during boot scan, so they don't need to be frozen 8348 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8349 // Caller asked to not kill app, so it's probably not frozen 8350 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8351 // Caller asked us to ignore frozen check for some reason; they 8352 // probably didn't know the package name 8353 } else { 8354 // We're doing major surgery on this package, so it better be frozen 8355 // right now to keep it from launching 8356 checkPackageFrozen(pkgName); 8357 } 8358 8359 // Also need to kill any apps that are dependent on the library. 8360 if (clientLibPkgs != null) { 8361 for (int i=0; i<clientLibPkgs.size(); i++) { 8362 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8363 killApplication(clientPkg.applicationInfo.packageName, 8364 clientPkg.applicationInfo.uid, "update lib"); 8365 } 8366 } 8367 8368 // Make sure we're not adding any bogus keyset info 8369 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8370 ksms.assertScannedPackageValid(pkg); 8371 8372 // writer 8373 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8374 8375 boolean createIdmapFailed = false; 8376 synchronized (mPackages) { 8377 // We don't expect installation to fail beyond this point 8378 8379 // Add the new setting to mSettings 8380 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8381 // Add the new setting to mPackages 8382 mPackages.put(pkg.applicationInfo.packageName, pkg); 8383 // Make sure we don't accidentally delete its data. 8384 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8385 while (iter.hasNext()) { 8386 PackageCleanItem item = iter.next(); 8387 if (pkgName.equals(item.packageName)) { 8388 iter.remove(); 8389 } 8390 } 8391 8392 // Take care of first install / last update times. 8393 if (currentTime != 0) { 8394 if (pkgSetting.firstInstallTime == 0) { 8395 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8396 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8397 pkgSetting.lastUpdateTime = currentTime; 8398 } 8399 } else if (pkgSetting.firstInstallTime == 0) { 8400 // We need *something*. Take time time stamp of the file. 8401 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8402 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8403 if (scanFileTime != pkgSetting.timeStamp) { 8404 // A package on the system image has changed; consider this 8405 // to be an update. 8406 pkgSetting.lastUpdateTime = scanFileTime; 8407 } 8408 } 8409 8410 // Add the package's KeySets to the global KeySetManagerService 8411 ksms.addScannedPackageLPw(pkg); 8412 8413 int N = pkg.providers.size(); 8414 StringBuilder r = null; 8415 int i; 8416 for (i=0; i<N; i++) { 8417 PackageParser.Provider p = pkg.providers.get(i); 8418 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8419 p.info.processName, pkg.applicationInfo.uid); 8420 mProviders.addProvider(p); 8421 p.syncable = p.info.isSyncable; 8422 if (p.info.authority != null) { 8423 String names[] = p.info.authority.split(";"); 8424 p.info.authority = null; 8425 for (int j = 0; j < names.length; j++) { 8426 if (j == 1 && p.syncable) { 8427 // We only want the first authority for a provider to possibly be 8428 // syncable, so if we already added this provider using a different 8429 // authority clear the syncable flag. We copy the provider before 8430 // changing it because the mProviders object contains a reference 8431 // to a provider that we don't want to change. 8432 // Only do this for the second authority since the resulting provider 8433 // object can be the same for all future authorities for this provider. 8434 p = new PackageParser.Provider(p); 8435 p.syncable = false; 8436 } 8437 if (!mProvidersByAuthority.containsKey(names[j])) { 8438 mProvidersByAuthority.put(names[j], p); 8439 if (p.info.authority == null) { 8440 p.info.authority = names[j]; 8441 } else { 8442 p.info.authority = p.info.authority + ";" + names[j]; 8443 } 8444 if (DEBUG_PACKAGE_SCANNING) { 8445 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8446 Log.d(TAG, "Registered content provider: " + names[j] 8447 + ", className = " + p.info.name + ", isSyncable = " 8448 + p.info.isSyncable); 8449 } 8450 } else { 8451 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8452 Slog.w(TAG, "Skipping provider name " + names[j] + 8453 " (in package " + pkg.applicationInfo.packageName + 8454 "): name already used by " 8455 + ((other != null && other.getComponentName() != null) 8456 ? other.getComponentName().getPackageName() : "?")); 8457 } 8458 } 8459 } 8460 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8461 if (r == null) { 8462 r = new StringBuilder(256); 8463 } else { 8464 r.append(' '); 8465 } 8466 r.append(p.info.name); 8467 } 8468 } 8469 if (r != null) { 8470 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8471 } 8472 8473 N = pkg.services.size(); 8474 r = null; 8475 for (i=0; i<N; i++) { 8476 PackageParser.Service s = pkg.services.get(i); 8477 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8478 s.info.processName, pkg.applicationInfo.uid); 8479 mServices.addService(s); 8480 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8481 if (r == null) { 8482 r = new StringBuilder(256); 8483 } else { 8484 r.append(' '); 8485 } 8486 r.append(s.info.name); 8487 } 8488 } 8489 if (r != null) { 8490 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8491 } 8492 8493 N = pkg.receivers.size(); 8494 r = null; 8495 for (i=0; i<N; i++) { 8496 PackageParser.Activity a = pkg.receivers.get(i); 8497 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8498 a.info.processName, pkg.applicationInfo.uid); 8499 mReceivers.addActivity(a, "receiver"); 8500 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8501 if (r == null) { 8502 r = new StringBuilder(256); 8503 } else { 8504 r.append(' '); 8505 } 8506 r.append(a.info.name); 8507 } 8508 } 8509 if (r != null) { 8510 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8511 } 8512 8513 N = pkg.activities.size(); 8514 r = null; 8515 for (i=0; i<N; i++) { 8516 PackageParser.Activity a = pkg.activities.get(i); 8517 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8518 a.info.processName, pkg.applicationInfo.uid); 8519 mActivities.addActivity(a, "activity"); 8520 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8521 if (r == null) { 8522 r = new StringBuilder(256); 8523 } else { 8524 r.append(' '); 8525 } 8526 r.append(a.info.name); 8527 } 8528 } 8529 if (r != null) { 8530 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8531 } 8532 8533 N = pkg.permissionGroups.size(); 8534 r = null; 8535 for (i=0; i<N; i++) { 8536 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8537 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8538 if (cur == null) { 8539 mPermissionGroups.put(pg.info.name, pg); 8540 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8541 if (r == null) { 8542 r = new StringBuilder(256); 8543 } else { 8544 r.append(' '); 8545 } 8546 r.append(pg.info.name); 8547 } 8548 } else { 8549 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8550 + pg.info.packageName + " ignored: original from " 8551 + cur.info.packageName); 8552 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8553 if (r == null) { 8554 r = new StringBuilder(256); 8555 } else { 8556 r.append(' '); 8557 } 8558 r.append("DUP:"); 8559 r.append(pg.info.name); 8560 } 8561 } 8562 } 8563 if (r != null) { 8564 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8565 } 8566 8567 N = pkg.permissions.size(); 8568 r = null; 8569 for (i=0; i<N; i++) { 8570 PackageParser.Permission p = pkg.permissions.get(i); 8571 8572 // Assume by default that we did not install this permission into the system. 8573 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8574 8575 // Now that permission groups have a special meaning, we ignore permission 8576 // groups for legacy apps to prevent unexpected behavior. In particular, 8577 // permissions for one app being granted to someone just becase they happen 8578 // to be in a group defined by another app (before this had no implications). 8579 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8580 p.group = mPermissionGroups.get(p.info.group); 8581 // Warn for a permission in an unknown group. 8582 if (p.info.group != null && p.group == null) { 8583 Slog.w(TAG, "Permission " + p.info.name + " from package " 8584 + p.info.packageName + " in an unknown group " + p.info.group); 8585 } 8586 } 8587 8588 ArrayMap<String, BasePermission> permissionMap = 8589 p.tree ? mSettings.mPermissionTrees 8590 : mSettings.mPermissions; 8591 BasePermission bp = permissionMap.get(p.info.name); 8592 8593 // Allow system apps to redefine non-system permissions 8594 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8595 final boolean currentOwnerIsSystem = (bp.perm != null 8596 && isSystemApp(bp.perm.owner)); 8597 if (isSystemApp(p.owner)) { 8598 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8599 // It's a built-in permission and no owner, take ownership now 8600 bp.packageSetting = pkgSetting; 8601 bp.perm = p; 8602 bp.uid = pkg.applicationInfo.uid; 8603 bp.sourcePackage = p.info.packageName; 8604 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8605 } else if (!currentOwnerIsSystem) { 8606 String msg = "New decl " + p.owner + " of permission " 8607 + p.info.name + " is system; overriding " + bp.sourcePackage; 8608 reportSettingsProblem(Log.WARN, msg); 8609 bp = null; 8610 } 8611 } 8612 } 8613 8614 if (bp == null) { 8615 bp = new BasePermission(p.info.name, p.info.packageName, 8616 BasePermission.TYPE_NORMAL); 8617 permissionMap.put(p.info.name, bp); 8618 } 8619 8620 if (bp.perm == null) { 8621 if (bp.sourcePackage == null 8622 || bp.sourcePackage.equals(p.info.packageName)) { 8623 BasePermission tree = findPermissionTreeLP(p.info.name); 8624 if (tree == null 8625 || tree.sourcePackage.equals(p.info.packageName)) { 8626 bp.packageSetting = pkgSetting; 8627 bp.perm = p; 8628 bp.uid = pkg.applicationInfo.uid; 8629 bp.sourcePackage = p.info.packageName; 8630 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8631 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8632 if (r == null) { 8633 r = new StringBuilder(256); 8634 } else { 8635 r.append(' '); 8636 } 8637 r.append(p.info.name); 8638 } 8639 } else { 8640 Slog.w(TAG, "Permission " + p.info.name + " from package " 8641 + p.info.packageName + " ignored: base tree " 8642 + tree.name + " is from package " 8643 + tree.sourcePackage); 8644 } 8645 } else { 8646 Slog.w(TAG, "Permission " + p.info.name + " from package " 8647 + p.info.packageName + " ignored: original from " 8648 + bp.sourcePackage); 8649 } 8650 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8651 if (r == null) { 8652 r = new StringBuilder(256); 8653 } else { 8654 r.append(' '); 8655 } 8656 r.append("DUP:"); 8657 r.append(p.info.name); 8658 } 8659 if (bp.perm == p) { 8660 bp.protectionLevel = p.info.protectionLevel; 8661 } 8662 } 8663 8664 if (r != null) { 8665 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8666 } 8667 8668 N = pkg.instrumentation.size(); 8669 r = null; 8670 for (i=0; i<N; i++) { 8671 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8672 a.info.packageName = pkg.applicationInfo.packageName; 8673 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8674 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8675 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8676 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8677 a.info.dataDir = pkg.applicationInfo.dataDir; 8678 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8679 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8680 8681 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8682 // need other information about the application, like the ABI and what not ? 8683 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8684 mInstrumentation.put(a.getComponentName(), a); 8685 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8686 if (r == null) { 8687 r = new StringBuilder(256); 8688 } else { 8689 r.append(' '); 8690 } 8691 r.append(a.info.name); 8692 } 8693 } 8694 if (r != null) { 8695 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8696 } 8697 8698 if (pkg.protectedBroadcasts != null) { 8699 N = pkg.protectedBroadcasts.size(); 8700 for (i=0; i<N; i++) { 8701 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8702 } 8703 } 8704 8705 pkgSetting.setTimeStamp(scanFileTime); 8706 8707 // Create idmap files for pairs of (packages, overlay packages). 8708 // Note: "android", ie framework-res.apk, is handled by native layers. 8709 if (pkg.mOverlayTarget != null) { 8710 // This is an overlay package. 8711 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8712 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8713 mOverlays.put(pkg.mOverlayTarget, 8714 new ArrayMap<String, PackageParser.Package>()); 8715 } 8716 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8717 map.put(pkg.packageName, pkg); 8718 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8719 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8720 createIdmapFailed = true; 8721 } 8722 } 8723 } else if (mOverlays.containsKey(pkg.packageName) && 8724 !pkg.packageName.equals("android")) { 8725 // This is a regular package, with one or more known overlay packages. 8726 createIdmapsForPackageLI(pkg); 8727 } 8728 } 8729 8730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8731 8732 if (createIdmapFailed) { 8733 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8734 "scanPackageLI failed to createIdmap"); 8735 } 8736 return pkg; 8737 } 8738 8739 /** 8740 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8741 * is derived purely on the basis of the contents of {@code scanFile} and 8742 * {@code cpuAbiOverride}. 8743 * 8744 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8745 */ 8746 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8747 String cpuAbiOverride, boolean extractLibs) 8748 throws PackageManagerException { 8749 // TODO: We can probably be smarter about this stuff. For installed apps, 8750 // we can calculate this information at install time once and for all. For 8751 // system apps, we can probably assume that this information doesn't change 8752 // after the first boot scan. As things stand, we do lots of unnecessary work. 8753 8754 // Give ourselves some initial paths; we'll come back for another 8755 // pass once we've determined ABI below. 8756 setNativeLibraryPaths(pkg); 8757 8758 // We would never need to extract libs for forward-locked and external packages, 8759 // since the container service will do it for us. We shouldn't attempt to 8760 // extract libs from system app when it was not updated. 8761 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8762 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8763 extractLibs = false; 8764 } 8765 8766 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8767 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8768 8769 NativeLibraryHelper.Handle handle = null; 8770 try { 8771 handle = NativeLibraryHelper.Handle.create(pkg); 8772 // TODO(multiArch): This can be null for apps that didn't go through the 8773 // usual installation process. We can calculate it again, like we 8774 // do during install time. 8775 // 8776 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8777 // unnecessary. 8778 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8779 8780 // Null out the abis so that they can be recalculated. 8781 pkg.applicationInfo.primaryCpuAbi = null; 8782 pkg.applicationInfo.secondaryCpuAbi = null; 8783 if (isMultiArch(pkg.applicationInfo)) { 8784 // Warn if we've set an abiOverride for multi-lib packages.. 8785 // By definition, we need to copy both 32 and 64 bit libraries for 8786 // such packages. 8787 if (pkg.cpuAbiOverride != null 8788 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8789 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8790 } 8791 8792 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8793 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8794 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8795 if (extractLibs) { 8796 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8797 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8798 useIsaSpecificSubdirs); 8799 } else { 8800 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8801 } 8802 } 8803 8804 maybeThrowExceptionForMultiArchCopy( 8805 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8806 8807 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8808 if (extractLibs) { 8809 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8810 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8811 useIsaSpecificSubdirs); 8812 } else { 8813 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8814 } 8815 } 8816 8817 maybeThrowExceptionForMultiArchCopy( 8818 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8819 8820 if (abi64 >= 0) { 8821 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8822 } 8823 8824 if (abi32 >= 0) { 8825 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8826 if (abi64 >= 0) { 8827 if (pkg.use32bitAbi) { 8828 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8829 pkg.applicationInfo.primaryCpuAbi = abi; 8830 } else { 8831 pkg.applicationInfo.secondaryCpuAbi = abi; 8832 } 8833 } else { 8834 pkg.applicationInfo.primaryCpuAbi = abi; 8835 } 8836 } 8837 8838 } else { 8839 String[] abiList = (cpuAbiOverride != null) ? 8840 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8841 8842 // Enable gross and lame hacks for apps that are built with old 8843 // SDK tools. We must scan their APKs for renderscript bitcode and 8844 // not launch them if it's present. Don't bother checking on devices 8845 // that don't have 64 bit support. 8846 boolean needsRenderScriptOverride = false; 8847 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8848 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8849 abiList = Build.SUPPORTED_32_BIT_ABIS; 8850 needsRenderScriptOverride = true; 8851 } 8852 8853 final int copyRet; 8854 if (extractLibs) { 8855 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8856 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8857 } else { 8858 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8859 } 8860 8861 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8862 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8863 "Error unpackaging native libs for app, errorCode=" + copyRet); 8864 } 8865 8866 if (copyRet >= 0) { 8867 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8868 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8869 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8870 } else if (needsRenderScriptOverride) { 8871 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8872 } 8873 } 8874 } catch (IOException ioe) { 8875 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8876 } finally { 8877 IoUtils.closeQuietly(handle); 8878 } 8879 8880 // Now that we've calculated the ABIs and determined if it's an internal app, 8881 // we will go ahead and populate the nativeLibraryPath. 8882 setNativeLibraryPaths(pkg); 8883 } 8884 8885 /** 8886 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8887 * i.e, so that all packages can be run inside a single process if required. 8888 * 8889 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8890 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8891 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8892 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8893 * updating a package that belongs to a shared user. 8894 * 8895 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8896 * adds unnecessary complexity. 8897 */ 8898 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8899 PackageParser.Package scannedPackage, boolean bootComplete) { 8900 String requiredInstructionSet = null; 8901 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8902 requiredInstructionSet = VMRuntime.getInstructionSet( 8903 scannedPackage.applicationInfo.primaryCpuAbi); 8904 } 8905 8906 PackageSetting requirer = null; 8907 for (PackageSetting ps : packagesForUser) { 8908 // If packagesForUser contains scannedPackage, we skip it. This will happen 8909 // when scannedPackage is an update of an existing package. Without this check, 8910 // we will never be able to change the ABI of any package belonging to a shared 8911 // user, even if it's compatible with other packages. 8912 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8913 if (ps.primaryCpuAbiString == null) { 8914 continue; 8915 } 8916 8917 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8918 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8919 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8920 // this but there's not much we can do. 8921 String errorMessage = "Instruction set mismatch, " 8922 + ((requirer == null) ? "[caller]" : requirer) 8923 + " requires " + requiredInstructionSet + " whereas " + ps 8924 + " requires " + instructionSet; 8925 Slog.w(TAG, errorMessage); 8926 } 8927 8928 if (requiredInstructionSet == null) { 8929 requiredInstructionSet = instructionSet; 8930 requirer = ps; 8931 } 8932 } 8933 } 8934 8935 if (requiredInstructionSet != null) { 8936 String adjustedAbi; 8937 if (requirer != null) { 8938 // requirer != null implies that either scannedPackage was null or that scannedPackage 8939 // did not require an ABI, in which case we have to adjust scannedPackage to match 8940 // the ABI of the set (which is the same as requirer's ABI) 8941 adjustedAbi = requirer.primaryCpuAbiString; 8942 if (scannedPackage != null) { 8943 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8944 } 8945 } else { 8946 // requirer == null implies that we're updating all ABIs in the set to 8947 // match scannedPackage. 8948 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8949 } 8950 8951 for (PackageSetting ps : packagesForUser) { 8952 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8953 if (ps.primaryCpuAbiString != null) { 8954 continue; 8955 } 8956 8957 ps.primaryCpuAbiString = adjustedAbi; 8958 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8959 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8960 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8961 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8962 + " (requirer=" 8963 + (requirer == null ? "null" : requirer.pkg.packageName) 8964 + ", scannedPackage=" 8965 + (scannedPackage != null ? scannedPackage.packageName : "null") 8966 + ")"); 8967 try { 8968 mInstaller.rmdex(ps.codePathString, 8969 getDexCodeInstructionSet(getPreferredInstructionSet())); 8970 } catch (InstallerException ignored) { 8971 } 8972 } 8973 } 8974 } 8975 } 8976 } 8977 8978 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8979 synchronized (mPackages) { 8980 mResolverReplaced = true; 8981 // Set up information for custom user intent resolution activity. 8982 mResolveActivity.applicationInfo = pkg.applicationInfo; 8983 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8984 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8985 mResolveActivity.processName = pkg.applicationInfo.packageName; 8986 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8987 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8988 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8989 mResolveActivity.theme = 0; 8990 mResolveActivity.exported = true; 8991 mResolveActivity.enabled = true; 8992 mResolveInfo.activityInfo = mResolveActivity; 8993 mResolveInfo.priority = 0; 8994 mResolveInfo.preferredOrder = 0; 8995 mResolveInfo.match = 0; 8996 mResolveComponentName = mCustomResolverComponentName; 8997 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8998 mResolveComponentName); 8999 } 9000 } 9001 9002 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9003 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9004 9005 // Set up information for ephemeral installer activity 9006 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9007 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9008 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9009 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9010 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9011 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9012 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9013 mEphemeralInstallerActivity.theme = 0; 9014 mEphemeralInstallerActivity.exported = true; 9015 mEphemeralInstallerActivity.enabled = true; 9016 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9017 mEphemeralInstallerInfo.priority = 0; 9018 mEphemeralInstallerInfo.preferredOrder = 0; 9019 mEphemeralInstallerInfo.match = 0; 9020 9021 if (DEBUG_EPHEMERAL) { 9022 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9023 } 9024 } 9025 9026 private static String calculateBundledApkRoot(final String codePathString) { 9027 final File codePath = new File(codePathString); 9028 final File codeRoot; 9029 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9030 codeRoot = Environment.getRootDirectory(); 9031 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9032 codeRoot = Environment.getOemDirectory(); 9033 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9034 codeRoot = Environment.getVendorDirectory(); 9035 } else { 9036 // Unrecognized code path; take its top real segment as the apk root: 9037 // e.g. /something/app/blah.apk => /something 9038 try { 9039 File f = codePath.getCanonicalFile(); 9040 File parent = f.getParentFile(); // non-null because codePath is a file 9041 File tmp; 9042 while ((tmp = parent.getParentFile()) != null) { 9043 f = parent; 9044 parent = tmp; 9045 } 9046 codeRoot = f; 9047 Slog.w(TAG, "Unrecognized code path " 9048 + codePath + " - using " + codeRoot); 9049 } catch (IOException e) { 9050 // Can't canonicalize the code path -- shenanigans? 9051 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9052 return Environment.getRootDirectory().getPath(); 9053 } 9054 } 9055 return codeRoot.getPath(); 9056 } 9057 9058 /** 9059 * Derive and set the location of native libraries for the given package, 9060 * which varies depending on where and how the package was installed. 9061 */ 9062 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9063 final ApplicationInfo info = pkg.applicationInfo; 9064 final String codePath = pkg.codePath; 9065 final File codeFile = new File(codePath); 9066 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9067 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9068 9069 info.nativeLibraryRootDir = null; 9070 info.nativeLibraryRootRequiresIsa = false; 9071 info.nativeLibraryDir = null; 9072 info.secondaryNativeLibraryDir = null; 9073 9074 if (isApkFile(codeFile)) { 9075 // Monolithic install 9076 if (bundledApp) { 9077 // If "/system/lib64/apkname" exists, assume that is the per-package 9078 // native library directory to use; otherwise use "/system/lib/apkname". 9079 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9080 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9081 getPrimaryInstructionSet(info)); 9082 9083 // This is a bundled system app so choose the path based on the ABI. 9084 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9085 // is just the default path. 9086 final String apkName = deriveCodePathName(codePath); 9087 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9088 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9089 apkName).getAbsolutePath(); 9090 9091 if (info.secondaryCpuAbi != null) { 9092 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9093 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9094 secondaryLibDir, apkName).getAbsolutePath(); 9095 } 9096 } else if (asecApp) { 9097 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9098 .getAbsolutePath(); 9099 } else { 9100 final String apkName = deriveCodePathName(codePath); 9101 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9102 .getAbsolutePath(); 9103 } 9104 9105 info.nativeLibraryRootRequiresIsa = false; 9106 info.nativeLibraryDir = info.nativeLibraryRootDir; 9107 } else { 9108 // Cluster install 9109 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9110 info.nativeLibraryRootRequiresIsa = true; 9111 9112 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9113 getPrimaryInstructionSet(info)).getAbsolutePath(); 9114 9115 if (info.secondaryCpuAbi != null) { 9116 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9117 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9118 } 9119 } 9120 } 9121 9122 /** 9123 * Calculate the abis and roots for a bundled app. These can uniquely 9124 * be determined from the contents of the system partition, i.e whether 9125 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9126 * of this information, and instead assume that the system was built 9127 * sensibly. 9128 */ 9129 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9130 PackageSetting pkgSetting) { 9131 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9132 9133 // If "/system/lib64/apkname" exists, assume that is the per-package 9134 // native library directory to use; otherwise use "/system/lib/apkname". 9135 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9136 setBundledAppAbi(pkg, apkRoot, apkName); 9137 // pkgSetting might be null during rescan following uninstall of updates 9138 // to a bundled app, so accommodate that possibility. The settings in 9139 // that case will be established later from the parsed package. 9140 // 9141 // If the settings aren't null, sync them up with what we've just derived. 9142 // note that apkRoot isn't stored in the package settings. 9143 if (pkgSetting != null) { 9144 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9145 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9146 } 9147 } 9148 9149 /** 9150 * Deduces the ABI of a bundled app and sets the relevant fields on the 9151 * parsed pkg object. 9152 * 9153 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9154 * under which system libraries are installed. 9155 * @param apkName the name of the installed package. 9156 */ 9157 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9158 final File codeFile = new File(pkg.codePath); 9159 9160 final boolean has64BitLibs; 9161 final boolean has32BitLibs; 9162 if (isApkFile(codeFile)) { 9163 // Monolithic install 9164 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9165 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9166 } else { 9167 // Cluster install 9168 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9169 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9170 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9171 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9172 has64BitLibs = (new File(rootDir, isa)).exists(); 9173 } else { 9174 has64BitLibs = false; 9175 } 9176 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9177 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9178 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9179 has32BitLibs = (new File(rootDir, isa)).exists(); 9180 } else { 9181 has32BitLibs = false; 9182 } 9183 } 9184 9185 if (has64BitLibs && !has32BitLibs) { 9186 // The package has 64 bit libs, but not 32 bit libs. Its primary 9187 // ABI should be 64 bit. We can safely assume here that the bundled 9188 // native libraries correspond to the most preferred ABI in the list. 9189 9190 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9191 pkg.applicationInfo.secondaryCpuAbi = null; 9192 } else if (has32BitLibs && !has64BitLibs) { 9193 // The package has 32 bit libs but not 64 bit libs. Its primary 9194 // ABI should be 32 bit. 9195 9196 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9197 pkg.applicationInfo.secondaryCpuAbi = null; 9198 } else if (has32BitLibs && has64BitLibs) { 9199 // The application has both 64 and 32 bit bundled libraries. We check 9200 // here that the app declares multiArch support, and warn if it doesn't. 9201 // 9202 // We will be lenient here and record both ABIs. The primary will be the 9203 // ABI that's higher on the list, i.e, a device that's configured to prefer 9204 // 64 bit apps will see a 64 bit primary ABI, 9205 9206 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9207 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9208 } 9209 9210 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9211 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9212 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9213 } else { 9214 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9215 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9216 } 9217 } else { 9218 pkg.applicationInfo.primaryCpuAbi = null; 9219 pkg.applicationInfo.secondaryCpuAbi = null; 9220 } 9221 } 9222 9223 private void killApplication(String pkgName, int appId, String reason) { 9224 // Request the ActivityManager to kill the process(only for existing packages) 9225 // so that we do not end up in a confused state while the user is still using the older 9226 // version of the application while the new one gets installed. 9227 final long token = Binder.clearCallingIdentity(); 9228 try { 9229 IActivityManager am = ActivityManagerNative.getDefault(); 9230 if (am != null) { 9231 try { 9232 am.killApplicationWithAppId(pkgName, appId, reason); 9233 } catch (RemoteException e) { 9234 } 9235 } 9236 } finally { 9237 Binder.restoreCallingIdentity(token); 9238 } 9239 } 9240 9241 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9242 // Remove the parent package setting 9243 PackageSetting ps = (PackageSetting) pkg.mExtras; 9244 if (ps != null) { 9245 removePackageLI(ps, chatty); 9246 } 9247 // Remove the child package setting 9248 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9249 for (int i = 0; i < childCount; i++) { 9250 PackageParser.Package childPkg = pkg.childPackages.get(i); 9251 ps = (PackageSetting) childPkg.mExtras; 9252 if (ps != null) { 9253 removePackageLI(ps, chatty); 9254 } 9255 } 9256 } 9257 9258 void removePackageLI(PackageSetting ps, boolean chatty) { 9259 if (DEBUG_INSTALL) { 9260 if (chatty) 9261 Log.d(TAG, "Removing package " + ps.name); 9262 } 9263 9264 // writer 9265 synchronized (mPackages) { 9266 mPackages.remove(ps.name); 9267 final PackageParser.Package pkg = ps.pkg; 9268 if (pkg != null) { 9269 cleanPackageDataStructuresLILPw(pkg, chatty); 9270 } 9271 } 9272 } 9273 9274 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9275 if (DEBUG_INSTALL) { 9276 if (chatty) 9277 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9278 } 9279 9280 // writer 9281 synchronized (mPackages) { 9282 // Remove the parent package 9283 mPackages.remove(pkg.applicationInfo.packageName); 9284 cleanPackageDataStructuresLILPw(pkg, chatty); 9285 9286 // Remove the child packages 9287 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9288 for (int i = 0; i < childCount; i++) { 9289 PackageParser.Package childPkg = pkg.childPackages.get(i); 9290 mPackages.remove(childPkg.applicationInfo.packageName); 9291 cleanPackageDataStructuresLILPw(childPkg, chatty); 9292 } 9293 } 9294 } 9295 9296 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9297 int N = pkg.providers.size(); 9298 StringBuilder r = null; 9299 int i; 9300 for (i=0; i<N; i++) { 9301 PackageParser.Provider p = pkg.providers.get(i); 9302 mProviders.removeProvider(p); 9303 if (p.info.authority == null) { 9304 9305 /* There was another ContentProvider with this authority when 9306 * this app was installed so this authority is null, 9307 * Ignore it as we don't have to unregister the provider. 9308 */ 9309 continue; 9310 } 9311 String names[] = p.info.authority.split(";"); 9312 for (int j = 0; j < names.length; j++) { 9313 if (mProvidersByAuthority.get(names[j]) == p) { 9314 mProvidersByAuthority.remove(names[j]); 9315 if (DEBUG_REMOVE) { 9316 if (chatty) 9317 Log.d(TAG, "Unregistered content provider: " + names[j] 9318 + ", className = " + p.info.name + ", isSyncable = " 9319 + p.info.isSyncable); 9320 } 9321 } 9322 } 9323 if (DEBUG_REMOVE && chatty) { 9324 if (r == null) { 9325 r = new StringBuilder(256); 9326 } else { 9327 r.append(' '); 9328 } 9329 r.append(p.info.name); 9330 } 9331 } 9332 if (r != null) { 9333 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9334 } 9335 9336 N = pkg.services.size(); 9337 r = null; 9338 for (i=0; i<N; i++) { 9339 PackageParser.Service s = pkg.services.get(i); 9340 mServices.removeService(s); 9341 if (chatty) { 9342 if (r == null) { 9343 r = new StringBuilder(256); 9344 } else { 9345 r.append(' '); 9346 } 9347 r.append(s.info.name); 9348 } 9349 } 9350 if (r != null) { 9351 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9352 } 9353 9354 N = pkg.receivers.size(); 9355 r = null; 9356 for (i=0; i<N; i++) { 9357 PackageParser.Activity a = pkg.receivers.get(i); 9358 mReceivers.removeActivity(a, "receiver"); 9359 if (DEBUG_REMOVE && chatty) { 9360 if (r == null) { 9361 r = new StringBuilder(256); 9362 } else { 9363 r.append(' '); 9364 } 9365 r.append(a.info.name); 9366 } 9367 } 9368 if (r != null) { 9369 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9370 } 9371 9372 N = pkg.activities.size(); 9373 r = null; 9374 for (i=0; i<N; i++) { 9375 PackageParser.Activity a = pkg.activities.get(i); 9376 mActivities.removeActivity(a, "activity"); 9377 if (DEBUG_REMOVE && chatty) { 9378 if (r == null) { 9379 r = new StringBuilder(256); 9380 } else { 9381 r.append(' '); 9382 } 9383 r.append(a.info.name); 9384 } 9385 } 9386 if (r != null) { 9387 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9388 } 9389 9390 N = pkg.permissions.size(); 9391 r = null; 9392 for (i=0; i<N; i++) { 9393 PackageParser.Permission p = pkg.permissions.get(i); 9394 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9395 if (bp == null) { 9396 bp = mSettings.mPermissionTrees.get(p.info.name); 9397 } 9398 if (bp != null && bp.perm == p) { 9399 bp.perm = null; 9400 if (DEBUG_REMOVE && chatty) { 9401 if (r == null) { 9402 r = new StringBuilder(256); 9403 } else { 9404 r.append(' '); 9405 } 9406 r.append(p.info.name); 9407 } 9408 } 9409 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9410 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9411 if (appOpPkgs != null) { 9412 appOpPkgs.remove(pkg.packageName); 9413 } 9414 } 9415 } 9416 if (r != null) { 9417 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9418 } 9419 9420 N = pkg.requestedPermissions.size(); 9421 r = null; 9422 for (i=0; i<N; i++) { 9423 String perm = pkg.requestedPermissions.get(i); 9424 BasePermission bp = mSettings.mPermissions.get(perm); 9425 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9426 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9427 if (appOpPkgs != null) { 9428 appOpPkgs.remove(pkg.packageName); 9429 if (appOpPkgs.isEmpty()) { 9430 mAppOpPermissionPackages.remove(perm); 9431 } 9432 } 9433 } 9434 } 9435 if (r != null) { 9436 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9437 } 9438 9439 N = pkg.instrumentation.size(); 9440 r = null; 9441 for (i=0; i<N; i++) { 9442 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9443 mInstrumentation.remove(a.getComponentName()); 9444 if (DEBUG_REMOVE && chatty) { 9445 if (r == null) { 9446 r = new StringBuilder(256); 9447 } else { 9448 r.append(' '); 9449 } 9450 r.append(a.info.name); 9451 } 9452 } 9453 if (r != null) { 9454 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9455 } 9456 9457 r = null; 9458 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9459 // Only system apps can hold shared libraries. 9460 if (pkg.libraryNames != null) { 9461 for (i=0; i<pkg.libraryNames.size(); i++) { 9462 String name = pkg.libraryNames.get(i); 9463 SharedLibraryEntry cur = mSharedLibraries.get(name); 9464 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9465 mSharedLibraries.remove(name); 9466 if (DEBUG_REMOVE && chatty) { 9467 if (r == null) { 9468 r = new StringBuilder(256); 9469 } else { 9470 r.append(' '); 9471 } 9472 r.append(name); 9473 } 9474 } 9475 } 9476 } 9477 } 9478 if (r != null) { 9479 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9480 } 9481 } 9482 9483 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9484 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9485 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9486 return true; 9487 } 9488 } 9489 return false; 9490 } 9491 9492 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9493 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9494 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9495 9496 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9497 // Update the parent permissions 9498 updatePermissionsLPw(pkg.packageName, pkg, flags); 9499 // Update the child permissions 9500 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9501 for (int i = 0; i < childCount; i++) { 9502 PackageParser.Package childPkg = pkg.childPackages.get(i); 9503 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9504 } 9505 } 9506 9507 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9508 int flags) { 9509 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9510 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9511 } 9512 9513 private void updatePermissionsLPw(String changingPkg, 9514 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9515 // Make sure there are no dangling permission trees. 9516 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9517 while (it.hasNext()) { 9518 final BasePermission bp = it.next(); 9519 if (bp.packageSetting == null) { 9520 // We may not yet have parsed the package, so just see if 9521 // we still know about its settings. 9522 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9523 } 9524 if (bp.packageSetting == null) { 9525 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9526 + " from package " + bp.sourcePackage); 9527 it.remove(); 9528 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9529 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9530 Slog.i(TAG, "Removing old permission tree: " + bp.name 9531 + " from package " + bp.sourcePackage); 9532 flags |= UPDATE_PERMISSIONS_ALL; 9533 it.remove(); 9534 } 9535 } 9536 } 9537 9538 // Make sure all dynamic permissions have been assigned to a package, 9539 // and make sure there are no dangling permissions. 9540 it = mSettings.mPermissions.values().iterator(); 9541 while (it.hasNext()) { 9542 final BasePermission bp = it.next(); 9543 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9544 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9545 + bp.name + " pkg=" + bp.sourcePackage 9546 + " info=" + bp.pendingInfo); 9547 if (bp.packageSetting == null && bp.pendingInfo != null) { 9548 final BasePermission tree = findPermissionTreeLP(bp.name); 9549 if (tree != null && tree.perm != null) { 9550 bp.packageSetting = tree.packageSetting; 9551 bp.perm = new PackageParser.Permission(tree.perm.owner, 9552 new PermissionInfo(bp.pendingInfo)); 9553 bp.perm.info.packageName = tree.perm.info.packageName; 9554 bp.perm.info.name = bp.name; 9555 bp.uid = tree.uid; 9556 } 9557 } 9558 } 9559 if (bp.packageSetting == null) { 9560 // We may not yet have parsed the package, so just see if 9561 // we still know about its settings. 9562 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9563 } 9564 if (bp.packageSetting == null) { 9565 Slog.w(TAG, "Removing dangling permission: " + bp.name 9566 + " from package " + bp.sourcePackage); 9567 it.remove(); 9568 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9569 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9570 Slog.i(TAG, "Removing old permission: " + bp.name 9571 + " from package " + bp.sourcePackage); 9572 flags |= UPDATE_PERMISSIONS_ALL; 9573 it.remove(); 9574 } 9575 } 9576 } 9577 9578 // Now update the permissions for all packages, in particular 9579 // replace the granted permissions of the system packages. 9580 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9581 for (PackageParser.Package pkg : mPackages.values()) { 9582 if (pkg != pkgInfo) { 9583 // Only replace for packages on requested volume 9584 final String volumeUuid = getVolumeUuidForPackage(pkg); 9585 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9586 && Objects.equals(replaceVolumeUuid, volumeUuid); 9587 grantPermissionsLPw(pkg, replace, changingPkg); 9588 } 9589 } 9590 } 9591 9592 if (pkgInfo != null) { 9593 // Only replace for packages on requested volume 9594 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9595 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9596 && Objects.equals(replaceVolumeUuid, volumeUuid); 9597 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9598 } 9599 } 9600 9601 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9602 String packageOfInterest) { 9603 // IMPORTANT: There are two types of permissions: install and runtime. 9604 // Install time permissions are granted when the app is installed to 9605 // all device users and users added in the future. Runtime permissions 9606 // are granted at runtime explicitly to specific users. Normal and signature 9607 // protected permissions are install time permissions. Dangerous permissions 9608 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9609 // otherwise they are runtime permissions. This function does not manage 9610 // runtime permissions except for the case an app targeting Lollipop MR1 9611 // being upgraded to target a newer SDK, in which case dangerous permissions 9612 // are transformed from install time to runtime ones. 9613 9614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9615 if (ps == null) { 9616 return; 9617 } 9618 9619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9620 9621 PermissionsState permissionsState = ps.getPermissionsState(); 9622 PermissionsState origPermissions = permissionsState; 9623 9624 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9625 9626 boolean runtimePermissionsRevoked = false; 9627 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9628 9629 boolean changedInstallPermission = false; 9630 9631 if (replace) { 9632 ps.installPermissionsFixed = false; 9633 if (!ps.isSharedUser()) { 9634 origPermissions = new PermissionsState(permissionsState); 9635 permissionsState.reset(); 9636 } else { 9637 // We need to know only about runtime permission changes since the 9638 // calling code always writes the install permissions state but 9639 // the runtime ones are written only if changed. The only cases of 9640 // changed runtime permissions here are promotion of an install to 9641 // runtime and revocation of a runtime from a shared user. 9642 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9643 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9644 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9645 runtimePermissionsRevoked = true; 9646 } 9647 } 9648 } 9649 9650 permissionsState.setGlobalGids(mGlobalGids); 9651 9652 final int N = pkg.requestedPermissions.size(); 9653 for (int i=0; i<N; i++) { 9654 final String name = pkg.requestedPermissions.get(i); 9655 final BasePermission bp = mSettings.mPermissions.get(name); 9656 9657 if (DEBUG_INSTALL) { 9658 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9659 } 9660 9661 if (bp == null || bp.packageSetting == null) { 9662 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9663 Slog.w(TAG, "Unknown permission " + name 9664 + " in package " + pkg.packageName); 9665 } 9666 continue; 9667 } 9668 9669 final String perm = bp.name; 9670 boolean allowedSig = false; 9671 int grant = GRANT_DENIED; 9672 9673 // Keep track of app op permissions. 9674 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9675 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9676 if (pkgs == null) { 9677 pkgs = new ArraySet<>(); 9678 mAppOpPermissionPackages.put(bp.name, pkgs); 9679 } 9680 pkgs.add(pkg.packageName); 9681 } 9682 9683 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9684 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9685 >= Build.VERSION_CODES.M; 9686 switch (level) { 9687 case PermissionInfo.PROTECTION_NORMAL: { 9688 // For all apps normal permissions are install time ones. 9689 grant = GRANT_INSTALL; 9690 } break; 9691 9692 case PermissionInfo.PROTECTION_DANGEROUS: { 9693 // If a permission review is required for legacy apps we represent 9694 // their permissions as always granted runtime ones since we need 9695 // to keep the review required permission flag per user while an 9696 // install permission's state is shared across all users. 9697 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9698 // For legacy apps dangerous permissions are install time ones. 9699 grant = GRANT_INSTALL; 9700 } else if (origPermissions.hasInstallPermission(bp.name)) { 9701 // For legacy apps that became modern, install becomes runtime. 9702 grant = GRANT_UPGRADE; 9703 } else if (mPromoteSystemApps 9704 && isSystemApp(ps) 9705 && mExistingSystemPackages.contains(ps.name)) { 9706 // For legacy system apps, install becomes runtime. 9707 // We cannot check hasInstallPermission() for system apps since those 9708 // permissions were granted implicitly and not persisted pre-M. 9709 grant = GRANT_UPGRADE; 9710 } else { 9711 // For modern apps keep runtime permissions unchanged. 9712 grant = GRANT_RUNTIME; 9713 } 9714 } break; 9715 9716 case PermissionInfo.PROTECTION_SIGNATURE: { 9717 // For all apps signature permissions are install time ones. 9718 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9719 if (allowedSig) { 9720 grant = GRANT_INSTALL; 9721 } 9722 } break; 9723 } 9724 9725 if (DEBUG_INSTALL) { 9726 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9727 } 9728 9729 if (grant != GRANT_DENIED) { 9730 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9731 // If this is an existing, non-system package, then 9732 // we can't add any new permissions to it. 9733 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9734 // Except... if this is a permission that was added 9735 // to the platform (note: need to only do this when 9736 // updating the platform). 9737 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9738 grant = GRANT_DENIED; 9739 } 9740 } 9741 } 9742 9743 switch (grant) { 9744 case GRANT_INSTALL: { 9745 // Revoke this as runtime permission to handle the case of 9746 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9747 for (int userId : UserManagerService.getInstance().getUserIds()) { 9748 if (origPermissions.getRuntimePermissionState( 9749 bp.name, userId) != null) { 9750 // Revoke the runtime permission and clear the flags. 9751 origPermissions.revokeRuntimePermission(bp, userId); 9752 origPermissions.updatePermissionFlags(bp, userId, 9753 PackageManager.MASK_PERMISSION_FLAGS, 0); 9754 // If we revoked a permission permission, we have to write. 9755 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9756 changedRuntimePermissionUserIds, userId); 9757 } 9758 } 9759 // Grant an install permission. 9760 if (permissionsState.grantInstallPermission(bp) != 9761 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9762 changedInstallPermission = true; 9763 } 9764 } break; 9765 9766 case GRANT_RUNTIME: { 9767 // Grant previously granted runtime permissions. 9768 for (int userId : UserManagerService.getInstance().getUserIds()) { 9769 PermissionState permissionState = origPermissions 9770 .getRuntimePermissionState(bp.name, userId); 9771 int flags = permissionState != null 9772 ? permissionState.getFlags() : 0; 9773 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9774 if (permissionsState.grantRuntimePermission(bp, userId) == 9775 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9776 // If we cannot put the permission as it was, we have to write. 9777 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9778 changedRuntimePermissionUserIds, userId); 9779 } 9780 // If the app supports runtime permissions no need for a review. 9781 if (Build.PERMISSIONS_REVIEW_REQUIRED 9782 && appSupportsRuntimePermissions 9783 && (flags & PackageManager 9784 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9785 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9786 // Since we changed the flags, we have to write. 9787 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9788 changedRuntimePermissionUserIds, userId); 9789 } 9790 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9791 && !appSupportsRuntimePermissions) { 9792 // For legacy apps that need a permission review, every new 9793 // runtime permission is granted but it is pending a review. 9794 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9795 permissionsState.grantRuntimePermission(bp, userId); 9796 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9797 // We changed the permission and flags, hence have to write. 9798 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9799 changedRuntimePermissionUserIds, userId); 9800 } 9801 } 9802 // Propagate the permission flags. 9803 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9804 } 9805 } break; 9806 9807 case GRANT_UPGRADE: { 9808 // Grant runtime permissions for a previously held install permission. 9809 PermissionState permissionState = origPermissions 9810 .getInstallPermissionState(bp.name); 9811 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9812 9813 if (origPermissions.revokeInstallPermission(bp) 9814 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9815 // We will be transferring the permission flags, so clear them. 9816 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9817 PackageManager.MASK_PERMISSION_FLAGS, 0); 9818 changedInstallPermission = true; 9819 } 9820 9821 // If the permission is not to be promoted to runtime we ignore it and 9822 // also its other flags as they are not applicable to install permissions. 9823 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9824 for (int userId : currentUserIds) { 9825 if (permissionsState.grantRuntimePermission(bp, userId) != 9826 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9827 // Transfer the permission flags. 9828 permissionsState.updatePermissionFlags(bp, userId, 9829 flags, flags); 9830 // If we granted the permission, we have to write. 9831 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9832 changedRuntimePermissionUserIds, userId); 9833 } 9834 } 9835 } 9836 } break; 9837 9838 default: { 9839 if (packageOfInterest == null 9840 || packageOfInterest.equals(pkg.packageName)) { 9841 Slog.w(TAG, "Not granting permission " + perm 9842 + " to package " + pkg.packageName 9843 + " because it was previously installed without"); 9844 } 9845 } break; 9846 } 9847 } else { 9848 if (permissionsState.revokeInstallPermission(bp) != 9849 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9850 // Also drop the permission flags. 9851 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9852 PackageManager.MASK_PERMISSION_FLAGS, 0); 9853 changedInstallPermission = true; 9854 Slog.i(TAG, "Un-granting permission " + perm 9855 + " from package " + pkg.packageName 9856 + " (protectionLevel=" + bp.protectionLevel 9857 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9858 + ")"); 9859 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9860 // Don't print warning for app op permissions, since it is fine for them 9861 // not to be granted, there is a UI for the user to decide. 9862 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9863 Slog.w(TAG, "Not granting permission " + perm 9864 + " to package " + pkg.packageName 9865 + " (protectionLevel=" + bp.protectionLevel 9866 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9867 + ")"); 9868 } 9869 } 9870 } 9871 } 9872 9873 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9874 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9875 // This is the first that we have heard about this package, so the 9876 // permissions we have now selected are fixed until explicitly 9877 // changed. 9878 ps.installPermissionsFixed = true; 9879 } 9880 9881 // Persist the runtime permissions state for users with changes. If permissions 9882 // were revoked because no app in the shared user declares them we have to 9883 // write synchronously to avoid losing runtime permissions state. 9884 for (int userId : changedRuntimePermissionUserIds) { 9885 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9886 } 9887 9888 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9889 } 9890 9891 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9892 boolean allowed = false; 9893 final int NP = PackageParser.NEW_PERMISSIONS.length; 9894 for (int ip=0; ip<NP; ip++) { 9895 final PackageParser.NewPermissionInfo npi 9896 = PackageParser.NEW_PERMISSIONS[ip]; 9897 if (npi.name.equals(perm) 9898 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9899 allowed = true; 9900 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9901 + pkg.packageName); 9902 break; 9903 } 9904 } 9905 return allowed; 9906 } 9907 9908 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9909 BasePermission bp, PermissionsState origPermissions) { 9910 boolean allowed; 9911 allowed = (compareSignatures( 9912 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9913 == PackageManager.SIGNATURE_MATCH) 9914 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9915 == PackageManager.SIGNATURE_MATCH); 9916 if (!allowed && (bp.protectionLevel 9917 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9918 if (isSystemApp(pkg)) { 9919 // For updated system applications, a system permission 9920 // is granted only if it had been defined by the original application. 9921 if (pkg.isUpdatedSystemApp()) { 9922 final PackageSetting sysPs = mSettings 9923 .getDisabledSystemPkgLPr(pkg.packageName); 9924 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9925 // If the original was granted this permission, we take 9926 // that grant decision as read and propagate it to the 9927 // update. 9928 if (sysPs.isPrivileged()) { 9929 allowed = true; 9930 } 9931 } else { 9932 // The system apk may have been updated with an older 9933 // version of the one on the data partition, but which 9934 // granted a new system permission that it didn't have 9935 // before. In this case we do want to allow the app to 9936 // now get the new permission if the ancestral apk is 9937 // privileged to get it. 9938 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9939 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9940 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9941 allowed = true; 9942 break; 9943 } 9944 } 9945 } 9946 // Also if a privileged parent package on the system image or any of 9947 // its children requested a privileged permission, the updated child 9948 // packages can also get the permission. 9949 if (pkg.parentPackage != null) { 9950 final PackageSetting disabledSysParentPs = mSettings 9951 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9952 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9953 && disabledSysParentPs.isPrivileged()) { 9954 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9955 allowed = true; 9956 } else if (disabledSysParentPs.pkg.childPackages != null) { 9957 final int count = disabledSysParentPs.pkg.childPackages.size(); 9958 for (int i = 0; i < count; i++) { 9959 PackageParser.Package disabledSysChildPkg = 9960 disabledSysParentPs.pkg.childPackages.get(i); 9961 if (isPackageRequestingPermission(disabledSysChildPkg, 9962 perm)) { 9963 allowed = true; 9964 break; 9965 } 9966 } 9967 } 9968 } 9969 } 9970 } 9971 } else { 9972 allowed = isPrivilegedApp(pkg); 9973 } 9974 } 9975 } 9976 if (!allowed) { 9977 if (!allowed && (bp.protectionLevel 9978 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9979 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9980 // If this was a previously normal/dangerous permission that got moved 9981 // to a system permission as part of the runtime permission redesign, then 9982 // we still want to blindly grant it to old apps. 9983 allowed = true; 9984 } 9985 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9986 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9987 // If this permission is to be granted to the system installer and 9988 // this app is an installer, then it gets the permission. 9989 allowed = true; 9990 } 9991 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9992 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9993 // If this permission is to be granted to the system verifier and 9994 // this app is a verifier, then it gets the permission. 9995 allowed = true; 9996 } 9997 if (!allowed && (bp.protectionLevel 9998 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9999 && isSystemApp(pkg)) { 10000 // Any pre-installed system app is allowed to get this permission. 10001 allowed = true; 10002 } 10003 if (!allowed && (bp.protectionLevel 10004 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10005 // For development permissions, a development permission 10006 // is granted only if it was already granted. 10007 allowed = origPermissions.hasInstallPermission(perm); 10008 } 10009 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10010 && pkg.packageName.equals(mSetupWizardPackage)) { 10011 // If this permission is to be granted to the system setup wizard and 10012 // this app is a setup wizard, then it gets the permission. 10013 allowed = true; 10014 } 10015 } 10016 return allowed; 10017 } 10018 10019 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10020 final int permCount = pkg.requestedPermissions.size(); 10021 for (int j = 0; j < permCount; j++) { 10022 String requestedPermission = pkg.requestedPermissions.get(j); 10023 if (permission.equals(requestedPermission)) { 10024 return true; 10025 } 10026 } 10027 return false; 10028 } 10029 10030 final class ActivityIntentResolver 10031 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10032 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10033 boolean defaultOnly, int userId) { 10034 if (!sUserManager.exists(userId)) return null; 10035 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10036 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10037 } 10038 10039 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10040 int userId) { 10041 if (!sUserManager.exists(userId)) return null; 10042 mFlags = flags; 10043 return super.queryIntent(intent, resolvedType, 10044 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10045 } 10046 10047 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10048 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10049 if (!sUserManager.exists(userId)) return null; 10050 if (packageActivities == null) { 10051 return null; 10052 } 10053 mFlags = flags; 10054 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10055 final int N = packageActivities.size(); 10056 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10057 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10058 10059 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10060 for (int i = 0; i < N; ++i) { 10061 intentFilters = packageActivities.get(i).intents; 10062 if (intentFilters != null && intentFilters.size() > 0) { 10063 PackageParser.ActivityIntentInfo[] array = 10064 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10065 intentFilters.toArray(array); 10066 listCut.add(array); 10067 } 10068 } 10069 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10070 } 10071 10072 /** 10073 * Finds a privileged activity that matches the specified activity names. 10074 */ 10075 private PackageParser.Activity findMatchingActivity( 10076 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10077 for (PackageParser.Activity sysActivity : activityList) { 10078 if (sysActivity.info.name.equals(activityInfo.name)) { 10079 return sysActivity; 10080 } 10081 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10082 return sysActivity; 10083 } 10084 if (sysActivity.info.targetActivity != null) { 10085 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10086 return sysActivity; 10087 } 10088 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10089 return sysActivity; 10090 } 10091 } 10092 } 10093 return null; 10094 } 10095 10096 public class IterGenerator<E> { 10097 public Iterator<E> generate(ActivityIntentInfo info) { 10098 return null; 10099 } 10100 } 10101 10102 public class ActionIterGenerator extends IterGenerator<String> { 10103 @Override 10104 public Iterator<String> generate(ActivityIntentInfo info) { 10105 return info.actionsIterator(); 10106 } 10107 } 10108 10109 public class CategoriesIterGenerator extends IterGenerator<String> { 10110 @Override 10111 public Iterator<String> generate(ActivityIntentInfo info) { 10112 return info.categoriesIterator(); 10113 } 10114 } 10115 10116 public class SchemesIterGenerator extends IterGenerator<String> { 10117 @Override 10118 public Iterator<String> generate(ActivityIntentInfo info) { 10119 return info.schemesIterator(); 10120 } 10121 } 10122 10123 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10124 @Override 10125 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10126 return info.authoritiesIterator(); 10127 } 10128 } 10129 10130 /** 10131 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10132 * MODIFIED. Do not pass in a list that should not be changed. 10133 */ 10134 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10135 IterGenerator<T> generator, Iterator<T> searchIterator) { 10136 // loop through the set of actions; every one must be found in the intent filter 10137 while (searchIterator.hasNext()) { 10138 // we must have at least one filter in the list to consider a match 10139 if (intentList.size() == 0) { 10140 break; 10141 } 10142 10143 final T searchAction = searchIterator.next(); 10144 10145 // loop through the set of intent filters 10146 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10147 while (intentIter.hasNext()) { 10148 final ActivityIntentInfo intentInfo = intentIter.next(); 10149 boolean selectionFound = false; 10150 10151 // loop through the intent filter's selection criteria; at least one 10152 // of them must match the searched criteria 10153 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10154 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10155 final T intentSelection = intentSelectionIter.next(); 10156 if (intentSelection != null && intentSelection.equals(searchAction)) { 10157 selectionFound = true; 10158 break; 10159 } 10160 } 10161 10162 // the selection criteria wasn't found in this filter's set; this filter 10163 // is not a potential match 10164 if (!selectionFound) { 10165 intentIter.remove(); 10166 } 10167 } 10168 } 10169 } 10170 10171 private boolean isProtectedAction(ActivityIntentInfo filter) { 10172 final Iterator<String> actionsIter = filter.actionsIterator(); 10173 while (actionsIter != null && actionsIter.hasNext()) { 10174 final String filterAction = actionsIter.next(); 10175 if (PROTECTED_ACTIONS.contains(filterAction)) { 10176 return true; 10177 } 10178 } 10179 return false; 10180 } 10181 10182 /** 10183 * Adjusts the priority of the given intent filter according to policy. 10184 * <p> 10185 * <ul> 10186 * <li>The priority for non privileged applications is capped to '0'</li> 10187 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10188 * <li>The priority for unbundled updates to privileged applications is capped to the 10189 * priority defined on the system partition</li> 10190 * </ul> 10191 * <p> 10192 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10193 * allowed to obtain any priority on any action. 10194 */ 10195 private void adjustPriority( 10196 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10197 // nothing to do; priority is fine as-is 10198 if (intent.getPriority() <= 0) { 10199 return; 10200 } 10201 10202 final ActivityInfo activityInfo = intent.activity.info; 10203 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10204 10205 final boolean privilegedApp = 10206 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10207 if (!privilegedApp) { 10208 // non-privileged applications can never define a priority >0 10209 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10210 + " package: " + applicationInfo.packageName 10211 + " activity: " + intent.activity.className 10212 + " origPrio: " + intent.getPriority()); 10213 intent.setPriority(0); 10214 return; 10215 } 10216 10217 if (systemActivities == null) { 10218 // the system package is not disabled; we're parsing the system partition 10219 if (isProtectedAction(intent)) { 10220 if (mDeferProtectedFilters) { 10221 // We can't deal with these just yet. No component should ever obtain a 10222 // >0 priority for a protected actions, with ONE exception -- the setup 10223 // wizard. The setup wizard, however, cannot be known until we're able to 10224 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10225 // until all intent filters have been processed. Chicken, meet egg. 10226 // Let the filter temporarily have a high priority and rectify the 10227 // priorities after all system packages have been scanned. 10228 mProtectedFilters.add(intent); 10229 if (DEBUG_FILTERS) { 10230 Slog.i(TAG, "Protected action; save for later;" 10231 + " package: " + applicationInfo.packageName 10232 + " activity: " + intent.activity.className 10233 + " origPrio: " + intent.getPriority()); 10234 } 10235 return; 10236 } else { 10237 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10238 Slog.i(TAG, "No setup wizard;" 10239 + " All protected intents capped to priority 0"); 10240 } 10241 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10242 if (DEBUG_FILTERS) { 10243 Slog.i(TAG, "Found setup wizard;" 10244 + " allow priority " + intent.getPriority() + ";" 10245 + " package: " + intent.activity.info.packageName 10246 + " activity: " + intent.activity.className 10247 + " priority: " + intent.getPriority()); 10248 } 10249 // setup wizard gets whatever it wants 10250 return; 10251 } 10252 Slog.w(TAG, "Protected action; cap priority to 0;" 10253 + " package: " + intent.activity.info.packageName 10254 + " activity: " + intent.activity.className 10255 + " origPrio: " + intent.getPriority()); 10256 intent.setPriority(0); 10257 return; 10258 } 10259 } 10260 // privileged apps on the system image get whatever priority they request 10261 return; 10262 } 10263 10264 // privileged app unbundled update ... try to find the same activity 10265 final PackageParser.Activity foundActivity = 10266 findMatchingActivity(systemActivities, activityInfo); 10267 if (foundActivity == null) { 10268 // this is a new activity; it cannot obtain >0 priority 10269 if (DEBUG_FILTERS) { 10270 Slog.i(TAG, "New activity; cap priority to 0;" 10271 + " package: " + applicationInfo.packageName 10272 + " activity: " + intent.activity.className 10273 + " origPrio: " + intent.getPriority()); 10274 } 10275 intent.setPriority(0); 10276 return; 10277 } 10278 10279 // found activity, now check for filter equivalence 10280 10281 // a shallow copy is enough; we modify the list, not its contents 10282 final List<ActivityIntentInfo> intentListCopy = 10283 new ArrayList<>(foundActivity.intents); 10284 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10285 10286 // find matching action subsets 10287 final Iterator<String> actionsIterator = intent.actionsIterator(); 10288 if (actionsIterator != null) { 10289 getIntentListSubset( 10290 intentListCopy, new ActionIterGenerator(), actionsIterator); 10291 if (intentListCopy.size() == 0) { 10292 // no more intents to match; we're not equivalent 10293 if (DEBUG_FILTERS) { 10294 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10295 + " package: " + applicationInfo.packageName 10296 + " activity: " + intent.activity.className 10297 + " origPrio: " + intent.getPriority()); 10298 } 10299 intent.setPriority(0); 10300 return; 10301 } 10302 } 10303 10304 // find matching category subsets 10305 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10306 if (categoriesIterator != null) { 10307 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10308 categoriesIterator); 10309 if (intentListCopy.size() == 0) { 10310 // no more intents to match; we're not equivalent 10311 if (DEBUG_FILTERS) { 10312 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10313 + " package: " + applicationInfo.packageName 10314 + " activity: " + intent.activity.className 10315 + " origPrio: " + intent.getPriority()); 10316 } 10317 intent.setPriority(0); 10318 return; 10319 } 10320 } 10321 10322 // find matching schemes subsets 10323 final Iterator<String> schemesIterator = intent.schemesIterator(); 10324 if (schemesIterator != null) { 10325 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10326 schemesIterator); 10327 if (intentListCopy.size() == 0) { 10328 // no more intents to match; we're not equivalent 10329 if (DEBUG_FILTERS) { 10330 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10331 + " package: " + applicationInfo.packageName 10332 + " activity: " + intent.activity.className 10333 + " origPrio: " + intent.getPriority()); 10334 } 10335 intent.setPriority(0); 10336 return; 10337 } 10338 } 10339 10340 // find matching authorities subsets 10341 final Iterator<IntentFilter.AuthorityEntry> 10342 authoritiesIterator = intent.authoritiesIterator(); 10343 if (authoritiesIterator != null) { 10344 getIntentListSubset(intentListCopy, 10345 new AuthoritiesIterGenerator(), 10346 authoritiesIterator); 10347 if (intentListCopy.size() == 0) { 10348 // no more intents to match; we're not equivalent 10349 if (DEBUG_FILTERS) { 10350 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10351 + " package: " + applicationInfo.packageName 10352 + " activity: " + intent.activity.className 10353 + " origPrio: " + intent.getPriority()); 10354 } 10355 intent.setPriority(0); 10356 return; 10357 } 10358 } 10359 10360 // we found matching filter(s); app gets the max priority of all intents 10361 int cappedPriority = 0; 10362 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10363 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10364 } 10365 if (intent.getPriority() > cappedPriority) { 10366 if (DEBUG_FILTERS) { 10367 Slog.i(TAG, "Found matching filter(s);" 10368 + " cap priority to " + cappedPriority + ";" 10369 + " package: " + applicationInfo.packageName 10370 + " activity: " + intent.activity.className 10371 + " origPrio: " + intent.getPriority()); 10372 } 10373 intent.setPriority(cappedPriority); 10374 return; 10375 } 10376 // all this for nothing; the requested priority was <= what was on the system 10377 } 10378 10379 public final void addActivity(PackageParser.Activity a, String type) { 10380 mActivities.put(a.getComponentName(), a); 10381 if (DEBUG_SHOW_INFO) 10382 Log.v( 10383 TAG, " " + type + " " + 10384 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10385 if (DEBUG_SHOW_INFO) 10386 Log.v(TAG, " Class=" + a.info.name); 10387 final int NI = a.intents.size(); 10388 for (int j=0; j<NI; j++) { 10389 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10390 if ("activity".equals(type)) { 10391 final PackageSetting ps = 10392 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10393 final List<PackageParser.Activity> systemActivities = 10394 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10395 adjustPriority(systemActivities, intent); 10396 } 10397 if (DEBUG_SHOW_INFO) { 10398 Log.v(TAG, " IntentFilter:"); 10399 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10400 } 10401 if (!intent.debugCheck()) { 10402 Log.w(TAG, "==> For Activity " + a.info.name); 10403 } 10404 addFilter(intent); 10405 } 10406 } 10407 10408 public final void removeActivity(PackageParser.Activity a, String type) { 10409 mActivities.remove(a.getComponentName()); 10410 if (DEBUG_SHOW_INFO) { 10411 Log.v(TAG, " " + type + " " 10412 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10413 : a.info.name) + ":"); 10414 Log.v(TAG, " Class=" + a.info.name); 10415 } 10416 final int NI = a.intents.size(); 10417 for (int j=0; j<NI; j++) { 10418 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10419 if (DEBUG_SHOW_INFO) { 10420 Log.v(TAG, " IntentFilter:"); 10421 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10422 } 10423 removeFilter(intent); 10424 } 10425 } 10426 10427 @Override 10428 protected boolean allowFilterResult( 10429 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10430 ActivityInfo filterAi = filter.activity.info; 10431 for (int i=dest.size()-1; i>=0; i--) { 10432 ActivityInfo destAi = dest.get(i).activityInfo; 10433 if (destAi.name == filterAi.name 10434 && destAi.packageName == filterAi.packageName) { 10435 return false; 10436 } 10437 } 10438 return true; 10439 } 10440 10441 @Override 10442 protected ActivityIntentInfo[] newArray(int size) { 10443 return new ActivityIntentInfo[size]; 10444 } 10445 10446 @Override 10447 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10448 if (!sUserManager.exists(userId)) return true; 10449 PackageParser.Package p = filter.activity.owner; 10450 if (p != null) { 10451 PackageSetting ps = (PackageSetting)p.mExtras; 10452 if (ps != null) { 10453 // System apps are never considered stopped for purposes of 10454 // filtering, because there may be no way for the user to 10455 // actually re-launch them. 10456 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10457 && ps.getStopped(userId); 10458 } 10459 } 10460 return false; 10461 } 10462 10463 @Override 10464 protected boolean isPackageForFilter(String packageName, 10465 PackageParser.ActivityIntentInfo info) { 10466 return packageName.equals(info.activity.owner.packageName); 10467 } 10468 10469 @Override 10470 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10471 int match, int userId) { 10472 if (!sUserManager.exists(userId)) return null; 10473 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10474 return null; 10475 } 10476 final PackageParser.Activity activity = info.activity; 10477 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10478 if (ps == null) { 10479 return null; 10480 } 10481 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10482 ps.readUserState(userId), userId); 10483 if (ai == null) { 10484 return null; 10485 } 10486 final ResolveInfo res = new ResolveInfo(); 10487 res.activityInfo = ai; 10488 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10489 res.filter = info; 10490 } 10491 if (info != null) { 10492 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10493 } 10494 res.priority = info.getPriority(); 10495 res.preferredOrder = activity.owner.mPreferredOrder; 10496 //System.out.println("Result: " + res.activityInfo.className + 10497 // " = " + res.priority); 10498 res.match = match; 10499 res.isDefault = info.hasDefault; 10500 res.labelRes = info.labelRes; 10501 res.nonLocalizedLabel = info.nonLocalizedLabel; 10502 if (userNeedsBadging(userId)) { 10503 res.noResourceId = true; 10504 } else { 10505 res.icon = info.icon; 10506 } 10507 res.iconResourceId = info.icon; 10508 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10509 return res; 10510 } 10511 10512 @Override 10513 protected void sortResults(List<ResolveInfo> results) { 10514 Collections.sort(results, mResolvePrioritySorter); 10515 } 10516 10517 @Override 10518 protected void dumpFilter(PrintWriter out, String prefix, 10519 PackageParser.ActivityIntentInfo filter) { 10520 out.print(prefix); out.print( 10521 Integer.toHexString(System.identityHashCode(filter.activity))); 10522 out.print(' '); 10523 filter.activity.printComponentShortName(out); 10524 out.print(" filter "); 10525 out.println(Integer.toHexString(System.identityHashCode(filter))); 10526 } 10527 10528 @Override 10529 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10530 return filter.activity; 10531 } 10532 10533 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10534 PackageParser.Activity activity = (PackageParser.Activity)label; 10535 out.print(prefix); out.print( 10536 Integer.toHexString(System.identityHashCode(activity))); 10537 out.print(' '); 10538 activity.printComponentShortName(out); 10539 if (count > 1) { 10540 out.print(" ("); out.print(count); out.print(" filters)"); 10541 } 10542 out.println(); 10543 } 10544 10545 // Keys are String (activity class name), values are Activity. 10546 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10547 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10548 private int mFlags; 10549 } 10550 10551 private final class ServiceIntentResolver 10552 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10553 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10554 boolean defaultOnly, int userId) { 10555 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10556 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10557 } 10558 10559 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10560 int userId) { 10561 if (!sUserManager.exists(userId)) return null; 10562 mFlags = flags; 10563 return super.queryIntent(intent, resolvedType, 10564 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10565 } 10566 10567 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10568 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10569 if (!sUserManager.exists(userId)) return null; 10570 if (packageServices == null) { 10571 return null; 10572 } 10573 mFlags = flags; 10574 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10575 final int N = packageServices.size(); 10576 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10577 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10578 10579 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10580 for (int i = 0; i < N; ++i) { 10581 intentFilters = packageServices.get(i).intents; 10582 if (intentFilters != null && intentFilters.size() > 0) { 10583 PackageParser.ServiceIntentInfo[] array = 10584 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10585 intentFilters.toArray(array); 10586 listCut.add(array); 10587 } 10588 } 10589 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10590 } 10591 10592 public final void addService(PackageParser.Service s) { 10593 mServices.put(s.getComponentName(), s); 10594 if (DEBUG_SHOW_INFO) { 10595 Log.v(TAG, " " 10596 + (s.info.nonLocalizedLabel != null 10597 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10598 Log.v(TAG, " Class=" + s.info.name); 10599 } 10600 final int NI = s.intents.size(); 10601 int j; 10602 for (j=0; j<NI; j++) { 10603 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10604 if (DEBUG_SHOW_INFO) { 10605 Log.v(TAG, " IntentFilter:"); 10606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10607 } 10608 if (!intent.debugCheck()) { 10609 Log.w(TAG, "==> For Service " + s.info.name); 10610 } 10611 addFilter(intent); 10612 } 10613 } 10614 10615 public final void removeService(PackageParser.Service s) { 10616 mServices.remove(s.getComponentName()); 10617 if (DEBUG_SHOW_INFO) { 10618 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10619 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10620 Log.v(TAG, " Class=" + s.info.name); 10621 } 10622 final int NI = s.intents.size(); 10623 int j; 10624 for (j=0; j<NI; j++) { 10625 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10626 if (DEBUG_SHOW_INFO) { 10627 Log.v(TAG, " IntentFilter:"); 10628 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10629 } 10630 removeFilter(intent); 10631 } 10632 } 10633 10634 @Override 10635 protected boolean allowFilterResult( 10636 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10637 ServiceInfo filterSi = filter.service.info; 10638 for (int i=dest.size()-1; i>=0; i--) { 10639 ServiceInfo destAi = dest.get(i).serviceInfo; 10640 if (destAi.name == filterSi.name 10641 && destAi.packageName == filterSi.packageName) { 10642 return false; 10643 } 10644 } 10645 return true; 10646 } 10647 10648 @Override 10649 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10650 return new PackageParser.ServiceIntentInfo[size]; 10651 } 10652 10653 @Override 10654 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10655 if (!sUserManager.exists(userId)) return true; 10656 PackageParser.Package p = filter.service.owner; 10657 if (p != null) { 10658 PackageSetting ps = (PackageSetting)p.mExtras; 10659 if (ps != null) { 10660 // System apps are never considered stopped for purposes of 10661 // filtering, because there may be no way for the user to 10662 // actually re-launch them. 10663 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10664 && ps.getStopped(userId); 10665 } 10666 } 10667 return false; 10668 } 10669 10670 @Override 10671 protected boolean isPackageForFilter(String packageName, 10672 PackageParser.ServiceIntentInfo info) { 10673 return packageName.equals(info.service.owner.packageName); 10674 } 10675 10676 @Override 10677 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10678 int match, int userId) { 10679 if (!sUserManager.exists(userId)) return null; 10680 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10681 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10682 return null; 10683 } 10684 final PackageParser.Service service = info.service; 10685 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10686 if (ps == null) { 10687 return null; 10688 } 10689 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10690 ps.readUserState(userId), userId); 10691 if (si == null) { 10692 return null; 10693 } 10694 final ResolveInfo res = new ResolveInfo(); 10695 res.serviceInfo = si; 10696 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10697 res.filter = filter; 10698 } 10699 res.priority = info.getPriority(); 10700 res.preferredOrder = service.owner.mPreferredOrder; 10701 res.match = match; 10702 res.isDefault = info.hasDefault; 10703 res.labelRes = info.labelRes; 10704 res.nonLocalizedLabel = info.nonLocalizedLabel; 10705 res.icon = info.icon; 10706 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10707 return res; 10708 } 10709 10710 @Override 10711 protected void sortResults(List<ResolveInfo> results) { 10712 Collections.sort(results, mResolvePrioritySorter); 10713 } 10714 10715 @Override 10716 protected void dumpFilter(PrintWriter out, String prefix, 10717 PackageParser.ServiceIntentInfo filter) { 10718 out.print(prefix); out.print( 10719 Integer.toHexString(System.identityHashCode(filter.service))); 10720 out.print(' '); 10721 filter.service.printComponentShortName(out); 10722 out.print(" filter "); 10723 out.println(Integer.toHexString(System.identityHashCode(filter))); 10724 } 10725 10726 @Override 10727 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10728 return filter.service; 10729 } 10730 10731 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10732 PackageParser.Service service = (PackageParser.Service)label; 10733 out.print(prefix); out.print( 10734 Integer.toHexString(System.identityHashCode(service))); 10735 out.print(' '); 10736 service.printComponentShortName(out); 10737 if (count > 1) { 10738 out.print(" ("); out.print(count); out.print(" filters)"); 10739 } 10740 out.println(); 10741 } 10742 10743// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10744// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10745// final List<ResolveInfo> retList = Lists.newArrayList(); 10746// while (i.hasNext()) { 10747// final ResolveInfo resolveInfo = (ResolveInfo) i; 10748// if (isEnabledLP(resolveInfo.serviceInfo)) { 10749// retList.add(resolveInfo); 10750// } 10751// } 10752// return retList; 10753// } 10754 10755 // Keys are String (activity class name), values are Activity. 10756 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10757 = new ArrayMap<ComponentName, PackageParser.Service>(); 10758 private int mFlags; 10759 }; 10760 10761 private final class ProviderIntentResolver 10762 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10763 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10764 boolean defaultOnly, int userId) { 10765 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10766 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10767 } 10768 10769 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10770 int userId) { 10771 if (!sUserManager.exists(userId)) 10772 return null; 10773 mFlags = flags; 10774 return super.queryIntent(intent, resolvedType, 10775 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10776 } 10777 10778 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10779 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10780 if (!sUserManager.exists(userId)) 10781 return null; 10782 if (packageProviders == null) { 10783 return null; 10784 } 10785 mFlags = flags; 10786 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10787 final int N = packageProviders.size(); 10788 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10789 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10790 10791 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10792 for (int i = 0; i < N; ++i) { 10793 intentFilters = packageProviders.get(i).intents; 10794 if (intentFilters != null && intentFilters.size() > 0) { 10795 PackageParser.ProviderIntentInfo[] array = 10796 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10797 intentFilters.toArray(array); 10798 listCut.add(array); 10799 } 10800 } 10801 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10802 } 10803 10804 public final void addProvider(PackageParser.Provider p) { 10805 if (mProviders.containsKey(p.getComponentName())) { 10806 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10807 return; 10808 } 10809 10810 mProviders.put(p.getComponentName(), p); 10811 if (DEBUG_SHOW_INFO) { 10812 Log.v(TAG, " " 10813 + (p.info.nonLocalizedLabel != null 10814 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10815 Log.v(TAG, " Class=" + p.info.name); 10816 } 10817 final int NI = p.intents.size(); 10818 int j; 10819 for (j = 0; j < NI; j++) { 10820 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10821 if (DEBUG_SHOW_INFO) { 10822 Log.v(TAG, " IntentFilter:"); 10823 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10824 } 10825 if (!intent.debugCheck()) { 10826 Log.w(TAG, "==> For Provider " + p.info.name); 10827 } 10828 addFilter(intent); 10829 } 10830 } 10831 10832 public final void removeProvider(PackageParser.Provider p) { 10833 mProviders.remove(p.getComponentName()); 10834 if (DEBUG_SHOW_INFO) { 10835 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10836 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10837 Log.v(TAG, " Class=" + p.info.name); 10838 } 10839 final int NI = p.intents.size(); 10840 int j; 10841 for (j = 0; j < NI; j++) { 10842 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10843 if (DEBUG_SHOW_INFO) { 10844 Log.v(TAG, " IntentFilter:"); 10845 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10846 } 10847 removeFilter(intent); 10848 } 10849 } 10850 10851 @Override 10852 protected boolean allowFilterResult( 10853 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10854 ProviderInfo filterPi = filter.provider.info; 10855 for (int i = dest.size() - 1; i >= 0; i--) { 10856 ProviderInfo destPi = dest.get(i).providerInfo; 10857 if (destPi.name == filterPi.name 10858 && destPi.packageName == filterPi.packageName) { 10859 return false; 10860 } 10861 } 10862 return true; 10863 } 10864 10865 @Override 10866 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10867 return new PackageParser.ProviderIntentInfo[size]; 10868 } 10869 10870 @Override 10871 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10872 if (!sUserManager.exists(userId)) 10873 return true; 10874 PackageParser.Package p = filter.provider.owner; 10875 if (p != null) { 10876 PackageSetting ps = (PackageSetting) p.mExtras; 10877 if (ps != null) { 10878 // System apps are never considered stopped for purposes of 10879 // filtering, because there may be no way for the user to 10880 // actually re-launch them. 10881 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10882 && ps.getStopped(userId); 10883 } 10884 } 10885 return false; 10886 } 10887 10888 @Override 10889 protected boolean isPackageForFilter(String packageName, 10890 PackageParser.ProviderIntentInfo info) { 10891 return packageName.equals(info.provider.owner.packageName); 10892 } 10893 10894 @Override 10895 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10896 int match, int userId) { 10897 if (!sUserManager.exists(userId)) 10898 return null; 10899 final PackageParser.ProviderIntentInfo info = filter; 10900 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10901 return null; 10902 } 10903 final PackageParser.Provider provider = info.provider; 10904 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10905 if (ps == null) { 10906 return null; 10907 } 10908 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10909 ps.readUserState(userId), userId); 10910 if (pi == null) { 10911 return null; 10912 } 10913 final ResolveInfo res = new ResolveInfo(); 10914 res.providerInfo = pi; 10915 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10916 res.filter = filter; 10917 } 10918 res.priority = info.getPriority(); 10919 res.preferredOrder = provider.owner.mPreferredOrder; 10920 res.match = match; 10921 res.isDefault = info.hasDefault; 10922 res.labelRes = info.labelRes; 10923 res.nonLocalizedLabel = info.nonLocalizedLabel; 10924 res.icon = info.icon; 10925 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10926 return res; 10927 } 10928 10929 @Override 10930 protected void sortResults(List<ResolveInfo> results) { 10931 Collections.sort(results, mResolvePrioritySorter); 10932 } 10933 10934 @Override 10935 protected void dumpFilter(PrintWriter out, String prefix, 10936 PackageParser.ProviderIntentInfo filter) { 10937 out.print(prefix); 10938 out.print( 10939 Integer.toHexString(System.identityHashCode(filter.provider))); 10940 out.print(' '); 10941 filter.provider.printComponentShortName(out); 10942 out.print(" filter "); 10943 out.println(Integer.toHexString(System.identityHashCode(filter))); 10944 } 10945 10946 @Override 10947 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10948 return filter.provider; 10949 } 10950 10951 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10952 PackageParser.Provider provider = (PackageParser.Provider)label; 10953 out.print(prefix); out.print( 10954 Integer.toHexString(System.identityHashCode(provider))); 10955 out.print(' '); 10956 provider.printComponentShortName(out); 10957 if (count > 1) { 10958 out.print(" ("); out.print(count); out.print(" filters)"); 10959 } 10960 out.println(); 10961 } 10962 10963 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10964 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10965 private int mFlags; 10966 } 10967 10968 private static final class EphemeralIntentResolver 10969 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10970 @Override 10971 protected EphemeralResolveIntentInfo[] newArray(int size) { 10972 return new EphemeralResolveIntentInfo[size]; 10973 } 10974 10975 @Override 10976 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10977 return true; 10978 } 10979 10980 @Override 10981 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10982 int userId) { 10983 if (!sUserManager.exists(userId)) { 10984 return null; 10985 } 10986 return info.getEphemeralResolveInfo(); 10987 } 10988 } 10989 10990 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10991 new Comparator<ResolveInfo>() { 10992 public int compare(ResolveInfo r1, ResolveInfo r2) { 10993 int v1 = r1.priority; 10994 int v2 = r2.priority; 10995 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10996 if (v1 != v2) { 10997 return (v1 > v2) ? -1 : 1; 10998 } 10999 v1 = r1.preferredOrder; 11000 v2 = r2.preferredOrder; 11001 if (v1 != v2) { 11002 return (v1 > v2) ? -1 : 1; 11003 } 11004 if (r1.isDefault != r2.isDefault) { 11005 return r1.isDefault ? -1 : 1; 11006 } 11007 v1 = r1.match; 11008 v2 = r2.match; 11009 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11010 if (v1 != v2) { 11011 return (v1 > v2) ? -1 : 1; 11012 } 11013 if (r1.system != r2.system) { 11014 return r1.system ? -1 : 1; 11015 } 11016 if (r1.activityInfo != null) { 11017 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11018 } 11019 if (r1.serviceInfo != null) { 11020 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11021 } 11022 if (r1.providerInfo != null) { 11023 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11024 } 11025 return 0; 11026 } 11027 }; 11028 11029 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11030 new Comparator<ProviderInfo>() { 11031 public int compare(ProviderInfo p1, ProviderInfo p2) { 11032 final int v1 = p1.initOrder; 11033 final int v2 = p2.initOrder; 11034 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11035 } 11036 }; 11037 11038 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11039 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11040 final int[] userIds) { 11041 mHandler.post(new Runnable() { 11042 @Override 11043 public void run() { 11044 try { 11045 final IActivityManager am = ActivityManagerNative.getDefault(); 11046 if (am == null) return; 11047 final int[] resolvedUserIds; 11048 if (userIds == null) { 11049 resolvedUserIds = am.getRunningUserIds(); 11050 } else { 11051 resolvedUserIds = userIds; 11052 } 11053 for (int id : resolvedUserIds) { 11054 final Intent intent = new Intent(action, 11055 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11056 if (extras != null) { 11057 intent.putExtras(extras); 11058 } 11059 if (targetPkg != null) { 11060 intent.setPackage(targetPkg); 11061 } 11062 // Modify the UID when posting to other users 11063 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11064 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11065 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11066 intent.putExtra(Intent.EXTRA_UID, uid); 11067 } 11068 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11069 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11070 if (DEBUG_BROADCASTS) { 11071 RuntimeException here = new RuntimeException("here"); 11072 here.fillInStackTrace(); 11073 Slog.d(TAG, "Sending to user " + id + ": " 11074 + intent.toShortString(false, true, false, false) 11075 + " " + intent.getExtras(), here); 11076 } 11077 am.broadcastIntent(null, intent, null, finishedReceiver, 11078 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11079 null, finishedReceiver != null, false, id); 11080 } 11081 } catch (RemoteException ex) { 11082 } 11083 } 11084 }); 11085 } 11086 11087 /** 11088 * Check if the external storage media is available. This is true if there 11089 * is a mounted external storage medium or if the external storage is 11090 * emulated. 11091 */ 11092 private boolean isExternalMediaAvailable() { 11093 return mMediaMounted || Environment.isExternalStorageEmulated(); 11094 } 11095 11096 @Override 11097 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11098 // writer 11099 synchronized (mPackages) { 11100 if (!isExternalMediaAvailable()) { 11101 // If the external storage is no longer mounted at this point, 11102 // the caller may not have been able to delete all of this 11103 // packages files and can not delete any more. Bail. 11104 return null; 11105 } 11106 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11107 if (lastPackage != null) { 11108 pkgs.remove(lastPackage); 11109 } 11110 if (pkgs.size() > 0) { 11111 return pkgs.get(0); 11112 } 11113 } 11114 return null; 11115 } 11116 11117 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11118 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11119 userId, andCode ? 1 : 0, packageName); 11120 if (mSystemReady) { 11121 msg.sendToTarget(); 11122 } else { 11123 if (mPostSystemReadyMessages == null) { 11124 mPostSystemReadyMessages = new ArrayList<>(); 11125 } 11126 mPostSystemReadyMessages.add(msg); 11127 } 11128 } 11129 11130 void startCleaningPackages() { 11131 // reader 11132 if (!isExternalMediaAvailable()) { 11133 return; 11134 } 11135 synchronized (mPackages) { 11136 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11137 return; 11138 } 11139 } 11140 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11141 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11142 IActivityManager am = ActivityManagerNative.getDefault(); 11143 if (am != null) { 11144 try { 11145 am.startService(null, intent, null, mContext.getOpPackageName(), 11146 UserHandle.USER_SYSTEM); 11147 } catch (RemoteException e) { 11148 } 11149 } 11150 } 11151 11152 @Override 11153 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11154 int installFlags, String installerPackageName, int userId) { 11155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11156 11157 final int callingUid = Binder.getCallingUid(); 11158 enforceCrossUserPermission(callingUid, userId, 11159 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11160 11161 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11162 try { 11163 if (observer != null) { 11164 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11165 } 11166 } catch (RemoteException re) { 11167 } 11168 return; 11169 } 11170 11171 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11172 installFlags |= PackageManager.INSTALL_FROM_ADB; 11173 11174 } else { 11175 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11176 // about installerPackageName. 11177 11178 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11179 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11180 } 11181 11182 UserHandle user; 11183 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11184 user = UserHandle.ALL; 11185 } else { 11186 user = new UserHandle(userId); 11187 } 11188 11189 // Only system components can circumvent runtime permissions when installing. 11190 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11191 && mContext.checkCallingOrSelfPermission(Manifest.permission 11192 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11193 throw new SecurityException("You need the " 11194 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11195 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11196 } 11197 11198 final File originFile = new File(originPath); 11199 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11200 11201 final Message msg = mHandler.obtainMessage(INIT_COPY); 11202 final VerificationInfo verificationInfo = new VerificationInfo( 11203 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11204 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11205 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11206 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11207 null /*certificates*/); 11208 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11209 msg.obj = params; 11210 11211 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11212 System.identityHashCode(msg.obj)); 11213 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11214 System.identityHashCode(msg.obj)); 11215 11216 mHandler.sendMessage(msg); 11217 } 11218 11219 void installStage(String packageName, File stagedDir, String stagedCid, 11220 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11221 String installerPackageName, int installerUid, UserHandle user, 11222 Certificate[][] certificates) { 11223 if (DEBUG_EPHEMERAL) { 11224 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11225 Slog.d(TAG, "Ephemeral install of " + packageName); 11226 } 11227 } 11228 final VerificationInfo verificationInfo = new VerificationInfo( 11229 sessionParams.originatingUri, sessionParams.referrerUri, 11230 sessionParams.originatingUid, installerUid); 11231 11232 final OriginInfo origin; 11233 if (stagedDir != null) { 11234 origin = OriginInfo.fromStagedFile(stagedDir); 11235 } else { 11236 origin = OriginInfo.fromStagedContainer(stagedCid); 11237 } 11238 11239 final Message msg = mHandler.obtainMessage(INIT_COPY); 11240 final InstallParams params = new InstallParams(origin, null, observer, 11241 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11242 verificationInfo, user, sessionParams.abiOverride, 11243 sessionParams.grantedRuntimePermissions, certificates); 11244 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11245 msg.obj = params; 11246 11247 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11248 System.identityHashCode(msg.obj)); 11249 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11250 System.identityHashCode(msg.obj)); 11251 11252 mHandler.sendMessage(msg); 11253 } 11254 11255 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11256 int userId) { 11257 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11258 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11259 } 11260 11261 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11262 int appId, int userId) { 11263 Bundle extras = new Bundle(1); 11264 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11265 11266 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11267 packageName, extras, 0, null, null, new int[] {userId}); 11268 try { 11269 IActivityManager am = ActivityManagerNative.getDefault(); 11270 if (isSystem && am.isUserRunning(userId, 0)) { 11271 // The just-installed/enabled app is bundled on the system, so presumed 11272 // to be able to run automatically without needing an explicit launch. 11273 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11274 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11275 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11276 .setPackage(packageName); 11277 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11278 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11279 } 11280 } catch (RemoteException e) { 11281 // shouldn't happen 11282 Slog.w(TAG, "Unable to bootstrap installed package", e); 11283 } 11284 } 11285 11286 @Override 11287 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11288 int userId) { 11289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11290 PackageSetting pkgSetting; 11291 final int uid = Binder.getCallingUid(); 11292 enforceCrossUserPermission(uid, userId, 11293 true /* requireFullPermission */, true /* checkShell */, 11294 "setApplicationHiddenSetting for user " + userId); 11295 11296 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11297 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11298 return false; 11299 } 11300 11301 long callingId = Binder.clearCallingIdentity(); 11302 try { 11303 boolean sendAdded = false; 11304 boolean sendRemoved = false; 11305 // writer 11306 synchronized (mPackages) { 11307 pkgSetting = mSettings.mPackages.get(packageName); 11308 if (pkgSetting == null) { 11309 return false; 11310 } 11311 if (pkgSetting.getHidden(userId) != hidden) { 11312 pkgSetting.setHidden(hidden, userId); 11313 mSettings.writePackageRestrictionsLPr(userId); 11314 if (hidden) { 11315 sendRemoved = true; 11316 } else { 11317 sendAdded = true; 11318 } 11319 } 11320 } 11321 if (sendAdded) { 11322 sendPackageAddedForUser(packageName, pkgSetting, userId); 11323 return true; 11324 } 11325 if (sendRemoved) { 11326 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11327 "hiding pkg"); 11328 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11329 return true; 11330 } 11331 } finally { 11332 Binder.restoreCallingIdentity(callingId); 11333 } 11334 return false; 11335 } 11336 11337 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11338 int userId) { 11339 final PackageRemovedInfo info = new PackageRemovedInfo(); 11340 info.removedPackage = packageName; 11341 info.removedUsers = new int[] {userId}; 11342 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11343 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11344 } 11345 11346 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11347 if (pkgList.length > 0) { 11348 Bundle extras = new Bundle(1); 11349 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11350 11351 sendPackageBroadcast( 11352 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11353 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11354 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11355 new int[] {userId}); 11356 } 11357 } 11358 11359 /** 11360 * Returns true if application is not found or there was an error. Otherwise it returns 11361 * the hidden state of the package for the given user. 11362 */ 11363 @Override 11364 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11366 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11367 true /* requireFullPermission */, false /* checkShell */, 11368 "getApplicationHidden for user " + userId); 11369 PackageSetting pkgSetting; 11370 long callingId = Binder.clearCallingIdentity(); 11371 try { 11372 // writer 11373 synchronized (mPackages) { 11374 pkgSetting = mSettings.mPackages.get(packageName); 11375 if (pkgSetting == null) { 11376 return true; 11377 } 11378 return pkgSetting.getHidden(userId); 11379 } 11380 } finally { 11381 Binder.restoreCallingIdentity(callingId); 11382 } 11383 } 11384 11385 /** 11386 * @hide 11387 */ 11388 @Override 11389 public int installExistingPackageAsUser(String packageName, int userId) { 11390 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11391 null); 11392 PackageSetting pkgSetting; 11393 final int uid = Binder.getCallingUid(); 11394 enforceCrossUserPermission(uid, userId, 11395 true /* requireFullPermission */, true /* checkShell */, 11396 "installExistingPackage for user " + userId); 11397 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11398 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11399 } 11400 11401 long callingId = Binder.clearCallingIdentity(); 11402 try { 11403 boolean installed = false; 11404 11405 // writer 11406 synchronized (mPackages) { 11407 pkgSetting = mSettings.mPackages.get(packageName); 11408 if (pkgSetting == null) { 11409 return PackageManager.INSTALL_FAILED_INVALID_URI; 11410 } 11411 if (!pkgSetting.getInstalled(userId)) { 11412 pkgSetting.setInstalled(true, userId); 11413 pkgSetting.setHidden(false, userId); 11414 mSettings.writePackageRestrictionsLPr(userId); 11415 installed = true; 11416 } 11417 } 11418 11419 if (installed) { 11420 if (pkgSetting.pkg != null) { 11421 synchronized (mInstallLock) { 11422 // We don't need to freeze for a brand new install 11423 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11424 } 11425 } 11426 sendPackageAddedForUser(packageName, pkgSetting, userId); 11427 } 11428 } finally { 11429 Binder.restoreCallingIdentity(callingId); 11430 } 11431 11432 return PackageManager.INSTALL_SUCCEEDED; 11433 } 11434 11435 boolean isUserRestricted(int userId, String restrictionKey) { 11436 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11437 if (restrictions.getBoolean(restrictionKey, false)) { 11438 Log.w(TAG, "User is restricted: " + restrictionKey); 11439 return true; 11440 } 11441 return false; 11442 } 11443 11444 @Override 11445 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11446 int userId) { 11447 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11448 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11449 true /* requireFullPermission */, true /* checkShell */, 11450 "setPackagesSuspended for user " + userId); 11451 11452 if (ArrayUtils.isEmpty(packageNames)) { 11453 return packageNames; 11454 } 11455 11456 // List of package names for whom the suspended state has changed. 11457 List<String> changedPackages = new ArrayList<>(packageNames.length); 11458 // List of package names for whom the suspended state is not set as requested in this 11459 // method. 11460 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11461 for (int i = 0; i < packageNames.length; i++) { 11462 String packageName = packageNames[i]; 11463 long callingId = Binder.clearCallingIdentity(); 11464 try { 11465 boolean changed = false; 11466 final int appId; 11467 synchronized (mPackages) { 11468 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11469 if (pkgSetting == null) { 11470 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11471 + "\". Skipping suspending/un-suspending."); 11472 unactionedPackages.add(packageName); 11473 continue; 11474 } 11475 appId = pkgSetting.appId; 11476 if (pkgSetting.getSuspended(userId) != suspended) { 11477 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11478 unactionedPackages.add(packageName); 11479 continue; 11480 } 11481 pkgSetting.setSuspended(suspended, userId); 11482 mSettings.writePackageRestrictionsLPr(userId); 11483 changed = true; 11484 changedPackages.add(packageName); 11485 } 11486 } 11487 11488 if (changed && suspended) { 11489 killApplication(packageName, UserHandle.getUid(userId, appId), 11490 "suspending package"); 11491 } 11492 } finally { 11493 Binder.restoreCallingIdentity(callingId); 11494 } 11495 } 11496 11497 if (!changedPackages.isEmpty()) { 11498 sendPackagesSuspendedForUser(changedPackages.toArray( 11499 new String[changedPackages.size()]), userId, suspended); 11500 } 11501 11502 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11503 } 11504 11505 @Override 11506 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11507 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11508 true /* requireFullPermission */, false /* checkShell */, 11509 "isPackageSuspendedForUser for user " + userId); 11510 synchronized (mPackages) { 11511 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11512 if (pkgSetting == null) { 11513 throw new IllegalArgumentException("Unknown target package: " + packageName); 11514 } 11515 return pkgSetting.getSuspended(userId); 11516 } 11517 } 11518 11519 /** 11520 * TODO: cache and disallow blocking the active dialer. 11521 * 11522 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11523 */ 11524 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11525 if (isPackageDeviceAdmin(packageName, userId)) { 11526 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11527 + "\": has an active device admin"); 11528 return false; 11529 } 11530 11531 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11532 if (packageName.equals(activeLauncherPackageName)) { 11533 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11534 + "\": contains the active launcher"); 11535 return false; 11536 } 11537 11538 if (packageName.equals(mRequiredInstallerPackage)) { 11539 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11540 + "\": required for package installation"); 11541 return false; 11542 } 11543 11544 if (packageName.equals(mRequiredVerifierPackage)) { 11545 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11546 + "\": required for package verification"); 11547 return false; 11548 } 11549 11550 final PackageParser.Package pkg = mPackages.get(packageName); 11551 if (pkg != null && isPrivilegedApp(pkg)) { 11552 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11553 + "\": is a privileged app"); 11554 return false; 11555 } 11556 11557 return true; 11558 } 11559 11560 private String getActiveLauncherPackageName(int userId) { 11561 Intent intent = new Intent(Intent.ACTION_MAIN); 11562 intent.addCategory(Intent.CATEGORY_HOME); 11563 ResolveInfo resolveInfo = resolveIntent( 11564 intent, 11565 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11566 PackageManager.MATCH_DEFAULT_ONLY, 11567 userId); 11568 11569 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11570 } 11571 11572 @Override 11573 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11574 mContext.enforceCallingOrSelfPermission( 11575 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11576 "Only package verification agents can verify applications"); 11577 11578 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11579 final PackageVerificationResponse response = new PackageVerificationResponse( 11580 verificationCode, Binder.getCallingUid()); 11581 msg.arg1 = id; 11582 msg.obj = response; 11583 mHandler.sendMessage(msg); 11584 } 11585 11586 @Override 11587 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11588 long millisecondsToDelay) { 11589 mContext.enforceCallingOrSelfPermission( 11590 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11591 "Only package verification agents can extend verification timeouts"); 11592 11593 final PackageVerificationState state = mPendingVerification.get(id); 11594 final PackageVerificationResponse response = new PackageVerificationResponse( 11595 verificationCodeAtTimeout, Binder.getCallingUid()); 11596 11597 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11598 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11599 } 11600 if (millisecondsToDelay < 0) { 11601 millisecondsToDelay = 0; 11602 } 11603 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11604 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11605 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11606 } 11607 11608 if ((state != null) && !state.timeoutExtended()) { 11609 state.extendTimeout(); 11610 11611 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11612 msg.arg1 = id; 11613 msg.obj = response; 11614 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11615 } 11616 } 11617 11618 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11619 int verificationCode, UserHandle user) { 11620 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11621 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11622 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11623 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11624 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11625 11626 mContext.sendBroadcastAsUser(intent, user, 11627 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11628 } 11629 11630 private ComponentName matchComponentForVerifier(String packageName, 11631 List<ResolveInfo> receivers) { 11632 ActivityInfo targetReceiver = null; 11633 11634 final int NR = receivers.size(); 11635 for (int i = 0; i < NR; i++) { 11636 final ResolveInfo info = receivers.get(i); 11637 if (info.activityInfo == null) { 11638 continue; 11639 } 11640 11641 if (packageName.equals(info.activityInfo.packageName)) { 11642 targetReceiver = info.activityInfo; 11643 break; 11644 } 11645 } 11646 11647 if (targetReceiver == null) { 11648 return null; 11649 } 11650 11651 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11652 } 11653 11654 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11655 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11656 if (pkgInfo.verifiers.length == 0) { 11657 return null; 11658 } 11659 11660 final int N = pkgInfo.verifiers.length; 11661 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11662 for (int i = 0; i < N; i++) { 11663 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11664 11665 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11666 receivers); 11667 if (comp == null) { 11668 continue; 11669 } 11670 11671 final int verifierUid = getUidForVerifier(verifierInfo); 11672 if (verifierUid == -1) { 11673 continue; 11674 } 11675 11676 if (DEBUG_VERIFY) { 11677 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11678 + " with the correct signature"); 11679 } 11680 sufficientVerifiers.add(comp); 11681 verificationState.addSufficientVerifier(verifierUid); 11682 } 11683 11684 return sufficientVerifiers; 11685 } 11686 11687 private int getUidForVerifier(VerifierInfo verifierInfo) { 11688 synchronized (mPackages) { 11689 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11690 if (pkg == null) { 11691 return -1; 11692 } else if (pkg.mSignatures.length != 1) { 11693 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11694 + " has more than one signature; ignoring"); 11695 return -1; 11696 } 11697 11698 /* 11699 * If the public key of the package's signature does not match 11700 * our expected public key, then this is a different package and 11701 * we should skip. 11702 */ 11703 11704 final byte[] expectedPublicKey; 11705 try { 11706 final Signature verifierSig = pkg.mSignatures[0]; 11707 final PublicKey publicKey = verifierSig.getPublicKey(); 11708 expectedPublicKey = publicKey.getEncoded(); 11709 } catch (CertificateException e) { 11710 return -1; 11711 } 11712 11713 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11714 11715 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11716 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11717 + " does not have the expected public key; ignoring"); 11718 return -1; 11719 } 11720 11721 return pkg.applicationInfo.uid; 11722 } 11723 } 11724 11725 @Override 11726 public void finishPackageInstall(int token) { 11727 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11728 11729 if (DEBUG_INSTALL) { 11730 Slog.v(TAG, "BM finishing package install for " + token); 11731 } 11732 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11733 11734 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11735 mHandler.sendMessage(msg); 11736 } 11737 11738 /** 11739 * Get the verification agent timeout. 11740 * 11741 * @return verification timeout in milliseconds 11742 */ 11743 private long getVerificationTimeout() { 11744 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11745 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11746 DEFAULT_VERIFICATION_TIMEOUT); 11747 } 11748 11749 /** 11750 * Get the default verification agent response code. 11751 * 11752 * @return default verification response code 11753 */ 11754 private int getDefaultVerificationResponse() { 11755 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11756 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11757 DEFAULT_VERIFICATION_RESPONSE); 11758 } 11759 11760 /** 11761 * Check whether or not package verification has been enabled. 11762 * 11763 * @return true if verification should be performed 11764 */ 11765 private boolean isVerificationEnabled(int userId, int installFlags) { 11766 if (!DEFAULT_VERIFY_ENABLE) { 11767 return false; 11768 } 11769 // Ephemeral apps don't get the full verification treatment 11770 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11771 if (DEBUG_EPHEMERAL) { 11772 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11773 } 11774 return false; 11775 } 11776 11777 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11778 11779 // Check if installing from ADB 11780 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11781 // Do not run verification in a test harness environment 11782 if (ActivityManager.isRunningInTestHarness()) { 11783 return false; 11784 } 11785 if (ensureVerifyAppsEnabled) { 11786 return true; 11787 } 11788 // Check if the developer does not want package verification for ADB installs 11789 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11790 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11791 return false; 11792 } 11793 } 11794 11795 if (ensureVerifyAppsEnabled) { 11796 return true; 11797 } 11798 11799 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11800 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11801 } 11802 11803 @Override 11804 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11805 throws RemoteException { 11806 mContext.enforceCallingOrSelfPermission( 11807 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11808 "Only intentfilter verification agents can verify applications"); 11809 11810 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11811 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11812 Binder.getCallingUid(), verificationCode, failedDomains); 11813 msg.arg1 = id; 11814 msg.obj = response; 11815 mHandler.sendMessage(msg); 11816 } 11817 11818 @Override 11819 public int getIntentVerificationStatus(String packageName, int userId) { 11820 synchronized (mPackages) { 11821 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11822 } 11823 } 11824 11825 @Override 11826 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11827 mContext.enforceCallingOrSelfPermission( 11828 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11829 11830 boolean result = false; 11831 synchronized (mPackages) { 11832 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11833 } 11834 if (result) { 11835 scheduleWritePackageRestrictionsLocked(userId); 11836 } 11837 return result; 11838 } 11839 11840 @Override 11841 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11842 String packageName) { 11843 synchronized (mPackages) { 11844 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11845 } 11846 } 11847 11848 @Override 11849 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11850 if (TextUtils.isEmpty(packageName)) { 11851 return ParceledListSlice.emptyList(); 11852 } 11853 synchronized (mPackages) { 11854 PackageParser.Package pkg = mPackages.get(packageName); 11855 if (pkg == null || pkg.activities == null) { 11856 return ParceledListSlice.emptyList(); 11857 } 11858 final int count = pkg.activities.size(); 11859 ArrayList<IntentFilter> result = new ArrayList<>(); 11860 for (int n=0; n<count; n++) { 11861 PackageParser.Activity activity = pkg.activities.get(n); 11862 if (activity.intents != null && activity.intents.size() > 0) { 11863 result.addAll(activity.intents); 11864 } 11865 } 11866 return new ParceledListSlice<>(result); 11867 } 11868 } 11869 11870 @Override 11871 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11872 mContext.enforceCallingOrSelfPermission( 11873 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11874 11875 synchronized (mPackages) { 11876 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11877 if (packageName != null) { 11878 result |= updateIntentVerificationStatus(packageName, 11879 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11880 userId); 11881 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11882 packageName, userId); 11883 } 11884 return result; 11885 } 11886 } 11887 11888 @Override 11889 public String getDefaultBrowserPackageName(int userId) { 11890 synchronized (mPackages) { 11891 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11892 } 11893 } 11894 11895 /** 11896 * Get the "allow unknown sources" setting. 11897 * 11898 * @return the current "allow unknown sources" setting 11899 */ 11900 private int getUnknownSourcesSettings() { 11901 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11902 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11903 -1); 11904 } 11905 11906 @Override 11907 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11908 final int uid = Binder.getCallingUid(); 11909 // writer 11910 synchronized (mPackages) { 11911 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11912 if (targetPackageSetting == null) { 11913 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11914 } 11915 11916 PackageSetting installerPackageSetting; 11917 if (installerPackageName != null) { 11918 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11919 if (installerPackageSetting == null) { 11920 throw new IllegalArgumentException("Unknown installer package: " 11921 + installerPackageName); 11922 } 11923 } else { 11924 installerPackageSetting = null; 11925 } 11926 11927 Signature[] callerSignature; 11928 Object obj = mSettings.getUserIdLPr(uid); 11929 if (obj != null) { 11930 if (obj instanceof SharedUserSetting) { 11931 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11932 } else if (obj instanceof PackageSetting) { 11933 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11934 } else { 11935 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11936 } 11937 } else { 11938 throw new SecurityException("Unknown calling UID: " + uid); 11939 } 11940 11941 // Verify: can't set installerPackageName to a package that is 11942 // not signed with the same cert as the caller. 11943 if (installerPackageSetting != null) { 11944 if (compareSignatures(callerSignature, 11945 installerPackageSetting.signatures.mSignatures) 11946 != PackageManager.SIGNATURE_MATCH) { 11947 throw new SecurityException( 11948 "Caller does not have same cert as new installer package " 11949 + installerPackageName); 11950 } 11951 } 11952 11953 // Verify: if target already has an installer package, it must 11954 // be signed with the same cert as the caller. 11955 if (targetPackageSetting.installerPackageName != null) { 11956 PackageSetting setting = mSettings.mPackages.get( 11957 targetPackageSetting.installerPackageName); 11958 // If the currently set package isn't valid, then it's always 11959 // okay to change it. 11960 if (setting != null) { 11961 if (compareSignatures(callerSignature, 11962 setting.signatures.mSignatures) 11963 != PackageManager.SIGNATURE_MATCH) { 11964 throw new SecurityException( 11965 "Caller does not have same cert as old installer package " 11966 + targetPackageSetting.installerPackageName); 11967 } 11968 } 11969 } 11970 11971 // Okay! 11972 targetPackageSetting.installerPackageName = installerPackageName; 11973 if (installerPackageName != null) { 11974 mSettings.mInstallerPackages.add(installerPackageName); 11975 } 11976 scheduleWriteSettingsLocked(); 11977 } 11978 } 11979 11980 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11981 // Queue up an async operation since the package installation may take a little while. 11982 mHandler.post(new Runnable() { 11983 public void run() { 11984 mHandler.removeCallbacks(this); 11985 // Result object to be returned 11986 PackageInstalledInfo res = new PackageInstalledInfo(); 11987 res.setReturnCode(currentStatus); 11988 res.uid = -1; 11989 res.pkg = null; 11990 res.removedInfo = null; 11991 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11992 args.doPreInstall(res.returnCode); 11993 synchronized (mInstallLock) { 11994 installPackageTracedLI(args, res); 11995 } 11996 args.doPostInstall(res.returnCode, res.uid); 11997 } 11998 11999 // A restore should be performed at this point if (a) the install 12000 // succeeded, (b) the operation is not an update, and (c) the new 12001 // package has not opted out of backup participation. 12002 final boolean update = res.removedInfo != null 12003 && res.removedInfo.removedPackage != null; 12004 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12005 boolean doRestore = !update 12006 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12007 12008 // Set up the post-install work request bookkeeping. This will be used 12009 // and cleaned up by the post-install event handling regardless of whether 12010 // there's a restore pass performed. Token values are >= 1. 12011 int token; 12012 if (mNextInstallToken < 0) mNextInstallToken = 1; 12013 token = mNextInstallToken++; 12014 12015 PostInstallData data = new PostInstallData(args, res); 12016 mRunningInstalls.put(token, data); 12017 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12018 12019 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12020 // Pass responsibility to the Backup Manager. It will perform a 12021 // restore if appropriate, then pass responsibility back to the 12022 // Package Manager to run the post-install observer callbacks 12023 // and broadcasts. 12024 IBackupManager bm = IBackupManager.Stub.asInterface( 12025 ServiceManager.getService(Context.BACKUP_SERVICE)); 12026 if (bm != null) { 12027 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12028 + " to BM for possible restore"); 12029 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12030 try { 12031 // TODO: http://b/22388012 12032 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12033 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12034 } else { 12035 doRestore = false; 12036 } 12037 } catch (RemoteException e) { 12038 // can't happen; the backup manager is local 12039 } catch (Exception e) { 12040 Slog.e(TAG, "Exception trying to enqueue restore", e); 12041 doRestore = false; 12042 } 12043 } else { 12044 Slog.e(TAG, "Backup Manager not found!"); 12045 doRestore = false; 12046 } 12047 } 12048 12049 if (!doRestore) { 12050 // No restore possible, or the Backup Manager was mysteriously not 12051 // available -- just fire the post-install work request directly. 12052 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12053 12054 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12055 12056 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12057 mHandler.sendMessage(msg); 12058 } 12059 } 12060 }); 12061 } 12062 12063 private abstract class HandlerParams { 12064 private static final int MAX_RETRIES = 4; 12065 12066 /** 12067 * Number of times startCopy() has been attempted and had a non-fatal 12068 * error. 12069 */ 12070 private int mRetries = 0; 12071 12072 /** User handle for the user requesting the information or installation. */ 12073 private final UserHandle mUser; 12074 String traceMethod; 12075 int traceCookie; 12076 12077 HandlerParams(UserHandle user) { 12078 mUser = user; 12079 } 12080 12081 UserHandle getUser() { 12082 return mUser; 12083 } 12084 12085 HandlerParams setTraceMethod(String traceMethod) { 12086 this.traceMethod = traceMethod; 12087 return this; 12088 } 12089 12090 HandlerParams setTraceCookie(int traceCookie) { 12091 this.traceCookie = traceCookie; 12092 return this; 12093 } 12094 12095 final boolean startCopy() { 12096 boolean res; 12097 try { 12098 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12099 12100 if (++mRetries > MAX_RETRIES) { 12101 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12102 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12103 handleServiceError(); 12104 return false; 12105 } else { 12106 handleStartCopy(); 12107 res = true; 12108 } 12109 } catch (RemoteException e) { 12110 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12111 mHandler.sendEmptyMessage(MCS_RECONNECT); 12112 res = false; 12113 } 12114 handleReturnCode(); 12115 return res; 12116 } 12117 12118 final void serviceError() { 12119 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12120 handleServiceError(); 12121 handleReturnCode(); 12122 } 12123 12124 abstract void handleStartCopy() throws RemoteException; 12125 abstract void handleServiceError(); 12126 abstract void handleReturnCode(); 12127 } 12128 12129 class MeasureParams extends HandlerParams { 12130 private final PackageStats mStats; 12131 private boolean mSuccess; 12132 12133 private final IPackageStatsObserver mObserver; 12134 12135 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12136 super(new UserHandle(stats.userHandle)); 12137 mObserver = observer; 12138 mStats = stats; 12139 } 12140 12141 @Override 12142 public String toString() { 12143 return "MeasureParams{" 12144 + Integer.toHexString(System.identityHashCode(this)) 12145 + " " + mStats.packageName + "}"; 12146 } 12147 12148 @Override 12149 void handleStartCopy() throws RemoteException { 12150 synchronized (mInstallLock) { 12151 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12152 } 12153 12154 if (mSuccess) { 12155 final boolean mounted; 12156 if (Environment.isExternalStorageEmulated()) { 12157 mounted = true; 12158 } else { 12159 final String status = Environment.getExternalStorageState(); 12160 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12161 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12162 } 12163 12164 if (mounted) { 12165 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12166 12167 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12168 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12169 12170 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12171 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12172 12173 // Always subtract cache size, since it's a subdirectory 12174 mStats.externalDataSize -= mStats.externalCacheSize; 12175 12176 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12177 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12178 12179 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12180 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12181 } 12182 } 12183 } 12184 12185 @Override 12186 void handleReturnCode() { 12187 if (mObserver != null) { 12188 try { 12189 mObserver.onGetStatsCompleted(mStats, mSuccess); 12190 } catch (RemoteException e) { 12191 Slog.i(TAG, "Observer no longer exists."); 12192 } 12193 } 12194 } 12195 12196 @Override 12197 void handleServiceError() { 12198 Slog.e(TAG, "Could not measure application " + mStats.packageName 12199 + " external storage"); 12200 } 12201 } 12202 12203 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12204 throws RemoteException { 12205 long result = 0; 12206 for (File path : paths) { 12207 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12208 } 12209 return result; 12210 } 12211 12212 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12213 for (File path : paths) { 12214 try { 12215 mcs.clearDirectory(path.getAbsolutePath()); 12216 } catch (RemoteException e) { 12217 } 12218 } 12219 } 12220 12221 static class OriginInfo { 12222 /** 12223 * Location where install is coming from, before it has been 12224 * copied/renamed into place. This could be a single monolithic APK 12225 * file, or a cluster directory. This location may be untrusted. 12226 */ 12227 final File file; 12228 final String cid; 12229 12230 /** 12231 * Flag indicating that {@link #file} or {@link #cid} has already been 12232 * staged, meaning downstream users don't need to defensively copy the 12233 * contents. 12234 */ 12235 final boolean staged; 12236 12237 /** 12238 * Flag indicating that {@link #file} or {@link #cid} is an already 12239 * installed app that is being moved. 12240 */ 12241 final boolean existing; 12242 12243 final String resolvedPath; 12244 final File resolvedFile; 12245 12246 static OriginInfo fromNothing() { 12247 return new OriginInfo(null, null, false, false); 12248 } 12249 12250 static OriginInfo fromUntrustedFile(File file) { 12251 return new OriginInfo(file, null, false, false); 12252 } 12253 12254 static OriginInfo fromExistingFile(File file) { 12255 return new OriginInfo(file, null, false, true); 12256 } 12257 12258 static OriginInfo fromStagedFile(File file) { 12259 return new OriginInfo(file, null, true, false); 12260 } 12261 12262 static OriginInfo fromStagedContainer(String cid) { 12263 return new OriginInfo(null, cid, true, false); 12264 } 12265 12266 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12267 this.file = file; 12268 this.cid = cid; 12269 this.staged = staged; 12270 this.existing = existing; 12271 12272 if (cid != null) { 12273 resolvedPath = PackageHelper.getSdDir(cid); 12274 resolvedFile = new File(resolvedPath); 12275 } else if (file != null) { 12276 resolvedPath = file.getAbsolutePath(); 12277 resolvedFile = file; 12278 } else { 12279 resolvedPath = null; 12280 resolvedFile = null; 12281 } 12282 } 12283 } 12284 12285 static class MoveInfo { 12286 final int moveId; 12287 final String fromUuid; 12288 final String toUuid; 12289 final String packageName; 12290 final String dataAppName; 12291 final int appId; 12292 final String seinfo; 12293 final int targetSdkVersion; 12294 12295 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12296 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12297 this.moveId = moveId; 12298 this.fromUuid = fromUuid; 12299 this.toUuid = toUuid; 12300 this.packageName = packageName; 12301 this.dataAppName = dataAppName; 12302 this.appId = appId; 12303 this.seinfo = seinfo; 12304 this.targetSdkVersion = targetSdkVersion; 12305 } 12306 } 12307 12308 static class VerificationInfo { 12309 /** A constant used to indicate that a uid value is not present. */ 12310 public static final int NO_UID = -1; 12311 12312 /** URI referencing where the package was downloaded from. */ 12313 final Uri originatingUri; 12314 12315 /** HTTP referrer URI associated with the originatingURI. */ 12316 final Uri referrer; 12317 12318 /** UID of the application that the install request originated from. */ 12319 final int originatingUid; 12320 12321 /** UID of application requesting the install */ 12322 final int installerUid; 12323 12324 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12325 this.originatingUri = originatingUri; 12326 this.referrer = referrer; 12327 this.originatingUid = originatingUid; 12328 this.installerUid = installerUid; 12329 } 12330 } 12331 12332 class InstallParams extends HandlerParams { 12333 final OriginInfo origin; 12334 final MoveInfo move; 12335 final IPackageInstallObserver2 observer; 12336 int installFlags; 12337 final String installerPackageName; 12338 final String volumeUuid; 12339 private InstallArgs mArgs; 12340 private int mRet; 12341 final String packageAbiOverride; 12342 final String[] grantedRuntimePermissions; 12343 final VerificationInfo verificationInfo; 12344 final Certificate[][] certificates; 12345 12346 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12347 int installFlags, String installerPackageName, String volumeUuid, 12348 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12349 String[] grantedPermissions, Certificate[][] certificates) { 12350 super(user); 12351 this.origin = origin; 12352 this.move = move; 12353 this.observer = observer; 12354 this.installFlags = installFlags; 12355 this.installerPackageName = installerPackageName; 12356 this.volumeUuid = volumeUuid; 12357 this.verificationInfo = verificationInfo; 12358 this.packageAbiOverride = packageAbiOverride; 12359 this.grantedRuntimePermissions = grantedPermissions; 12360 this.certificates = certificates; 12361 } 12362 12363 @Override 12364 public String toString() { 12365 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12366 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12367 } 12368 12369 private int installLocationPolicy(PackageInfoLite pkgLite) { 12370 String packageName = pkgLite.packageName; 12371 int installLocation = pkgLite.installLocation; 12372 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12373 // reader 12374 synchronized (mPackages) { 12375 // Currently installed package which the new package is attempting to replace or 12376 // null if no such package is installed. 12377 PackageParser.Package installedPkg = mPackages.get(packageName); 12378 // Package which currently owns the data which the new package will own if installed. 12379 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12380 // will be null whereas dataOwnerPkg will contain information about the package 12381 // which was uninstalled while keeping its data. 12382 PackageParser.Package dataOwnerPkg = installedPkg; 12383 if (dataOwnerPkg == null) { 12384 PackageSetting ps = mSettings.mPackages.get(packageName); 12385 if (ps != null) { 12386 dataOwnerPkg = ps.pkg; 12387 } 12388 } 12389 12390 if (dataOwnerPkg != null) { 12391 // If installed, the package will get access to data left on the device by its 12392 // predecessor. As a security measure, this is permited only if this is not a 12393 // version downgrade or if the predecessor package is marked as debuggable and 12394 // a downgrade is explicitly requested. 12395 // 12396 // On debuggable platform builds, downgrades are permitted even for 12397 // non-debuggable packages to make testing easier. Debuggable platform builds do 12398 // not offer security guarantees and thus it's OK to disable some security 12399 // mechanisms to make debugging/testing easier on those builds. However, even on 12400 // debuggable builds downgrades of packages are permitted only if requested via 12401 // installFlags. This is because we aim to keep the behavior of debuggable 12402 // platform builds as close as possible to the behavior of non-debuggable 12403 // platform builds. 12404 final boolean downgradeRequested = 12405 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12406 final boolean packageDebuggable = 12407 (dataOwnerPkg.applicationInfo.flags 12408 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12409 final boolean downgradePermitted = 12410 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12411 if (!downgradePermitted) { 12412 try { 12413 checkDowngrade(dataOwnerPkg, pkgLite); 12414 } catch (PackageManagerException e) { 12415 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12416 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12417 } 12418 } 12419 } 12420 12421 if (installedPkg != null) { 12422 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12423 // Check for updated system application. 12424 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12425 if (onSd) { 12426 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12427 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12428 } 12429 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12430 } else { 12431 if (onSd) { 12432 // Install flag overrides everything. 12433 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12434 } 12435 // If current upgrade specifies particular preference 12436 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12437 // Application explicitly specified internal. 12438 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12439 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12440 // App explictly prefers external. Let policy decide 12441 } else { 12442 // Prefer previous location 12443 if (isExternal(installedPkg)) { 12444 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12445 } 12446 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12447 } 12448 } 12449 } else { 12450 // Invalid install. Return error code 12451 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12452 } 12453 } 12454 } 12455 // All the special cases have been taken care of. 12456 // Return result based on recommended install location. 12457 if (onSd) { 12458 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12459 } 12460 return pkgLite.recommendedInstallLocation; 12461 } 12462 12463 /* 12464 * Invoke remote method to get package information and install 12465 * location values. Override install location based on default 12466 * policy if needed and then create install arguments based 12467 * on the install location. 12468 */ 12469 public void handleStartCopy() throws RemoteException { 12470 int ret = PackageManager.INSTALL_SUCCEEDED; 12471 12472 // If we're already staged, we've firmly committed to an install location 12473 if (origin.staged) { 12474 if (origin.file != null) { 12475 installFlags |= PackageManager.INSTALL_INTERNAL; 12476 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12477 } else if (origin.cid != null) { 12478 installFlags |= PackageManager.INSTALL_EXTERNAL; 12479 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12480 } else { 12481 throw new IllegalStateException("Invalid stage location"); 12482 } 12483 } 12484 12485 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12486 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12487 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12488 PackageInfoLite pkgLite = null; 12489 12490 if (onInt && onSd) { 12491 // Check if both bits are set. 12492 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12493 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12494 } else if (onSd && ephemeral) { 12495 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12496 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12497 } else { 12498 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12499 packageAbiOverride); 12500 12501 if (DEBUG_EPHEMERAL && ephemeral) { 12502 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12503 } 12504 12505 /* 12506 * If we have too little free space, try to free cache 12507 * before giving up. 12508 */ 12509 if (!origin.staged && pkgLite.recommendedInstallLocation 12510 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12511 // TODO: focus freeing disk space on the target device 12512 final StorageManager storage = StorageManager.from(mContext); 12513 final long lowThreshold = storage.getStorageLowBytes( 12514 Environment.getDataDirectory()); 12515 12516 final long sizeBytes = mContainerService.calculateInstalledSize( 12517 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12518 12519 try { 12520 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12521 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12522 installFlags, packageAbiOverride); 12523 } catch (InstallerException e) { 12524 Slog.w(TAG, "Failed to free cache", e); 12525 } 12526 12527 /* 12528 * The cache free must have deleted the file we 12529 * downloaded to install. 12530 * 12531 * TODO: fix the "freeCache" call to not delete 12532 * the file we care about. 12533 */ 12534 if (pkgLite.recommendedInstallLocation 12535 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12536 pkgLite.recommendedInstallLocation 12537 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12538 } 12539 } 12540 } 12541 12542 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12543 int loc = pkgLite.recommendedInstallLocation; 12544 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12545 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12546 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12547 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12548 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12549 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12550 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12551 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12552 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12553 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12554 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12555 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12556 } else { 12557 // Override with defaults if needed. 12558 loc = installLocationPolicy(pkgLite); 12559 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12560 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12561 } else if (!onSd && !onInt) { 12562 // Override install location with flags 12563 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12564 // Set the flag to install on external media. 12565 installFlags |= PackageManager.INSTALL_EXTERNAL; 12566 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12567 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12568 if (DEBUG_EPHEMERAL) { 12569 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12570 } 12571 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12572 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12573 |PackageManager.INSTALL_INTERNAL); 12574 } else { 12575 // Make sure the flag for installing on external 12576 // media is unset 12577 installFlags |= PackageManager.INSTALL_INTERNAL; 12578 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12579 } 12580 } 12581 } 12582 } 12583 12584 final InstallArgs args = createInstallArgs(this); 12585 mArgs = args; 12586 12587 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12588 // TODO: http://b/22976637 12589 // Apps installed for "all" users use the device owner to verify the app 12590 UserHandle verifierUser = getUser(); 12591 if (verifierUser == UserHandle.ALL) { 12592 verifierUser = UserHandle.SYSTEM; 12593 } 12594 12595 /* 12596 * Determine if we have any installed package verifiers. If we 12597 * do, then we'll defer to them to verify the packages. 12598 */ 12599 final int requiredUid = mRequiredVerifierPackage == null ? -1 12600 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12601 verifierUser.getIdentifier()); 12602 if (!origin.existing && requiredUid != -1 12603 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12604 final Intent verification = new Intent( 12605 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12606 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12607 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12608 PACKAGE_MIME_TYPE); 12609 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12610 12611 // Query all live verifiers based on current user state 12612 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12613 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12614 12615 if (DEBUG_VERIFY) { 12616 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12617 + verification.toString() + " with " + pkgLite.verifiers.length 12618 + " optional verifiers"); 12619 } 12620 12621 final int verificationId = mPendingVerificationToken++; 12622 12623 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12624 12625 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12626 installerPackageName); 12627 12628 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12629 installFlags); 12630 12631 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12632 pkgLite.packageName); 12633 12634 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12635 pkgLite.versionCode); 12636 12637 if (verificationInfo != null) { 12638 if (verificationInfo.originatingUri != null) { 12639 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12640 verificationInfo.originatingUri); 12641 } 12642 if (verificationInfo.referrer != null) { 12643 verification.putExtra(Intent.EXTRA_REFERRER, 12644 verificationInfo.referrer); 12645 } 12646 if (verificationInfo.originatingUid >= 0) { 12647 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12648 verificationInfo.originatingUid); 12649 } 12650 if (verificationInfo.installerUid >= 0) { 12651 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12652 verificationInfo.installerUid); 12653 } 12654 } 12655 12656 final PackageVerificationState verificationState = new PackageVerificationState( 12657 requiredUid, args); 12658 12659 mPendingVerification.append(verificationId, verificationState); 12660 12661 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12662 receivers, verificationState); 12663 12664 /* 12665 * If any sufficient verifiers were listed in the package 12666 * manifest, attempt to ask them. 12667 */ 12668 if (sufficientVerifiers != null) { 12669 final int N = sufficientVerifiers.size(); 12670 if (N == 0) { 12671 Slog.i(TAG, "Additional verifiers required, but none installed."); 12672 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12673 } else { 12674 for (int i = 0; i < N; i++) { 12675 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12676 12677 final Intent sufficientIntent = new Intent(verification); 12678 sufficientIntent.setComponent(verifierComponent); 12679 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12680 } 12681 } 12682 } 12683 12684 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12685 mRequiredVerifierPackage, receivers); 12686 if (ret == PackageManager.INSTALL_SUCCEEDED 12687 && mRequiredVerifierPackage != null) { 12688 Trace.asyncTraceBegin( 12689 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12690 /* 12691 * Send the intent to the required verification agent, 12692 * but only start the verification timeout after the 12693 * target BroadcastReceivers have run. 12694 */ 12695 verification.setComponent(requiredVerifierComponent); 12696 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12697 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12698 new BroadcastReceiver() { 12699 @Override 12700 public void onReceive(Context context, Intent intent) { 12701 final Message msg = mHandler 12702 .obtainMessage(CHECK_PENDING_VERIFICATION); 12703 msg.arg1 = verificationId; 12704 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12705 } 12706 }, null, 0, null, null); 12707 12708 /* 12709 * We don't want the copy to proceed until verification 12710 * succeeds, so null out this field. 12711 */ 12712 mArgs = null; 12713 } 12714 } else { 12715 /* 12716 * No package verification is enabled, so immediately start 12717 * the remote call to initiate copy using temporary file. 12718 */ 12719 ret = args.copyApk(mContainerService, true); 12720 } 12721 } 12722 12723 mRet = ret; 12724 } 12725 12726 @Override 12727 void handleReturnCode() { 12728 // If mArgs is null, then MCS couldn't be reached. When it 12729 // reconnects, it will try again to install. At that point, this 12730 // will succeed. 12731 if (mArgs != null) { 12732 processPendingInstall(mArgs, mRet); 12733 } 12734 } 12735 12736 @Override 12737 void handleServiceError() { 12738 mArgs = createInstallArgs(this); 12739 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12740 } 12741 12742 public boolean isForwardLocked() { 12743 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12744 } 12745 } 12746 12747 /** 12748 * Used during creation of InstallArgs 12749 * 12750 * @param installFlags package installation flags 12751 * @return true if should be installed on external storage 12752 */ 12753 private static boolean installOnExternalAsec(int installFlags) { 12754 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12755 return false; 12756 } 12757 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12758 return true; 12759 } 12760 return false; 12761 } 12762 12763 /** 12764 * Used during creation of InstallArgs 12765 * 12766 * @param installFlags package installation flags 12767 * @return true if should be installed as forward locked 12768 */ 12769 private static boolean installForwardLocked(int installFlags) { 12770 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12771 } 12772 12773 private InstallArgs createInstallArgs(InstallParams params) { 12774 if (params.move != null) { 12775 return new MoveInstallArgs(params); 12776 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12777 return new AsecInstallArgs(params); 12778 } else { 12779 return new FileInstallArgs(params); 12780 } 12781 } 12782 12783 /** 12784 * Create args that describe an existing installed package. Typically used 12785 * when cleaning up old installs, or used as a move source. 12786 */ 12787 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12788 String resourcePath, String[] instructionSets) { 12789 final boolean isInAsec; 12790 if (installOnExternalAsec(installFlags)) { 12791 /* Apps on SD card are always in ASEC containers. */ 12792 isInAsec = true; 12793 } else if (installForwardLocked(installFlags) 12794 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12795 /* 12796 * Forward-locked apps are only in ASEC containers if they're the 12797 * new style 12798 */ 12799 isInAsec = true; 12800 } else { 12801 isInAsec = false; 12802 } 12803 12804 if (isInAsec) { 12805 return new AsecInstallArgs(codePath, instructionSets, 12806 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12807 } else { 12808 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12809 } 12810 } 12811 12812 static abstract class InstallArgs { 12813 /** @see InstallParams#origin */ 12814 final OriginInfo origin; 12815 /** @see InstallParams#move */ 12816 final MoveInfo move; 12817 12818 final IPackageInstallObserver2 observer; 12819 // Always refers to PackageManager flags only 12820 final int installFlags; 12821 final String installerPackageName; 12822 final String volumeUuid; 12823 final UserHandle user; 12824 final String abiOverride; 12825 final String[] installGrantPermissions; 12826 /** If non-null, drop an async trace when the install completes */ 12827 final String traceMethod; 12828 final int traceCookie; 12829 final Certificate[][] certificates; 12830 12831 // The list of instruction sets supported by this app. This is currently 12832 // only used during the rmdex() phase to clean up resources. We can get rid of this 12833 // if we move dex files under the common app path. 12834 /* nullable */ String[] instructionSets; 12835 12836 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12837 int installFlags, String installerPackageName, String volumeUuid, 12838 UserHandle user, String[] instructionSets, 12839 String abiOverride, String[] installGrantPermissions, 12840 String traceMethod, int traceCookie, Certificate[][] certificates) { 12841 this.origin = origin; 12842 this.move = move; 12843 this.installFlags = installFlags; 12844 this.observer = observer; 12845 this.installerPackageName = installerPackageName; 12846 this.volumeUuid = volumeUuid; 12847 this.user = user; 12848 this.instructionSets = instructionSets; 12849 this.abiOverride = abiOverride; 12850 this.installGrantPermissions = installGrantPermissions; 12851 this.traceMethod = traceMethod; 12852 this.traceCookie = traceCookie; 12853 this.certificates = certificates; 12854 } 12855 12856 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12857 abstract int doPreInstall(int status); 12858 12859 /** 12860 * Rename package into final resting place. All paths on the given 12861 * scanned package should be updated to reflect the rename. 12862 */ 12863 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12864 abstract int doPostInstall(int status, int uid); 12865 12866 /** @see PackageSettingBase#codePathString */ 12867 abstract String getCodePath(); 12868 /** @see PackageSettingBase#resourcePathString */ 12869 abstract String getResourcePath(); 12870 12871 // Need installer lock especially for dex file removal. 12872 abstract void cleanUpResourcesLI(); 12873 abstract boolean doPostDeleteLI(boolean delete); 12874 12875 /** 12876 * Called before the source arguments are copied. This is used mostly 12877 * for MoveParams when it needs to read the source file to put it in the 12878 * destination. 12879 */ 12880 int doPreCopy() { 12881 return PackageManager.INSTALL_SUCCEEDED; 12882 } 12883 12884 /** 12885 * Called after the source arguments are copied. This is used mostly for 12886 * MoveParams when it needs to read the source file to put it in the 12887 * destination. 12888 */ 12889 int doPostCopy(int uid) { 12890 return PackageManager.INSTALL_SUCCEEDED; 12891 } 12892 12893 protected boolean isFwdLocked() { 12894 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12895 } 12896 12897 protected boolean isExternalAsec() { 12898 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12899 } 12900 12901 protected boolean isEphemeral() { 12902 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12903 } 12904 12905 UserHandle getUser() { 12906 return user; 12907 } 12908 } 12909 12910 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12911 if (!allCodePaths.isEmpty()) { 12912 if (instructionSets == null) { 12913 throw new IllegalStateException("instructionSet == null"); 12914 } 12915 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12916 for (String codePath : allCodePaths) { 12917 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12918 try { 12919 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12920 } catch (InstallerException ignored) { 12921 } 12922 } 12923 } 12924 } 12925 } 12926 12927 /** 12928 * Logic to handle installation of non-ASEC applications, including copying 12929 * and renaming logic. 12930 */ 12931 class FileInstallArgs extends InstallArgs { 12932 private File codeFile; 12933 private File resourceFile; 12934 12935 // Example topology: 12936 // /data/app/com.example/base.apk 12937 // /data/app/com.example/split_foo.apk 12938 // /data/app/com.example/lib/arm/libfoo.so 12939 // /data/app/com.example/lib/arm64/libfoo.so 12940 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12941 12942 /** New install */ 12943 FileInstallArgs(InstallParams params) { 12944 super(params.origin, params.move, params.observer, params.installFlags, 12945 params.installerPackageName, params.volumeUuid, 12946 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12947 params.grantedRuntimePermissions, 12948 params.traceMethod, params.traceCookie, params.certificates); 12949 if (isFwdLocked()) { 12950 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12951 } 12952 } 12953 12954 /** Existing install */ 12955 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12956 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12957 null, null, null, 0, null /*certificates*/); 12958 this.codeFile = (codePath != null) ? new File(codePath) : null; 12959 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12960 } 12961 12962 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12964 try { 12965 return doCopyApk(imcs, temp); 12966 } finally { 12967 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12968 } 12969 } 12970 12971 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12972 if (origin.staged) { 12973 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12974 codeFile = origin.file; 12975 resourceFile = origin.file; 12976 return PackageManager.INSTALL_SUCCEEDED; 12977 } 12978 12979 try { 12980 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12981 final File tempDir = 12982 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12983 codeFile = tempDir; 12984 resourceFile = tempDir; 12985 } catch (IOException e) { 12986 Slog.w(TAG, "Failed to create copy file: " + e); 12987 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12988 } 12989 12990 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12991 @Override 12992 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12993 if (!FileUtils.isValidExtFilename(name)) { 12994 throw new IllegalArgumentException("Invalid filename: " + name); 12995 } 12996 try { 12997 final File file = new File(codeFile, name); 12998 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12999 O_RDWR | O_CREAT, 0644); 13000 Os.chmod(file.getAbsolutePath(), 0644); 13001 return new ParcelFileDescriptor(fd); 13002 } catch (ErrnoException e) { 13003 throw new RemoteException("Failed to open: " + e.getMessage()); 13004 } 13005 } 13006 }; 13007 13008 int ret = PackageManager.INSTALL_SUCCEEDED; 13009 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13010 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13011 Slog.e(TAG, "Failed to copy package"); 13012 return ret; 13013 } 13014 13015 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13016 NativeLibraryHelper.Handle handle = null; 13017 try { 13018 handle = NativeLibraryHelper.Handle.create(codeFile); 13019 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13020 abiOverride); 13021 } catch (IOException e) { 13022 Slog.e(TAG, "Copying native libraries failed", e); 13023 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13024 } finally { 13025 IoUtils.closeQuietly(handle); 13026 } 13027 13028 return ret; 13029 } 13030 13031 int doPreInstall(int status) { 13032 if (status != PackageManager.INSTALL_SUCCEEDED) { 13033 cleanUp(); 13034 } 13035 return status; 13036 } 13037 13038 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13039 if (status != PackageManager.INSTALL_SUCCEEDED) { 13040 cleanUp(); 13041 return false; 13042 } 13043 13044 final File targetDir = codeFile.getParentFile(); 13045 final File beforeCodeFile = codeFile; 13046 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13047 13048 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13049 try { 13050 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13051 } catch (ErrnoException e) { 13052 Slog.w(TAG, "Failed to rename", e); 13053 return false; 13054 } 13055 13056 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13057 Slog.w(TAG, "Failed to restorecon"); 13058 return false; 13059 } 13060 13061 // Reflect the rename internally 13062 codeFile = afterCodeFile; 13063 resourceFile = afterCodeFile; 13064 13065 // Reflect the rename in scanned details 13066 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13067 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13068 afterCodeFile, pkg.baseCodePath)); 13069 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13070 afterCodeFile, pkg.splitCodePaths)); 13071 13072 // Reflect the rename in app info 13073 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13074 pkg.setApplicationInfoCodePath(pkg.codePath); 13075 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13076 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13077 pkg.setApplicationInfoResourcePath(pkg.codePath); 13078 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13079 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13080 13081 return true; 13082 } 13083 13084 int doPostInstall(int status, int uid) { 13085 if (status != PackageManager.INSTALL_SUCCEEDED) { 13086 cleanUp(); 13087 } 13088 return status; 13089 } 13090 13091 @Override 13092 String getCodePath() { 13093 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13094 } 13095 13096 @Override 13097 String getResourcePath() { 13098 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13099 } 13100 13101 private boolean cleanUp() { 13102 if (codeFile == null || !codeFile.exists()) { 13103 return false; 13104 } 13105 13106 removeCodePathLI(codeFile); 13107 13108 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13109 resourceFile.delete(); 13110 } 13111 13112 return true; 13113 } 13114 13115 void cleanUpResourcesLI() { 13116 // Try enumerating all code paths before deleting 13117 List<String> allCodePaths = Collections.EMPTY_LIST; 13118 if (codeFile != null && codeFile.exists()) { 13119 try { 13120 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13121 allCodePaths = pkg.getAllCodePaths(); 13122 } catch (PackageParserException e) { 13123 // Ignored; we tried our best 13124 } 13125 } 13126 13127 cleanUp(); 13128 removeDexFiles(allCodePaths, instructionSets); 13129 } 13130 13131 boolean doPostDeleteLI(boolean delete) { 13132 // XXX err, shouldn't we respect the delete flag? 13133 cleanUpResourcesLI(); 13134 return true; 13135 } 13136 } 13137 13138 private boolean isAsecExternal(String cid) { 13139 final String asecPath = PackageHelper.getSdFilesystem(cid); 13140 return !asecPath.startsWith(mAsecInternalPath); 13141 } 13142 13143 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13144 PackageManagerException { 13145 if (copyRet < 0) { 13146 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13147 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13148 throw new PackageManagerException(copyRet, message); 13149 } 13150 } 13151 } 13152 13153 /** 13154 * Extract the MountService "container ID" from the full code path of an 13155 * .apk. 13156 */ 13157 static String cidFromCodePath(String fullCodePath) { 13158 int eidx = fullCodePath.lastIndexOf("/"); 13159 String subStr1 = fullCodePath.substring(0, eidx); 13160 int sidx = subStr1.lastIndexOf("/"); 13161 return subStr1.substring(sidx+1, eidx); 13162 } 13163 13164 /** 13165 * Logic to handle installation of ASEC applications, including copying and 13166 * renaming logic. 13167 */ 13168 class AsecInstallArgs extends InstallArgs { 13169 static final String RES_FILE_NAME = "pkg.apk"; 13170 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13171 13172 String cid; 13173 String packagePath; 13174 String resourcePath; 13175 13176 /** New install */ 13177 AsecInstallArgs(InstallParams params) { 13178 super(params.origin, params.move, params.observer, params.installFlags, 13179 params.installerPackageName, params.volumeUuid, 13180 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13181 params.grantedRuntimePermissions, 13182 params.traceMethod, params.traceCookie, params.certificates); 13183 } 13184 13185 /** Existing install */ 13186 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13187 boolean isExternal, boolean isForwardLocked) { 13188 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13189 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13190 instructionSets, null, null, null, 0, null /*certificates*/); 13191 // Hackily pretend we're still looking at a full code path 13192 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13193 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13194 } 13195 13196 // Extract cid from fullCodePath 13197 int eidx = fullCodePath.lastIndexOf("/"); 13198 String subStr1 = fullCodePath.substring(0, eidx); 13199 int sidx = subStr1.lastIndexOf("/"); 13200 cid = subStr1.substring(sidx+1, eidx); 13201 setMountPath(subStr1); 13202 } 13203 13204 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13205 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13206 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13207 instructionSets, null, null, null, 0, null /*certificates*/); 13208 this.cid = cid; 13209 setMountPath(PackageHelper.getSdDir(cid)); 13210 } 13211 13212 void createCopyFile() { 13213 cid = mInstallerService.allocateExternalStageCidLegacy(); 13214 } 13215 13216 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13217 if (origin.staged && origin.cid != null) { 13218 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13219 cid = origin.cid; 13220 setMountPath(PackageHelper.getSdDir(cid)); 13221 return PackageManager.INSTALL_SUCCEEDED; 13222 } 13223 13224 if (temp) { 13225 createCopyFile(); 13226 } else { 13227 /* 13228 * Pre-emptively destroy the container since it's destroyed if 13229 * copying fails due to it existing anyway. 13230 */ 13231 PackageHelper.destroySdDir(cid); 13232 } 13233 13234 final String newMountPath = imcs.copyPackageToContainer( 13235 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13236 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13237 13238 if (newMountPath != null) { 13239 setMountPath(newMountPath); 13240 return PackageManager.INSTALL_SUCCEEDED; 13241 } else { 13242 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13243 } 13244 } 13245 13246 @Override 13247 String getCodePath() { 13248 return packagePath; 13249 } 13250 13251 @Override 13252 String getResourcePath() { 13253 return resourcePath; 13254 } 13255 13256 int doPreInstall(int status) { 13257 if (status != PackageManager.INSTALL_SUCCEEDED) { 13258 // Destroy container 13259 PackageHelper.destroySdDir(cid); 13260 } else { 13261 boolean mounted = PackageHelper.isContainerMounted(cid); 13262 if (!mounted) { 13263 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13264 Process.SYSTEM_UID); 13265 if (newMountPath != null) { 13266 setMountPath(newMountPath); 13267 } else { 13268 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13269 } 13270 } 13271 } 13272 return status; 13273 } 13274 13275 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13276 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13277 String newMountPath = null; 13278 if (PackageHelper.isContainerMounted(cid)) { 13279 // Unmount the container 13280 if (!PackageHelper.unMountSdDir(cid)) { 13281 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13282 return false; 13283 } 13284 } 13285 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13286 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13287 " which might be stale. Will try to clean up."); 13288 // Clean up the stale container and proceed to recreate. 13289 if (!PackageHelper.destroySdDir(newCacheId)) { 13290 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13291 return false; 13292 } 13293 // Successfully cleaned up stale container. Try to rename again. 13294 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13295 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13296 + " inspite of cleaning it up."); 13297 return false; 13298 } 13299 } 13300 if (!PackageHelper.isContainerMounted(newCacheId)) { 13301 Slog.w(TAG, "Mounting container " + newCacheId); 13302 newMountPath = PackageHelper.mountSdDir(newCacheId, 13303 getEncryptKey(), Process.SYSTEM_UID); 13304 } else { 13305 newMountPath = PackageHelper.getSdDir(newCacheId); 13306 } 13307 if (newMountPath == null) { 13308 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13309 return false; 13310 } 13311 Log.i(TAG, "Succesfully renamed " + cid + 13312 " to " + newCacheId + 13313 " at new path: " + newMountPath); 13314 cid = newCacheId; 13315 13316 final File beforeCodeFile = new File(packagePath); 13317 setMountPath(newMountPath); 13318 final File afterCodeFile = new File(packagePath); 13319 13320 // Reflect the rename in scanned details 13321 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13322 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13323 afterCodeFile, pkg.baseCodePath)); 13324 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13325 afterCodeFile, pkg.splitCodePaths)); 13326 13327 // Reflect the rename in app info 13328 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13329 pkg.setApplicationInfoCodePath(pkg.codePath); 13330 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13331 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13332 pkg.setApplicationInfoResourcePath(pkg.codePath); 13333 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13334 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13335 13336 return true; 13337 } 13338 13339 private void setMountPath(String mountPath) { 13340 final File mountFile = new File(mountPath); 13341 13342 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13343 if (monolithicFile.exists()) { 13344 packagePath = monolithicFile.getAbsolutePath(); 13345 if (isFwdLocked()) { 13346 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13347 } else { 13348 resourcePath = packagePath; 13349 } 13350 } else { 13351 packagePath = mountFile.getAbsolutePath(); 13352 resourcePath = packagePath; 13353 } 13354 } 13355 13356 int doPostInstall(int status, int uid) { 13357 if (status != PackageManager.INSTALL_SUCCEEDED) { 13358 cleanUp(); 13359 } else { 13360 final int groupOwner; 13361 final String protectedFile; 13362 if (isFwdLocked()) { 13363 groupOwner = UserHandle.getSharedAppGid(uid); 13364 protectedFile = RES_FILE_NAME; 13365 } else { 13366 groupOwner = -1; 13367 protectedFile = null; 13368 } 13369 13370 if (uid < Process.FIRST_APPLICATION_UID 13371 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13372 Slog.e(TAG, "Failed to finalize " + cid); 13373 PackageHelper.destroySdDir(cid); 13374 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13375 } 13376 13377 boolean mounted = PackageHelper.isContainerMounted(cid); 13378 if (!mounted) { 13379 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13380 } 13381 } 13382 return status; 13383 } 13384 13385 private void cleanUp() { 13386 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13387 13388 // Destroy secure container 13389 PackageHelper.destroySdDir(cid); 13390 } 13391 13392 private List<String> getAllCodePaths() { 13393 final File codeFile = new File(getCodePath()); 13394 if (codeFile != null && codeFile.exists()) { 13395 try { 13396 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13397 return pkg.getAllCodePaths(); 13398 } catch (PackageParserException e) { 13399 // Ignored; we tried our best 13400 } 13401 } 13402 return Collections.EMPTY_LIST; 13403 } 13404 13405 void cleanUpResourcesLI() { 13406 // Enumerate all code paths before deleting 13407 cleanUpResourcesLI(getAllCodePaths()); 13408 } 13409 13410 private void cleanUpResourcesLI(List<String> allCodePaths) { 13411 cleanUp(); 13412 removeDexFiles(allCodePaths, instructionSets); 13413 } 13414 13415 String getPackageName() { 13416 return getAsecPackageName(cid); 13417 } 13418 13419 boolean doPostDeleteLI(boolean delete) { 13420 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13421 final List<String> allCodePaths = getAllCodePaths(); 13422 boolean mounted = PackageHelper.isContainerMounted(cid); 13423 if (mounted) { 13424 // Unmount first 13425 if (PackageHelper.unMountSdDir(cid)) { 13426 mounted = false; 13427 } 13428 } 13429 if (!mounted && delete) { 13430 cleanUpResourcesLI(allCodePaths); 13431 } 13432 return !mounted; 13433 } 13434 13435 @Override 13436 int doPreCopy() { 13437 if (isFwdLocked()) { 13438 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13439 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13440 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13441 } 13442 } 13443 13444 return PackageManager.INSTALL_SUCCEEDED; 13445 } 13446 13447 @Override 13448 int doPostCopy(int uid) { 13449 if (isFwdLocked()) { 13450 if (uid < Process.FIRST_APPLICATION_UID 13451 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13452 RES_FILE_NAME)) { 13453 Slog.e(TAG, "Failed to finalize " + cid); 13454 PackageHelper.destroySdDir(cid); 13455 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13456 } 13457 } 13458 13459 return PackageManager.INSTALL_SUCCEEDED; 13460 } 13461 } 13462 13463 /** 13464 * Logic to handle movement of existing installed applications. 13465 */ 13466 class MoveInstallArgs extends InstallArgs { 13467 private File codeFile; 13468 private File resourceFile; 13469 13470 /** New install */ 13471 MoveInstallArgs(InstallParams params) { 13472 super(params.origin, params.move, params.observer, params.installFlags, 13473 params.installerPackageName, params.volumeUuid, 13474 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13475 params.grantedRuntimePermissions, 13476 params.traceMethod, params.traceCookie, params.certificates); 13477 } 13478 13479 int copyApk(IMediaContainerService imcs, boolean temp) { 13480 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13481 + move.fromUuid + " to " + move.toUuid); 13482 synchronized (mInstaller) { 13483 try { 13484 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13485 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13486 } catch (InstallerException e) { 13487 Slog.w(TAG, "Failed to move app", e); 13488 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13489 } 13490 } 13491 13492 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13493 resourceFile = codeFile; 13494 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13495 13496 return PackageManager.INSTALL_SUCCEEDED; 13497 } 13498 13499 int doPreInstall(int status) { 13500 if (status != PackageManager.INSTALL_SUCCEEDED) { 13501 cleanUp(move.toUuid); 13502 } 13503 return status; 13504 } 13505 13506 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13507 if (status != PackageManager.INSTALL_SUCCEEDED) { 13508 cleanUp(move.toUuid); 13509 return false; 13510 } 13511 13512 // Reflect the move in app info 13513 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13514 pkg.setApplicationInfoCodePath(pkg.codePath); 13515 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13516 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13517 pkg.setApplicationInfoResourcePath(pkg.codePath); 13518 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13519 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13520 13521 return true; 13522 } 13523 13524 int doPostInstall(int status, int uid) { 13525 if (status == PackageManager.INSTALL_SUCCEEDED) { 13526 cleanUp(move.fromUuid); 13527 } else { 13528 cleanUp(move.toUuid); 13529 } 13530 return status; 13531 } 13532 13533 @Override 13534 String getCodePath() { 13535 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13536 } 13537 13538 @Override 13539 String getResourcePath() { 13540 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13541 } 13542 13543 private boolean cleanUp(String volumeUuid) { 13544 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13545 move.dataAppName); 13546 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13547 final int[] userIds = sUserManager.getUserIds(); 13548 synchronized (mInstallLock) { 13549 // Clean up both app data and code 13550 // All package moves are frozen until finished 13551 for (int userId : userIds) { 13552 try { 13553 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13554 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13555 } catch (InstallerException e) { 13556 Slog.w(TAG, String.valueOf(e)); 13557 } 13558 } 13559 removeCodePathLI(codeFile); 13560 } 13561 return true; 13562 } 13563 13564 void cleanUpResourcesLI() { 13565 throw new UnsupportedOperationException(); 13566 } 13567 13568 boolean doPostDeleteLI(boolean delete) { 13569 throw new UnsupportedOperationException(); 13570 } 13571 } 13572 13573 static String getAsecPackageName(String packageCid) { 13574 int idx = packageCid.lastIndexOf("-"); 13575 if (idx == -1) { 13576 return packageCid; 13577 } 13578 return packageCid.substring(0, idx); 13579 } 13580 13581 // Utility method used to create code paths based on package name and available index. 13582 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13583 String idxStr = ""; 13584 int idx = 1; 13585 // Fall back to default value of idx=1 if prefix is not 13586 // part of oldCodePath 13587 if (oldCodePath != null) { 13588 String subStr = oldCodePath; 13589 // Drop the suffix right away 13590 if (suffix != null && subStr.endsWith(suffix)) { 13591 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13592 } 13593 // If oldCodePath already contains prefix find out the 13594 // ending index to either increment or decrement. 13595 int sidx = subStr.lastIndexOf(prefix); 13596 if (sidx != -1) { 13597 subStr = subStr.substring(sidx + prefix.length()); 13598 if (subStr != null) { 13599 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13600 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13601 } 13602 try { 13603 idx = Integer.parseInt(subStr); 13604 if (idx <= 1) { 13605 idx++; 13606 } else { 13607 idx--; 13608 } 13609 } catch(NumberFormatException e) { 13610 } 13611 } 13612 } 13613 } 13614 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13615 return prefix + idxStr; 13616 } 13617 13618 private File getNextCodePath(File targetDir, String packageName) { 13619 int suffix = 1; 13620 File result; 13621 do { 13622 result = new File(targetDir, packageName + "-" + suffix); 13623 suffix++; 13624 } while (result.exists()); 13625 return result; 13626 } 13627 13628 // Utility method that returns the relative package path with respect 13629 // to the installation directory. Like say for /data/data/com.test-1.apk 13630 // string com.test-1 is returned. 13631 static String deriveCodePathName(String codePath) { 13632 if (codePath == null) { 13633 return null; 13634 } 13635 final File codeFile = new File(codePath); 13636 final String name = codeFile.getName(); 13637 if (codeFile.isDirectory()) { 13638 return name; 13639 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13640 final int lastDot = name.lastIndexOf('.'); 13641 return name.substring(0, lastDot); 13642 } else { 13643 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13644 return null; 13645 } 13646 } 13647 13648 static class PackageInstalledInfo { 13649 String name; 13650 int uid; 13651 // The set of users that originally had this package installed. 13652 int[] origUsers; 13653 // The set of users that now have this package installed. 13654 int[] newUsers; 13655 PackageParser.Package pkg; 13656 int returnCode; 13657 String returnMsg; 13658 PackageRemovedInfo removedInfo; 13659 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13660 13661 public void setError(int code, String msg) { 13662 setReturnCode(code); 13663 setReturnMessage(msg); 13664 Slog.w(TAG, msg); 13665 } 13666 13667 public void setError(String msg, PackageParserException e) { 13668 setReturnCode(e.error); 13669 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13670 Slog.w(TAG, msg, e); 13671 } 13672 13673 public void setError(String msg, PackageManagerException e) { 13674 returnCode = e.error; 13675 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13676 Slog.w(TAG, msg, e); 13677 } 13678 13679 public void setReturnCode(int returnCode) { 13680 this.returnCode = returnCode; 13681 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13682 for (int i = 0; i < childCount; i++) { 13683 addedChildPackages.valueAt(i).returnCode = returnCode; 13684 } 13685 } 13686 13687 private void setReturnMessage(String returnMsg) { 13688 this.returnMsg = returnMsg; 13689 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13690 for (int i = 0; i < childCount; i++) { 13691 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13692 } 13693 } 13694 13695 // In some error cases we want to convey more info back to the observer 13696 String origPackage; 13697 String origPermission; 13698 } 13699 13700 /* 13701 * Install a non-existing package. 13702 */ 13703 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13704 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13705 PackageInstalledInfo res) { 13706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13707 13708 // Remember this for later, in case we need to rollback this install 13709 String pkgName = pkg.packageName; 13710 13711 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13712 13713 synchronized(mPackages) { 13714 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13715 // A package with the same name is already installed, though 13716 // it has been renamed to an older name. The package we 13717 // are trying to install should be installed as an update to 13718 // the existing one, but that has not been requested, so bail. 13719 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13720 + " without first uninstalling package running as " 13721 + mSettings.mRenamedPackages.get(pkgName)); 13722 return; 13723 } 13724 if (mPackages.containsKey(pkgName)) { 13725 // Don't allow installation over an existing package with the same name. 13726 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13727 + " without first uninstalling."); 13728 return; 13729 } 13730 } 13731 13732 try { 13733 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13734 System.currentTimeMillis(), user); 13735 13736 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13737 13738 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13739 prepareAppDataAfterInstallLIF(newPackage); 13740 13741 } else { 13742 // Remove package from internal structures, but keep around any 13743 // data that might have already existed 13744 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13745 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13746 } 13747 } catch (PackageManagerException e) { 13748 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13749 } 13750 13751 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13752 } 13753 13754 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13755 // Can't rotate keys during boot or if sharedUser. 13756 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13757 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13758 return false; 13759 } 13760 // app is using upgradeKeySets; make sure all are valid 13761 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13762 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13763 for (int i = 0; i < upgradeKeySets.length; i++) { 13764 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13765 Slog.wtf(TAG, "Package " 13766 + (oldPs.name != null ? oldPs.name : "<null>") 13767 + " contains upgrade-key-set reference to unknown key-set: " 13768 + upgradeKeySets[i] 13769 + " reverting to signatures check."); 13770 return false; 13771 } 13772 } 13773 return true; 13774 } 13775 13776 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13777 // Upgrade keysets are being used. Determine if new package has a superset of the 13778 // required keys. 13779 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13780 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13781 for (int i = 0; i < upgradeKeySets.length; i++) { 13782 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13783 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13784 return true; 13785 } 13786 } 13787 return false; 13788 } 13789 13790 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13791 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13792 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13793 13794 final PackageParser.Package oldPackage; 13795 final String pkgName = pkg.packageName; 13796 final int[] allUsers; 13797 final int[] installedUsers; 13798 13799 synchronized(mPackages) { 13800 oldPackage = mPackages.get(pkgName); 13801 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13802 13803 // don't allow upgrade to target a release SDK from a pre-release SDK 13804 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13805 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13806 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13807 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13808 if (oldTargetsPreRelease 13809 && !newTargetsPreRelease 13810 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13811 Slog.w(TAG, "Can't install package targeting released sdk"); 13812 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13813 return; 13814 } 13815 13816 // don't allow an upgrade from full to ephemeral 13817 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13818 if (isEphemeral && !oldIsEphemeral) { 13819 // can't downgrade from full to ephemeral 13820 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13821 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13822 return; 13823 } 13824 13825 // verify signatures are valid 13826 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13827 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13828 if (!checkUpgradeKeySetLP(ps, pkg)) { 13829 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13830 "New package not signed by keys specified by upgrade-keysets: " 13831 + pkgName); 13832 return; 13833 } 13834 } else { 13835 // default to original signature matching 13836 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13837 != PackageManager.SIGNATURE_MATCH) { 13838 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13839 "New package has a different signature: " + pkgName); 13840 return; 13841 } 13842 } 13843 13844 // Check for shared user id changes 13845 String invalidPackageName = 13846 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13847 if (invalidPackageName != null) { 13848 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13849 "Package " + invalidPackageName + " tried to change user " 13850 + oldPackage.mSharedUserId); 13851 return; 13852 } 13853 13854 // In case of rollback, remember per-user/profile install state 13855 allUsers = sUserManager.getUserIds(); 13856 installedUsers = ps.queryInstalledUsers(allUsers, true); 13857 } 13858 13859 // Update what is removed 13860 res.removedInfo = new PackageRemovedInfo(); 13861 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13862 res.removedInfo.removedPackage = oldPackage.packageName; 13863 res.removedInfo.isUpdate = true; 13864 res.removedInfo.origUsers = installedUsers; 13865 final int childCount = (oldPackage.childPackages != null) 13866 ? oldPackage.childPackages.size() : 0; 13867 for (int i = 0; i < childCount; i++) { 13868 boolean childPackageUpdated = false; 13869 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13870 if (res.addedChildPackages != null) { 13871 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13872 if (childRes != null) { 13873 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13874 childRes.removedInfo.removedPackage = childPkg.packageName; 13875 childRes.removedInfo.isUpdate = true; 13876 childPackageUpdated = true; 13877 } 13878 } 13879 if (!childPackageUpdated) { 13880 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13881 childRemovedRes.removedPackage = childPkg.packageName; 13882 childRemovedRes.isUpdate = false; 13883 childRemovedRes.dataRemoved = true; 13884 synchronized (mPackages) { 13885 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13886 if (childPs != null) { 13887 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13888 } 13889 } 13890 if (res.removedInfo.removedChildPackages == null) { 13891 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13892 } 13893 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13894 } 13895 } 13896 13897 boolean sysPkg = (isSystemApp(oldPackage)); 13898 if (sysPkg) { 13899 // Set the system/privileged flags as needed 13900 final boolean privileged = 13901 (oldPackage.applicationInfo.privateFlags 13902 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13903 final int systemPolicyFlags = policyFlags 13904 | PackageParser.PARSE_IS_SYSTEM 13905 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13906 13907 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13908 user, allUsers, installerPackageName, res); 13909 } else { 13910 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13911 user, allUsers, installerPackageName, res); 13912 } 13913 } 13914 13915 public List<String> getPreviousCodePaths(String packageName) { 13916 final PackageSetting ps = mSettings.mPackages.get(packageName); 13917 final List<String> result = new ArrayList<String>(); 13918 if (ps != null && ps.oldCodePaths != null) { 13919 result.addAll(ps.oldCodePaths); 13920 } 13921 return result; 13922 } 13923 13924 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13925 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13926 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13927 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13928 + deletedPackage); 13929 13930 String pkgName = deletedPackage.packageName; 13931 boolean deletedPkg = true; 13932 boolean addedPkg = false; 13933 boolean updatedSettings = false; 13934 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13935 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13936 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13937 13938 final long origUpdateTime = (pkg.mExtras != null) 13939 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13940 13941 // First delete the existing package while retaining the data directory 13942 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13943 res.removedInfo, true, pkg)) { 13944 // If the existing package wasn't successfully deleted 13945 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13946 deletedPkg = false; 13947 } else { 13948 // Successfully deleted the old package; proceed with replace. 13949 13950 // If deleted package lived in a container, give users a chance to 13951 // relinquish resources before killing. 13952 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13953 if (DEBUG_INSTALL) { 13954 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13955 } 13956 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13957 final ArrayList<String> pkgList = new ArrayList<String>(1); 13958 pkgList.add(deletedPackage.applicationInfo.packageName); 13959 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13960 } 13961 13962 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13963 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13964 clearAppProfilesLIF(pkg); 13965 13966 try { 13967 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13968 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13969 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13970 13971 // Update the in-memory copy of the previous code paths. 13972 PackageSetting ps = mSettings.mPackages.get(pkgName); 13973 if (!killApp) { 13974 if (ps.oldCodePaths == null) { 13975 ps.oldCodePaths = new ArraySet<>(); 13976 } 13977 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13978 if (deletedPackage.splitCodePaths != null) { 13979 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13980 } 13981 } else { 13982 ps.oldCodePaths = null; 13983 } 13984 if (ps.childPackageNames != null) { 13985 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13986 final String childPkgName = ps.childPackageNames.get(i); 13987 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13988 childPs.oldCodePaths = ps.oldCodePaths; 13989 } 13990 } 13991 prepareAppDataAfterInstallLIF(newPackage); 13992 addedPkg = true; 13993 } catch (PackageManagerException e) { 13994 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13995 } 13996 } 13997 13998 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13999 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14000 14001 // Revert all internal state mutations and added folders for the failed install 14002 if (addedPkg) { 14003 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14004 res.removedInfo, true, null); 14005 } 14006 14007 // Restore the old package 14008 if (deletedPkg) { 14009 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14010 File restoreFile = new File(deletedPackage.codePath); 14011 // Parse old package 14012 boolean oldExternal = isExternal(deletedPackage); 14013 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14014 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14015 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14016 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14017 try { 14018 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14019 null); 14020 } catch (PackageManagerException e) { 14021 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14022 + e.getMessage()); 14023 return; 14024 } 14025 14026 synchronized (mPackages) { 14027 // Ensure the installer package name up to date 14028 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14029 14030 // Update permissions for restored package 14031 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14032 14033 mSettings.writeLPr(); 14034 } 14035 14036 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14037 } 14038 } else { 14039 synchronized (mPackages) { 14040 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14041 if (ps != null) { 14042 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14043 if (res.removedInfo.removedChildPackages != null) { 14044 final int childCount = res.removedInfo.removedChildPackages.size(); 14045 // Iterate in reverse as we may modify the collection 14046 for (int i = childCount - 1; i >= 0; i--) { 14047 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14048 if (res.addedChildPackages.containsKey(childPackageName)) { 14049 res.removedInfo.removedChildPackages.removeAt(i); 14050 } else { 14051 PackageRemovedInfo childInfo = res.removedInfo 14052 .removedChildPackages.valueAt(i); 14053 childInfo.removedForAllUsers = mPackages.get( 14054 childInfo.removedPackage) == null; 14055 } 14056 } 14057 } 14058 } 14059 } 14060 } 14061 } 14062 14063 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14064 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14065 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14066 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14067 + ", old=" + deletedPackage); 14068 14069 final boolean disabledSystem; 14070 14071 // Remove existing system package 14072 removePackageLI(deletedPackage, true); 14073 14074 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14075 if (!disabledSystem) { 14076 // We didn't need to disable the .apk as a current system package, 14077 // which means we are replacing another update that is already 14078 // installed. We need to make sure to delete the older one's .apk. 14079 res.removedInfo.args = createInstallArgsForExisting(0, 14080 deletedPackage.applicationInfo.getCodePath(), 14081 deletedPackage.applicationInfo.getResourcePath(), 14082 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14083 } else { 14084 res.removedInfo.args = null; 14085 } 14086 14087 // Successfully disabled the old package. Now proceed with re-installation 14088 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14089 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14090 clearAppProfilesLIF(pkg); 14091 14092 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14093 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14094 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14095 14096 PackageParser.Package newPackage = null; 14097 try { 14098 // Add the package to the internal data structures 14099 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14100 14101 // Set the update and install times 14102 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14103 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14104 System.currentTimeMillis()); 14105 14106 // Update the package dynamic state if succeeded 14107 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14108 // Now that the install succeeded make sure we remove data 14109 // directories for any child package the update removed. 14110 final int deletedChildCount = (deletedPackage.childPackages != null) 14111 ? deletedPackage.childPackages.size() : 0; 14112 final int newChildCount = (newPackage.childPackages != null) 14113 ? newPackage.childPackages.size() : 0; 14114 for (int i = 0; i < deletedChildCount; i++) { 14115 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14116 boolean childPackageDeleted = true; 14117 for (int j = 0; j < newChildCount; j++) { 14118 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14119 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14120 childPackageDeleted = false; 14121 break; 14122 } 14123 } 14124 if (childPackageDeleted) { 14125 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14126 deletedChildPkg.packageName); 14127 if (ps != null && res.removedInfo.removedChildPackages != null) { 14128 PackageRemovedInfo removedChildRes = res.removedInfo 14129 .removedChildPackages.get(deletedChildPkg.packageName); 14130 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14131 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14132 } 14133 } 14134 } 14135 14136 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14137 prepareAppDataAfterInstallLIF(newPackage); 14138 } 14139 } catch (PackageManagerException e) { 14140 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14141 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14142 } 14143 14144 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14145 // Re installation failed. Restore old information 14146 // Remove new pkg information 14147 if (newPackage != null) { 14148 removeInstalledPackageLI(newPackage, true); 14149 } 14150 // Add back the old system package 14151 try { 14152 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14153 } catch (PackageManagerException e) { 14154 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14155 } 14156 14157 synchronized (mPackages) { 14158 if (disabledSystem) { 14159 enableSystemPackageLPw(deletedPackage); 14160 } 14161 14162 // Ensure the installer package name up to date 14163 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14164 14165 // Update permissions for restored package 14166 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14167 14168 mSettings.writeLPr(); 14169 } 14170 14171 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14172 + " after failed upgrade"); 14173 } 14174 } 14175 14176 /** 14177 * Checks whether the parent or any of the child packages have a change shared 14178 * user. For a package to be a valid update the shred users of the parent and 14179 * the children should match. We may later support changing child shared users. 14180 * @param oldPkg The updated package. 14181 * @param newPkg The update package. 14182 * @return The shared user that change between the versions. 14183 */ 14184 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14185 PackageParser.Package newPkg) { 14186 // Check parent shared user 14187 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14188 return newPkg.packageName; 14189 } 14190 // Check child shared users 14191 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14192 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14193 for (int i = 0; i < newChildCount; i++) { 14194 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14195 // If this child was present, did it have the same shared user? 14196 for (int j = 0; j < oldChildCount; j++) { 14197 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14198 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14199 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14200 return newChildPkg.packageName; 14201 } 14202 } 14203 } 14204 return null; 14205 } 14206 14207 private void removeNativeBinariesLI(PackageSetting ps) { 14208 // Remove the lib path for the parent package 14209 if (ps != null) { 14210 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14211 // Remove the lib path for the child packages 14212 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14213 for (int i = 0; i < childCount; i++) { 14214 PackageSetting childPs = null; 14215 synchronized (mPackages) { 14216 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14217 } 14218 if (childPs != null) { 14219 NativeLibraryHelper.removeNativeBinariesLI(childPs 14220 .legacyNativeLibraryPathString); 14221 } 14222 } 14223 } 14224 } 14225 14226 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14227 // Enable the parent package 14228 mSettings.enableSystemPackageLPw(pkg.packageName); 14229 // Enable the child packages 14230 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14231 for (int i = 0; i < childCount; i++) { 14232 PackageParser.Package childPkg = pkg.childPackages.get(i); 14233 mSettings.enableSystemPackageLPw(childPkg.packageName); 14234 } 14235 } 14236 14237 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14238 PackageParser.Package newPkg) { 14239 // Disable the parent package (parent always replaced) 14240 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14241 // Disable the child packages 14242 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14243 for (int i = 0; i < childCount; i++) { 14244 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14245 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14246 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14247 } 14248 return disabled; 14249 } 14250 14251 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14252 String installerPackageName) { 14253 // Enable the parent package 14254 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14255 // Enable the child packages 14256 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14257 for (int i = 0; i < childCount; i++) { 14258 PackageParser.Package childPkg = pkg.childPackages.get(i); 14259 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14260 } 14261 } 14262 14263 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14264 // Collect all used permissions in the UID 14265 ArraySet<String> usedPermissions = new ArraySet<>(); 14266 final int packageCount = su.packages.size(); 14267 for (int i = 0; i < packageCount; i++) { 14268 PackageSetting ps = su.packages.valueAt(i); 14269 if (ps.pkg == null) { 14270 continue; 14271 } 14272 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14273 for (int j = 0; j < requestedPermCount; j++) { 14274 String permission = ps.pkg.requestedPermissions.get(j); 14275 BasePermission bp = mSettings.mPermissions.get(permission); 14276 if (bp != null) { 14277 usedPermissions.add(permission); 14278 } 14279 } 14280 } 14281 14282 PermissionsState permissionsState = su.getPermissionsState(); 14283 // Prune install permissions 14284 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14285 final int installPermCount = installPermStates.size(); 14286 for (int i = installPermCount - 1; i >= 0; i--) { 14287 PermissionState permissionState = installPermStates.get(i); 14288 if (!usedPermissions.contains(permissionState.getName())) { 14289 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14290 if (bp != null) { 14291 permissionsState.revokeInstallPermission(bp); 14292 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14293 PackageManager.MASK_PERMISSION_FLAGS, 0); 14294 } 14295 } 14296 } 14297 14298 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14299 14300 // Prune runtime permissions 14301 for (int userId : allUserIds) { 14302 List<PermissionState> runtimePermStates = permissionsState 14303 .getRuntimePermissionStates(userId); 14304 final int runtimePermCount = runtimePermStates.size(); 14305 for (int i = runtimePermCount - 1; i >= 0; i--) { 14306 PermissionState permissionState = runtimePermStates.get(i); 14307 if (!usedPermissions.contains(permissionState.getName())) { 14308 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14309 if (bp != null) { 14310 permissionsState.revokeRuntimePermission(bp, userId); 14311 permissionsState.updatePermissionFlags(bp, userId, 14312 PackageManager.MASK_PERMISSION_FLAGS, 0); 14313 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14314 runtimePermissionChangedUserIds, userId); 14315 } 14316 } 14317 } 14318 } 14319 14320 return runtimePermissionChangedUserIds; 14321 } 14322 14323 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14324 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14325 // Update the parent package setting 14326 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14327 res, user); 14328 // Update the child packages setting 14329 final int childCount = (newPackage.childPackages != null) 14330 ? newPackage.childPackages.size() : 0; 14331 for (int i = 0; i < childCount; i++) { 14332 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14333 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14334 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14335 childRes.origUsers, childRes, user); 14336 } 14337 } 14338 14339 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14340 String installerPackageName, int[] allUsers, int[] installedForUsers, 14341 PackageInstalledInfo res, UserHandle user) { 14342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14343 14344 String pkgName = newPackage.packageName; 14345 synchronized (mPackages) { 14346 //write settings. the installStatus will be incomplete at this stage. 14347 //note that the new package setting would have already been 14348 //added to mPackages. It hasn't been persisted yet. 14349 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14350 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14351 mSettings.writeLPr(); 14352 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14353 } 14354 14355 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14356 synchronized (mPackages) { 14357 updatePermissionsLPw(newPackage.packageName, newPackage, 14358 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14359 ? UPDATE_PERMISSIONS_ALL : 0)); 14360 // For system-bundled packages, we assume that installing an upgraded version 14361 // of the package implies that the user actually wants to run that new code, 14362 // so we enable the package. 14363 PackageSetting ps = mSettings.mPackages.get(pkgName); 14364 final int userId = user.getIdentifier(); 14365 if (ps != null) { 14366 if (isSystemApp(newPackage)) { 14367 if (DEBUG_INSTALL) { 14368 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14369 } 14370 // Enable system package for requested users 14371 if (res.origUsers != null) { 14372 for (int origUserId : res.origUsers) { 14373 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14374 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14375 origUserId, installerPackageName); 14376 } 14377 } 14378 } 14379 // Also convey the prior install/uninstall state 14380 if (allUsers != null && installedForUsers != null) { 14381 for (int currentUserId : allUsers) { 14382 final boolean installed = ArrayUtils.contains( 14383 installedForUsers, currentUserId); 14384 if (DEBUG_INSTALL) { 14385 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14386 } 14387 ps.setInstalled(installed, currentUserId); 14388 } 14389 // these install state changes will be persisted in the 14390 // upcoming call to mSettings.writeLPr(). 14391 } 14392 } 14393 // It's implied that when a user requests installation, they want the app to be 14394 // installed and enabled. 14395 if (userId != UserHandle.USER_ALL) { 14396 ps.setInstalled(true, userId); 14397 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14398 } 14399 } 14400 res.name = pkgName; 14401 res.uid = newPackage.applicationInfo.uid; 14402 res.pkg = newPackage; 14403 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14404 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14405 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14406 //to update install status 14407 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14408 mSettings.writeLPr(); 14409 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14410 } 14411 14412 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14413 } 14414 14415 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14416 try { 14417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14418 installPackageLI(args, res); 14419 } finally { 14420 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14421 } 14422 } 14423 14424 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14425 final int installFlags = args.installFlags; 14426 final String installerPackageName = args.installerPackageName; 14427 final String volumeUuid = args.volumeUuid; 14428 final File tmpPackageFile = new File(args.getCodePath()); 14429 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14430 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14431 || (args.volumeUuid != null)); 14432 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14433 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14434 boolean replace = false; 14435 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14436 if (args.move != null) { 14437 // moving a complete application; perform an initial scan on the new install location 14438 scanFlags |= SCAN_INITIAL; 14439 } 14440 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14441 scanFlags |= SCAN_DONT_KILL_APP; 14442 } 14443 14444 // Result object to be returned 14445 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14446 14447 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14448 14449 // Sanity check 14450 if (ephemeral && (forwardLocked || onExternal)) { 14451 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14452 + " external=" + onExternal); 14453 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14454 return; 14455 } 14456 14457 // Retrieve PackageSettings and parse package 14458 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14459 | PackageParser.PARSE_ENFORCE_CODE 14460 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14461 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14462 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14463 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14464 PackageParser pp = new PackageParser(); 14465 pp.setSeparateProcesses(mSeparateProcesses); 14466 pp.setDisplayMetrics(mMetrics); 14467 14468 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14469 final PackageParser.Package pkg; 14470 try { 14471 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14472 } catch (PackageParserException e) { 14473 res.setError("Failed parse during installPackageLI", e); 14474 return; 14475 } finally { 14476 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14477 } 14478 14479 // If we are installing a clustered package add results for the children 14480 if (pkg.childPackages != null) { 14481 synchronized (mPackages) { 14482 final int childCount = pkg.childPackages.size(); 14483 for (int i = 0; i < childCount; i++) { 14484 PackageParser.Package childPkg = pkg.childPackages.get(i); 14485 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14486 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14487 childRes.pkg = childPkg; 14488 childRes.name = childPkg.packageName; 14489 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14490 if (childPs != null) { 14491 childRes.origUsers = childPs.queryInstalledUsers( 14492 sUserManager.getUserIds(), true); 14493 } 14494 if ((mPackages.containsKey(childPkg.packageName))) { 14495 childRes.removedInfo = new PackageRemovedInfo(); 14496 childRes.removedInfo.removedPackage = childPkg.packageName; 14497 } 14498 if (res.addedChildPackages == null) { 14499 res.addedChildPackages = new ArrayMap<>(); 14500 } 14501 res.addedChildPackages.put(childPkg.packageName, childRes); 14502 } 14503 } 14504 } 14505 14506 // If package doesn't declare API override, mark that we have an install 14507 // time CPU ABI override. 14508 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14509 pkg.cpuAbiOverride = args.abiOverride; 14510 } 14511 14512 String pkgName = res.name = pkg.packageName; 14513 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14514 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14515 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14516 return; 14517 } 14518 } 14519 14520 try { 14521 // either use what we've been given or parse directly from the APK 14522 if (args.certificates != null) { 14523 try { 14524 PackageParser.populateCertificates(pkg, args.certificates); 14525 } catch (PackageParserException e) { 14526 // there was something wrong with the certificates we were given; 14527 // try to pull them from the APK 14528 PackageParser.collectCertificates(pkg, parseFlags); 14529 } 14530 } else { 14531 PackageParser.collectCertificates(pkg, parseFlags); 14532 } 14533 } catch (PackageParserException e) { 14534 res.setError("Failed collect during installPackageLI", e); 14535 return; 14536 } 14537 14538 // Get rid of all references to package scan path via parser. 14539 pp = null; 14540 String oldCodePath = null; 14541 boolean systemApp = false; 14542 synchronized (mPackages) { 14543 // Check if installing already existing package 14544 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14545 String oldName = mSettings.mRenamedPackages.get(pkgName); 14546 if (pkg.mOriginalPackages != null 14547 && pkg.mOriginalPackages.contains(oldName) 14548 && mPackages.containsKey(oldName)) { 14549 // This package is derived from an original package, 14550 // and this device has been updating from that original 14551 // name. We must continue using the original name, so 14552 // rename the new package here. 14553 pkg.setPackageName(oldName); 14554 pkgName = pkg.packageName; 14555 replace = true; 14556 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14557 + oldName + " pkgName=" + pkgName); 14558 } else if (mPackages.containsKey(pkgName)) { 14559 // This package, under its official name, already exists 14560 // on the device; we should replace it. 14561 replace = true; 14562 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14563 } 14564 14565 // Child packages are installed through the parent package 14566 if (pkg.parentPackage != null) { 14567 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14568 "Package " + pkg.packageName + " is child of package " 14569 + pkg.parentPackage.parentPackage + ". Child packages " 14570 + "can be updated only through the parent package."); 14571 return; 14572 } 14573 14574 if (replace) { 14575 // Prevent apps opting out from runtime permissions 14576 PackageParser.Package oldPackage = mPackages.get(pkgName); 14577 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14578 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14579 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14580 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14581 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14582 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14583 + " doesn't support runtime permissions but the old" 14584 + " target SDK " + oldTargetSdk + " does."); 14585 return; 14586 } 14587 14588 // Prevent installing of child packages 14589 if (oldPackage.parentPackage != null) { 14590 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14591 "Package " + pkg.packageName + " is child of package " 14592 + oldPackage.parentPackage + ". Child packages " 14593 + "can be updated only through the parent package."); 14594 return; 14595 } 14596 } 14597 } 14598 14599 PackageSetting ps = mSettings.mPackages.get(pkgName); 14600 if (ps != null) { 14601 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14602 14603 // Quick sanity check that we're signed correctly if updating; 14604 // we'll check this again later when scanning, but we want to 14605 // bail early here before tripping over redefined permissions. 14606 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14607 if (!checkUpgradeKeySetLP(ps, pkg)) { 14608 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14609 + pkg.packageName + " upgrade keys do not match the " 14610 + "previously installed version"); 14611 return; 14612 } 14613 } else { 14614 try { 14615 verifySignaturesLP(ps, pkg); 14616 } catch (PackageManagerException e) { 14617 res.setError(e.error, e.getMessage()); 14618 return; 14619 } 14620 } 14621 14622 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14623 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14624 systemApp = (ps.pkg.applicationInfo.flags & 14625 ApplicationInfo.FLAG_SYSTEM) != 0; 14626 } 14627 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14628 } 14629 14630 // Check whether the newly-scanned package wants to define an already-defined perm 14631 int N = pkg.permissions.size(); 14632 for (int i = N-1; i >= 0; i--) { 14633 PackageParser.Permission perm = pkg.permissions.get(i); 14634 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14635 if (bp != null) { 14636 // If the defining package is signed with our cert, it's okay. This 14637 // also includes the "updating the same package" case, of course. 14638 // "updating same package" could also involve key-rotation. 14639 final boolean sigsOk; 14640 if (bp.sourcePackage.equals(pkg.packageName) 14641 && (bp.packageSetting instanceof PackageSetting) 14642 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14643 scanFlags))) { 14644 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14645 } else { 14646 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14647 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14648 } 14649 if (!sigsOk) { 14650 // If the owning package is the system itself, we log but allow 14651 // install to proceed; we fail the install on all other permission 14652 // redefinitions. 14653 if (!bp.sourcePackage.equals("android")) { 14654 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14655 + pkg.packageName + " attempting to redeclare permission " 14656 + perm.info.name + " already owned by " + bp.sourcePackage); 14657 res.origPermission = perm.info.name; 14658 res.origPackage = bp.sourcePackage; 14659 return; 14660 } else { 14661 Slog.w(TAG, "Package " + pkg.packageName 14662 + " attempting to redeclare system permission " 14663 + perm.info.name + "; ignoring new declaration"); 14664 pkg.permissions.remove(i); 14665 } 14666 } 14667 } 14668 } 14669 } 14670 14671 if (systemApp) { 14672 if (onExternal) { 14673 // Abort update; system app can't be replaced with app on sdcard 14674 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14675 "Cannot install updates to system apps on sdcard"); 14676 return; 14677 } else if (ephemeral) { 14678 // Abort update; system app can't be replaced with an ephemeral app 14679 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14680 "Cannot update a system app with an ephemeral app"); 14681 return; 14682 } 14683 } 14684 14685 if (args.move != null) { 14686 // We did an in-place move, so dex is ready to roll 14687 scanFlags |= SCAN_NO_DEX; 14688 scanFlags |= SCAN_MOVE; 14689 14690 synchronized (mPackages) { 14691 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14692 if (ps == null) { 14693 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14694 "Missing settings for moved package " + pkgName); 14695 } 14696 14697 // We moved the entire application as-is, so bring over the 14698 // previously derived ABI information. 14699 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14700 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14701 } 14702 14703 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14704 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14705 scanFlags |= SCAN_NO_DEX; 14706 14707 try { 14708 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14709 args.abiOverride : pkg.cpuAbiOverride); 14710 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14711 true /* extract libs */); 14712 } catch (PackageManagerException pme) { 14713 Slog.e(TAG, "Error deriving application ABI", pme); 14714 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14715 return; 14716 } 14717 14718 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14719 // Do not run PackageDexOptimizer through the local performDexOpt 14720 // method because `pkg` is not in `mPackages` yet. 14721 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14722 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14723 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14724 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14725 String msg = "Extracting package failed for " + pkgName; 14726 res.setError(INSTALL_FAILED_DEXOPT, msg); 14727 return; 14728 } 14729 14730 // Notify BackgroundDexOptService that the package has been changed. 14731 // If this is an update of a package which used to fail to compile, 14732 // BDOS will remove it from its blacklist. 14733 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14734 } 14735 14736 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14737 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14738 return; 14739 } 14740 14741 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14742 14743 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14744 "installPackageLI")) { 14745 if (replace) { 14746 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14747 installerPackageName, res); 14748 } else { 14749 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14750 args.user, installerPackageName, volumeUuid, res); 14751 } 14752 } 14753 synchronized (mPackages) { 14754 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14755 if (ps != null) { 14756 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14757 } 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 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14763 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14764 if (childPs != null) { 14765 childRes.newUsers = childPs.queryInstalledUsers( 14766 sUserManager.getUserIds(), true); 14767 } 14768 } 14769 } 14770 } 14771 14772 private void startIntentFilterVerifications(int userId, boolean replacing, 14773 PackageParser.Package pkg) { 14774 if (mIntentFilterVerifierComponent == null) { 14775 Slog.w(TAG, "No IntentFilter verification will not be done as " 14776 + "there is no IntentFilterVerifier available!"); 14777 return; 14778 } 14779 14780 final int verifierUid = getPackageUid( 14781 mIntentFilterVerifierComponent.getPackageName(), 14782 MATCH_DEBUG_TRIAGED_MISSING, 14783 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14784 14785 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14786 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14787 mHandler.sendMessage(msg); 14788 14789 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14790 for (int i = 0; i < childCount; i++) { 14791 PackageParser.Package childPkg = pkg.childPackages.get(i); 14792 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14793 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14794 mHandler.sendMessage(msg); 14795 } 14796 } 14797 14798 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14799 PackageParser.Package pkg) { 14800 int size = pkg.activities.size(); 14801 if (size == 0) { 14802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14803 "No activity, so no need to verify any IntentFilter!"); 14804 return; 14805 } 14806 14807 final boolean hasDomainURLs = hasDomainURLs(pkg); 14808 if (!hasDomainURLs) { 14809 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14810 "No domain URLs, so no need to verify any IntentFilter!"); 14811 return; 14812 } 14813 14814 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14815 + " if any IntentFilter from the " + size 14816 + " Activities needs verification ..."); 14817 14818 int count = 0; 14819 final String packageName = pkg.packageName; 14820 14821 synchronized (mPackages) { 14822 // If this is a new install and we see that we've already run verification for this 14823 // package, we have nothing to do: it means the state was restored from backup. 14824 if (!replacing) { 14825 IntentFilterVerificationInfo ivi = 14826 mSettings.getIntentFilterVerificationLPr(packageName); 14827 if (ivi != null) { 14828 if (DEBUG_DOMAIN_VERIFICATION) { 14829 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14830 + ivi.getStatusString()); 14831 } 14832 return; 14833 } 14834 } 14835 14836 // If any filters need to be verified, then all need to be. 14837 boolean needToVerify = false; 14838 for (PackageParser.Activity a : pkg.activities) { 14839 for (ActivityIntentInfo filter : a.intents) { 14840 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14841 if (DEBUG_DOMAIN_VERIFICATION) { 14842 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14843 } 14844 needToVerify = true; 14845 break; 14846 } 14847 } 14848 } 14849 14850 if (needToVerify) { 14851 final int verificationId = mIntentFilterVerificationToken++; 14852 for (PackageParser.Activity a : pkg.activities) { 14853 for (ActivityIntentInfo filter : a.intents) { 14854 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14856 "Verification needed for IntentFilter:" + filter.toString()); 14857 mIntentFilterVerifier.addOneIntentFilterVerification( 14858 verifierUid, userId, verificationId, filter, packageName); 14859 count++; 14860 } 14861 } 14862 } 14863 } 14864 } 14865 14866 if (count > 0) { 14867 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14868 + " IntentFilter verification" + (count > 1 ? "s" : "") 14869 + " for userId:" + userId); 14870 mIntentFilterVerifier.startVerifications(userId); 14871 } else { 14872 if (DEBUG_DOMAIN_VERIFICATION) { 14873 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14874 } 14875 } 14876 } 14877 14878 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14879 final ComponentName cn = filter.activity.getComponentName(); 14880 final String packageName = cn.getPackageName(); 14881 14882 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14883 packageName); 14884 if (ivi == null) { 14885 return true; 14886 } 14887 int status = ivi.getStatus(); 14888 switch (status) { 14889 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14890 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14891 return true; 14892 14893 default: 14894 // Nothing to do 14895 return false; 14896 } 14897 } 14898 14899 private static boolean isMultiArch(ApplicationInfo info) { 14900 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14901 } 14902 14903 private static boolean isExternal(PackageParser.Package pkg) { 14904 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14905 } 14906 14907 private static boolean isExternal(PackageSetting ps) { 14908 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14909 } 14910 14911 private static boolean isEphemeral(PackageParser.Package pkg) { 14912 return pkg.applicationInfo.isEphemeralApp(); 14913 } 14914 14915 private static boolean isEphemeral(PackageSetting ps) { 14916 return ps.pkg != null && isEphemeral(ps.pkg); 14917 } 14918 14919 private static boolean isSystemApp(PackageParser.Package pkg) { 14920 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14921 } 14922 14923 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14924 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14925 } 14926 14927 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14928 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14929 } 14930 14931 private static boolean isSystemApp(PackageSetting ps) { 14932 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14933 } 14934 14935 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14936 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14937 } 14938 14939 private int packageFlagsToInstallFlags(PackageSetting ps) { 14940 int installFlags = 0; 14941 if (isEphemeral(ps)) { 14942 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14943 } 14944 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14945 // This existing package was an external ASEC install when we have 14946 // the external flag without a UUID 14947 installFlags |= PackageManager.INSTALL_EXTERNAL; 14948 } 14949 if (ps.isForwardLocked()) { 14950 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14951 } 14952 return installFlags; 14953 } 14954 14955 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14956 if (isExternal(pkg)) { 14957 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14958 return StorageManager.UUID_PRIMARY_PHYSICAL; 14959 } else { 14960 return pkg.volumeUuid; 14961 } 14962 } else { 14963 return StorageManager.UUID_PRIVATE_INTERNAL; 14964 } 14965 } 14966 14967 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14968 if (isExternal(pkg)) { 14969 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14970 return mSettings.getExternalVersion(); 14971 } else { 14972 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14973 } 14974 } else { 14975 return mSettings.getInternalVersion(); 14976 } 14977 } 14978 14979 private void deleteTempPackageFiles() { 14980 final FilenameFilter filter = new FilenameFilter() { 14981 public boolean accept(File dir, String name) { 14982 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14983 } 14984 }; 14985 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14986 file.delete(); 14987 } 14988 } 14989 14990 @Override 14991 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14992 int flags) { 14993 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14994 flags); 14995 } 14996 14997 @Override 14998 public void deletePackage(final String packageName, 14999 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15000 mContext.enforceCallingOrSelfPermission( 15001 android.Manifest.permission.DELETE_PACKAGES, null); 15002 Preconditions.checkNotNull(packageName); 15003 Preconditions.checkNotNull(observer); 15004 final int uid = Binder.getCallingUid(); 15005 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15006 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15007 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15008 mContext.enforceCallingOrSelfPermission( 15009 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15010 "deletePackage for user " + userId); 15011 } 15012 15013 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15014 try { 15015 observer.onPackageDeleted(packageName, 15016 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15017 } catch (RemoteException re) { 15018 } 15019 return; 15020 } 15021 15022 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15023 try { 15024 observer.onPackageDeleted(packageName, 15025 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15026 } catch (RemoteException re) { 15027 } 15028 return; 15029 } 15030 15031 if (DEBUG_REMOVE) { 15032 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15033 + " deleteAllUsers: " + deleteAllUsers ); 15034 } 15035 // Queue up an async operation since the package deletion may take a little while. 15036 mHandler.post(new Runnable() { 15037 public void run() { 15038 mHandler.removeCallbacks(this); 15039 int returnCode; 15040 if (!deleteAllUsers) { 15041 returnCode = deletePackageX(packageName, userId, deleteFlags); 15042 } else { 15043 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15044 // If nobody is blocking uninstall, proceed with delete for all users 15045 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15046 returnCode = deletePackageX(packageName, userId, deleteFlags); 15047 } else { 15048 // Otherwise uninstall individually for users with blockUninstalls=false 15049 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15050 for (int userId : users) { 15051 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15052 returnCode = deletePackageX(packageName, userId, userFlags); 15053 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15054 Slog.w(TAG, "Package delete failed for user " + userId 15055 + ", returnCode " + returnCode); 15056 } 15057 } 15058 } 15059 // The app has only been marked uninstalled for certain users. 15060 // We still need to report that delete was blocked 15061 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15062 } 15063 } 15064 try { 15065 observer.onPackageDeleted(packageName, returnCode, null); 15066 } catch (RemoteException e) { 15067 Log.i(TAG, "Observer no longer exists."); 15068 } //end catch 15069 } //end run 15070 }); 15071 } 15072 15073 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15074 int[] result = EMPTY_INT_ARRAY; 15075 for (int userId : userIds) { 15076 if (getBlockUninstallForUser(packageName, userId)) { 15077 result = ArrayUtils.appendInt(result, userId); 15078 } 15079 } 15080 return result; 15081 } 15082 15083 @Override 15084 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15085 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15086 } 15087 15088 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15089 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15090 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15091 try { 15092 if (dpm != null) { 15093 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15094 /* callingUserOnly =*/ false); 15095 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15096 : deviceOwnerComponentName.getPackageName(); 15097 // Does the package contains the device owner? 15098 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15099 // this check is probably not needed, since DO should be registered as a device 15100 // admin on some user too. (Original bug for this: b/17657954) 15101 if (packageName.equals(deviceOwnerPackageName)) { 15102 return true; 15103 } 15104 // Does it contain a device admin for any user? 15105 int[] users; 15106 if (userId == UserHandle.USER_ALL) { 15107 users = sUserManager.getUserIds(); 15108 } else { 15109 users = new int[]{userId}; 15110 } 15111 for (int i = 0; i < users.length; ++i) { 15112 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15113 return true; 15114 } 15115 } 15116 } 15117 } catch (RemoteException e) { 15118 } 15119 return false; 15120 } 15121 15122 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15123 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15124 } 15125 15126 /** 15127 * This method is an internal method that could be get invoked either 15128 * to delete an installed package or to clean up a failed installation. 15129 * After deleting an installed package, a broadcast is sent to notify any 15130 * listeners that the package has been removed. For cleaning up a failed 15131 * installation, the broadcast is not necessary since the package's 15132 * installation wouldn't have sent the initial broadcast either 15133 * The key steps in deleting a package are 15134 * deleting the package information in internal structures like mPackages, 15135 * deleting the packages base directories through installd 15136 * updating mSettings to reflect current status 15137 * persisting settings for later use 15138 * sending a broadcast if necessary 15139 */ 15140 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15141 final PackageRemovedInfo info = new PackageRemovedInfo(); 15142 final boolean res; 15143 15144 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15145 ? UserHandle.ALL : new UserHandle(userId); 15146 15147 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15148 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15149 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15150 } 15151 15152 PackageSetting uninstalledPs = null; 15153 15154 // for the uninstall-updates case and restricted profiles, remember the per- 15155 // user handle installed state 15156 int[] allUsers; 15157 synchronized (mPackages) { 15158 uninstalledPs = mSettings.mPackages.get(packageName); 15159 if (uninstalledPs == null) { 15160 Slog.w(TAG, "Not removing non-existent package " + packageName); 15161 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15162 } 15163 allUsers = sUserManager.getUserIds(); 15164 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15165 } 15166 15167 synchronized (mInstallLock) { 15168 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15169 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15170 "deletePackageX")) { 15171 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15172 deleteFlags | REMOVE_CHATTY, info, true, null); 15173 } 15174 synchronized (mPackages) { 15175 if (res) { 15176 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15177 } 15178 } 15179 } 15180 15181 if (res) { 15182 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15183 info.sendPackageRemovedBroadcasts(killApp); 15184 info.sendSystemPackageUpdatedBroadcasts(); 15185 info.sendSystemPackageAppearedBroadcasts(); 15186 } 15187 // Force a gc here. 15188 Runtime.getRuntime().gc(); 15189 // Delete the resources here after sending the broadcast to let 15190 // other processes clean up before deleting resources. 15191 if (info.args != null) { 15192 synchronized (mInstallLock) { 15193 info.args.doPostDeleteLI(true); 15194 } 15195 } 15196 15197 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15198 } 15199 15200 class PackageRemovedInfo { 15201 String removedPackage; 15202 int uid = -1; 15203 int removedAppId = -1; 15204 int[] origUsers; 15205 int[] removedUsers = null; 15206 boolean isRemovedPackageSystemUpdate = false; 15207 boolean isUpdate; 15208 boolean dataRemoved; 15209 boolean removedForAllUsers; 15210 // Clean up resources deleted packages. 15211 InstallArgs args = null; 15212 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15213 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15214 15215 void sendPackageRemovedBroadcasts(boolean killApp) { 15216 sendPackageRemovedBroadcastInternal(killApp); 15217 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15218 for (int i = 0; i < childCount; i++) { 15219 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15220 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15221 } 15222 } 15223 15224 void sendSystemPackageUpdatedBroadcasts() { 15225 if (isRemovedPackageSystemUpdate) { 15226 sendSystemPackageUpdatedBroadcastsInternal(); 15227 final int childCount = (removedChildPackages != null) 15228 ? removedChildPackages.size() : 0; 15229 for (int i = 0; i < childCount; i++) { 15230 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15231 if (childInfo.isRemovedPackageSystemUpdate) { 15232 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15233 } 15234 } 15235 } 15236 } 15237 15238 void sendSystemPackageAppearedBroadcasts() { 15239 final int packageCount = (appearedChildPackages != null) 15240 ? appearedChildPackages.size() : 0; 15241 for (int i = 0; i < packageCount; i++) { 15242 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15243 for (int userId : installedInfo.newUsers) { 15244 sendPackageAddedForUser(installedInfo.name, true, 15245 UserHandle.getAppId(installedInfo.uid), userId); 15246 } 15247 } 15248 } 15249 15250 private void sendSystemPackageUpdatedBroadcastsInternal() { 15251 Bundle extras = new Bundle(2); 15252 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15253 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15254 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15255 extras, 0, null, null, null); 15256 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15257 extras, 0, null, null, null); 15258 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15259 null, 0, removedPackage, null, null); 15260 } 15261 15262 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15263 Bundle extras = new Bundle(2); 15264 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15265 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15266 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15267 if (isUpdate || isRemovedPackageSystemUpdate) { 15268 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15269 } 15270 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15271 if (removedPackage != null) { 15272 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15273 extras, 0, null, null, removedUsers); 15274 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15275 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15276 removedPackage, extras, 0, null, null, removedUsers); 15277 } 15278 } 15279 if (removedAppId >= 0) { 15280 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15281 removedUsers); 15282 } 15283 } 15284 } 15285 15286 /* 15287 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15288 * flag is not set, the data directory is removed as well. 15289 * make sure this flag is set for partially installed apps. If not its meaningless to 15290 * delete a partially installed application. 15291 */ 15292 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15293 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15294 String packageName = ps.name; 15295 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15296 // Retrieve object to delete permissions for shared user later on 15297 final PackageParser.Package deletedPkg; 15298 final PackageSetting deletedPs; 15299 // reader 15300 synchronized (mPackages) { 15301 deletedPkg = mPackages.get(packageName); 15302 deletedPs = mSettings.mPackages.get(packageName); 15303 if (outInfo != null) { 15304 outInfo.removedPackage = packageName; 15305 outInfo.removedUsers = deletedPs != null 15306 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15307 : null; 15308 } 15309 } 15310 15311 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15312 15313 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15314 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15315 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15316 destroyAppProfilesLIF(deletedPkg); 15317 if (outInfo != null) { 15318 outInfo.dataRemoved = true; 15319 } 15320 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15321 } 15322 15323 // writer 15324 synchronized (mPackages) { 15325 if (deletedPs != null) { 15326 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15327 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15328 clearDefaultBrowserIfNeeded(packageName); 15329 if (outInfo != null) { 15330 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15331 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15332 } 15333 updatePermissionsLPw(deletedPs.name, null, 0); 15334 if (deletedPs.sharedUser != null) { 15335 // Remove permissions associated with package. Since runtime 15336 // permissions are per user we have to kill the removed package 15337 // or packages running under the shared user of the removed 15338 // package if revoking the permissions requested only by the removed 15339 // package is successful and this causes a change in gids. 15340 for (int userId : UserManagerService.getInstance().getUserIds()) { 15341 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15342 userId); 15343 if (userIdToKill == UserHandle.USER_ALL 15344 || userIdToKill >= UserHandle.USER_SYSTEM) { 15345 // If gids changed for this user, kill all affected packages. 15346 mHandler.post(new Runnable() { 15347 @Override 15348 public void run() { 15349 // This has to happen with no lock held. 15350 killApplication(deletedPs.name, deletedPs.appId, 15351 KILL_APP_REASON_GIDS_CHANGED); 15352 } 15353 }); 15354 break; 15355 } 15356 } 15357 } 15358 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15359 } 15360 // make sure to preserve per-user disabled state if this removal was just 15361 // a downgrade of a system app to the factory package 15362 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15363 if (DEBUG_REMOVE) { 15364 Slog.d(TAG, "Propagating install state across downgrade"); 15365 } 15366 for (int userId : allUserHandles) { 15367 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15368 if (DEBUG_REMOVE) { 15369 Slog.d(TAG, " user " + userId + " => " + installed); 15370 } 15371 ps.setInstalled(installed, userId); 15372 } 15373 } 15374 } 15375 // can downgrade to reader 15376 if (writeSettings) { 15377 // Save settings now 15378 mSettings.writeLPr(); 15379 } 15380 } 15381 if (outInfo != null) { 15382 // A user ID was deleted here. Go through all users and remove it 15383 // from KeyStore. 15384 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15385 } 15386 } 15387 15388 static boolean locationIsPrivileged(File path) { 15389 try { 15390 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15391 .getCanonicalPath(); 15392 return path.getCanonicalPath().startsWith(privilegedAppDir); 15393 } catch (IOException e) { 15394 Slog.e(TAG, "Unable to access code path " + path); 15395 } 15396 return false; 15397 } 15398 15399 /* 15400 * Tries to delete system package. 15401 */ 15402 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15403 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15404 boolean writeSettings) { 15405 if (deletedPs.parentPackageName != null) { 15406 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15407 return false; 15408 } 15409 15410 final boolean applyUserRestrictions 15411 = (allUserHandles != null) && (outInfo.origUsers != null); 15412 final PackageSetting disabledPs; 15413 // Confirm if the system package has been updated 15414 // An updated system app can be deleted. This will also have to restore 15415 // the system pkg from system partition 15416 // reader 15417 synchronized (mPackages) { 15418 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15419 } 15420 15421 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15422 + " disabledPs=" + disabledPs); 15423 15424 if (disabledPs == null) { 15425 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15426 return false; 15427 } else if (DEBUG_REMOVE) { 15428 Slog.d(TAG, "Deleting system pkg from data partition"); 15429 } 15430 15431 if (DEBUG_REMOVE) { 15432 if (applyUserRestrictions) { 15433 Slog.d(TAG, "Remembering install states:"); 15434 for (int userId : allUserHandles) { 15435 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15436 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15437 } 15438 } 15439 } 15440 15441 // Delete the updated package 15442 outInfo.isRemovedPackageSystemUpdate = true; 15443 if (outInfo.removedChildPackages != null) { 15444 final int childCount = (deletedPs.childPackageNames != null) 15445 ? deletedPs.childPackageNames.size() : 0; 15446 for (int i = 0; i < childCount; i++) { 15447 String childPackageName = deletedPs.childPackageNames.get(i); 15448 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15449 .contains(childPackageName)) { 15450 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15451 childPackageName); 15452 if (childInfo != null) { 15453 childInfo.isRemovedPackageSystemUpdate = true; 15454 } 15455 } 15456 } 15457 } 15458 15459 if (disabledPs.versionCode < deletedPs.versionCode) { 15460 // Delete data for downgrades 15461 flags &= ~PackageManager.DELETE_KEEP_DATA; 15462 } else { 15463 // Preserve data by setting flag 15464 flags |= PackageManager.DELETE_KEEP_DATA; 15465 } 15466 15467 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15468 outInfo, writeSettings, disabledPs.pkg); 15469 if (!ret) { 15470 return false; 15471 } 15472 15473 // writer 15474 synchronized (mPackages) { 15475 // Reinstate the old system package 15476 enableSystemPackageLPw(disabledPs.pkg); 15477 // Remove any native libraries from the upgraded package. 15478 removeNativeBinariesLI(deletedPs); 15479 } 15480 15481 // Install the system package 15482 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15483 int parseFlags = mDefParseFlags 15484 | PackageParser.PARSE_MUST_BE_APK 15485 | PackageParser.PARSE_IS_SYSTEM 15486 | PackageParser.PARSE_IS_SYSTEM_DIR; 15487 if (locationIsPrivileged(disabledPs.codePath)) { 15488 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15489 } 15490 15491 final PackageParser.Package newPkg; 15492 try { 15493 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15494 } catch (PackageManagerException e) { 15495 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15496 + e.getMessage()); 15497 return false; 15498 } 15499 15500 prepareAppDataAfterInstallLIF(newPkg); 15501 15502 // writer 15503 synchronized (mPackages) { 15504 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15505 15506 // Propagate the permissions state as we do not want to drop on the floor 15507 // runtime permissions. The update permissions method below will take 15508 // care of removing obsolete permissions and grant install permissions. 15509 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15510 updatePermissionsLPw(newPkg.packageName, newPkg, 15511 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15512 15513 if (applyUserRestrictions) { 15514 if (DEBUG_REMOVE) { 15515 Slog.d(TAG, "Propagating install state across reinstall"); 15516 } 15517 for (int userId : allUserHandles) { 15518 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15519 if (DEBUG_REMOVE) { 15520 Slog.d(TAG, " user " + userId + " => " + installed); 15521 } 15522 ps.setInstalled(installed, userId); 15523 15524 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15525 } 15526 // Regardless of writeSettings we need to ensure that this restriction 15527 // state propagation is persisted 15528 mSettings.writeAllUsersPackageRestrictionsLPr(); 15529 } 15530 // can downgrade to reader here 15531 if (writeSettings) { 15532 mSettings.writeLPr(); 15533 } 15534 } 15535 return true; 15536 } 15537 15538 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15539 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15540 PackageRemovedInfo outInfo, boolean writeSettings, 15541 PackageParser.Package replacingPackage) { 15542 synchronized (mPackages) { 15543 if (outInfo != null) { 15544 outInfo.uid = ps.appId; 15545 } 15546 15547 if (outInfo != null && outInfo.removedChildPackages != null) { 15548 final int childCount = (ps.childPackageNames != null) 15549 ? ps.childPackageNames.size() : 0; 15550 for (int i = 0; i < childCount; i++) { 15551 String childPackageName = ps.childPackageNames.get(i); 15552 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15553 if (childPs == null) { 15554 return false; 15555 } 15556 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15557 childPackageName); 15558 if (childInfo != null) { 15559 childInfo.uid = childPs.appId; 15560 } 15561 } 15562 } 15563 } 15564 15565 // Delete package data from internal structures and also remove data if flag is set 15566 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15567 15568 // Delete the child packages data 15569 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15570 for (int i = 0; i < childCount; i++) { 15571 PackageSetting childPs; 15572 synchronized (mPackages) { 15573 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15574 } 15575 if (childPs != null) { 15576 PackageRemovedInfo childOutInfo = (outInfo != null 15577 && outInfo.removedChildPackages != null) 15578 ? outInfo.removedChildPackages.get(childPs.name) : null; 15579 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15580 && (replacingPackage != null 15581 && !replacingPackage.hasChildPackage(childPs.name)) 15582 ? flags & ~DELETE_KEEP_DATA : flags; 15583 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15584 deleteFlags, writeSettings); 15585 } 15586 } 15587 15588 // Delete application code and resources only for parent packages 15589 if (ps.parentPackageName == null) { 15590 if (deleteCodeAndResources && (outInfo != null)) { 15591 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15592 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15593 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15594 } 15595 } 15596 15597 return true; 15598 } 15599 15600 @Override 15601 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15602 int userId) { 15603 mContext.enforceCallingOrSelfPermission( 15604 android.Manifest.permission.DELETE_PACKAGES, null); 15605 synchronized (mPackages) { 15606 PackageSetting ps = mSettings.mPackages.get(packageName); 15607 if (ps == null) { 15608 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15609 return false; 15610 } 15611 if (!ps.getInstalled(userId)) { 15612 // Can't block uninstall for an app that is not installed or enabled. 15613 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15614 return false; 15615 } 15616 ps.setBlockUninstall(blockUninstall, userId); 15617 mSettings.writePackageRestrictionsLPr(userId); 15618 } 15619 return true; 15620 } 15621 15622 @Override 15623 public boolean getBlockUninstallForUser(String packageName, int userId) { 15624 synchronized (mPackages) { 15625 PackageSetting ps = mSettings.mPackages.get(packageName); 15626 if (ps == null) { 15627 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15628 return false; 15629 } 15630 return ps.getBlockUninstall(userId); 15631 } 15632 } 15633 15634 @Override 15635 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15636 int callingUid = Binder.getCallingUid(); 15637 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15638 throw new SecurityException( 15639 "setRequiredForSystemUser can only be run by the system or root"); 15640 } 15641 synchronized (mPackages) { 15642 PackageSetting ps = mSettings.mPackages.get(packageName); 15643 if (ps == null) { 15644 Log.w(TAG, "Package doesn't exist: " + packageName); 15645 return false; 15646 } 15647 if (systemUserApp) { 15648 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15649 } else { 15650 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15651 } 15652 mSettings.writeLPr(); 15653 } 15654 return true; 15655 } 15656 15657 /* 15658 * This method handles package deletion in general 15659 */ 15660 private boolean deletePackageLIF(String packageName, UserHandle user, 15661 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15662 PackageRemovedInfo outInfo, boolean writeSettings, 15663 PackageParser.Package replacingPackage) { 15664 if (packageName == null) { 15665 Slog.w(TAG, "Attempt to delete null packageName."); 15666 return false; 15667 } 15668 15669 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15670 15671 PackageSetting ps; 15672 15673 synchronized (mPackages) { 15674 ps = mSettings.mPackages.get(packageName); 15675 if (ps == null) { 15676 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15677 return false; 15678 } 15679 15680 if (ps.parentPackageName != null && (!isSystemApp(ps) 15681 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15682 if (DEBUG_REMOVE) { 15683 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15684 + ((user == null) ? UserHandle.USER_ALL : user)); 15685 } 15686 final int removedUserId = (user != null) ? user.getIdentifier() 15687 : UserHandle.USER_ALL; 15688 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15689 return false; 15690 } 15691 markPackageUninstalledForUserLPw(ps, user); 15692 scheduleWritePackageRestrictionsLocked(user); 15693 return true; 15694 } 15695 } 15696 15697 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15698 && user.getIdentifier() != UserHandle.USER_ALL)) { 15699 // The caller is asking that the package only be deleted for a single 15700 // user. To do this, we just mark its uninstalled state and delete 15701 // its data. If this is a system app, we only allow this to happen if 15702 // they have set the special DELETE_SYSTEM_APP which requests different 15703 // semantics than normal for uninstalling system apps. 15704 markPackageUninstalledForUserLPw(ps, user); 15705 15706 if (!isSystemApp(ps)) { 15707 // Do not uninstall the APK if an app should be cached 15708 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15709 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15710 // Other user still have this package installed, so all 15711 // we need to do is clear this user's data and save that 15712 // it is uninstalled. 15713 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15714 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15715 return false; 15716 } 15717 scheduleWritePackageRestrictionsLocked(user); 15718 return true; 15719 } else { 15720 // We need to set it back to 'installed' so the uninstall 15721 // broadcasts will be sent correctly. 15722 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15723 ps.setInstalled(true, user.getIdentifier()); 15724 } 15725 } else { 15726 // This is a system app, so we assume that the 15727 // other users still have this package installed, so all 15728 // we need to do is clear this user's data and save that 15729 // it is uninstalled. 15730 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15731 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15732 return false; 15733 } 15734 scheduleWritePackageRestrictionsLocked(user); 15735 return true; 15736 } 15737 } 15738 15739 // If we are deleting a composite package for all users, keep track 15740 // of result for each child. 15741 if (ps.childPackageNames != null && outInfo != null) { 15742 synchronized (mPackages) { 15743 final int childCount = ps.childPackageNames.size(); 15744 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15745 for (int i = 0; i < childCount; i++) { 15746 String childPackageName = ps.childPackageNames.get(i); 15747 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15748 childInfo.removedPackage = childPackageName; 15749 outInfo.removedChildPackages.put(childPackageName, childInfo); 15750 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15751 if (childPs != null) { 15752 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15753 } 15754 } 15755 } 15756 } 15757 15758 boolean ret = false; 15759 if (isSystemApp(ps)) { 15760 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15761 // When an updated system application is deleted we delete the existing resources 15762 // as well and fall back to existing code in system partition 15763 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15764 } else { 15765 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15766 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15767 outInfo, writeSettings, replacingPackage); 15768 } 15769 15770 // Take a note whether we deleted the package for all users 15771 if (outInfo != null) { 15772 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15773 if (outInfo.removedChildPackages != null) { 15774 synchronized (mPackages) { 15775 final int childCount = outInfo.removedChildPackages.size(); 15776 for (int i = 0; i < childCount; i++) { 15777 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15778 if (childInfo != null) { 15779 childInfo.removedForAllUsers = mPackages.get( 15780 childInfo.removedPackage) == null; 15781 } 15782 } 15783 } 15784 } 15785 // If we uninstalled an update to a system app there may be some 15786 // child packages that appeared as they are declared in the system 15787 // app but were not declared in the update. 15788 if (isSystemApp(ps)) { 15789 synchronized (mPackages) { 15790 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15791 final int childCount = (updatedPs.childPackageNames != null) 15792 ? updatedPs.childPackageNames.size() : 0; 15793 for (int i = 0; i < childCount; i++) { 15794 String childPackageName = updatedPs.childPackageNames.get(i); 15795 if (outInfo.removedChildPackages == null 15796 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15797 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15798 if (childPs == null) { 15799 continue; 15800 } 15801 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15802 installRes.name = childPackageName; 15803 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15804 installRes.pkg = mPackages.get(childPackageName); 15805 installRes.uid = childPs.pkg.applicationInfo.uid; 15806 if (outInfo.appearedChildPackages == null) { 15807 outInfo.appearedChildPackages = new ArrayMap<>(); 15808 } 15809 outInfo.appearedChildPackages.put(childPackageName, installRes); 15810 } 15811 } 15812 } 15813 } 15814 } 15815 15816 return ret; 15817 } 15818 15819 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15820 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15821 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15822 for (int nextUserId : userIds) { 15823 if (DEBUG_REMOVE) { 15824 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15825 } 15826 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15827 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15828 false /*hidden*/, false /*suspended*/, null, null, null, 15829 false /*blockUninstall*/, 15830 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15831 } 15832 } 15833 15834 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15835 PackageRemovedInfo outInfo) { 15836 final PackageParser.Package pkg; 15837 synchronized (mPackages) { 15838 pkg = mPackages.get(ps.name); 15839 } 15840 15841 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15842 : new int[] {userId}; 15843 for (int nextUserId : userIds) { 15844 if (DEBUG_REMOVE) { 15845 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15846 + nextUserId); 15847 } 15848 15849 destroyAppDataLIF(pkg, userId, 15850 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15851 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15852 schedulePackageCleaning(ps.name, nextUserId, false); 15853 synchronized (mPackages) { 15854 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15855 scheduleWritePackageRestrictionsLocked(nextUserId); 15856 } 15857 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15858 } 15859 } 15860 15861 if (outInfo != null) { 15862 outInfo.removedPackage = ps.name; 15863 outInfo.removedAppId = ps.appId; 15864 outInfo.removedUsers = userIds; 15865 } 15866 15867 return true; 15868 } 15869 15870 private final class ClearStorageConnection implements ServiceConnection { 15871 IMediaContainerService mContainerService; 15872 15873 @Override 15874 public void onServiceConnected(ComponentName name, IBinder service) { 15875 synchronized (this) { 15876 mContainerService = IMediaContainerService.Stub.asInterface(service); 15877 notifyAll(); 15878 } 15879 } 15880 15881 @Override 15882 public void onServiceDisconnected(ComponentName name) { 15883 } 15884 } 15885 15886 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15887 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15888 15889 final boolean mounted; 15890 if (Environment.isExternalStorageEmulated()) { 15891 mounted = true; 15892 } else { 15893 final String status = Environment.getExternalStorageState(); 15894 15895 mounted = status.equals(Environment.MEDIA_MOUNTED) 15896 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15897 } 15898 15899 if (!mounted) { 15900 return; 15901 } 15902 15903 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15904 int[] users; 15905 if (userId == UserHandle.USER_ALL) { 15906 users = sUserManager.getUserIds(); 15907 } else { 15908 users = new int[] { userId }; 15909 } 15910 final ClearStorageConnection conn = new ClearStorageConnection(); 15911 if (mContext.bindServiceAsUser( 15912 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15913 try { 15914 for (int curUser : users) { 15915 long timeout = SystemClock.uptimeMillis() + 5000; 15916 synchronized (conn) { 15917 long now = SystemClock.uptimeMillis(); 15918 while (conn.mContainerService == null && now < timeout) { 15919 try { 15920 conn.wait(timeout - now); 15921 } catch (InterruptedException e) { 15922 } 15923 } 15924 } 15925 if (conn.mContainerService == null) { 15926 return; 15927 } 15928 15929 final UserEnvironment userEnv = new UserEnvironment(curUser); 15930 clearDirectory(conn.mContainerService, 15931 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15932 if (allData) { 15933 clearDirectory(conn.mContainerService, 15934 userEnv.buildExternalStorageAppDataDirs(packageName)); 15935 clearDirectory(conn.mContainerService, 15936 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15937 } 15938 } 15939 } finally { 15940 mContext.unbindService(conn); 15941 } 15942 } 15943 } 15944 15945 @Override 15946 public void clearApplicationProfileData(String packageName) { 15947 enforceSystemOrRoot("Only the system can clear all profile data"); 15948 15949 final PackageParser.Package pkg; 15950 synchronized (mPackages) { 15951 pkg = mPackages.get(packageName); 15952 } 15953 15954 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15955 synchronized (mInstallLock) { 15956 clearAppProfilesLIF(pkg); 15957 } 15958 } 15959 } 15960 15961 @Override 15962 public void clearApplicationUserData(final String packageName, 15963 final IPackageDataObserver observer, final int userId) { 15964 mContext.enforceCallingOrSelfPermission( 15965 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15966 15967 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15968 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15969 15970 final DevicePolicyManagerInternal dpmi = LocalServices 15971 .getService(DevicePolicyManagerInternal.class); 15972 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15973 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15974 } 15975 // Queue up an async operation since the package deletion may take a little while. 15976 mHandler.post(new Runnable() { 15977 public void run() { 15978 mHandler.removeCallbacks(this); 15979 final boolean succeeded; 15980 try (PackageFreezer freezer = freezePackage(packageName, 15981 "clearApplicationUserData")) { 15982 synchronized (mInstallLock) { 15983 succeeded = clearApplicationUserDataLIF(packageName, userId); 15984 } 15985 clearExternalStorageDataSync(packageName, userId, true); 15986 } 15987 if (succeeded) { 15988 // invoke DeviceStorageMonitor's update method to clear any notifications 15989 DeviceStorageMonitorInternal dsm = LocalServices 15990 .getService(DeviceStorageMonitorInternal.class); 15991 if (dsm != null) { 15992 dsm.checkMemory(); 15993 } 15994 } 15995 if(observer != null) { 15996 try { 15997 observer.onRemoveCompleted(packageName, succeeded); 15998 } catch (RemoteException e) { 15999 Log.i(TAG, "Observer no longer exists."); 16000 } 16001 } //end if observer 16002 } //end run 16003 }); 16004 } 16005 16006 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16007 if (packageName == null) { 16008 Slog.w(TAG, "Attempt to delete null packageName."); 16009 return false; 16010 } 16011 16012 // Try finding details about the requested package 16013 PackageParser.Package pkg; 16014 synchronized (mPackages) { 16015 pkg = mPackages.get(packageName); 16016 if (pkg == null) { 16017 final PackageSetting ps = mSettings.mPackages.get(packageName); 16018 if (ps != null) { 16019 pkg = ps.pkg; 16020 } 16021 } 16022 16023 if (pkg == null) { 16024 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16025 return false; 16026 } 16027 16028 PackageSetting ps = (PackageSetting) pkg.mExtras; 16029 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16030 } 16031 16032 clearAppDataLIF(pkg, userId, 16033 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16034 16035 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16036 removeKeystoreDataIfNeeded(userId, appId); 16037 16038 final UserManager um = mContext.getSystemService(UserManager.class); 16039 final int flags; 16040 if (um.isUserUnlocked(userId)) { 16041 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16042 } else if (um.isUserRunning(userId)) { 16043 flags = StorageManager.FLAG_STORAGE_DE; 16044 } else { 16045 flags = 0; 16046 } 16047 prepareAppDataContentsLIF(pkg, userId, flags); 16048 16049 return true; 16050 } 16051 16052 /** 16053 * Reverts user permission state changes (permissions and flags) in 16054 * all packages for a given user. 16055 * 16056 * @param userId The device user for which to do a reset. 16057 */ 16058 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16059 final int packageCount = mPackages.size(); 16060 for (int i = 0; i < packageCount; i++) { 16061 PackageParser.Package pkg = mPackages.valueAt(i); 16062 PackageSetting ps = (PackageSetting) pkg.mExtras; 16063 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16064 } 16065 } 16066 16067 /** 16068 * Reverts user permission state changes (permissions and flags). 16069 * 16070 * @param ps The package for which to reset. 16071 * @param userId The device user for which to do a reset. 16072 */ 16073 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16074 final PackageSetting ps, final int userId) { 16075 if (ps.pkg == null) { 16076 return; 16077 } 16078 16079 // These are flags that can change base on user actions. 16080 final int userSettableMask = FLAG_PERMISSION_USER_SET 16081 | FLAG_PERMISSION_USER_FIXED 16082 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16083 | FLAG_PERMISSION_REVIEW_REQUIRED; 16084 16085 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16086 | FLAG_PERMISSION_POLICY_FIXED; 16087 16088 boolean writeInstallPermissions = false; 16089 boolean writeRuntimePermissions = false; 16090 16091 final int permissionCount = ps.pkg.requestedPermissions.size(); 16092 for (int i = 0; i < permissionCount; i++) { 16093 String permission = ps.pkg.requestedPermissions.get(i); 16094 16095 BasePermission bp = mSettings.mPermissions.get(permission); 16096 if (bp == null) { 16097 continue; 16098 } 16099 16100 // If shared user we just reset the state to which only this app contributed. 16101 if (ps.sharedUser != null) { 16102 boolean used = false; 16103 final int packageCount = ps.sharedUser.packages.size(); 16104 for (int j = 0; j < packageCount; j++) { 16105 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16106 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16107 && pkg.pkg.requestedPermissions.contains(permission)) { 16108 used = true; 16109 break; 16110 } 16111 } 16112 if (used) { 16113 continue; 16114 } 16115 } 16116 16117 PermissionsState permissionsState = ps.getPermissionsState(); 16118 16119 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16120 16121 // Always clear the user settable flags. 16122 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16123 bp.name) != null; 16124 // If permission review is enabled and this is a legacy app, mark the 16125 // permission as requiring a review as this is the initial state. 16126 int flags = 0; 16127 if (Build.PERMISSIONS_REVIEW_REQUIRED 16128 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16129 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16130 } 16131 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16132 if (hasInstallState) { 16133 writeInstallPermissions = true; 16134 } else { 16135 writeRuntimePermissions = true; 16136 } 16137 } 16138 16139 // Below is only runtime permission handling. 16140 if (!bp.isRuntime()) { 16141 continue; 16142 } 16143 16144 // Never clobber system or policy. 16145 if ((oldFlags & policyOrSystemFlags) != 0) { 16146 continue; 16147 } 16148 16149 // If this permission was granted by default, make sure it is. 16150 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16151 if (permissionsState.grantRuntimePermission(bp, userId) 16152 != PERMISSION_OPERATION_FAILURE) { 16153 writeRuntimePermissions = true; 16154 } 16155 // If permission review is enabled the permissions for a legacy apps 16156 // are represented as constantly granted runtime ones, so don't revoke. 16157 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16158 // Otherwise, reset the permission. 16159 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16160 switch (revokeResult) { 16161 case PERMISSION_OPERATION_SUCCESS: 16162 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16163 writeRuntimePermissions = true; 16164 final int appId = ps.appId; 16165 mHandler.post(new Runnable() { 16166 @Override 16167 public void run() { 16168 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16169 } 16170 }); 16171 } break; 16172 } 16173 } 16174 } 16175 16176 // Synchronously write as we are taking permissions away. 16177 if (writeRuntimePermissions) { 16178 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16179 } 16180 16181 // Synchronously write as we are taking permissions away. 16182 if (writeInstallPermissions) { 16183 mSettings.writeLPr(); 16184 } 16185 } 16186 16187 /** 16188 * Remove entries from the keystore daemon. Will only remove it if the 16189 * {@code appId} is valid. 16190 */ 16191 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16192 if (appId < 0) { 16193 return; 16194 } 16195 16196 final KeyStore keyStore = KeyStore.getInstance(); 16197 if (keyStore != null) { 16198 if (userId == UserHandle.USER_ALL) { 16199 for (final int individual : sUserManager.getUserIds()) { 16200 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16201 } 16202 } else { 16203 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16204 } 16205 } else { 16206 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16207 } 16208 } 16209 16210 @Override 16211 public void deleteApplicationCacheFiles(final String packageName, 16212 final IPackageDataObserver observer) { 16213 final int userId = UserHandle.getCallingUserId(); 16214 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16215 } 16216 16217 @Override 16218 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16219 final IPackageDataObserver observer) { 16220 mContext.enforceCallingOrSelfPermission( 16221 android.Manifest.permission.DELETE_CACHE_FILES, null); 16222 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16223 /* requireFullPermission= */ true, /* checkShell= */ false, 16224 "delete application cache files"); 16225 16226 final PackageParser.Package pkg; 16227 synchronized (mPackages) { 16228 pkg = mPackages.get(packageName); 16229 } 16230 16231 // Queue up an async operation since the package deletion may take a little while. 16232 mHandler.post(new Runnable() { 16233 public void run() { 16234 synchronized (mInstallLock) { 16235 final int flags = StorageManager.FLAG_STORAGE_DE 16236 | StorageManager.FLAG_STORAGE_CE; 16237 // We're only clearing cache files, so we don't care if the 16238 // app is unfrozen and still able to run 16239 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16240 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16241 } 16242 clearExternalStorageDataSync(packageName, userId, false); 16243 if (observer != null) { 16244 try { 16245 observer.onRemoveCompleted(packageName, true); 16246 } catch (RemoteException e) { 16247 Log.i(TAG, "Observer no longer exists."); 16248 } 16249 } 16250 } 16251 }); 16252 } 16253 16254 @Override 16255 public void getPackageSizeInfo(final String packageName, int userHandle, 16256 final IPackageStatsObserver observer) { 16257 mContext.enforceCallingOrSelfPermission( 16258 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16259 if (packageName == null) { 16260 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16261 } 16262 16263 PackageStats stats = new PackageStats(packageName, userHandle); 16264 16265 /* 16266 * Queue up an async operation since the package measurement may take a 16267 * little while. 16268 */ 16269 Message msg = mHandler.obtainMessage(INIT_COPY); 16270 msg.obj = new MeasureParams(stats, observer); 16271 mHandler.sendMessage(msg); 16272 } 16273 16274 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16275 final PackageSetting ps; 16276 synchronized (mPackages) { 16277 ps = mSettings.mPackages.get(packageName); 16278 if (ps == null) { 16279 Slog.w(TAG, "Failed to find settings for " + packageName); 16280 return false; 16281 } 16282 } 16283 try { 16284 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16285 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16286 ps.getCeDataInode(userId), ps.codePathString, stats); 16287 } catch (InstallerException e) { 16288 Slog.w(TAG, String.valueOf(e)); 16289 return false; 16290 } 16291 16292 // For now, ignore code size of packages on system partition 16293 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16294 stats.codeSize = 0; 16295 } 16296 16297 return true; 16298 } 16299 16300 private int getUidTargetSdkVersionLockedLPr(int uid) { 16301 Object obj = mSettings.getUserIdLPr(uid); 16302 if (obj instanceof SharedUserSetting) { 16303 final SharedUserSetting sus = (SharedUserSetting) obj; 16304 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16305 final Iterator<PackageSetting> it = sus.packages.iterator(); 16306 while (it.hasNext()) { 16307 final PackageSetting ps = it.next(); 16308 if (ps.pkg != null) { 16309 int v = ps.pkg.applicationInfo.targetSdkVersion; 16310 if (v < vers) vers = v; 16311 } 16312 } 16313 return vers; 16314 } else if (obj instanceof PackageSetting) { 16315 final PackageSetting ps = (PackageSetting) obj; 16316 if (ps.pkg != null) { 16317 return ps.pkg.applicationInfo.targetSdkVersion; 16318 } 16319 } 16320 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16321 } 16322 16323 @Override 16324 public void addPreferredActivity(IntentFilter filter, int match, 16325 ComponentName[] set, ComponentName activity, int userId) { 16326 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16327 "Adding preferred"); 16328 } 16329 16330 private void addPreferredActivityInternal(IntentFilter filter, int match, 16331 ComponentName[] set, ComponentName activity, boolean always, int userId, 16332 String opname) { 16333 // writer 16334 int callingUid = Binder.getCallingUid(); 16335 enforceCrossUserPermission(callingUid, userId, 16336 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16337 if (filter.countActions() == 0) { 16338 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16339 return; 16340 } 16341 synchronized (mPackages) { 16342 if (mContext.checkCallingOrSelfPermission( 16343 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16344 != PackageManager.PERMISSION_GRANTED) { 16345 if (getUidTargetSdkVersionLockedLPr(callingUid) 16346 < Build.VERSION_CODES.FROYO) { 16347 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16348 + callingUid); 16349 return; 16350 } 16351 mContext.enforceCallingOrSelfPermission( 16352 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16353 } 16354 16355 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16356 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16357 + userId + ":"); 16358 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16359 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16360 scheduleWritePackageRestrictionsLocked(userId); 16361 } 16362 } 16363 16364 @Override 16365 public void replacePreferredActivity(IntentFilter filter, int match, 16366 ComponentName[] set, ComponentName activity, int userId) { 16367 if (filter.countActions() != 1) { 16368 throw new IllegalArgumentException( 16369 "replacePreferredActivity expects filter to have only 1 action."); 16370 } 16371 if (filter.countDataAuthorities() != 0 16372 || filter.countDataPaths() != 0 16373 || filter.countDataSchemes() > 1 16374 || filter.countDataTypes() != 0) { 16375 throw new IllegalArgumentException( 16376 "replacePreferredActivity expects filter to have no data authorities, " + 16377 "paths, or types; and at most one scheme."); 16378 } 16379 16380 final int callingUid = Binder.getCallingUid(); 16381 enforceCrossUserPermission(callingUid, userId, 16382 true /* requireFullPermission */, false /* checkShell */, 16383 "replace preferred activity"); 16384 synchronized (mPackages) { 16385 if (mContext.checkCallingOrSelfPermission( 16386 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16387 != PackageManager.PERMISSION_GRANTED) { 16388 if (getUidTargetSdkVersionLockedLPr(callingUid) 16389 < Build.VERSION_CODES.FROYO) { 16390 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16391 + Binder.getCallingUid()); 16392 return; 16393 } 16394 mContext.enforceCallingOrSelfPermission( 16395 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16396 } 16397 16398 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16399 if (pir != null) { 16400 // Get all of the existing entries that exactly match this filter. 16401 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16402 if (existing != null && existing.size() == 1) { 16403 PreferredActivity cur = existing.get(0); 16404 if (DEBUG_PREFERRED) { 16405 Slog.i(TAG, "Checking replace of preferred:"); 16406 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16407 if (!cur.mPref.mAlways) { 16408 Slog.i(TAG, " -- CUR; not mAlways!"); 16409 } else { 16410 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16411 Slog.i(TAG, " -- CUR: mSet=" 16412 + Arrays.toString(cur.mPref.mSetComponents)); 16413 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16414 Slog.i(TAG, " -- NEW: mMatch=" 16415 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16416 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16417 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16418 } 16419 } 16420 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16421 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16422 && cur.mPref.sameSet(set)) { 16423 // Setting the preferred activity to what it happens to be already 16424 if (DEBUG_PREFERRED) { 16425 Slog.i(TAG, "Replacing with same preferred activity " 16426 + cur.mPref.mShortComponent + " for user " 16427 + userId + ":"); 16428 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16429 } 16430 return; 16431 } 16432 } 16433 16434 if (existing != null) { 16435 if (DEBUG_PREFERRED) { 16436 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16437 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16438 } 16439 for (int i = 0; i < existing.size(); i++) { 16440 PreferredActivity pa = existing.get(i); 16441 if (DEBUG_PREFERRED) { 16442 Slog.i(TAG, "Removing existing preferred activity " 16443 + pa.mPref.mComponent + ":"); 16444 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16445 } 16446 pir.removeFilter(pa); 16447 } 16448 } 16449 } 16450 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16451 "Replacing preferred"); 16452 } 16453 } 16454 16455 @Override 16456 public void clearPackagePreferredActivities(String packageName) { 16457 final int uid = Binder.getCallingUid(); 16458 // writer 16459 synchronized (mPackages) { 16460 PackageParser.Package pkg = mPackages.get(packageName); 16461 if (pkg == null || pkg.applicationInfo.uid != uid) { 16462 if (mContext.checkCallingOrSelfPermission( 16463 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16464 != PackageManager.PERMISSION_GRANTED) { 16465 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16466 < Build.VERSION_CODES.FROYO) { 16467 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16468 + Binder.getCallingUid()); 16469 return; 16470 } 16471 mContext.enforceCallingOrSelfPermission( 16472 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16473 } 16474 } 16475 16476 int user = UserHandle.getCallingUserId(); 16477 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16478 scheduleWritePackageRestrictionsLocked(user); 16479 } 16480 } 16481 } 16482 16483 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16484 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16485 ArrayList<PreferredActivity> removed = null; 16486 boolean changed = false; 16487 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16488 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16489 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16490 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16491 continue; 16492 } 16493 Iterator<PreferredActivity> it = pir.filterIterator(); 16494 while (it.hasNext()) { 16495 PreferredActivity pa = it.next(); 16496 // Mark entry for removal only if it matches the package name 16497 // and the entry is of type "always". 16498 if (packageName == null || 16499 (pa.mPref.mComponent.getPackageName().equals(packageName) 16500 && pa.mPref.mAlways)) { 16501 if (removed == null) { 16502 removed = new ArrayList<PreferredActivity>(); 16503 } 16504 removed.add(pa); 16505 } 16506 } 16507 if (removed != null) { 16508 for (int j=0; j<removed.size(); j++) { 16509 PreferredActivity pa = removed.get(j); 16510 pir.removeFilter(pa); 16511 } 16512 changed = true; 16513 } 16514 } 16515 return changed; 16516 } 16517 16518 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16519 private void clearIntentFilterVerificationsLPw(int userId) { 16520 final int packageCount = mPackages.size(); 16521 for (int i = 0; i < packageCount; i++) { 16522 PackageParser.Package pkg = mPackages.valueAt(i); 16523 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16524 } 16525 } 16526 16527 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16528 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16529 if (userId == UserHandle.USER_ALL) { 16530 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16531 sUserManager.getUserIds())) { 16532 for (int oneUserId : sUserManager.getUserIds()) { 16533 scheduleWritePackageRestrictionsLocked(oneUserId); 16534 } 16535 } 16536 } else { 16537 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16538 scheduleWritePackageRestrictionsLocked(userId); 16539 } 16540 } 16541 } 16542 16543 void clearDefaultBrowserIfNeeded(String packageName) { 16544 for (int oneUserId : sUserManager.getUserIds()) { 16545 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16546 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16547 if (packageName.equals(defaultBrowserPackageName)) { 16548 setDefaultBrowserPackageName(null, oneUserId); 16549 } 16550 } 16551 } 16552 16553 @Override 16554 public void resetApplicationPreferences(int userId) { 16555 mContext.enforceCallingOrSelfPermission( 16556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16557 // writer 16558 synchronized (mPackages) { 16559 final long identity = Binder.clearCallingIdentity(); 16560 try { 16561 clearPackagePreferredActivitiesLPw(null, userId); 16562 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16563 // TODO: We have to reset the default SMS and Phone. This requires 16564 // significant refactoring to keep all default apps in the package 16565 // manager (cleaner but more work) or have the services provide 16566 // callbacks to the package manager to request a default app reset. 16567 applyFactoryDefaultBrowserLPw(userId); 16568 clearIntentFilterVerificationsLPw(userId); 16569 primeDomainVerificationsLPw(userId); 16570 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16571 scheduleWritePackageRestrictionsLocked(userId); 16572 } finally { 16573 Binder.restoreCallingIdentity(identity); 16574 } 16575 } 16576 } 16577 16578 @Override 16579 public int getPreferredActivities(List<IntentFilter> outFilters, 16580 List<ComponentName> outActivities, String packageName) { 16581 16582 int num = 0; 16583 final int userId = UserHandle.getCallingUserId(); 16584 // reader 16585 synchronized (mPackages) { 16586 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16587 if (pir != null) { 16588 final Iterator<PreferredActivity> it = pir.filterIterator(); 16589 while (it.hasNext()) { 16590 final PreferredActivity pa = it.next(); 16591 if (packageName == null 16592 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16593 && pa.mPref.mAlways)) { 16594 if (outFilters != null) { 16595 outFilters.add(new IntentFilter(pa)); 16596 } 16597 if (outActivities != null) { 16598 outActivities.add(pa.mPref.mComponent); 16599 } 16600 } 16601 } 16602 } 16603 } 16604 16605 return num; 16606 } 16607 16608 @Override 16609 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16610 int userId) { 16611 int callingUid = Binder.getCallingUid(); 16612 if (callingUid != Process.SYSTEM_UID) { 16613 throw new SecurityException( 16614 "addPersistentPreferredActivity can only be run by the system"); 16615 } 16616 if (filter.countActions() == 0) { 16617 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16618 return; 16619 } 16620 synchronized (mPackages) { 16621 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16622 ":"); 16623 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16624 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16625 new PersistentPreferredActivity(filter, activity)); 16626 scheduleWritePackageRestrictionsLocked(userId); 16627 } 16628 } 16629 16630 @Override 16631 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16632 int callingUid = Binder.getCallingUid(); 16633 if (callingUid != Process.SYSTEM_UID) { 16634 throw new SecurityException( 16635 "clearPackagePersistentPreferredActivities can only be run by the system"); 16636 } 16637 ArrayList<PersistentPreferredActivity> removed = null; 16638 boolean changed = false; 16639 synchronized (mPackages) { 16640 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16641 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16642 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16643 .valueAt(i); 16644 if (userId != thisUserId) { 16645 continue; 16646 } 16647 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16648 while (it.hasNext()) { 16649 PersistentPreferredActivity ppa = it.next(); 16650 // Mark entry for removal only if it matches the package name. 16651 if (ppa.mComponent.getPackageName().equals(packageName)) { 16652 if (removed == null) { 16653 removed = new ArrayList<PersistentPreferredActivity>(); 16654 } 16655 removed.add(ppa); 16656 } 16657 } 16658 if (removed != null) { 16659 for (int j=0; j<removed.size(); j++) { 16660 PersistentPreferredActivity ppa = removed.get(j); 16661 ppir.removeFilter(ppa); 16662 } 16663 changed = true; 16664 } 16665 } 16666 16667 if (changed) { 16668 scheduleWritePackageRestrictionsLocked(userId); 16669 } 16670 } 16671 } 16672 16673 /** 16674 * Common machinery for picking apart a restored XML blob and passing 16675 * it to a caller-supplied functor to be applied to the running system. 16676 */ 16677 private void restoreFromXml(XmlPullParser parser, int userId, 16678 String expectedStartTag, BlobXmlRestorer functor) 16679 throws IOException, XmlPullParserException { 16680 int type; 16681 while ((type = parser.next()) != XmlPullParser.START_TAG 16682 && type != XmlPullParser.END_DOCUMENT) { 16683 } 16684 if (type != XmlPullParser.START_TAG) { 16685 // oops didn't find a start tag?! 16686 if (DEBUG_BACKUP) { 16687 Slog.e(TAG, "Didn't find start tag during restore"); 16688 } 16689 return; 16690 } 16691Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16692 // this is supposed to be TAG_PREFERRED_BACKUP 16693 if (!expectedStartTag.equals(parser.getName())) { 16694 if (DEBUG_BACKUP) { 16695 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16696 } 16697 return; 16698 } 16699 16700 // skip interfering stuff, then we're aligned with the backing implementation 16701 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16702Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16703 functor.apply(parser, userId); 16704 } 16705 16706 private interface BlobXmlRestorer { 16707 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16708 } 16709 16710 /** 16711 * Non-Binder method, support for the backup/restore mechanism: write the 16712 * full set of preferred activities in its canonical XML format. Returns the 16713 * XML output as a byte array, or null if there is none. 16714 */ 16715 @Override 16716 public byte[] getPreferredActivityBackup(int userId) { 16717 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16718 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16719 } 16720 16721 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16722 try { 16723 final XmlSerializer serializer = new FastXmlSerializer(); 16724 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16725 serializer.startDocument(null, true); 16726 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16727 16728 synchronized (mPackages) { 16729 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16730 } 16731 16732 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16733 serializer.endDocument(); 16734 serializer.flush(); 16735 } catch (Exception e) { 16736 if (DEBUG_BACKUP) { 16737 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16738 } 16739 return null; 16740 } 16741 16742 return dataStream.toByteArray(); 16743 } 16744 16745 @Override 16746 public void restorePreferredActivities(byte[] backup, int userId) { 16747 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16748 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16749 } 16750 16751 try { 16752 final XmlPullParser parser = Xml.newPullParser(); 16753 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16754 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16755 new BlobXmlRestorer() { 16756 @Override 16757 public void apply(XmlPullParser parser, int userId) 16758 throws XmlPullParserException, IOException { 16759 synchronized (mPackages) { 16760 mSettings.readPreferredActivitiesLPw(parser, userId); 16761 } 16762 } 16763 } ); 16764 } catch (Exception e) { 16765 if (DEBUG_BACKUP) { 16766 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16767 } 16768 } 16769 } 16770 16771 /** 16772 * Non-Binder method, support for the backup/restore mechanism: write the 16773 * default browser (etc) settings in its canonical XML format. Returns the default 16774 * browser XML representation as a byte array, or null if there is none. 16775 */ 16776 @Override 16777 public byte[] getDefaultAppsBackup(int userId) { 16778 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16779 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16780 } 16781 16782 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16783 try { 16784 final XmlSerializer serializer = new FastXmlSerializer(); 16785 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16786 serializer.startDocument(null, true); 16787 serializer.startTag(null, TAG_DEFAULT_APPS); 16788 16789 synchronized (mPackages) { 16790 mSettings.writeDefaultAppsLPr(serializer, userId); 16791 } 16792 16793 serializer.endTag(null, TAG_DEFAULT_APPS); 16794 serializer.endDocument(); 16795 serializer.flush(); 16796 } catch (Exception e) { 16797 if (DEBUG_BACKUP) { 16798 Slog.e(TAG, "Unable to write default apps for backup", e); 16799 } 16800 return null; 16801 } 16802 16803 return dataStream.toByteArray(); 16804 } 16805 16806 @Override 16807 public void restoreDefaultApps(byte[] backup, int userId) { 16808 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16809 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16810 } 16811 16812 try { 16813 final XmlPullParser parser = Xml.newPullParser(); 16814 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16815 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16816 new BlobXmlRestorer() { 16817 @Override 16818 public void apply(XmlPullParser parser, int userId) 16819 throws XmlPullParserException, IOException { 16820 synchronized (mPackages) { 16821 mSettings.readDefaultAppsLPw(parser, userId); 16822 } 16823 } 16824 } ); 16825 } catch (Exception e) { 16826 if (DEBUG_BACKUP) { 16827 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16828 } 16829 } 16830 } 16831 16832 @Override 16833 public byte[] getIntentFilterVerificationBackup(int userId) { 16834 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16835 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16836 } 16837 16838 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16839 try { 16840 final XmlSerializer serializer = new FastXmlSerializer(); 16841 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16842 serializer.startDocument(null, true); 16843 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16844 16845 synchronized (mPackages) { 16846 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16847 } 16848 16849 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16850 serializer.endDocument(); 16851 serializer.flush(); 16852 } catch (Exception e) { 16853 if (DEBUG_BACKUP) { 16854 Slog.e(TAG, "Unable to write default apps for backup", e); 16855 } 16856 return null; 16857 } 16858 16859 return dataStream.toByteArray(); 16860 } 16861 16862 @Override 16863 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16864 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16865 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16866 } 16867 16868 try { 16869 final XmlPullParser parser = Xml.newPullParser(); 16870 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16871 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16872 new BlobXmlRestorer() { 16873 @Override 16874 public void apply(XmlPullParser parser, int userId) 16875 throws XmlPullParserException, IOException { 16876 synchronized (mPackages) { 16877 mSettings.readAllDomainVerificationsLPr(parser, userId); 16878 mSettings.writeLPr(); 16879 } 16880 } 16881 } ); 16882 } catch (Exception e) { 16883 if (DEBUG_BACKUP) { 16884 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16885 } 16886 } 16887 } 16888 16889 @Override 16890 public byte[] getPermissionGrantBackup(int userId) { 16891 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16892 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16893 } 16894 16895 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16896 try { 16897 final XmlSerializer serializer = new FastXmlSerializer(); 16898 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16899 serializer.startDocument(null, true); 16900 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16901 16902 synchronized (mPackages) { 16903 serializeRuntimePermissionGrantsLPr(serializer, userId); 16904 } 16905 16906 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16907 serializer.endDocument(); 16908 serializer.flush(); 16909 } catch (Exception e) { 16910 if (DEBUG_BACKUP) { 16911 Slog.e(TAG, "Unable to write default apps for backup", e); 16912 } 16913 return null; 16914 } 16915 16916 return dataStream.toByteArray(); 16917 } 16918 16919 @Override 16920 public void restorePermissionGrants(byte[] backup, int userId) { 16921 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16922 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16923 } 16924 16925 try { 16926 final XmlPullParser parser = Xml.newPullParser(); 16927 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16928 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16929 new BlobXmlRestorer() { 16930 @Override 16931 public void apply(XmlPullParser parser, int userId) 16932 throws XmlPullParserException, IOException { 16933 synchronized (mPackages) { 16934 processRestoredPermissionGrantsLPr(parser, userId); 16935 } 16936 } 16937 } ); 16938 } catch (Exception e) { 16939 if (DEBUG_BACKUP) { 16940 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16941 } 16942 } 16943 } 16944 16945 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16946 throws IOException { 16947 serializer.startTag(null, TAG_ALL_GRANTS); 16948 16949 final int N = mSettings.mPackages.size(); 16950 for (int i = 0; i < N; i++) { 16951 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16952 boolean pkgGrantsKnown = false; 16953 16954 PermissionsState packagePerms = ps.getPermissionsState(); 16955 16956 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16957 final int grantFlags = state.getFlags(); 16958 // only look at grants that are not system/policy fixed 16959 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16960 final boolean isGranted = state.isGranted(); 16961 // And only back up the user-twiddled state bits 16962 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16963 final String packageName = mSettings.mPackages.keyAt(i); 16964 if (!pkgGrantsKnown) { 16965 serializer.startTag(null, TAG_GRANT); 16966 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16967 pkgGrantsKnown = true; 16968 } 16969 16970 final boolean userSet = 16971 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16972 final boolean userFixed = 16973 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16974 final boolean revoke = 16975 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16976 16977 serializer.startTag(null, TAG_PERMISSION); 16978 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16979 if (isGranted) { 16980 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16981 } 16982 if (userSet) { 16983 serializer.attribute(null, ATTR_USER_SET, "true"); 16984 } 16985 if (userFixed) { 16986 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16987 } 16988 if (revoke) { 16989 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16990 } 16991 serializer.endTag(null, TAG_PERMISSION); 16992 } 16993 } 16994 } 16995 16996 if (pkgGrantsKnown) { 16997 serializer.endTag(null, TAG_GRANT); 16998 } 16999 } 17000 17001 serializer.endTag(null, TAG_ALL_GRANTS); 17002 } 17003 17004 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17005 throws XmlPullParserException, IOException { 17006 String pkgName = null; 17007 int outerDepth = parser.getDepth(); 17008 int type; 17009 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17010 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17011 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17012 continue; 17013 } 17014 17015 final String tagName = parser.getName(); 17016 if (tagName.equals(TAG_GRANT)) { 17017 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17018 if (DEBUG_BACKUP) { 17019 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17020 } 17021 } else if (tagName.equals(TAG_PERMISSION)) { 17022 17023 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17024 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17025 17026 int newFlagSet = 0; 17027 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17028 newFlagSet |= FLAG_PERMISSION_USER_SET; 17029 } 17030 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17031 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17032 } 17033 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17034 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17035 } 17036 if (DEBUG_BACKUP) { 17037 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17038 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17039 } 17040 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17041 if (ps != null) { 17042 // Already installed so we apply the grant immediately 17043 if (DEBUG_BACKUP) { 17044 Slog.v(TAG, " + already installed; applying"); 17045 } 17046 PermissionsState perms = ps.getPermissionsState(); 17047 BasePermission bp = mSettings.mPermissions.get(permName); 17048 if (bp != null) { 17049 if (isGranted) { 17050 perms.grantRuntimePermission(bp, userId); 17051 } 17052 if (newFlagSet != 0) { 17053 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17054 } 17055 } 17056 } else { 17057 // Need to wait for post-restore install to apply the grant 17058 if (DEBUG_BACKUP) { 17059 Slog.v(TAG, " - not yet installed; saving for later"); 17060 } 17061 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17062 isGranted, newFlagSet, userId); 17063 } 17064 } else { 17065 PackageManagerService.reportSettingsProblem(Log.WARN, 17066 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17067 XmlUtils.skipCurrentTag(parser); 17068 } 17069 } 17070 17071 scheduleWriteSettingsLocked(); 17072 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17073 } 17074 17075 @Override 17076 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17077 int sourceUserId, int targetUserId, int flags) { 17078 mContext.enforceCallingOrSelfPermission( 17079 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17080 int callingUid = Binder.getCallingUid(); 17081 enforceOwnerRights(ownerPackage, callingUid); 17082 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17083 if (intentFilter.countActions() == 0) { 17084 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17085 return; 17086 } 17087 synchronized (mPackages) { 17088 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17089 ownerPackage, targetUserId, flags); 17090 CrossProfileIntentResolver resolver = 17091 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17092 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17093 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17094 if (existing != null) { 17095 int size = existing.size(); 17096 for (int i = 0; i < size; i++) { 17097 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17098 return; 17099 } 17100 } 17101 } 17102 resolver.addFilter(newFilter); 17103 scheduleWritePackageRestrictionsLocked(sourceUserId); 17104 } 17105 } 17106 17107 @Override 17108 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17109 mContext.enforceCallingOrSelfPermission( 17110 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17111 int callingUid = Binder.getCallingUid(); 17112 enforceOwnerRights(ownerPackage, callingUid); 17113 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17114 synchronized (mPackages) { 17115 CrossProfileIntentResolver resolver = 17116 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17117 ArraySet<CrossProfileIntentFilter> set = 17118 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17119 for (CrossProfileIntentFilter filter : set) { 17120 if (filter.getOwnerPackage().equals(ownerPackage)) { 17121 resolver.removeFilter(filter); 17122 } 17123 } 17124 scheduleWritePackageRestrictionsLocked(sourceUserId); 17125 } 17126 } 17127 17128 // Enforcing that callingUid is owning pkg on userId 17129 private void enforceOwnerRights(String pkg, int callingUid) { 17130 // The system owns everything. 17131 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17132 return; 17133 } 17134 int callingUserId = UserHandle.getUserId(callingUid); 17135 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17136 if (pi == null) { 17137 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17138 + callingUserId); 17139 } 17140 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17141 throw new SecurityException("Calling uid " + callingUid 17142 + " does not own package " + pkg); 17143 } 17144 } 17145 17146 @Override 17147 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17148 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17149 } 17150 17151 private Intent getHomeIntent() { 17152 Intent intent = new Intent(Intent.ACTION_MAIN); 17153 intent.addCategory(Intent.CATEGORY_HOME); 17154 return intent; 17155 } 17156 17157 private IntentFilter getHomeFilter() { 17158 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17159 filter.addCategory(Intent.CATEGORY_HOME); 17160 filter.addCategory(Intent.CATEGORY_DEFAULT); 17161 return filter; 17162 } 17163 17164 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17165 int userId) { 17166 Intent intent = getHomeIntent(); 17167 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17168 PackageManager.GET_META_DATA, userId); 17169 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17170 true, false, false, userId); 17171 17172 allHomeCandidates.clear(); 17173 if (list != null) { 17174 for (ResolveInfo ri : list) { 17175 allHomeCandidates.add(ri); 17176 } 17177 } 17178 return (preferred == null || preferred.activityInfo == null) 17179 ? null 17180 : new ComponentName(preferred.activityInfo.packageName, 17181 preferred.activityInfo.name); 17182 } 17183 17184 @Override 17185 public void setHomeActivity(ComponentName comp, int userId) { 17186 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17187 getHomeActivitiesAsUser(homeActivities, userId); 17188 17189 boolean found = false; 17190 17191 final int size = homeActivities.size(); 17192 final ComponentName[] set = new ComponentName[size]; 17193 for (int i = 0; i < size; i++) { 17194 final ResolveInfo candidate = homeActivities.get(i); 17195 final ActivityInfo info = candidate.activityInfo; 17196 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17197 set[i] = activityName; 17198 if (!found && activityName.equals(comp)) { 17199 found = true; 17200 } 17201 } 17202 if (!found) { 17203 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17204 + userId); 17205 } 17206 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17207 set, comp, userId); 17208 } 17209 17210 private @Nullable String getSetupWizardPackageName() { 17211 final Intent intent = new Intent(Intent.ACTION_MAIN); 17212 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17213 17214 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17215 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17216 | MATCH_DISABLED_COMPONENTS, 17217 UserHandle.myUserId()); 17218 if (matches.size() == 1) { 17219 return matches.get(0).getComponentInfo().packageName; 17220 } else { 17221 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17222 + ": matches=" + matches); 17223 return null; 17224 } 17225 } 17226 17227 @Override 17228 public void setApplicationEnabledSetting(String appPackageName, 17229 int newState, int flags, int userId, String callingPackage) { 17230 if (!sUserManager.exists(userId)) return; 17231 if (callingPackage == null) { 17232 callingPackage = Integer.toString(Binder.getCallingUid()); 17233 } 17234 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17235 } 17236 17237 @Override 17238 public void setComponentEnabledSetting(ComponentName componentName, 17239 int newState, int flags, int userId) { 17240 if (!sUserManager.exists(userId)) return; 17241 setEnabledSetting(componentName.getPackageName(), 17242 componentName.getClassName(), newState, flags, userId, null); 17243 } 17244 17245 private void setEnabledSetting(final String packageName, String className, int newState, 17246 final int flags, int userId, String callingPackage) { 17247 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17248 || newState == COMPONENT_ENABLED_STATE_ENABLED 17249 || newState == COMPONENT_ENABLED_STATE_DISABLED 17250 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17251 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17252 throw new IllegalArgumentException("Invalid new component state: " 17253 + newState); 17254 } 17255 PackageSetting pkgSetting; 17256 final int uid = Binder.getCallingUid(); 17257 final int permission; 17258 if (uid == Process.SYSTEM_UID) { 17259 permission = PackageManager.PERMISSION_GRANTED; 17260 } else { 17261 permission = mContext.checkCallingOrSelfPermission( 17262 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17263 } 17264 enforceCrossUserPermission(uid, userId, 17265 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17266 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17267 boolean sendNow = false; 17268 boolean isApp = (className == null); 17269 String componentName = isApp ? packageName : className; 17270 int packageUid = -1; 17271 ArrayList<String> components; 17272 17273 // writer 17274 synchronized (mPackages) { 17275 pkgSetting = mSettings.mPackages.get(packageName); 17276 if (pkgSetting == null) { 17277 if (className == null) { 17278 throw new IllegalArgumentException("Unknown package: " + packageName); 17279 } 17280 throw new IllegalArgumentException( 17281 "Unknown component: " + packageName + "/" + className); 17282 } 17283 // Allow root and verify that userId is not being specified by a different user 17284 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17285 throw new SecurityException( 17286 "Permission Denial: attempt to change component state from pid=" 17287 + Binder.getCallingPid() 17288 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17289 } 17290 if (className == null) { 17291 // We're dealing with an application/package level state change 17292 if (pkgSetting.getEnabled(userId) == newState) { 17293 // Nothing to do 17294 return; 17295 } 17296 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17297 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17298 // Don't care about who enables an app. 17299 callingPackage = null; 17300 } 17301 pkgSetting.setEnabled(newState, userId, callingPackage); 17302 // pkgSetting.pkg.mSetEnabled = newState; 17303 } else { 17304 // We're dealing with a component level state change 17305 // First, verify that this is a valid class name. 17306 PackageParser.Package pkg = pkgSetting.pkg; 17307 if (pkg == null || !pkg.hasComponentClassName(className)) { 17308 if (pkg != null && 17309 pkg.applicationInfo.targetSdkVersion >= 17310 Build.VERSION_CODES.JELLY_BEAN) { 17311 throw new IllegalArgumentException("Component class " + className 17312 + " does not exist in " + packageName); 17313 } else { 17314 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17315 + className + " does not exist in " + packageName); 17316 } 17317 } 17318 switch (newState) { 17319 case COMPONENT_ENABLED_STATE_ENABLED: 17320 if (!pkgSetting.enableComponentLPw(className, userId)) { 17321 return; 17322 } 17323 break; 17324 case COMPONENT_ENABLED_STATE_DISABLED: 17325 if (!pkgSetting.disableComponentLPw(className, userId)) { 17326 return; 17327 } 17328 break; 17329 case COMPONENT_ENABLED_STATE_DEFAULT: 17330 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17331 return; 17332 } 17333 break; 17334 default: 17335 Slog.e(TAG, "Invalid new component state: " + newState); 17336 return; 17337 } 17338 } 17339 scheduleWritePackageRestrictionsLocked(userId); 17340 components = mPendingBroadcasts.get(userId, packageName); 17341 final boolean newPackage = components == null; 17342 if (newPackage) { 17343 components = new ArrayList<String>(); 17344 } 17345 if (!components.contains(componentName)) { 17346 components.add(componentName); 17347 } 17348 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17349 sendNow = true; 17350 // Purge entry from pending broadcast list if another one exists already 17351 // since we are sending one right away. 17352 mPendingBroadcasts.remove(userId, packageName); 17353 } else { 17354 if (newPackage) { 17355 mPendingBroadcasts.put(userId, packageName, components); 17356 } 17357 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17358 // Schedule a message 17359 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17360 } 17361 } 17362 } 17363 17364 long callingId = Binder.clearCallingIdentity(); 17365 try { 17366 if (sendNow) { 17367 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17368 sendPackageChangedBroadcast(packageName, 17369 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17370 } 17371 } finally { 17372 Binder.restoreCallingIdentity(callingId); 17373 } 17374 } 17375 17376 @Override 17377 public void flushPackageRestrictionsAsUser(int userId) { 17378 if (!sUserManager.exists(userId)) { 17379 return; 17380 } 17381 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17382 false /* checkShell */, "flushPackageRestrictions"); 17383 synchronized (mPackages) { 17384 mSettings.writePackageRestrictionsLPr(userId); 17385 mDirtyUsers.remove(userId); 17386 if (mDirtyUsers.isEmpty()) { 17387 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17388 } 17389 } 17390 } 17391 17392 private void sendPackageChangedBroadcast(String packageName, 17393 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17394 if (DEBUG_INSTALL) 17395 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17396 + componentNames); 17397 Bundle extras = new Bundle(4); 17398 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17399 String nameList[] = new String[componentNames.size()]; 17400 componentNames.toArray(nameList); 17401 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17402 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17403 extras.putInt(Intent.EXTRA_UID, packageUid); 17404 // If this is not reporting a change of the overall package, then only send it 17405 // to registered receivers. We don't want to launch a swath of apps for every 17406 // little component state change. 17407 final int flags = !componentNames.contains(packageName) 17408 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17409 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17410 new int[] {UserHandle.getUserId(packageUid)}); 17411 } 17412 17413 @Override 17414 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17415 if (!sUserManager.exists(userId)) return; 17416 final int uid = Binder.getCallingUid(); 17417 final int permission = mContext.checkCallingOrSelfPermission( 17418 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17419 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17420 enforceCrossUserPermission(uid, userId, 17421 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17422 // writer 17423 synchronized (mPackages) { 17424 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17425 allowedByPermission, uid, userId)) { 17426 scheduleWritePackageRestrictionsLocked(userId); 17427 } 17428 } 17429 } 17430 17431 @Override 17432 public String getInstallerPackageName(String packageName) { 17433 // reader 17434 synchronized (mPackages) { 17435 return mSettings.getInstallerPackageNameLPr(packageName); 17436 } 17437 } 17438 17439 @Override 17440 public int getApplicationEnabledSetting(String packageName, int userId) { 17441 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17442 int uid = Binder.getCallingUid(); 17443 enforceCrossUserPermission(uid, userId, 17444 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17445 // reader 17446 synchronized (mPackages) { 17447 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17448 } 17449 } 17450 17451 @Override 17452 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17453 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17454 int uid = Binder.getCallingUid(); 17455 enforceCrossUserPermission(uid, userId, 17456 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17457 // reader 17458 synchronized (mPackages) { 17459 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17460 } 17461 } 17462 17463 @Override 17464 public void enterSafeMode() { 17465 enforceSystemOrRoot("Only the system can request entering safe mode"); 17466 17467 if (!mSystemReady) { 17468 mSafeMode = true; 17469 } 17470 } 17471 17472 @Override 17473 public void systemReady() { 17474 mSystemReady = true; 17475 17476 // Read the compatibilty setting when the system is ready. 17477 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17478 mContext.getContentResolver(), 17479 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17480 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17481 if (DEBUG_SETTINGS) { 17482 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17483 } 17484 17485 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17486 17487 synchronized (mPackages) { 17488 // Verify that all of the preferred activity components actually 17489 // exist. It is possible for applications to be updated and at 17490 // that point remove a previously declared activity component that 17491 // had been set as a preferred activity. We try to clean this up 17492 // the next time we encounter that preferred activity, but it is 17493 // possible for the user flow to never be able to return to that 17494 // situation so here we do a sanity check to make sure we haven't 17495 // left any junk around. 17496 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17497 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17498 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17499 removed.clear(); 17500 for (PreferredActivity pa : pir.filterSet()) { 17501 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17502 removed.add(pa); 17503 } 17504 } 17505 if (removed.size() > 0) { 17506 for (int r=0; r<removed.size(); r++) { 17507 PreferredActivity pa = removed.get(r); 17508 Slog.w(TAG, "Removing dangling preferred activity: " 17509 + pa.mPref.mComponent); 17510 pir.removeFilter(pa); 17511 } 17512 mSettings.writePackageRestrictionsLPr( 17513 mSettings.mPreferredActivities.keyAt(i)); 17514 } 17515 } 17516 17517 for (int userId : UserManagerService.getInstance().getUserIds()) { 17518 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17519 grantPermissionsUserIds = ArrayUtils.appendInt( 17520 grantPermissionsUserIds, userId); 17521 } 17522 } 17523 } 17524 sUserManager.systemReady(); 17525 17526 // If we upgraded grant all default permissions before kicking off. 17527 for (int userId : grantPermissionsUserIds) { 17528 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17529 } 17530 17531 // Kick off any messages waiting for system ready 17532 if (mPostSystemReadyMessages != null) { 17533 for (Message msg : mPostSystemReadyMessages) { 17534 msg.sendToTarget(); 17535 } 17536 mPostSystemReadyMessages = null; 17537 } 17538 17539 // Watch for external volumes that come and go over time 17540 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17541 storage.registerListener(mStorageListener); 17542 17543 mInstallerService.systemReady(); 17544 mPackageDexOptimizer.systemReady(); 17545 17546 MountServiceInternal mountServiceInternal = LocalServices.getService( 17547 MountServiceInternal.class); 17548 mountServiceInternal.addExternalStoragePolicy( 17549 new MountServiceInternal.ExternalStorageMountPolicy() { 17550 @Override 17551 public int getMountMode(int uid, String packageName) { 17552 if (Process.isIsolated(uid)) { 17553 return Zygote.MOUNT_EXTERNAL_NONE; 17554 } 17555 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17556 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17557 } 17558 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17559 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17560 } 17561 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17562 return Zygote.MOUNT_EXTERNAL_READ; 17563 } 17564 return Zygote.MOUNT_EXTERNAL_WRITE; 17565 } 17566 17567 @Override 17568 public boolean hasExternalStorage(int uid, String packageName) { 17569 return true; 17570 } 17571 }); 17572 17573 // Now that we're mostly running, clean up stale users and apps 17574 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17575 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17576 } 17577 17578 @Override 17579 public boolean isSafeMode() { 17580 return mSafeMode; 17581 } 17582 17583 @Override 17584 public boolean hasSystemUidErrors() { 17585 return mHasSystemUidErrors; 17586 } 17587 17588 static String arrayToString(int[] array) { 17589 StringBuffer buf = new StringBuffer(128); 17590 buf.append('['); 17591 if (array != null) { 17592 for (int i=0; i<array.length; i++) { 17593 if (i > 0) buf.append(", "); 17594 buf.append(array[i]); 17595 } 17596 } 17597 buf.append(']'); 17598 return buf.toString(); 17599 } 17600 17601 static class DumpState { 17602 public static final int DUMP_LIBS = 1 << 0; 17603 public static final int DUMP_FEATURES = 1 << 1; 17604 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17605 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17606 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17607 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17608 public static final int DUMP_PERMISSIONS = 1 << 6; 17609 public static final int DUMP_PACKAGES = 1 << 7; 17610 public static final int DUMP_SHARED_USERS = 1 << 8; 17611 public static final int DUMP_MESSAGES = 1 << 9; 17612 public static final int DUMP_PROVIDERS = 1 << 10; 17613 public static final int DUMP_VERIFIERS = 1 << 11; 17614 public static final int DUMP_PREFERRED = 1 << 12; 17615 public static final int DUMP_PREFERRED_XML = 1 << 13; 17616 public static final int DUMP_KEYSETS = 1 << 14; 17617 public static final int DUMP_VERSION = 1 << 15; 17618 public static final int DUMP_INSTALLS = 1 << 16; 17619 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17620 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17621 public static final int DUMP_FROZEN = 1 << 19; 17622 17623 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17624 17625 private int mTypes; 17626 17627 private int mOptions; 17628 17629 private boolean mTitlePrinted; 17630 17631 private SharedUserSetting mSharedUser; 17632 17633 public boolean isDumping(int type) { 17634 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17635 return true; 17636 } 17637 17638 return (mTypes & type) != 0; 17639 } 17640 17641 public void setDump(int type) { 17642 mTypes |= type; 17643 } 17644 17645 public boolean isOptionEnabled(int option) { 17646 return (mOptions & option) != 0; 17647 } 17648 17649 public void setOptionEnabled(int option) { 17650 mOptions |= option; 17651 } 17652 17653 public boolean onTitlePrinted() { 17654 final boolean printed = mTitlePrinted; 17655 mTitlePrinted = true; 17656 return printed; 17657 } 17658 17659 public boolean getTitlePrinted() { 17660 return mTitlePrinted; 17661 } 17662 17663 public void setTitlePrinted(boolean enabled) { 17664 mTitlePrinted = enabled; 17665 } 17666 17667 public SharedUserSetting getSharedUser() { 17668 return mSharedUser; 17669 } 17670 17671 public void setSharedUser(SharedUserSetting user) { 17672 mSharedUser = user; 17673 } 17674 } 17675 17676 @Override 17677 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17678 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17679 (new PackageManagerShellCommand(this)).exec( 17680 this, in, out, err, args, resultReceiver); 17681 } 17682 17683 @Override 17684 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17685 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17686 != PackageManager.PERMISSION_GRANTED) { 17687 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17688 + Binder.getCallingPid() 17689 + ", uid=" + Binder.getCallingUid() 17690 + " without permission " 17691 + android.Manifest.permission.DUMP); 17692 return; 17693 } 17694 17695 DumpState dumpState = new DumpState(); 17696 boolean fullPreferred = false; 17697 boolean checkin = false; 17698 17699 String packageName = null; 17700 ArraySet<String> permissionNames = null; 17701 17702 int opti = 0; 17703 while (opti < args.length) { 17704 String opt = args[opti]; 17705 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17706 break; 17707 } 17708 opti++; 17709 17710 if ("-a".equals(opt)) { 17711 // Right now we only know how to print all. 17712 } else if ("-h".equals(opt)) { 17713 pw.println("Package manager dump options:"); 17714 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17715 pw.println(" --checkin: dump for a checkin"); 17716 pw.println(" -f: print details of intent filters"); 17717 pw.println(" -h: print this help"); 17718 pw.println(" cmd may be one of:"); 17719 pw.println(" l[ibraries]: list known shared libraries"); 17720 pw.println(" f[eatures]: list device features"); 17721 pw.println(" k[eysets]: print known keysets"); 17722 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17723 pw.println(" perm[issions]: dump permissions"); 17724 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17725 pw.println(" pref[erred]: print preferred package settings"); 17726 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17727 pw.println(" prov[iders]: dump content providers"); 17728 pw.println(" p[ackages]: dump installed packages"); 17729 pw.println(" s[hared-users]: dump shared user IDs"); 17730 pw.println(" m[essages]: print collected runtime messages"); 17731 pw.println(" v[erifiers]: print package verifier info"); 17732 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17733 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17734 pw.println(" version: print database version info"); 17735 pw.println(" write: write current settings now"); 17736 pw.println(" installs: details about install sessions"); 17737 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17738 pw.println(" <package.name>: info about given package"); 17739 return; 17740 } else if ("--checkin".equals(opt)) { 17741 checkin = true; 17742 } else if ("-f".equals(opt)) { 17743 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17744 } else { 17745 pw.println("Unknown argument: " + opt + "; use -h for help"); 17746 } 17747 } 17748 17749 // Is the caller requesting to dump a particular piece of data? 17750 if (opti < args.length) { 17751 String cmd = args[opti]; 17752 opti++; 17753 // Is this a package name? 17754 if ("android".equals(cmd) || cmd.contains(".")) { 17755 packageName = cmd; 17756 // When dumping a single package, we always dump all of its 17757 // filter information since the amount of data will be reasonable. 17758 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17759 } else if ("check-permission".equals(cmd)) { 17760 if (opti >= args.length) { 17761 pw.println("Error: check-permission missing permission argument"); 17762 return; 17763 } 17764 String perm = args[opti]; 17765 opti++; 17766 if (opti >= args.length) { 17767 pw.println("Error: check-permission missing package argument"); 17768 return; 17769 } 17770 String pkg = args[opti]; 17771 opti++; 17772 int user = UserHandle.getUserId(Binder.getCallingUid()); 17773 if (opti < args.length) { 17774 try { 17775 user = Integer.parseInt(args[opti]); 17776 } catch (NumberFormatException e) { 17777 pw.println("Error: check-permission user argument is not a number: " 17778 + args[opti]); 17779 return; 17780 } 17781 } 17782 pw.println(checkPermission(perm, pkg, user)); 17783 return; 17784 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17785 dumpState.setDump(DumpState.DUMP_LIBS); 17786 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17787 dumpState.setDump(DumpState.DUMP_FEATURES); 17788 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17789 if (opti >= args.length) { 17790 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17791 | DumpState.DUMP_SERVICE_RESOLVERS 17792 | DumpState.DUMP_RECEIVER_RESOLVERS 17793 | DumpState.DUMP_CONTENT_RESOLVERS); 17794 } else { 17795 while (opti < args.length) { 17796 String name = args[opti]; 17797 if ("a".equals(name) || "activity".equals(name)) { 17798 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17799 } else if ("s".equals(name) || "service".equals(name)) { 17800 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17801 } else if ("r".equals(name) || "receiver".equals(name)) { 17802 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17803 } else if ("c".equals(name) || "content".equals(name)) { 17804 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17805 } else { 17806 pw.println("Error: unknown resolver table type: " + name); 17807 return; 17808 } 17809 opti++; 17810 } 17811 } 17812 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17813 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17814 } else if ("permission".equals(cmd)) { 17815 if (opti >= args.length) { 17816 pw.println("Error: permission requires permission name"); 17817 return; 17818 } 17819 permissionNames = new ArraySet<>(); 17820 while (opti < args.length) { 17821 permissionNames.add(args[opti]); 17822 opti++; 17823 } 17824 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17825 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17826 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17827 dumpState.setDump(DumpState.DUMP_PREFERRED); 17828 } else if ("preferred-xml".equals(cmd)) { 17829 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17830 if (opti < args.length && "--full".equals(args[opti])) { 17831 fullPreferred = true; 17832 opti++; 17833 } 17834 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17835 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17836 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17837 dumpState.setDump(DumpState.DUMP_PACKAGES); 17838 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17839 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17840 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17841 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17842 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17843 dumpState.setDump(DumpState.DUMP_MESSAGES); 17844 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17845 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17846 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17847 || "intent-filter-verifiers".equals(cmd)) { 17848 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17849 } else if ("version".equals(cmd)) { 17850 dumpState.setDump(DumpState.DUMP_VERSION); 17851 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17852 dumpState.setDump(DumpState.DUMP_KEYSETS); 17853 } else if ("installs".equals(cmd)) { 17854 dumpState.setDump(DumpState.DUMP_INSTALLS); 17855 } else if ("frozen".equals(cmd)) { 17856 dumpState.setDump(DumpState.DUMP_FROZEN); 17857 } else if ("write".equals(cmd)) { 17858 synchronized (mPackages) { 17859 mSettings.writeLPr(); 17860 pw.println("Settings written."); 17861 return; 17862 } 17863 } 17864 } 17865 17866 if (checkin) { 17867 pw.println("vers,1"); 17868 } 17869 17870 // reader 17871 synchronized (mPackages) { 17872 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17873 if (!checkin) { 17874 if (dumpState.onTitlePrinted()) 17875 pw.println(); 17876 pw.println("Database versions:"); 17877 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17878 } 17879 } 17880 17881 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17882 if (!checkin) { 17883 if (dumpState.onTitlePrinted()) 17884 pw.println(); 17885 pw.println("Verifiers:"); 17886 pw.print(" Required: "); 17887 pw.print(mRequiredVerifierPackage); 17888 pw.print(" (uid="); 17889 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17890 UserHandle.USER_SYSTEM)); 17891 pw.println(")"); 17892 } else if (mRequiredVerifierPackage != null) { 17893 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17894 pw.print(","); 17895 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17896 UserHandle.USER_SYSTEM)); 17897 } 17898 } 17899 17900 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17901 packageName == null) { 17902 if (mIntentFilterVerifierComponent != null) { 17903 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17904 if (!checkin) { 17905 if (dumpState.onTitlePrinted()) 17906 pw.println(); 17907 pw.println("Intent Filter Verifier:"); 17908 pw.print(" Using: "); 17909 pw.print(verifierPackageName); 17910 pw.print(" (uid="); 17911 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17912 UserHandle.USER_SYSTEM)); 17913 pw.println(")"); 17914 } else if (verifierPackageName != null) { 17915 pw.print("ifv,"); pw.print(verifierPackageName); 17916 pw.print(","); 17917 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17918 UserHandle.USER_SYSTEM)); 17919 } 17920 } else { 17921 pw.println(); 17922 pw.println("No Intent Filter Verifier available!"); 17923 } 17924 } 17925 17926 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17927 boolean printedHeader = false; 17928 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17929 while (it.hasNext()) { 17930 String name = it.next(); 17931 SharedLibraryEntry ent = mSharedLibraries.get(name); 17932 if (!checkin) { 17933 if (!printedHeader) { 17934 if (dumpState.onTitlePrinted()) 17935 pw.println(); 17936 pw.println("Libraries:"); 17937 printedHeader = true; 17938 } 17939 pw.print(" "); 17940 } else { 17941 pw.print("lib,"); 17942 } 17943 pw.print(name); 17944 if (!checkin) { 17945 pw.print(" -> "); 17946 } 17947 if (ent.path != null) { 17948 if (!checkin) { 17949 pw.print("(jar) "); 17950 pw.print(ent.path); 17951 } else { 17952 pw.print(",jar,"); 17953 pw.print(ent.path); 17954 } 17955 } else { 17956 if (!checkin) { 17957 pw.print("(apk) "); 17958 pw.print(ent.apk); 17959 } else { 17960 pw.print(",apk,"); 17961 pw.print(ent.apk); 17962 } 17963 } 17964 pw.println(); 17965 } 17966 } 17967 17968 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17969 if (dumpState.onTitlePrinted()) 17970 pw.println(); 17971 if (!checkin) { 17972 pw.println("Features:"); 17973 } 17974 17975 for (FeatureInfo feat : mAvailableFeatures.values()) { 17976 if (checkin) { 17977 pw.print("feat,"); 17978 pw.print(feat.name); 17979 pw.print(","); 17980 pw.println(feat.version); 17981 } else { 17982 pw.print(" "); 17983 pw.print(feat.name); 17984 if (feat.version > 0) { 17985 pw.print(" version="); 17986 pw.print(feat.version); 17987 } 17988 pw.println(); 17989 } 17990 } 17991 } 17992 17993 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17994 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17995 : "Activity Resolver Table:", " ", packageName, 17996 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17997 dumpState.setTitlePrinted(true); 17998 } 17999 } 18000 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18001 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18002 : "Receiver Resolver Table:", " ", packageName, 18003 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18004 dumpState.setTitlePrinted(true); 18005 } 18006 } 18007 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18008 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18009 : "Service Resolver Table:", " ", packageName, 18010 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18011 dumpState.setTitlePrinted(true); 18012 } 18013 } 18014 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18015 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18016 : "Provider Resolver Table:", " ", packageName, 18017 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18018 dumpState.setTitlePrinted(true); 18019 } 18020 } 18021 18022 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18023 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18024 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18025 int user = mSettings.mPreferredActivities.keyAt(i); 18026 if (pir.dump(pw, 18027 dumpState.getTitlePrinted() 18028 ? "\nPreferred Activities User " + user + ":" 18029 : "Preferred Activities User " + user + ":", " ", 18030 packageName, true, false)) { 18031 dumpState.setTitlePrinted(true); 18032 } 18033 } 18034 } 18035 18036 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18037 pw.flush(); 18038 FileOutputStream fout = new FileOutputStream(fd); 18039 BufferedOutputStream str = new BufferedOutputStream(fout); 18040 XmlSerializer serializer = new FastXmlSerializer(); 18041 try { 18042 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18043 serializer.startDocument(null, true); 18044 serializer.setFeature( 18045 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18046 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18047 serializer.endDocument(); 18048 serializer.flush(); 18049 } catch (IllegalArgumentException e) { 18050 pw.println("Failed writing: " + e); 18051 } catch (IllegalStateException e) { 18052 pw.println("Failed writing: " + e); 18053 } catch (IOException e) { 18054 pw.println("Failed writing: " + e); 18055 } 18056 } 18057 18058 if (!checkin 18059 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18060 && packageName == null) { 18061 pw.println(); 18062 int count = mSettings.mPackages.size(); 18063 if (count == 0) { 18064 pw.println("No applications!"); 18065 pw.println(); 18066 } else { 18067 final String prefix = " "; 18068 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18069 if (allPackageSettings.size() == 0) { 18070 pw.println("No domain preferred apps!"); 18071 pw.println(); 18072 } else { 18073 pw.println("App verification status:"); 18074 pw.println(); 18075 count = 0; 18076 for (PackageSetting ps : allPackageSettings) { 18077 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18078 if (ivi == null || ivi.getPackageName() == null) continue; 18079 pw.println(prefix + "Package: " + ivi.getPackageName()); 18080 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18081 pw.println(prefix + "Status: " + ivi.getStatusString()); 18082 pw.println(); 18083 count++; 18084 } 18085 if (count == 0) { 18086 pw.println(prefix + "No app verification established."); 18087 pw.println(); 18088 } 18089 for (int userId : sUserManager.getUserIds()) { 18090 pw.println("App linkages for user " + userId + ":"); 18091 pw.println(); 18092 count = 0; 18093 for (PackageSetting ps : allPackageSettings) { 18094 final long status = ps.getDomainVerificationStatusForUser(userId); 18095 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18096 continue; 18097 } 18098 pw.println(prefix + "Package: " + ps.name); 18099 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18100 String statusStr = IntentFilterVerificationInfo. 18101 getStatusStringFromValue(status); 18102 pw.println(prefix + "Status: " + statusStr); 18103 pw.println(); 18104 count++; 18105 } 18106 if (count == 0) { 18107 pw.println(prefix + "No configured app linkages."); 18108 pw.println(); 18109 } 18110 } 18111 } 18112 } 18113 } 18114 18115 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18116 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18117 if (packageName == null && permissionNames == null) { 18118 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18119 if (iperm == 0) { 18120 if (dumpState.onTitlePrinted()) 18121 pw.println(); 18122 pw.println("AppOp Permissions:"); 18123 } 18124 pw.print(" AppOp Permission "); 18125 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18126 pw.println(":"); 18127 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18128 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18129 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18130 } 18131 } 18132 } 18133 } 18134 18135 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18136 boolean printedSomething = false; 18137 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18138 if (packageName != null && !packageName.equals(p.info.packageName)) { 18139 continue; 18140 } 18141 if (!printedSomething) { 18142 if (dumpState.onTitlePrinted()) 18143 pw.println(); 18144 pw.println("Registered ContentProviders:"); 18145 printedSomething = true; 18146 } 18147 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18148 pw.print(" "); pw.println(p.toString()); 18149 } 18150 printedSomething = false; 18151 for (Map.Entry<String, PackageParser.Provider> entry : 18152 mProvidersByAuthority.entrySet()) { 18153 PackageParser.Provider p = entry.getValue(); 18154 if (packageName != null && !packageName.equals(p.info.packageName)) { 18155 continue; 18156 } 18157 if (!printedSomething) { 18158 if (dumpState.onTitlePrinted()) 18159 pw.println(); 18160 pw.println("ContentProvider Authorities:"); 18161 printedSomething = true; 18162 } 18163 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18164 pw.print(" "); pw.println(p.toString()); 18165 if (p.info != null && p.info.applicationInfo != null) { 18166 final String appInfo = p.info.applicationInfo.toString(); 18167 pw.print(" applicationInfo="); pw.println(appInfo); 18168 } 18169 } 18170 } 18171 18172 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18173 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18174 } 18175 18176 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18177 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18178 } 18179 18180 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18181 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18182 } 18183 18184 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18185 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18186 } 18187 18188 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18189 // XXX should handle packageName != null by dumping only install data that 18190 // the given package is involved with. 18191 if (dumpState.onTitlePrinted()) pw.println(); 18192 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18193 } 18194 18195 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18196 // XXX should handle packageName != null by dumping only install data that 18197 // the given package is involved with. 18198 if (dumpState.onTitlePrinted()) pw.println(); 18199 18200 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18201 ipw.println(); 18202 ipw.println("Frozen packages:"); 18203 ipw.increaseIndent(); 18204 if (mFrozenPackages.size() == 0) { 18205 ipw.println("(none)"); 18206 } else { 18207 for (int i = 0; i < mFrozenPackages.size(); i++) { 18208 ipw.println(mFrozenPackages.valueAt(i)); 18209 } 18210 } 18211 ipw.decreaseIndent(); 18212 } 18213 18214 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18215 if (dumpState.onTitlePrinted()) pw.println(); 18216 mSettings.dumpReadMessagesLPr(pw, dumpState); 18217 18218 pw.println(); 18219 pw.println("Package warning messages:"); 18220 BufferedReader in = null; 18221 String line = null; 18222 try { 18223 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18224 while ((line = in.readLine()) != null) { 18225 if (line.contains("ignored: updated version")) continue; 18226 pw.println(line); 18227 } 18228 } catch (IOException ignored) { 18229 } finally { 18230 IoUtils.closeQuietly(in); 18231 } 18232 } 18233 18234 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18235 BufferedReader in = null; 18236 String line = null; 18237 try { 18238 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18239 while ((line = in.readLine()) != null) { 18240 if (line.contains("ignored: updated version")) continue; 18241 pw.print("msg,"); 18242 pw.println(line); 18243 } 18244 } catch (IOException ignored) { 18245 } finally { 18246 IoUtils.closeQuietly(in); 18247 } 18248 } 18249 } 18250 } 18251 18252 private String dumpDomainString(String packageName) { 18253 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18254 .getList(); 18255 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18256 18257 ArraySet<String> result = new ArraySet<>(); 18258 if (iviList.size() > 0) { 18259 for (IntentFilterVerificationInfo ivi : iviList) { 18260 for (String host : ivi.getDomains()) { 18261 result.add(host); 18262 } 18263 } 18264 } 18265 if (filters != null && filters.size() > 0) { 18266 for (IntentFilter filter : filters) { 18267 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18268 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18269 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18270 result.addAll(filter.getHostsList()); 18271 } 18272 } 18273 } 18274 18275 StringBuilder sb = new StringBuilder(result.size() * 16); 18276 for (String domain : result) { 18277 if (sb.length() > 0) sb.append(" "); 18278 sb.append(domain); 18279 } 18280 return sb.toString(); 18281 } 18282 18283 // ------- apps on sdcard specific code ------- 18284 static final boolean DEBUG_SD_INSTALL = false; 18285 18286 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18287 18288 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18289 18290 private boolean mMediaMounted = false; 18291 18292 static String getEncryptKey() { 18293 try { 18294 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18295 SD_ENCRYPTION_KEYSTORE_NAME); 18296 if (sdEncKey == null) { 18297 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18298 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18299 if (sdEncKey == null) { 18300 Slog.e(TAG, "Failed to create encryption keys"); 18301 return null; 18302 } 18303 } 18304 return sdEncKey; 18305 } catch (NoSuchAlgorithmException nsae) { 18306 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18307 return null; 18308 } catch (IOException ioe) { 18309 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18310 return null; 18311 } 18312 } 18313 18314 /* 18315 * Update media status on PackageManager. 18316 */ 18317 @Override 18318 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18319 int callingUid = Binder.getCallingUid(); 18320 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18321 throw new SecurityException("Media status can only be updated by the system"); 18322 } 18323 // reader; this apparently protects mMediaMounted, but should probably 18324 // be a different lock in that case. 18325 synchronized (mPackages) { 18326 Log.i(TAG, "Updating external media status from " 18327 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18328 + (mediaStatus ? "mounted" : "unmounted")); 18329 if (DEBUG_SD_INSTALL) 18330 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18331 + ", mMediaMounted=" + mMediaMounted); 18332 if (mediaStatus == mMediaMounted) { 18333 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18334 : 0, -1); 18335 mHandler.sendMessage(msg); 18336 return; 18337 } 18338 mMediaMounted = mediaStatus; 18339 } 18340 // Queue up an async operation since the package installation may take a 18341 // little while. 18342 mHandler.post(new Runnable() { 18343 public void run() { 18344 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18345 } 18346 }); 18347 } 18348 18349 /** 18350 * Called by MountService when the initial ASECs to scan are available. 18351 * Should block until all the ASEC containers are finished being scanned. 18352 */ 18353 public void scanAvailableAsecs() { 18354 updateExternalMediaStatusInner(true, false, false); 18355 } 18356 18357 /* 18358 * Collect information of applications on external media, map them against 18359 * existing containers and update information based on current mount status. 18360 * Please note that we always have to report status if reportStatus has been 18361 * set to true especially when unloading packages. 18362 */ 18363 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18364 boolean externalStorage) { 18365 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18366 int[] uidArr = EmptyArray.INT; 18367 18368 final String[] list = PackageHelper.getSecureContainerList(); 18369 if (ArrayUtils.isEmpty(list)) { 18370 Log.i(TAG, "No secure containers found"); 18371 } else { 18372 // Process list of secure containers and categorize them 18373 // as active or stale based on their package internal state. 18374 18375 // reader 18376 synchronized (mPackages) { 18377 for (String cid : list) { 18378 // Leave stages untouched for now; installer service owns them 18379 if (PackageInstallerService.isStageName(cid)) continue; 18380 18381 if (DEBUG_SD_INSTALL) 18382 Log.i(TAG, "Processing container " + cid); 18383 String pkgName = getAsecPackageName(cid); 18384 if (pkgName == null) { 18385 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18386 continue; 18387 } 18388 if (DEBUG_SD_INSTALL) 18389 Log.i(TAG, "Looking for pkg : " + pkgName); 18390 18391 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18392 if (ps == null) { 18393 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18394 continue; 18395 } 18396 18397 /* 18398 * Skip packages that are not external if we're unmounting 18399 * external storage. 18400 */ 18401 if (externalStorage && !isMounted && !isExternal(ps)) { 18402 continue; 18403 } 18404 18405 final AsecInstallArgs args = new AsecInstallArgs(cid, 18406 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18407 // The package status is changed only if the code path 18408 // matches between settings and the container id. 18409 if (ps.codePathString != null 18410 && ps.codePathString.startsWith(args.getCodePath())) { 18411 if (DEBUG_SD_INSTALL) { 18412 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18413 + " at code path: " + ps.codePathString); 18414 } 18415 18416 // We do have a valid package installed on sdcard 18417 processCids.put(args, ps.codePathString); 18418 final int uid = ps.appId; 18419 if (uid != -1) { 18420 uidArr = ArrayUtils.appendInt(uidArr, uid); 18421 } 18422 } else { 18423 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18424 + ps.codePathString); 18425 } 18426 } 18427 } 18428 18429 Arrays.sort(uidArr); 18430 } 18431 18432 // Process packages with valid entries. 18433 if (isMounted) { 18434 if (DEBUG_SD_INSTALL) 18435 Log.i(TAG, "Loading packages"); 18436 loadMediaPackages(processCids, uidArr, externalStorage); 18437 startCleaningPackages(); 18438 mInstallerService.onSecureContainersAvailable(); 18439 } else { 18440 if (DEBUG_SD_INSTALL) 18441 Log.i(TAG, "Unloading packages"); 18442 unloadMediaPackages(processCids, uidArr, reportStatus); 18443 } 18444 } 18445 18446 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18447 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18448 final int size = infos.size(); 18449 final String[] packageNames = new String[size]; 18450 final int[] packageUids = new int[size]; 18451 for (int i = 0; i < size; i++) { 18452 final ApplicationInfo info = infos.get(i); 18453 packageNames[i] = info.packageName; 18454 packageUids[i] = info.uid; 18455 } 18456 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18457 finishedReceiver); 18458 } 18459 18460 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18461 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18462 sendResourcesChangedBroadcast(mediaStatus, replacing, 18463 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18464 } 18465 18466 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18467 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18468 int size = pkgList.length; 18469 if (size > 0) { 18470 // Send broadcasts here 18471 Bundle extras = new Bundle(); 18472 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18473 if (uidArr != null) { 18474 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18475 } 18476 if (replacing) { 18477 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18478 } 18479 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18480 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18481 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18482 } 18483 } 18484 18485 /* 18486 * Look at potentially valid container ids from processCids If package 18487 * information doesn't match the one on record or package scanning fails, 18488 * the cid is added to list of removeCids. We currently don't delete stale 18489 * containers. 18490 */ 18491 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18492 boolean externalStorage) { 18493 ArrayList<String> pkgList = new ArrayList<String>(); 18494 Set<AsecInstallArgs> keys = processCids.keySet(); 18495 18496 for (AsecInstallArgs args : keys) { 18497 String codePath = processCids.get(args); 18498 if (DEBUG_SD_INSTALL) 18499 Log.i(TAG, "Loading container : " + args.cid); 18500 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18501 try { 18502 // Make sure there are no container errors first. 18503 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18504 Slog.e(TAG, "Failed to mount cid : " + args.cid 18505 + " when installing from sdcard"); 18506 continue; 18507 } 18508 // Check code path here. 18509 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18510 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18511 + " does not match one in settings " + codePath); 18512 continue; 18513 } 18514 // Parse package 18515 int parseFlags = mDefParseFlags; 18516 if (args.isExternalAsec()) { 18517 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18518 } 18519 if (args.isFwdLocked()) { 18520 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18521 } 18522 18523 synchronized (mInstallLock) { 18524 PackageParser.Package pkg = null; 18525 try { 18526 // Sadly we don't know the package name yet to freeze it 18527 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18528 SCAN_IGNORE_FROZEN, 0, null); 18529 } catch (PackageManagerException e) { 18530 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18531 } 18532 // Scan the package 18533 if (pkg != null) { 18534 /* 18535 * TODO why is the lock being held? doPostInstall is 18536 * called in other places without the lock. This needs 18537 * to be straightened out. 18538 */ 18539 // writer 18540 synchronized (mPackages) { 18541 retCode = PackageManager.INSTALL_SUCCEEDED; 18542 pkgList.add(pkg.packageName); 18543 // Post process args 18544 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18545 pkg.applicationInfo.uid); 18546 } 18547 } else { 18548 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18549 } 18550 } 18551 18552 } finally { 18553 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18554 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18555 } 18556 } 18557 } 18558 // writer 18559 synchronized (mPackages) { 18560 // If the platform SDK has changed since the last time we booted, 18561 // we need to re-grant app permission to catch any new ones that 18562 // appear. This is really a hack, and means that apps can in some 18563 // cases get permissions that the user didn't initially explicitly 18564 // allow... it would be nice to have some better way to handle 18565 // this situation. 18566 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18567 : mSettings.getInternalVersion(); 18568 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18569 : StorageManager.UUID_PRIVATE_INTERNAL; 18570 18571 int updateFlags = UPDATE_PERMISSIONS_ALL; 18572 if (ver.sdkVersion != mSdkVersion) { 18573 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18574 + mSdkVersion + "; regranting permissions for external"); 18575 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18576 } 18577 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18578 18579 // Yay, everything is now upgraded 18580 ver.forceCurrent(); 18581 18582 // can downgrade to reader 18583 // Persist settings 18584 mSettings.writeLPr(); 18585 } 18586 // Send a broadcast to let everyone know we are done processing 18587 if (pkgList.size() > 0) { 18588 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18589 } 18590 } 18591 18592 /* 18593 * Utility method to unload a list of specified containers 18594 */ 18595 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18596 // Just unmount all valid containers. 18597 for (AsecInstallArgs arg : cidArgs) { 18598 synchronized (mInstallLock) { 18599 arg.doPostDeleteLI(false); 18600 } 18601 } 18602 } 18603 18604 /* 18605 * Unload packages mounted on external media. This involves deleting package 18606 * data from internal structures, sending broadcasts about disabled packages, 18607 * gc'ing to free up references, unmounting all secure containers 18608 * corresponding to packages on external media, and posting a 18609 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18610 * that we always have to post this message if status has been requested no 18611 * matter what. 18612 */ 18613 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18614 final boolean reportStatus) { 18615 if (DEBUG_SD_INSTALL) 18616 Log.i(TAG, "unloading media packages"); 18617 ArrayList<String> pkgList = new ArrayList<String>(); 18618 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18619 final Set<AsecInstallArgs> keys = processCids.keySet(); 18620 for (AsecInstallArgs args : keys) { 18621 String pkgName = args.getPackageName(); 18622 if (DEBUG_SD_INSTALL) 18623 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18624 // Delete package internally 18625 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18626 synchronized (mInstallLock) { 18627 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18628 final boolean res; 18629 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18630 "unloadMediaPackages")) { 18631 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18632 null); 18633 } 18634 if (res) { 18635 pkgList.add(pkgName); 18636 } else { 18637 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18638 failedList.add(args); 18639 } 18640 } 18641 } 18642 18643 // reader 18644 synchronized (mPackages) { 18645 // We didn't update the settings after removing each package; 18646 // write them now for all packages. 18647 mSettings.writeLPr(); 18648 } 18649 18650 // We have to absolutely send UPDATED_MEDIA_STATUS only 18651 // after confirming that all the receivers processed the ordered 18652 // broadcast when packages get disabled, force a gc to clean things up. 18653 // and unload all the containers. 18654 if (pkgList.size() > 0) { 18655 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18656 new IIntentReceiver.Stub() { 18657 public void performReceive(Intent intent, int resultCode, String data, 18658 Bundle extras, boolean ordered, boolean sticky, 18659 int sendingUser) throws RemoteException { 18660 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18661 reportStatus ? 1 : 0, 1, keys); 18662 mHandler.sendMessage(msg); 18663 } 18664 }); 18665 } else { 18666 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18667 keys); 18668 mHandler.sendMessage(msg); 18669 } 18670 } 18671 18672 private void loadPrivatePackages(final VolumeInfo vol) { 18673 mHandler.post(new Runnable() { 18674 @Override 18675 public void run() { 18676 loadPrivatePackagesInner(vol); 18677 } 18678 }); 18679 } 18680 18681 private void loadPrivatePackagesInner(VolumeInfo vol) { 18682 final String volumeUuid = vol.fsUuid; 18683 if (TextUtils.isEmpty(volumeUuid)) { 18684 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18685 return; 18686 } 18687 18688 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18689 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18690 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18691 18692 final VersionInfo ver; 18693 final List<PackageSetting> packages; 18694 synchronized (mPackages) { 18695 ver = mSettings.findOrCreateVersion(volumeUuid); 18696 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18697 } 18698 18699 for (PackageSetting ps : packages) { 18700 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18701 synchronized (mInstallLock) { 18702 final PackageParser.Package pkg; 18703 try { 18704 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18705 loaded.add(pkg.applicationInfo); 18706 18707 } catch (PackageManagerException e) { 18708 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18709 } 18710 18711 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18712 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18713 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18714 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18715 } 18716 } 18717 } 18718 18719 // Reconcile app data for all started/unlocked users 18720 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18721 final UserManager um = mContext.getSystemService(UserManager.class); 18722 for (UserInfo user : um.getUsers()) { 18723 final int flags; 18724 if (um.isUserUnlocked(user.id)) { 18725 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18726 } else if (um.isUserRunning(user.id)) { 18727 flags = StorageManager.FLAG_STORAGE_DE; 18728 } else { 18729 continue; 18730 } 18731 18732 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18733 synchronized (mInstallLock) { 18734 reconcileAppsDataLI(volumeUuid, user.id, flags); 18735 } 18736 } 18737 18738 synchronized (mPackages) { 18739 int updateFlags = UPDATE_PERMISSIONS_ALL; 18740 if (ver.sdkVersion != mSdkVersion) { 18741 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18742 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18743 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18744 } 18745 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18746 18747 // Yay, everything is now upgraded 18748 ver.forceCurrent(); 18749 18750 mSettings.writeLPr(); 18751 } 18752 18753 for (PackageFreezer freezer : freezers) { 18754 freezer.close(); 18755 } 18756 18757 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18758 sendResourcesChangedBroadcast(true, false, loaded, null); 18759 } 18760 18761 private void unloadPrivatePackages(final VolumeInfo vol) { 18762 mHandler.post(new Runnable() { 18763 @Override 18764 public void run() { 18765 unloadPrivatePackagesInner(vol); 18766 } 18767 }); 18768 } 18769 18770 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18771 final String volumeUuid = vol.fsUuid; 18772 if (TextUtils.isEmpty(volumeUuid)) { 18773 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18774 return; 18775 } 18776 18777 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18778 synchronized (mInstallLock) { 18779 synchronized (mPackages) { 18780 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18781 for (PackageSetting ps : packages) { 18782 if (ps.pkg == null) continue; 18783 18784 final ApplicationInfo info = ps.pkg.applicationInfo; 18785 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18786 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18787 18788 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18789 "unloadPrivatePackagesInner")) { 18790 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18791 false, null)) { 18792 unloaded.add(info); 18793 } else { 18794 Slog.w(TAG, "Failed to unload " + ps.codePath); 18795 } 18796 } 18797 } 18798 18799 mSettings.writeLPr(); 18800 } 18801 } 18802 18803 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18804 sendResourcesChangedBroadcast(false, false, unloaded, null); 18805 } 18806 18807 /** 18808 * Prepare storage areas for given user on all mounted devices. 18809 */ 18810 void prepareUserData(int userId, int userSerial, int flags) { 18811 synchronized (mInstallLock) { 18812 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18813 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18814 final String volumeUuid = vol.getFsUuid(); 18815 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18816 } 18817 } 18818 } 18819 18820 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18821 boolean allowRecover) { 18822 // Prepare storage and verify that serial numbers are consistent; if 18823 // there's a mismatch we need to destroy to avoid leaking data 18824 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18825 try { 18826 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18827 18828 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18829 UserManagerService.enforceSerialNumber( 18830 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18831 } 18832 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18833 UserManagerService.enforceSerialNumber( 18834 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18835 } 18836 18837 synchronized (mInstallLock) { 18838 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18839 } 18840 } catch (Exception e) { 18841 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18842 + " because we failed to prepare: " + e); 18843 destroyUserDataLI(volumeUuid, userId, 18844 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18845 18846 if (allowRecover) { 18847 // Try one last time; if we fail again we're really in trouble 18848 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18849 } 18850 } 18851 } 18852 18853 /** 18854 * Destroy storage areas for given user on all mounted devices. 18855 */ 18856 void destroyUserData(int userId, int flags) { 18857 synchronized (mInstallLock) { 18858 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18859 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18860 final String volumeUuid = vol.getFsUuid(); 18861 destroyUserDataLI(volumeUuid, userId, flags); 18862 } 18863 } 18864 } 18865 18866 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18867 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18868 try { 18869 // Clean up app data, profile data, and media data 18870 mInstaller.destroyUserData(volumeUuid, userId, flags); 18871 18872 // Clean up system data 18873 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18874 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18875 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18876 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18877 } 18878 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18879 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18880 } 18881 } 18882 18883 // Data with special labels is now gone, so finish the job 18884 storage.destroyUserStorage(volumeUuid, userId, flags); 18885 18886 } catch (Exception e) { 18887 logCriticalInfo(Log.WARN, 18888 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18889 } 18890 } 18891 18892 /** 18893 * Examine all users present on given mounted volume, and destroy data 18894 * belonging to users that are no longer valid, or whose user ID has been 18895 * recycled. 18896 */ 18897 private void reconcileUsers(String volumeUuid) { 18898 final List<File> files = new ArrayList<>(); 18899 Collections.addAll(files, FileUtils 18900 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18901 Collections.addAll(files, FileUtils 18902 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18903 for (File file : files) { 18904 if (!file.isDirectory()) continue; 18905 18906 final int userId; 18907 final UserInfo info; 18908 try { 18909 userId = Integer.parseInt(file.getName()); 18910 info = sUserManager.getUserInfo(userId); 18911 } catch (NumberFormatException e) { 18912 Slog.w(TAG, "Invalid user directory " + file); 18913 continue; 18914 } 18915 18916 boolean destroyUser = false; 18917 if (info == null) { 18918 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18919 + " because no matching user was found"); 18920 destroyUser = true; 18921 } else if (!mOnlyCore) { 18922 try { 18923 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18924 } catch (IOException e) { 18925 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18926 + " because we failed to enforce serial number: " + e); 18927 destroyUser = true; 18928 } 18929 } 18930 18931 if (destroyUser) { 18932 synchronized (mInstallLock) { 18933 destroyUserDataLI(volumeUuid, userId, 18934 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18935 } 18936 } 18937 } 18938 } 18939 18940 private void assertPackageKnown(String volumeUuid, String packageName) 18941 throws PackageManagerException { 18942 synchronized (mPackages) { 18943 final PackageSetting ps = mSettings.mPackages.get(packageName); 18944 if (ps == null) { 18945 throw new PackageManagerException("Package " + packageName + " is unknown"); 18946 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18947 throw new PackageManagerException( 18948 "Package " + packageName + " found on unknown volume " + volumeUuid 18949 + "; expected volume " + ps.volumeUuid); 18950 } 18951 } 18952 } 18953 18954 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18955 throws PackageManagerException { 18956 synchronized (mPackages) { 18957 final PackageSetting ps = mSettings.mPackages.get(packageName); 18958 if (ps == null) { 18959 throw new PackageManagerException("Package " + packageName + " is unknown"); 18960 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18961 throw new PackageManagerException( 18962 "Package " + packageName + " found on unknown volume " + volumeUuid 18963 + "; expected volume " + ps.volumeUuid); 18964 } else if (!ps.getInstalled(userId)) { 18965 throw new PackageManagerException( 18966 "Package " + packageName + " not installed for user " + userId); 18967 } 18968 } 18969 } 18970 18971 /** 18972 * Examine all apps present on given mounted volume, and destroy apps that 18973 * aren't expected, either due to uninstallation or reinstallation on 18974 * another volume. 18975 */ 18976 private void reconcileApps(String volumeUuid) { 18977 final File[] files = FileUtils 18978 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18979 for (File file : files) { 18980 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18981 && !PackageInstallerService.isStageName(file.getName()); 18982 if (!isPackage) { 18983 // Ignore entries which are not packages 18984 continue; 18985 } 18986 18987 try { 18988 final PackageLite pkg = PackageParser.parsePackageLite(file, 18989 PackageParser.PARSE_MUST_BE_APK); 18990 assertPackageKnown(volumeUuid, pkg.packageName); 18991 18992 } catch (PackageParserException | PackageManagerException e) { 18993 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18994 synchronized (mInstallLock) { 18995 removeCodePathLI(file); 18996 } 18997 } 18998 } 18999 } 19000 19001 /** 19002 * Reconcile all app data for the given user. 19003 * <p> 19004 * Verifies that directories exist and that ownership and labeling is 19005 * correct for all installed apps on all mounted volumes. 19006 */ 19007 void reconcileAppsData(int userId, int flags) { 19008 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19009 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19010 final String volumeUuid = vol.getFsUuid(); 19011 synchronized (mInstallLock) { 19012 reconcileAppsDataLI(volumeUuid, userId, flags); 19013 } 19014 } 19015 } 19016 19017 /** 19018 * Reconcile all app data on given mounted volume. 19019 * <p> 19020 * Destroys app data that isn't expected, either due to uninstallation or 19021 * reinstallation on another volume. 19022 * <p> 19023 * Verifies that directories exist and that ownership and labeling is 19024 * correct for all installed apps. 19025 */ 19026 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19027 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19028 + Integer.toHexString(flags)); 19029 19030 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19031 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19032 19033 boolean restoreconNeeded = false; 19034 19035 // First look for stale data that doesn't belong, and check if things 19036 // have changed since we did our last restorecon 19037 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19038 if (!isUserKeyUnlocked(userId)) { 19039 throw new RuntimeException( 19040 "Yikes, someone asked us to reconcile CE storage while " + userId 19041 + " was still locked; this would have caused massive data loss!"); 19042 } 19043 19044 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19045 19046 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19047 for (File file : files) { 19048 final String packageName = file.getName(); 19049 try { 19050 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19051 } catch (PackageManagerException e) { 19052 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19053 try { 19054 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19055 StorageManager.FLAG_STORAGE_CE, 0); 19056 } catch (InstallerException e2) { 19057 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19058 } 19059 } 19060 } 19061 } 19062 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19063 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19064 19065 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19066 for (File file : files) { 19067 final String packageName = file.getName(); 19068 try { 19069 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19070 } catch (PackageManagerException e) { 19071 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19072 try { 19073 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19074 StorageManager.FLAG_STORAGE_DE, 0); 19075 } catch (InstallerException e2) { 19076 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19077 } 19078 } 19079 } 19080 } 19081 19082 // Ensure that data directories are ready to roll for all packages 19083 // installed for this volume and user 19084 final List<PackageSetting> packages; 19085 synchronized (mPackages) { 19086 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19087 } 19088 int preparedCount = 0; 19089 for (PackageSetting ps : packages) { 19090 final String packageName = ps.name; 19091 if (ps.pkg == null) { 19092 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19093 // TODO: might be due to legacy ASEC apps; we should circle back 19094 // and reconcile again once they're scanned 19095 continue; 19096 } 19097 19098 if (ps.getInstalled(userId)) { 19099 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19100 19101 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19102 // We may have just shuffled around app data directories, so 19103 // prepare them one more time 19104 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19105 } 19106 19107 preparedCount++; 19108 } 19109 } 19110 19111 if (restoreconNeeded) { 19112 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19113 SELinuxMMAC.setRestoreconDone(ceDir); 19114 } 19115 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19116 SELinuxMMAC.setRestoreconDone(deDir); 19117 } 19118 } 19119 19120 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19121 + " packages; restoreconNeeded was " + restoreconNeeded); 19122 } 19123 19124 /** 19125 * Prepare app data for the given app just after it was installed or 19126 * upgraded. This method carefully only touches users that it's installed 19127 * for, and it forces a restorecon to handle any seinfo changes. 19128 * <p> 19129 * Verifies that directories exist and that ownership and labeling is 19130 * correct for all installed apps. If there is an ownership mismatch, it 19131 * will try recovering system apps by wiping data; third-party app data is 19132 * left intact. 19133 * <p> 19134 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19135 */ 19136 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19137 final PackageSetting ps; 19138 synchronized (mPackages) { 19139 ps = mSettings.mPackages.get(pkg.packageName); 19140 mSettings.writeKernelMappingLPr(ps); 19141 } 19142 19143 final UserManager um = mContext.getSystemService(UserManager.class); 19144 for (UserInfo user : um.getUsers()) { 19145 final int flags; 19146 if (um.isUserUnlocked(user.id)) { 19147 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19148 } else if (um.isUserRunning(user.id)) { 19149 flags = StorageManager.FLAG_STORAGE_DE; 19150 } else { 19151 continue; 19152 } 19153 19154 if (ps.getInstalled(user.id)) { 19155 // Whenever an app changes, force a restorecon of its data 19156 // TODO: when user data is locked, mark that we're still dirty 19157 prepareAppDataLIF(pkg, user.id, flags, true); 19158 } 19159 } 19160 } 19161 19162 /** 19163 * Prepare app data for the given app. 19164 * <p> 19165 * Verifies that directories exist and that ownership and labeling is 19166 * correct for all installed apps. If there is an ownership mismatch, this 19167 * will try recovering system apps by wiping data; third-party app data is 19168 * left intact. 19169 */ 19170 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19171 boolean restoreconNeeded) { 19172 if (pkg == null) { 19173 Slog.wtf(TAG, "Package was null!", new Throwable()); 19174 return; 19175 } 19176 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19177 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19178 for (int i = 0; i < childCount; i++) { 19179 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19180 } 19181 } 19182 19183 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19184 boolean restoreconNeeded) { 19185 if (DEBUG_APP_DATA) { 19186 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19187 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19188 } 19189 19190 final String volumeUuid = pkg.volumeUuid; 19191 final String packageName = pkg.packageName; 19192 final ApplicationInfo app = pkg.applicationInfo; 19193 final int appId = UserHandle.getAppId(app.uid); 19194 19195 Preconditions.checkNotNull(app.seinfo); 19196 19197 try { 19198 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19199 appId, app.seinfo, app.targetSdkVersion); 19200 } catch (InstallerException e) { 19201 if (app.isSystemApp()) { 19202 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19203 + ", but trying to recover: " + e); 19204 destroyAppDataLeafLIF(pkg, userId, flags); 19205 try { 19206 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19207 appId, app.seinfo, app.targetSdkVersion); 19208 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19209 } catch (InstallerException e2) { 19210 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19211 } 19212 } else { 19213 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19214 } 19215 } 19216 19217 if (restoreconNeeded) { 19218 try { 19219 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19220 app.seinfo); 19221 } catch (InstallerException e) { 19222 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19223 } 19224 } 19225 19226 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19227 try { 19228 // CE storage is unlocked right now, so read out the inode and 19229 // remember for use later when it's locked 19230 // TODO: mark this structure as dirty so we persist it! 19231 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19232 StorageManager.FLAG_STORAGE_CE); 19233 synchronized (mPackages) { 19234 final PackageSetting ps = mSettings.mPackages.get(packageName); 19235 if (ps != null) { 19236 ps.setCeDataInode(ceDataInode, userId); 19237 } 19238 } 19239 } catch (InstallerException e) { 19240 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19241 } 19242 } 19243 19244 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19245 } 19246 19247 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19248 if (pkg == null) { 19249 Slog.wtf(TAG, "Package was null!", new Throwable()); 19250 return; 19251 } 19252 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19253 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19254 for (int i = 0; i < childCount; i++) { 19255 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19256 } 19257 } 19258 19259 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19260 final String volumeUuid = pkg.volumeUuid; 19261 final String packageName = pkg.packageName; 19262 final ApplicationInfo app = pkg.applicationInfo; 19263 19264 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19265 // Create a native library symlink only if we have native libraries 19266 // and if the native libraries are 32 bit libraries. We do not provide 19267 // this symlink for 64 bit libraries. 19268 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19269 final String nativeLibPath = app.nativeLibraryDir; 19270 try { 19271 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19272 nativeLibPath, userId); 19273 } catch (InstallerException e) { 19274 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19275 } 19276 } 19277 } 19278 } 19279 19280 /** 19281 * For system apps on non-FBE devices, this method migrates any existing 19282 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19283 * requested by the app. 19284 */ 19285 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19286 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19287 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19288 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19289 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19290 try { 19291 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19292 storageTarget); 19293 } catch (InstallerException e) { 19294 logCriticalInfo(Log.WARN, 19295 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19296 } 19297 return true; 19298 } else { 19299 return false; 19300 } 19301 } 19302 19303 public PackageFreezer freezePackage(String packageName, String killReason) { 19304 return new PackageFreezer(packageName, killReason); 19305 } 19306 19307 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19308 String killReason) { 19309 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19310 return new PackageFreezer(); 19311 } else { 19312 return freezePackage(packageName, killReason); 19313 } 19314 } 19315 19316 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19317 String killReason) { 19318 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19319 return new PackageFreezer(); 19320 } else { 19321 return freezePackage(packageName, killReason); 19322 } 19323 } 19324 19325 /** 19326 * Class that freezes and kills the given package upon creation, and 19327 * unfreezes it upon closing. This is typically used when doing surgery on 19328 * app code/data to prevent the app from running while you're working. 19329 */ 19330 private class PackageFreezer implements AutoCloseable { 19331 private final String mPackageName; 19332 private final PackageFreezer[] mChildren; 19333 19334 private final boolean mWeFroze; 19335 19336 private final AtomicBoolean mClosed = new AtomicBoolean(); 19337 private final CloseGuard mCloseGuard = CloseGuard.get(); 19338 19339 /** 19340 * Create and return a stub freezer that doesn't actually do anything, 19341 * typically used when someone requested 19342 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19343 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19344 */ 19345 public PackageFreezer() { 19346 mPackageName = null; 19347 mChildren = null; 19348 mWeFroze = false; 19349 mCloseGuard.open("close"); 19350 } 19351 19352 public PackageFreezer(String packageName, String killReason) { 19353 synchronized (mPackages) { 19354 mPackageName = packageName; 19355 mWeFroze = mFrozenPackages.add(mPackageName); 19356 19357 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19358 if (ps != null) { 19359 killApplication(ps.name, ps.appId, killReason); 19360 } 19361 19362 final PackageParser.Package p = mPackages.get(packageName); 19363 if (p != null && p.childPackages != null) { 19364 final int N = p.childPackages.size(); 19365 mChildren = new PackageFreezer[N]; 19366 for (int i = 0; i < N; i++) { 19367 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19368 killReason); 19369 } 19370 } else { 19371 mChildren = null; 19372 } 19373 } 19374 mCloseGuard.open("close"); 19375 } 19376 19377 @Override 19378 protected void finalize() throws Throwable { 19379 try { 19380 mCloseGuard.warnIfOpen(); 19381 close(); 19382 } finally { 19383 super.finalize(); 19384 } 19385 } 19386 19387 @Override 19388 public void close() { 19389 mCloseGuard.close(); 19390 if (mClosed.compareAndSet(false, true)) { 19391 synchronized (mPackages) { 19392 if (mWeFroze) { 19393 mFrozenPackages.remove(mPackageName); 19394 } 19395 19396 if (mChildren != null) { 19397 for (PackageFreezer freezer : mChildren) { 19398 freezer.close(); 19399 } 19400 } 19401 } 19402 } 19403 } 19404 } 19405 19406 /** 19407 * Verify that given package is currently frozen. 19408 */ 19409 private void checkPackageFrozen(String packageName) { 19410 synchronized (mPackages) { 19411 if (!mFrozenPackages.contains(packageName)) { 19412 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19413 } 19414 } 19415 } 19416 19417 @Override 19418 public int movePackage(final String packageName, final String volumeUuid) { 19419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19420 19421 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19422 final int moveId = mNextMoveId.getAndIncrement(); 19423 mHandler.post(new Runnable() { 19424 @Override 19425 public void run() { 19426 try { 19427 movePackageInternal(packageName, volumeUuid, moveId, user); 19428 } catch (PackageManagerException e) { 19429 Slog.w(TAG, "Failed to move " + packageName, e); 19430 mMoveCallbacks.notifyStatusChanged(moveId, 19431 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19432 } 19433 } 19434 }); 19435 return moveId; 19436 } 19437 19438 private void movePackageInternal(final String packageName, final String volumeUuid, 19439 final int moveId, UserHandle user) throws PackageManagerException { 19440 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19441 final PackageManager pm = mContext.getPackageManager(); 19442 19443 final boolean currentAsec; 19444 final String currentVolumeUuid; 19445 final File codeFile; 19446 final String installerPackageName; 19447 final String packageAbiOverride; 19448 final int appId; 19449 final String seinfo; 19450 final String label; 19451 final int targetSdkVersion; 19452 final PackageFreezer freezer; 19453 19454 // reader 19455 synchronized (mPackages) { 19456 final PackageParser.Package pkg = mPackages.get(packageName); 19457 final PackageSetting ps = mSettings.mPackages.get(packageName); 19458 if (pkg == null || ps == null) { 19459 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19460 } 19461 19462 if (pkg.applicationInfo.isSystemApp()) { 19463 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19464 "Cannot move system application"); 19465 } 19466 19467 if (pkg.applicationInfo.isExternalAsec()) { 19468 currentAsec = true; 19469 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19470 } else if (pkg.applicationInfo.isForwardLocked()) { 19471 currentAsec = true; 19472 currentVolumeUuid = "forward_locked"; 19473 } else { 19474 currentAsec = false; 19475 currentVolumeUuid = ps.volumeUuid; 19476 19477 final File probe = new File(pkg.codePath); 19478 final File probeOat = new File(probe, "oat"); 19479 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19480 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19481 "Move only supported for modern cluster style installs"); 19482 } 19483 } 19484 19485 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19486 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19487 "Package already moved to " + volumeUuid); 19488 } 19489 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19490 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19491 "Device admin cannot be moved"); 19492 } 19493 19494 if (mFrozenPackages.contains(packageName)) { 19495 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19496 "Failed to move already frozen package"); 19497 } 19498 19499 codeFile = new File(pkg.codePath); 19500 installerPackageName = ps.installerPackageName; 19501 packageAbiOverride = ps.cpuAbiOverrideString; 19502 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19503 seinfo = pkg.applicationInfo.seinfo; 19504 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19505 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19506 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19507 } 19508 19509 final Bundle extras = new Bundle(); 19510 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19511 extras.putString(Intent.EXTRA_TITLE, label); 19512 mMoveCallbacks.notifyCreated(moveId, extras); 19513 19514 int installFlags; 19515 final boolean moveCompleteApp; 19516 final File measurePath; 19517 19518 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19519 installFlags = INSTALL_INTERNAL; 19520 moveCompleteApp = !currentAsec; 19521 measurePath = Environment.getDataAppDirectory(volumeUuid); 19522 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19523 installFlags = INSTALL_EXTERNAL; 19524 moveCompleteApp = false; 19525 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19526 } else { 19527 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19528 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19529 || !volume.isMountedWritable()) { 19530 freezer.close(); 19531 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19532 "Move location not mounted private volume"); 19533 } 19534 19535 Preconditions.checkState(!currentAsec); 19536 19537 installFlags = INSTALL_INTERNAL; 19538 moveCompleteApp = true; 19539 measurePath = Environment.getDataAppDirectory(volumeUuid); 19540 } 19541 19542 final PackageStats stats = new PackageStats(null, -1); 19543 synchronized (mInstaller) { 19544 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19545 freezer.close(); 19546 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19547 "Failed to measure package size"); 19548 } 19549 } 19550 19551 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19552 + stats.dataSize); 19553 19554 final long startFreeBytes = measurePath.getFreeSpace(); 19555 final long sizeBytes; 19556 if (moveCompleteApp) { 19557 sizeBytes = stats.codeSize + stats.dataSize; 19558 } else { 19559 sizeBytes = stats.codeSize; 19560 } 19561 19562 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19563 freezer.close(); 19564 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19565 "Not enough free space to move"); 19566 } 19567 19568 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19569 19570 final CountDownLatch installedLatch = new CountDownLatch(1); 19571 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19572 @Override 19573 public void onUserActionRequired(Intent intent) throws RemoteException { 19574 throw new IllegalStateException(); 19575 } 19576 19577 @Override 19578 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19579 Bundle extras) throws RemoteException { 19580 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19581 + PackageManager.installStatusToString(returnCode, msg)); 19582 19583 installedLatch.countDown(); 19584 freezer.close(); 19585 19586 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19587 switch (status) { 19588 case PackageInstaller.STATUS_SUCCESS: 19589 mMoveCallbacks.notifyStatusChanged(moveId, 19590 PackageManager.MOVE_SUCCEEDED); 19591 break; 19592 case PackageInstaller.STATUS_FAILURE_STORAGE: 19593 mMoveCallbacks.notifyStatusChanged(moveId, 19594 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19595 break; 19596 default: 19597 mMoveCallbacks.notifyStatusChanged(moveId, 19598 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19599 break; 19600 } 19601 } 19602 }; 19603 19604 final MoveInfo move; 19605 if (moveCompleteApp) { 19606 // Kick off a thread to report progress estimates 19607 new Thread() { 19608 @Override 19609 public void run() { 19610 while (true) { 19611 try { 19612 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19613 break; 19614 } 19615 } catch (InterruptedException ignored) { 19616 } 19617 19618 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19619 final int progress = 10 + (int) MathUtils.constrain( 19620 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19621 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19622 } 19623 } 19624 }.start(); 19625 19626 final String dataAppName = codeFile.getName(); 19627 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19628 dataAppName, appId, seinfo, targetSdkVersion); 19629 } else { 19630 move = null; 19631 } 19632 19633 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19634 19635 final Message msg = mHandler.obtainMessage(INIT_COPY); 19636 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19637 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19638 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19639 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19640 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19641 msg.obj = params; 19642 19643 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19644 System.identityHashCode(msg.obj)); 19645 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19646 System.identityHashCode(msg.obj)); 19647 19648 mHandler.sendMessage(msg); 19649 } 19650 19651 @Override 19652 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19654 19655 final int realMoveId = mNextMoveId.getAndIncrement(); 19656 final Bundle extras = new Bundle(); 19657 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19658 mMoveCallbacks.notifyCreated(realMoveId, extras); 19659 19660 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19661 @Override 19662 public void onCreated(int moveId, Bundle extras) { 19663 // Ignored 19664 } 19665 19666 @Override 19667 public void onStatusChanged(int moveId, int status, long estMillis) { 19668 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19669 } 19670 }; 19671 19672 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19673 storage.setPrimaryStorageUuid(volumeUuid, callback); 19674 return realMoveId; 19675 } 19676 19677 @Override 19678 public int getMoveStatus(int moveId) { 19679 mContext.enforceCallingOrSelfPermission( 19680 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19681 return mMoveCallbacks.mLastStatus.get(moveId); 19682 } 19683 19684 @Override 19685 public void registerMoveCallback(IPackageMoveObserver callback) { 19686 mContext.enforceCallingOrSelfPermission( 19687 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19688 mMoveCallbacks.register(callback); 19689 } 19690 19691 @Override 19692 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19693 mContext.enforceCallingOrSelfPermission( 19694 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19695 mMoveCallbacks.unregister(callback); 19696 } 19697 19698 @Override 19699 public boolean setInstallLocation(int loc) { 19700 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19701 null); 19702 if (getInstallLocation() == loc) { 19703 return true; 19704 } 19705 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19706 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19707 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19708 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19709 return true; 19710 } 19711 return false; 19712 } 19713 19714 @Override 19715 public int getInstallLocation() { 19716 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19717 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19718 PackageHelper.APP_INSTALL_AUTO); 19719 } 19720 19721 /** Called by UserManagerService */ 19722 void cleanUpUser(UserManagerService userManager, int userHandle) { 19723 synchronized (mPackages) { 19724 mDirtyUsers.remove(userHandle); 19725 mUserNeedsBadging.delete(userHandle); 19726 mSettings.removeUserLPw(userHandle); 19727 mPendingBroadcasts.remove(userHandle); 19728 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19729 removeUnusedPackagesLPw(userManager, userHandle); 19730 } 19731 } 19732 19733 /** 19734 * We're removing userHandle and would like to remove any downloaded packages 19735 * that are no longer in use by any other user. 19736 * @param userHandle the user being removed 19737 */ 19738 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19739 final boolean DEBUG_CLEAN_APKS = false; 19740 int [] users = userManager.getUserIds(); 19741 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19742 while (psit.hasNext()) { 19743 PackageSetting ps = psit.next(); 19744 if (ps.pkg == null) { 19745 continue; 19746 } 19747 final String packageName = ps.pkg.packageName; 19748 // Skip over if system app 19749 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19750 continue; 19751 } 19752 if (DEBUG_CLEAN_APKS) { 19753 Slog.i(TAG, "Checking package " + packageName); 19754 } 19755 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19756 if (keep) { 19757 if (DEBUG_CLEAN_APKS) { 19758 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19759 } 19760 } else { 19761 for (int i = 0; i < users.length; i++) { 19762 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19763 keep = true; 19764 if (DEBUG_CLEAN_APKS) { 19765 Slog.i(TAG, " Keeping package " + packageName + " for user " 19766 + users[i]); 19767 } 19768 break; 19769 } 19770 } 19771 } 19772 if (!keep) { 19773 if (DEBUG_CLEAN_APKS) { 19774 Slog.i(TAG, " Removing package " + packageName); 19775 } 19776 mHandler.post(new Runnable() { 19777 public void run() { 19778 deletePackageX(packageName, userHandle, 0); 19779 } //end run 19780 }); 19781 } 19782 } 19783 } 19784 19785 /** Called by UserManagerService */ 19786 void createNewUser(int userHandle) { 19787 synchronized (mInstallLock) { 19788 mSettings.createNewUserLI(this, mInstaller, userHandle); 19789 } 19790 synchronized (mPackages) { 19791 applyFactoryDefaultBrowserLPw(userHandle); 19792 primeDomainVerificationsLPw(userHandle); 19793 } 19794 } 19795 19796 void newUserCreated(final int userHandle) { 19797 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19798 // If permission review for legacy apps is required, we represent 19799 // dagerous permissions for such apps as always granted runtime 19800 // permissions to keep per user flag state whether review is needed. 19801 // Hence, if a new user is added we have to propagate dangerous 19802 // permission grants for these legacy apps. 19803 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19804 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19805 | UPDATE_PERMISSIONS_REPLACE_ALL); 19806 } 19807 } 19808 19809 @Override 19810 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19811 mContext.enforceCallingOrSelfPermission( 19812 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19813 "Only package verification agents can read the verifier device identity"); 19814 19815 synchronized (mPackages) { 19816 return mSettings.getVerifierDeviceIdentityLPw(); 19817 } 19818 } 19819 19820 @Override 19821 public void setPermissionEnforced(String permission, boolean enforced) { 19822 // TODO: Now that we no longer change GID for storage, this should to away. 19823 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19824 "setPermissionEnforced"); 19825 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19826 synchronized (mPackages) { 19827 if (mSettings.mReadExternalStorageEnforced == null 19828 || mSettings.mReadExternalStorageEnforced != enforced) { 19829 mSettings.mReadExternalStorageEnforced = enforced; 19830 mSettings.writeLPr(); 19831 } 19832 } 19833 // kill any non-foreground processes so we restart them and 19834 // grant/revoke the GID. 19835 final IActivityManager am = ActivityManagerNative.getDefault(); 19836 if (am != null) { 19837 final long token = Binder.clearCallingIdentity(); 19838 try { 19839 am.killProcessesBelowForeground("setPermissionEnforcement"); 19840 } catch (RemoteException e) { 19841 } finally { 19842 Binder.restoreCallingIdentity(token); 19843 } 19844 } 19845 } else { 19846 throw new IllegalArgumentException("No selective enforcement for " + permission); 19847 } 19848 } 19849 19850 @Override 19851 @Deprecated 19852 public boolean isPermissionEnforced(String permission) { 19853 return true; 19854 } 19855 19856 @Override 19857 public boolean isStorageLow() { 19858 final long token = Binder.clearCallingIdentity(); 19859 try { 19860 final DeviceStorageMonitorInternal 19861 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19862 if (dsm != null) { 19863 return dsm.isMemoryLow(); 19864 } else { 19865 return false; 19866 } 19867 } finally { 19868 Binder.restoreCallingIdentity(token); 19869 } 19870 } 19871 19872 @Override 19873 public IPackageInstaller getPackageInstaller() { 19874 return mInstallerService; 19875 } 19876 19877 private boolean userNeedsBadging(int userId) { 19878 int index = mUserNeedsBadging.indexOfKey(userId); 19879 if (index < 0) { 19880 final UserInfo userInfo; 19881 final long token = Binder.clearCallingIdentity(); 19882 try { 19883 userInfo = sUserManager.getUserInfo(userId); 19884 } finally { 19885 Binder.restoreCallingIdentity(token); 19886 } 19887 final boolean b; 19888 if (userInfo != null && userInfo.isManagedProfile()) { 19889 b = true; 19890 } else { 19891 b = false; 19892 } 19893 mUserNeedsBadging.put(userId, b); 19894 return b; 19895 } 19896 return mUserNeedsBadging.valueAt(index); 19897 } 19898 19899 @Override 19900 public KeySet getKeySetByAlias(String packageName, String alias) { 19901 if (packageName == null || alias == null) { 19902 return null; 19903 } 19904 synchronized(mPackages) { 19905 final PackageParser.Package pkg = mPackages.get(packageName); 19906 if (pkg == null) { 19907 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19908 throw new IllegalArgumentException("Unknown package: " + packageName); 19909 } 19910 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19911 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19912 } 19913 } 19914 19915 @Override 19916 public KeySet getSigningKeySet(String packageName) { 19917 if (packageName == null) { 19918 return null; 19919 } 19920 synchronized(mPackages) { 19921 final PackageParser.Package pkg = mPackages.get(packageName); 19922 if (pkg == null) { 19923 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19924 throw new IllegalArgumentException("Unknown package: " + packageName); 19925 } 19926 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19927 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19928 throw new SecurityException("May not access signing KeySet of other apps."); 19929 } 19930 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19931 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19932 } 19933 } 19934 19935 @Override 19936 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19937 if (packageName == null || ks == null) { 19938 return false; 19939 } 19940 synchronized(mPackages) { 19941 final PackageParser.Package pkg = mPackages.get(packageName); 19942 if (pkg == null) { 19943 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19944 throw new IllegalArgumentException("Unknown package: " + packageName); 19945 } 19946 IBinder ksh = ks.getToken(); 19947 if (ksh instanceof KeySetHandle) { 19948 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19949 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19950 } 19951 return false; 19952 } 19953 } 19954 19955 @Override 19956 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19957 if (packageName == null || ks == null) { 19958 return false; 19959 } 19960 synchronized(mPackages) { 19961 final PackageParser.Package pkg = mPackages.get(packageName); 19962 if (pkg == null) { 19963 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19964 throw new IllegalArgumentException("Unknown package: " + packageName); 19965 } 19966 IBinder ksh = ks.getToken(); 19967 if (ksh instanceof KeySetHandle) { 19968 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19969 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19970 } 19971 return false; 19972 } 19973 } 19974 19975 private void deletePackageIfUnusedLPr(final String packageName) { 19976 PackageSetting ps = mSettings.mPackages.get(packageName); 19977 if (ps == null) { 19978 return; 19979 } 19980 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19981 // TODO Implement atomic delete if package is unused 19982 // It is currently possible that the package will be deleted even if it is installed 19983 // after this method returns. 19984 mHandler.post(new Runnable() { 19985 public void run() { 19986 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19987 } 19988 }); 19989 } 19990 } 19991 19992 /** 19993 * Check and throw if the given before/after packages would be considered a 19994 * downgrade. 19995 */ 19996 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19997 throws PackageManagerException { 19998 if (after.versionCode < before.mVersionCode) { 19999 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20000 "Update version code " + after.versionCode + " is older than current " 20001 + before.mVersionCode); 20002 } else if (after.versionCode == before.mVersionCode) { 20003 if (after.baseRevisionCode < before.baseRevisionCode) { 20004 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20005 "Update base revision code " + after.baseRevisionCode 20006 + " is older than current " + before.baseRevisionCode); 20007 } 20008 20009 if (!ArrayUtils.isEmpty(after.splitNames)) { 20010 for (int i = 0; i < after.splitNames.length; i++) { 20011 final String splitName = after.splitNames[i]; 20012 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20013 if (j != -1) { 20014 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20015 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20016 "Update split " + splitName + " revision code " 20017 + after.splitRevisionCodes[i] + " is older than current " 20018 + before.splitRevisionCodes[j]); 20019 } 20020 } 20021 } 20022 } 20023 } 20024 } 20025 20026 private static class MoveCallbacks extends Handler { 20027 private static final int MSG_CREATED = 1; 20028 private static final int MSG_STATUS_CHANGED = 2; 20029 20030 private final RemoteCallbackList<IPackageMoveObserver> 20031 mCallbacks = new RemoteCallbackList<>(); 20032 20033 private final SparseIntArray mLastStatus = new SparseIntArray(); 20034 20035 public MoveCallbacks(Looper looper) { 20036 super(looper); 20037 } 20038 20039 public void register(IPackageMoveObserver callback) { 20040 mCallbacks.register(callback); 20041 } 20042 20043 public void unregister(IPackageMoveObserver callback) { 20044 mCallbacks.unregister(callback); 20045 } 20046 20047 @Override 20048 public void handleMessage(Message msg) { 20049 final SomeArgs args = (SomeArgs) msg.obj; 20050 final int n = mCallbacks.beginBroadcast(); 20051 for (int i = 0; i < n; i++) { 20052 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20053 try { 20054 invokeCallback(callback, msg.what, args); 20055 } catch (RemoteException ignored) { 20056 } 20057 } 20058 mCallbacks.finishBroadcast(); 20059 args.recycle(); 20060 } 20061 20062 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20063 throws RemoteException { 20064 switch (what) { 20065 case MSG_CREATED: { 20066 callback.onCreated(args.argi1, (Bundle) args.arg2); 20067 break; 20068 } 20069 case MSG_STATUS_CHANGED: { 20070 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20071 break; 20072 } 20073 } 20074 } 20075 20076 private void notifyCreated(int moveId, Bundle extras) { 20077 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20078 20079 final SomeArgs args = SomeArgs.obtain(); 20080 args.argi1 = moveId; 20081 args.arg2 = extras; 20082 obtainMessage(MSG_CREATED, args).sendToTarget(); 20083 } 20084 20085 private void notifyStatusChanged(int moveId, int status) { 20086 notifyStatusChanged(moveId, status, -1); 20087 } 20088 20089 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20090 Slog.v(TAG, "Move " + moveId + " status " + status); 20091 20092 final SomeArgs args = SomeArgs.obtain(); 20093 args.argi1 = moveId; 20094 args.argi2 = status; 20095 args.arg3 = estMillis; 20096 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20097 20098 synchronized (mLastStatus) { 20099 mLastStatus.put(moveId, status); 20100 } 20101 } 20102 } 20103 20104 private final static class OnPermissionChangeListeners extends Handler { 20105 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20106 20107 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20108 new RemoteCallbackList<>(); 20109 20110 public OnPermissionChangeListeners(Looper looper) { 20111 super(looper); 20112 } 20113 20114 @Override 20115 public void handleMessage(Message msg) { 20116 switch (msg.what) { 20117 case MSG_ON_PERMISSIONS_CHANGED: { 20118 final int uid = msg.arg1; 20119 handleOnPermissionsChanged(uid); 20120 } break; 20121 } 20122 } 20123 20124 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20125 mPermissionListeners.register(listener); 20126 20127 } 20128 20129 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20130 mPermissionListeners.unregister(listener); 20131 } 20132 20133 public void onPermissionsChanged(int uid) { 20134 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20135 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20136 } 20137 } 20138 20139 private void handleOnPermissionsChanged(int uid) { 20140 final int count = mPermissionListeners.beginBroadcast(); 20141 try { 20142 for (int i = 0; i < count; i++) { 20143 IOnPermissionsChangeListener callback = mPermissionListeners 20144 .getBroadcastItem(i); 20145 try { 20146 callback.onPermissionsChanged(uid); 20147 } catch (RemoteException e) { 20148 Log.e(TAG, "Permission listener is dead", e); 20149 } 20150 } 20151 } finally { 20152 mPermissionListeners.finishBroadcast(); 20153 } 20154 } 20155 } 20156 20157 private class PackageManagerInternalImpl extends PackageManagerInternal { 20158 @Override 20159 public void setLocationPackagesProvider(PackagesProvider provider) { 20160 synchronized (mPackages) { 20161 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20162 } 20163 } 20164 20165 @Override 20166 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20167 synchronized (mPackages) { 20168 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20169 } 20170 } 20171 20172 @Override 20173 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20174 synchronized (mPackages) { 20175 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20176 } 20177 } 20178 20179 @Override 20180 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20181 synchronized (mPackages) { 20182 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20183 } 20184 } 20185 20186 @Override 20187 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20188 synchronized (mPackages) { 20189 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20190 } 20191 } 20192 20193 @Override 20194 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20195 synchronized (mPackages) { 20196 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20197 } 20198 } 20199 20200 @Override 20201 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20202 synchronized (mPackages) { 20203 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20204 packageName, userId); 20205 } 20206 } 20207 20208 @Override 20209 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20210 synchronized (mPackages) { 20211 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20212 packageName, userId); 20213 } 20214 } 20215 20216 @Override 20217 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20218 synchronized (mPackages) { 20219 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20220 packageName, userId); 20221 } 20222 } 20223 20224 @Override 20225 public void setKeepUninstalledPackages(final List<String> packageList) { 20226 Preconditions.checkNotNull(packageList); 20227 List<String> removedFromList = null; 20228 synchronized (mPackages) { 20229 if (mKeepUninstalledPackages != null) { 20230 final int packagesCount = mKeepUninstalledPackages.size(); 20231 for (int i = 0; i < packagesCount; i++) { 20232 String oldPackage = mKeepUninstalledPackages.get(i); 20233 if (packageList != null && packageList.contains(oldPackage)) { 20234 continue; 20235 } 20236 if (removedFromList == null) { 20237 removedFromList = new ArrayList<>(); 20238 } 20239 removedFromList.add(oldPackage); 20240 } 20241 } 20242 mKeepUninstalledPackages = new ArrayList<>(packageList); 20243 if (removedFromList != null) { 20244 final int removedCount = removedFromList.size(); 20245 for (int i = 0; i < removedCount; i++) { 20246 deletePackageIfUnusedLPr(removedFromList.get(i)); 20247 } 20248 } 20249 } 20250 } 20251 20252 @Override 20253 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20254 synchronized (mPackages) { 20255 // If we do not support permission review, done. 20256 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20257 return false; 20258 } 20259 20260 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20261 if (packageSetting == null) { 20262 return false; 20263 } 20264 20265 // Permission review applies only to apps not supporting the new permission model. 20266 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20267 return false; 20268 } 20269 20270 // Legacy apps have the permission and get user consent on launch. 20271 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20272 return permissionsState.isPermissionReviewRequired(userId); 20273 } 20274 } 20275 20276 @Override 20277 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20278 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20279 } 20280 20281 @Override 20282 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20283 int userId) { 20284 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20285 } 20286 } 20287 20288 @Override 20289 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20290 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20291 synchronized (mPackages) { 20292 final long identity = Binder.clearCallingIdentity(); 20293 try { 20294 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20295 packageNames, userId); 20296 } finally { 20297 Binder.restoreCallingIdentity(identity); 20298 } 20299 } 20300 } 20301 20302 private static void enforceSystemOrPhoneCaller(String tag) { 20303 int callingUid = Binder.getCallingUid(); 20304 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20305 throw new SecurityException( 20306 "Cannot call " + tag + " from UID " + callingUid); 20307 } 20308 } 20309 20310 boolean isHistoricalPackageUsageAvailable() { 20311 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20312 } 20313 20314 /** 20315 * Return a <b>copy</b> of the collection of packages known to the package manager. 20316 * @return A copy of the values of mPackages. 20317 */ 20318 Collection<PackageParser.Package> getPackages() { 20319 synchronized (mPackages) { 20320 return new ArrayList<>(mPackages.values()); 20321 } 20322 } 20323 20324 /** 20325 * Logs process start information (including base APK hash) to the security log. 20326 * @hide 20327 */ 20328 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20329 String apkFile, int pid) { 20330 if (!SecurityLog.isLoggingEnabled()) { 20331 return; 20332 } 20333 Bundle data = new Bundle(); 20334 data.putLong("startTimestamp", System.currentTimeMillis()); 20335 data.putString("processName", processName); 20336 data.putInt("uid", uid); 20337 data.putString("seinfo", seinfo); 20338 data.putString("apkFile", apkFile); 20339 data.putInt("pid", pid); 20340 Message msg = mProcessLoggingHandler.obtainMessage( 20341 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20342 msg.setData(data); 20343 mProcessLoggingHandler.sendMessage(msg); 20344 } 20345} 20346