PackageManagerService.java revision fdd241a1e026afeeb68d30cb3d999ee9506769ce
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.FileInputStream; 270import java.io.FileNotFoundException; 271import java.io.FileOutputStream; 272import java.io.FileReader; 273import java.io.FilenameFilter; 274import java.io.IOException; 275import java.io.InputStream; 276import java.io.PrintWriter; 277import java.nio.charset.StandardCharsets; 278import java.security.DigestInputStream; 279import java.security.MessageDigest; 280import java.security.NoSuchAlgorithmException; 281import java.security.PublicKey; 282import java.security.cert.Certificate; 283import java.security.cert.CertificateEncodingException; 284import java.security.cert.CertificateException; 285import java.text.SimpleDateFormat; 286import java.util.ArrayList; 287import java.util.Arrays; 288import java.util.Collection; 289import java.util.Collections; 290import java.util.Comparator; 291import java.util.Date; 292import java.util.HashSet; 293import java.util.Iterator; 294import java.util.List; 295import java.util.Map; 296import java.util.Objects; 297import java.util.Set; 298import java.util.concurrent.CountDownLatch; 299import java.util.concurrent.TimeUnit; 300import java.util.concurrent.atomic.AtomicBoolean; 301import java.util.concurrent.atomic.AtomicInteger; 302import java.util.concurrent.atomic.AtomicLong; 303 304/** 305 * Keep track of all those APKs everywhere. 306 * <p> 307 * Internally there are two important locks: 308 * <ul> 309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 310 * and other related state. It is a fine-grained lock that should only be held 311 * momentarily, as it's one of the most contended locks in the system. 312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 313 * operations typically involve heavy lifting of application data on disk. Since 314 * {@code installd} is single-threaded, and it's operations can often be slow, 315 * this lock should never be acquired while already holding {@link #mPackages}. 316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 317 * holding {@link #mInstallLock}. 318 * </ul> 319 * Many internal methods rely on the caller to hold the appropriate locks, and 320 * this contract is expressed through method name suffixes: 321 * <ul> 322 * <li>fooLI(): the caller must hold {@link #mInstallLock} 323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 324 * being modified must be frozen 325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 327 * </ul> 328 * <p> 329 * Because this class is very central to the platform's security; please run all 330 * CTS and unit tests whenever making modifications: 331 * 332 * <pre> 333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 335 * </pre> 336 */ 337public class PackageManagerService extends IPackageManager.Stub { 338 static final String TAG = "PackageManager"; 339 static final boolean DEBUG_SETTINGS = false; 340 static final boolean DEBUG_PREFERRED = false; 341 static final boolean DEBUG_UPGRADE = false; 342 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 343 private static final boolean DEBUG_BACKUP = false; 344 private static final boolean DEBUG_INSTALL = false; 345 private static final boolean DEBUG_REMOVE = false; 346 private static final boolean DEBUG_BROADCASTS = false; 347 private static final boolean DEBUG_SHOW_INFO = false; 348 private static final boolean DEBUG_PACKAGE_INFO = false; 349 private static final boolean DEBUG_INTENT_MATCHING = false; 350 private static final boolean DEBUG_PACKAGE_SCANNING = false; 351 private static final boolean DEBUG_VERIFY = false; 352 private static final boolean DEBUG_FILTERS = false; 353 354 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 355 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 356 // user, but by default initialize to this. 357 static final boolean DEBUG_DEXOPT = false; 358 359 private static final boolean DEBUG_ABI_SELECTION = false; 360 private static final boolean DEBUG_EPHEMERAL = false; 361 private static final boolean DEBUG_TRIAGED_MISSING = false; 362 private static final boolean DEBUG_APP_DATA = false; 363 364 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 365 366 private static final boolean DISABLE_EPHEMERAL_APPS = true; 367 368 private static final int RADIO_UID = Process.PHONE_UID; 369 private static final int LOG_UID = Process.LOG_UID; 370 private static final int NFC_UID = Process.NFC_UID; 371 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 372 private static final int SHELL_UID = Process.SHELL_UID; 373 374 // Cap the size of permission trees that 3rd party apps can define 375 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 376 377 // Suffix used during package installation when copying/moving 378 // package apks to install directory. 379 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 380 381 static final int SCAN_NO_DEX = 1<<1; 382 static final int SCAN_FORCE_DEX = 1<<2; 383 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 384 static final int SCAN_NEW_INSTALL = 1<<4; 385 static final int SCAN_NO_PATHS = 1<<5; 386 static final int SCAN_UPDATE_TIME = 1<<6; 387 static final int SCAN_DEFER_DEX = 1<<7; 388 static final int SCAN_BOOTING = 1<<8; 389 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 390 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 391 static final int SCAN_REPLACING = 1<<11; 392 static final int SCAN_REQUIRE_KNOWN = 1<<12; 393 static final int SCAN_MOVE = 1<<13; 394 static final int SCAN_INITIAL = 1<<14; 395 static final int SCAN_CHECK_ONLY = 1<<15; 396 static final int SCAN_DONT_KILL_APP = 1<<17; 397 static final int SCAN_IGNORE_FROZEN = 1<<18; 398 399 static final int REMOVE_CHATTY = 1<<16; 400 401 private static final int[] EMPTY_INT_ARRAY = new int[0]; 402 403 /** 404 * Timeout (in milliseconds) after which the watchdog should declare that 405 * our handler thread is wedged. The usual default for such things is one 406 * minute but we sometimes do very lengthy I/O operations on this thread, 407 * such as installing multi-gigabyte applications, so ours needs to be longer. 408 */ 409 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 410 411 /** 412 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 413 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 414 * settings entry if available, otherwise we use the hardcoded default. If it's been 415 * more than this long since the last fstrim, we force one during the boot sequence. 416 * 417 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 418 * one gets run at the next available charging+idle time. This final mandatory 419 * no-fstrim check kicks in only of the other scheduling criteria is never met. 420 */ 421 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 422 423 /** 424 * Whether verification is enabled by default. 425 */ 426 private static final boolean DEFAULT_VERIFY_ENABLE = true; 427 428 /** 429 * The default maximum time to wait for the verification agent to return in 430 * milliseconds. 431 */ 432 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 433 434 /** 435 * The default response for package verification timeout. 436 * 437 * This can be either PackageManager.VERIFICATION_ALLOW or 438 * PackageManager.VERIFICATION_REJECT. 439 */ 440 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 441 442 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 443 444 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 445 DEFAULT_CONTAINER_PACKAGE, 446 "com.android.defcontainer.DefaultContainerService"); 447 448 private static final String KILL_APP_REASON_GIDS_CHANGED = 449 "permission grant or revoke changed gids"; 450 451 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 452 "permissions revoked"; 453 454 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 455 456 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 457 458 /** Permission grant: not grant the permission. */ 459 private static final int GRANT_DENIED = 1; 460 461 /** Permission grant: grant the permission as an install permission. */ 462 private static final int GRANT_INSTALL = 2; 463 464 /** Permission grant: grant the permission as a runtime one. */ 465 private static final int GRANT_RUNTIME = 3; 466 467 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 468 private static final int GRANT_UPGRADE = 4; 469 470 /** Canonical intent used to identify what counts as a "web browser" app */ 471 private static final Intent sBrowserIntent; 472 static { 473 sBrowserIntent = new Intent(); 474 sBrowserIntent.setAction(Intent.ACTION_VIEW); 475 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 476 sBrowserIntent.setData(Uri.parse("http:")); 477 } 478 479 /** 480 * The set of all protected actions [i.e. those actions for which a high priority 481 * intent filter is disallowed]. 482 */ 483 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 484 static { 485 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 486 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 487 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 488 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 489 } 490 491 // Compilation reasons. 492 public static final int REASON_FIRST_BOOT = 0; 493 public static final int REASON_BOOT = 1; 494 public static final int REASON_INSTALL = 2; 495 public static final int REASON_BACKGROUND_DEXOPT = 3; 496 public static final int REASON_AB_OTA = 4; 497 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 498 public static final int REASON_SHARED_APK = 6; 499 public static final int REASON_FORCED_DEXOPT = 7; 500 501 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 502 503 // Special String to skip shared libraries check during compilation. 504 private static final String SPECIAL_SHARED_LIBRARY = "&"; 505 506 final ServiceThread mHandlerThread; 507 508 final PackageHandler mHandler; 509 510 private final ProcessLoggingHandler mProcessLoggingHandler; 511 512 /** 513 * Messages for {@link #mHandler} that need to wait for system ready before 514 * being dispatched. 515 */ 516 private ArrayList<Message> mPostSystemReadyMessages; 517 518 final int mSdkVersion = Build.VERSION.SDK_INT; 519 520 final Context mContext; 521 final boolean mFactoryTest; 522 final boolean mOnlyCore; 523 final DisplayMetrics mMetrics; 524 final int mDefParseFlags; 525 final String[] mSeparateProcesses; 526 final boolean mIsUpgrade; 527 final boolean mIsPreNUpgrade; 528 529 /** The location for ASEC container files on internal storage. */ 530 final String mAsecInternalPath; 531 532 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 533 // LOCK HELD. Can be called with mInstallLock held. 534 @GuardedBy("mInstallLock") 535 final Installer mInstaller; 536 537 /** Directory where installed third-party apps stored */ 538 final File mAppInstallDir; 539 final File mEphemeralInstallDir; 540 541 /** 542 * Directory to which applications installed internally have their 543 * 32 bit native libraries copied. 544 */ 545 private File mAppLib32InstallDir; 546 547 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 548 // apps. 549 final File mDrmAppPrivateInstallDir; 550 551 // ---------------------------------------------------------------- 552 553 // Lock for state used when installing and doing other long running 554 // operations. Methods that must be called with this lock held have 555 // the suffix "LI". 556 final Object mInstallLock = new Object(); 557 558 // ---------------------------------------------------------------- 559 560 // Keys are String (package name), values are Package. This also serves 561 // as the lock for the global state. Methods that must be called with 562 // this lock held have the prefix "LP". 563 @GuardedBy("mPackages") 564 final ArrayMap<String, PackageParser.Package> mPackages = 565 new ArrayMap<String, PackageParser.Package>(); 566 567 final ArrayMap<String, Set<String>> mKnownCodebase = 568 new ArrayMap<String, Set<String>>(); 569 570 // Tracks available target package names -> overlay package paths. 571 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 572 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 573 574 /** 575 * Tracks new system packages [received in an OTA] that we expect to 576 * find updated user-installed versions. Keys are package name, values 577 * are package location. 578 */ 579 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 580 /** 581 * Tracks high priority intent filters for protected actions. During boot, certain 582 * filter actions are protected and should never be allowed to have a high priority 583 * intent filter for them. However, there is one, and only one exception -- the 584 * setup wizard. It must be able to define a high priority intent filter for these 585 * actions to ensure there are no escapes from the wizard. We need to delay processing 586 * of these during boot as we need to look at all of the system packages in order 587 * to know which component is the setup wizard. 588 */ 589 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 590 /** 591 * Whether or not processing protected filters should be deferred. 592 */ 593 private boolean mDeferProtectedFilters = true; 594 595 /** 596 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 597 */ 598 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 599 /** 600 * Whether or not system app permissions should be promoted from install to runtime. 601 */ 602 boolean mPromoteSystemApps; 603 604 @GuardedBy("mPackages") 605 final Settings mSettings; 606 607 /** 608 * Set of package names that are currently "frozen", which means active 609 * surgery is being done on the code/data for that package. The platform 610 * will refuse to launch frozen packages to avoid race conditions. 611 * 612 * @see PackageFreezer 613 */ 614 @GuardedBy("mPackages") 615 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 616 617 boolean mRestoredSettings; 618 619 // System configuration read by SystemConfig. 620 final int[] mGlobalGids; 621 final SparseArray<ArraySet<String>> mSystemPermissions; 622 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 623 624 // If mac_permissions.xml was found for seinfo labeling. 625 boolean mFoundPolicyFile; 626 627 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 628 629 public static final class SharedLibraryEntry { 630 public final String path; 631 public final String apk; 632 633 SharedLibraryEntry(String _path, String _apk) { 634 path = _path; 635 apk = _apk; 636 } 637 } 638 639 // Currently known shared libraries. 640 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 641 new ArrayMap<String, SharedLibraryEntry>(); 642 643 // All available activities, for your resolving pleasure. 644 final ActivityIntentResolver mActivities = 645 new ActivityIntentResolver(); 646 647 // All available receivers, for your resolving pleasure. 648 final ActivityIntentResolver mReceivers = 649 new ActivityIntentResolver(); 650 651 // All available services, for your resolving pleasure. 652 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 653 654 // All available providers, for your resolving pleasure. 655 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 656 657 // Mapping from provider base names (first directory in content URI codePath) 658 // to the provider information. 659 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 660 new ArrayMap<String, PackageParser.Provider>(); 661 662 // Mapping from instrumentation class names to info about them. 663 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 664 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 665 666 // Mapping from permission names to info about them. 667 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 668 new ArrayMap<String, PackageParser.PermissionGroup>(); 669 670 // Packages whose data we have transfered into another package, thus 671 // should no longer exist. 672 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 673 674 // Broadcast actions that are only available to the system. 675 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 676 677 /** List of packages waiting for verification. */ 678 final SparseArray<PackageVerificationState> mPendingVerification 679 = new SparseArray<PackageVerificationState>(); 680 681 /** Set of packages associated with each app op permission. */ 682 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 683 684 final PackageInstallerService mInstallerService; 685 686 private final PackageDexOptimizer mPackageDexOptimizer; 687 688 private AtomicInteger mNextMoveId = new AtomicInteger(); 689 private final MoveCallbacks mMoveCallbacks; 690 691 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 692 693 // Cache of users who need badging. 694 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 695 696 /** Token for keys in mPendingVerification. */ 697 private int mPendingVerificationToken = 0; 698 699 volatile boolean mSystemReady; 700 volatile boolean mSafeMode; 701 volatile boolean mHasSystemUidErrors; 702 703 ApplicationInfo mAndroidApplication; 704 final ActivityInfo mResolveActivity = new ActivityInfo(); 705 final ResolveInfo mResolveInfo = new ResolveInfo(); 706 ComponentName mResolveComponentName; 707 PackageParser.Package mPlatformPackage; 708 ComponentName mCustomResolverComponentName; 709 710 boolean mResolverReplaced = false; 711 712 private final @Nullable ComponentName mIntentFilterVerifierComponent; 713 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 714 715 private int mIntentFilterVerificationToken = 0; 716 717 /** Component that knows whether or not an ephemeral application exists */ 718 final ComponentName mEphemeralResolverComponent; 719 /** The service connection to the ephemeral resolver */ 720 final EphemeralResolverConnection mEphemeralResolverConnection; 721 722 /** Component used to install ephemeral applications */ 723 final ComponentName mEphemeralInstallerComponent; 724 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 725 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 726 727 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 728 = new SparseArray<IntentFilterVerificationState>(); 729 730 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 731 new DefaultPermissionGrantPolicy(this); 732 733 // List of packages names to keep cached, even if they are uninstalled for all users 734 private List<String> mKeepUninstalledPackages; 735 736 private static class IFVerificationParams { 737 PackageParser.Package pkg; 738 boolean replacing; 739 int userId; 740 int verifierUid; 741 742 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 743 int _userId, int _verifierUid) { 744 pkg = _pkg; 745 replacing = _replacing; 746 userId = _userId; 747 replacing = _replacing; 748 verifierUid = _verifierUid; 749 } 750 } 751 752 private interface IntentFilterVerifier<T extends IntentFilter> { 753 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 754 T filter, String packageName); 755 void startVerifications(int userId); 756 void receiveVerificationResponse(int verificationId); 757 } 758 759 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 760 private Context mContext; 761 private ComponentName mIntentFilterVerifierComponent; 762 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 763 764 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 765 mContext = context; 766 mIntentFilterVerifierComponent = verifierComponent; 767 } 768 769 private String getDefaultScheme() { 770 return IntentFilter.SCHEME_HTTPS; 771 } 772 773 @Override 774 public void startVerifications(int userId) { 775 // Launch verifications requests 776 int count = mCurrentIntentFilterVerifications.size(); 777 for (int n=0; n<count; n++) { 778 int verificationId = mCurrentIntentFilterVerifications.get(n); 779 final IntentFilterVerificationState ivs = 780 mIntentFilterVerificationStates.get(verificationId); 781 782 String packageName = ivs.getPackageName(); 783 784 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 785 final int filterCount = filters.size(); 786 ArraySet<String> domainsSet = new ArraySet<>(); 787 for (int m=0; m<filterCount; m++) { 788 PackageParser.ActivityIntentInfo filter = filters.get(m); 789 domainsSet.addAll(filter.getHostsList()); 790 } 791 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 792 synchronized (mPackages) { 793 if (mSettings.createIntentFilterVerificationIfNeededLPw( 794 packageName, domainsList) != null) { 795 scheduleWriteSettingsLocked(); 796 } 797 } 798 sendVerificationRequest(userId, verificationId, ivs); 799 } 800 mCurrentIntentFilterVerifications.clear(); 801 } 802 803 private void sendVerificationRequest(int userId, int verificationId, 804 IntentFilterVerificationState ivs) { 805 806 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 807 verificationIntent.putExtra( 808 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 809 verificationId); 810 verificationIntent.putExtra( 811 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 812 getDefaultScheme()); 813 verificationIntent.putExtra( 814 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 815 ivs.getHostsString()); 816 verificationIntent.putExtra( 817 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 818 ivs.getPackageName()); 819 verificationIntent.setComponent(mIntentFilterVerifierComponent); 820 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 821 822 UserHandle user = new UserHandle(userId); 823 mContext.sendBroadcastAsUser(verificationIntent, user); 824 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 825 "Sending IntentFilter verification broadcast"); 826 } 827 828 public void receiveVerificationResponse(int verificationId) { 829 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 830 831 final boolean verified = ivs.isVerified(); 832 833 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 834 final int count = filters.size(); 835 if (DEBUG_DOMAIN_VERIFICATION) { 836 Slog.i(TAG, "Received verification response " + verificationId 837 + " for " + count + " filters, verified=" + verified); 838 } 839 for (int n=0; n<count; n++) { 840 PackageParser.ActivityIntentInfo filter = filters.get(n); 841 filter.setVerified(verified); 842 843 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 844 + " verified with result:" + verified + " and hosts:" 845 + ivs.getHostsString()); 846 } 847 848 mIntentFilterVerificationStates.remove(verificationId); 849 850 final String packageName = ivs.getPackageName(); 851 IntentFilterVerificationInfo ivi = null; 852 853 synchronized (mPackages) { 854 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 855 } 856 if (ivi == null) { 857 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 858 + verificationId + " packageName:" + packageName); 859 return; 860 } 861 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 862 "Updating IntentFilterVerificationInfo for package " + packageName 863 +" verificationId:" + verificationId); 864 865 synchronized (mPackages) { 866 if (verified) { 867 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 868 } else { 869 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 870 } 871 scheduleWriteSettingsLocked(); 872 873 final int userId = ivs.getUserId(); 874 if (userId != UserHandle.USER_ALL) { 875 final int userStatus = 876 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 877 878 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 879 boolean needUpdate = false; 880 881 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 882 // already been set by the User thru the Disambiguation dialog 883 switch (userStatus) { 884 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 885 if (verified) { 886 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 887 } else { 888 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 889 } 890 needUpdate = true; 891 break; 892 893 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 894 if (verified) { 895 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 896 needUpdate = true; 897 } 898 break; 899 900 default: 901 // Nothing to do 902 } 903 904 if (needUpdate) { 905 mSettings.updateIntentFilterVerificationStatusLPw( 906 packageName, updatedStatus, userId); 907 scheduleWritePackageRestrictionsLocked(userId); 908 } 909 } 910 } 911 } 912 913 @Override 914 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 915 ActivityIntentInfo filter, String packageName) { 916 if (!hasValidDomains(filter)) { 917 return false; 918 } 919 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 920 if (ivs == null) { 921 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 922 packageName); 923 } 924 if (DEBUG_DOMAIN_VERIFICATION) { 925 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 926 } 927 ivs.addFilter(filter); 928 return true; 929 } 930 931 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 932 int userId, int verificationId, String packageName) { 933 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 934 verifierUid, userId, packageName); 935 ivs.setPendingState(); 936 synchronized (mPackages) { 937 mIntentFilterVerificationStates.append(verificationId, ivs); 938 mCurrentIntentFilterVerifications.add(verificationId); 939 } 940 return ivs; 941 } 942 } 943 944 private static boolean hasValidDomains(ActivityIntentInfo filter) { 945 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 946 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 947 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 948 } 949 950 // Set of pending broadcasts for aggregating enable/disable of components. 951 static class PendingPackageBroadcasts { 952 // for each user id, a map of <package name -> components within that package> 953 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 954 955 public PendingPackageBroadcasts() { 956 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 957 } 958 959 public ArrayList<String> get(int userId, String packageName) { 960 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 961 return packages.get(packageName); 962 } 963 964 public void put(int userId, String packageName, ArrayList<String> components) { 965 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 966 packages.put(packageName, components); 967 } 968 969 public void remove(int userId, String packageName) { 970 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 971 if (packages != null) { 972 packages.remove(packageName); 973 } 974 } 975 976 public void remove(int userId) { 977 mUidMap.remove(userId); 978 } 979 980 public int userIdCount() { 981 return mUidMap.size(); 982 } 983 984 public int userIdAt(int n) { 985 return mUidMap.keyAt(n); 986 } 987 988 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 989 return mUidMap.get(userId); 990 } 991 992 public int size() { 993 // total number of pending broadcast entries across all userIds 994 int num = 0; 995 for (int i = 0; i< mUidMap.size(); i++) { 996 num += mUidMap.valueAt(i).size(); 997 } 998 return num; 999 } 1000 1001 public void clear() { 1002 mUidMap.clear(); 1003 } 1004 1005 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1006 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1007 if (map == null) { 1008 map = new ArrayMap<String, ArrayList<String>>(); 1009 mUidMap.put(userId, map); 1010 } 1011 return map; 1012 } 1013 } 1014 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1015 1016 // Service Connection to remote media container service to copy 1017 // package uri's from external media onto secure containers 1018 // or internal storage. 1019 private IMediaContainerService mContainerService = null; 1020 1021 static final int SEND_PENDING_BROADCAST = 1; 1022 static final int MCS_BOUND = 3; 1023 static final int END_COPY = 4; 1024 static final int INIT_COPY = 5; 1025 static final int MCS_UNBIND = 6; 1026 static final int START_CLEANING_PACKAGE = 7; 1027 static final int FIND_INSTALL_LOC = 8; 1028 static final int POST_INSTALL = 9; 1029 static final int MCS_RECONNECT = 10; 1030 static final int MCS_GIVE_UP = 11; 1031 static final int UPDATED_MEDIA_STATUS = 12; 1032 static final int WRITE_SETTINGS = 13; 1033 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1034 static final int PACKAGE_VERIFIED = 15; 1035 static final int CHECK_PENDING_VERIFICATION = 16; 1036 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1037 static final int INTENT_FILTER_VERIFIED = 18; 1038 1039 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1040 1041 // Delay time in millisecs 1042 static final int BROADCAST_DELAY = 10 * 1000; 1043 1044 static UserManagerService sUserManager; 1045 1046 // Stores a list of users whose package restrictions file needs to be updated 1047 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1048 1049 final private DefaultContainerConnection mDefContainerConn = 1050 new DefaultContainerConnection(); 1051 class DefaultContainerConnection implements ServiceConnection { 1052 public void onServiceConnected(ComponentName name, IBinder service) { 1053 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1054 IMediaContainerService imcs = 1055 IMediaContainerService.Stub.asInterface(service); 1056 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1057 } 1058 1059 public void onServiceDisconnected(ComponentName name) { 1060 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1061 } 1062 } 1063 1064 // Recordkeeping of restore-after-install operations that are currently in flight 1065 // between the Package Manager and the Backup Manager 1066 static class PostInstallData { 1067 public InstallArgs args; 1068 public PackageInstalledInfo res; 1069 1070 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1071 args = _a; 1072 res = _r; 1073 } 1074 } 1075 1076 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1077 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1078 1079 // XML tags for backup/restore of various bits of state 1080 private static final String TAG_PREFERRED_BACKUP = "pa"; 1081 private static final String TAG_DEFAULT_APPS = "da"; 1082 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1083 1084 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1085 private static final String TAG_ALL_GRANTS = "rt-grants"; 1086 private static final String TAG_GRANT = "grant"; 1087 private static final String ATTR_PACKAGE_NAME = "pkg"; 1088 1089 private static final String TAG_PERMISSION = "perm"; 1090 private static final String ATTR_PERMISSION_NAME = "name"; 1091 private static final String ATTR_IS_GRANTED = "g"; 1092 private static final String ATTR_USER_SET = "set"; 1093 private static final String ATTR_USER_FIXED = "fixed"; 1094 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1095 1096 // System/policy permission grants are not backed up 1097 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1098 FLAG_PERMISSION_POLICY_FIXED 1099 | FLAG_PERMISSION_SYSTEM_FIXED 1100 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1101 1102 // And we back up these user-adjusted states 1103 private static final int USER_RUNTIME_GRANT_MASK = 1104 FLAG_PERMISSION_USER_SET 1105 | FLAG_PERMISSION_USER_FIXED 1106 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1107 1108 final @Nullable String mRequiredVerifierPackage; 1109 final @NonNull String mRequiredInstallerPackage; 1110 final @Nullable String mSetupWizardPackage; 1111 final @NonNull String mServicesSystemSharedLibraryPackageName; 1112 final @NonNull String mSharedSystemSharedLibraryPackageName; 1113 1114 private final PackageUsage mPackageUsage = new PackageUsage(); 1115 1116 private class PackageUsage { 1117 private static final int WRITE_INTERVAL 1118 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1119 1120 private final Object mFileLock = new Object(); 1121 private final AtomicLong mLastWritten = new AtomicLong(0); 1122 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1123 1124 private boolean mIsHistoricalPackageUsageAvailable = true; 1125 1126 boolean isHistoricalPackageUsageAvailable() { 1127 return mIsHistoricalPackageUsageAvailable; 1128 } 1129 1130 void write(boolean force) { 1131 if (force) { 1132 writeInternal(); 1133 return; 1134 } 1135 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1136 && !DEBUG_DEXOPT) { 1137 return; 1138 } 1139 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1140 new Thread("PackageUsage_DiskWriter") { 1141 @Override 1142 public void run() { 1143 try { 1144 writeInternal(); 1145 } finally { 1146 mBackgroundWriteRunning.set(false); 1147 } 1148 } 1149 }.start(); 1150 } 1151 } 1152 1153 private void writeInternal() { 1154 synchronized (mPackages) { 1155 synchronized (mFileLock) { 1156 AtomicFile file = getFile(); 1157 FileOutputStream f = null; 1158 try { 1159 f = file.startWrite(); 1160 BufferedOutputStream out = new BufferedOutputStream(f); 1161 FileUtils.setPermissions(file.getBaseFile().getPath(), 1162 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1163 StringBuilder sb = new StringBuilder(); 1164 1165 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1166 sb.append('\n'); 1167 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1168 1169 for (PackageParser.Package pkg : mPackages.values()) { 1170 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1171 continue; 1172 } 1173 sb.setLength(0); 1174 sb.append(pkg.packageName); 1175 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1176 sb.append(' '); 1177 sb.append(usageTimeInMillis); 1178 } 1179 sb.append('\n'); 1180 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1181 } 1182 out.flush(); 1183 file.finishWrite(f); 1184 } catch (IOException e) { 1185 if (f != null) { 1186 file.failWrite(f); 1187 } 1188 Log.e(TAG, "Failed to write package usage times", e); 1189 } 1190 } 1191 } 1192 mLastWritten.set(SystemClock.elapsedRealtime()); 1193 } 1194 1195 void readLP() { 1196 synchronized (mFileLock) { 1197 AtomicFile file = getFile(); 1198 BufferedInputStream in = null; 1199 try { 1200 in = new BufferedInputStream(file.openRead()); 1201 StringBuffer sb = new StringBuffer(); 1202 1203 String firstLine = readLine(in, sb); 1204 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1205 readVersion1LP(in, sb); 1206 } else { 1207 readVersion0LP(in, sb, firstLine); 1208 } 1209 } catch (FileNotFoundException expected) { 1210 mIsHistoricalPackageUsageAvailable = false; 1211 } catch (IOException e) { 1212 Log.w(TAG, "Failed to read package usage times", e); 1213 } finally { 1214 IoUtils.closeQuietly(in); 1215 } 1216 } 1217 mLastWritten.set(SystemClock.elapsedRealtime()); 1218 } 1219 1220 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1221 throws IOException { 1222 // Initial version of the file had no version number and stored one 1223 // package-timestamp pair per line. 1224 // Note that the first line has already been read from the InputStream. 1225 for (String line = firstLine; line != null; line = readLine(in, sb)) { 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 } 1246 1247 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1248 // Version 1 of the file started with the corresponding version 1249 // number and then stored a package name and eight timestamps per line. 1250 String line; 1251 while ((line = readLine(in, sb)) != null) { 1252 String[] tokens = line.split(" "); 1253 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1254 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1255 } 1256 1257 String packageName = tokens[0]; 1258 PackageParser.Package pkg = mPackages.get(packageName); 1259 if (pkg == null) { 1260 continue; 1261 } 1262 1263 for (int reason = 0; 1264 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1265 reason++) { 1266 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1267 } 1268 } 1269 } 1270 1271 private long parseAsLong(String token) throws IOException { 1272 try { 1273 return Long.parseLong(token); 1274 } catch (NumberFormatException e) { 1275 throw new IOException("Failed to parse " + token + " as a long.", e); 1276 } 1277 } 1278 1279 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1280 return readToken(in, sb, '\n'); 1281 } 1282 1283 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1284 throws IOException { 1285 sb.setLength(0); 1286 while (true) { 1287 int ch = in.read(); 1288 if (ch == -1) { 1289 if (sb.length() == 0) { 1290 return null; 1291 } 1292 throw new IOException("Unexpected EOF"); 1293 } 1294 if (ch == endOfToken) { 1295 return sb.toString(); 1296 } 1297 sb.append((char)ch); 1298 } 1299 } 1300 1301 private AtomicFile getFile() { 1302 File dataDir = Environment.getDataDirectory(); 1303 File systemDir = new File(dataDir, "system"); 1304 File fname = new File(systemDir, "package-usage.list"); 1305 return new AtomicFile(fname); 1306 } 1307 1308 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1309 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1310 } 1311 1312 class PackageHandler extends Handler { 1313 private boolean mBound = false; 1314 final ArrayList<HandlerParams> mPendingInstalls = 1315 new ArrayList<HandlerParams>(); 1316 1317 private boolean connectToService() { 1318 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1319 " DefaultContainerService"); 1320 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1321 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1322 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1323 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1324 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1325 mBound = true; 1326 return true; 1327 } 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1329 return false; 1330 } 1331 1332 private void disconnectService() { 1333 mContainerService = null; 1334 mBound = false; 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1336 mContext.unbindService(mDefContainerConn); 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1338 } 1339 1340 PackageHandler(Looper looper) { 1341 super(looper); 1342 } 1343 1344 public void handleMessage(Message msg) { 1345 try { 1346 doHandleMessage(msg); 1347 } finally { 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 } 1350 } 1351 1352 void doHandleMessage(Message msg) { 1353 switch (msg.what) { 1354 case INIT_COPY: { 1355 HandlerParams params = (HandlerParams) msg.obj; 1356 int idx = mPendingInstalls.size(); 1357 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1358 // If a bind was already initiated we dont really 1359 // need to do anything. The pending install 1360 // will be processed later on. 1361 if (!mBound) { 1362 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1363 System.identityHashCode(mHandler)); 1364 // If this is the only one pending we might 1365 // have to bind to the service again. 1366 if (!connectToService()) { 1367 Slog.e(TAG, "Failed to bind to media container service"); 1368 params.serviceError(); 1369 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1370 System.identityHashCode(mHandler)); 1371 if (params.traceMethod != null) { 1372 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1373 params.traceCookie); 1374 } 1375 return; 1376 } else { 1377 // Once we bind to the service, the first 1378 // pending request will be processed. 1379 mPendingInstalls.add(idx, params); 1380 } 1381 } else { 1382 mPendingInstalls.add(idx, params); 1383 // Already bound to the service. Just make 1384 // sure we trigger off processing the first request. 1385 if (idx == 0) { 1386 mHandler.sendEmptyMessage(MCS_BOUND); 1387 } 1388 } 1389 break; 1390 } 1391 case MCS_BOUND: { 1392 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1393 if (msg.obj != null) { 1394 mContainerService = (IMediaContainerService) msg.obj; 1395 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1396 System.identityHashCode(mHandler)); 1397 } 1398 if (mContainerService == null) { 1399 if (!mBound) { 1400 // Something seriously wrong since we are not bound and we are not 1401 // waiting for connection. Bail out. 1402 Slog.e(TAG, "Cannot bind to media container service"); 1403 for (HandlerParams params : mPendingInstalls) { 1404 // Indicate service bind error 1405 params.serviceError(); 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1407 System.identityHashCode(params)); 1408 if (params.traceMethod != null) { 1409 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1410 params.traceMethod, params.traceCookie); 1411 } 1412 return; 1413 } 1414 mPendingInstalls.clear(); 1415 } else { 1416 Slog.w(TAG, "Waiting to connect to media container service"); 1417 } 1418 } else if (mPendingInstalls.size() > 0) { 1419 HandlerParams params = mPendingInstalls.get(0); 1420 if (params != null) { 1421 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1422 System.identityHashCode(params)); 1423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1424 if (params.startCopy()) { 1425 // We are done... look for more work or to 1426 // go idle. 1427 if (DEBUG_SD_INSTALL) Log.i(TAG, 1428 "Checking for more work or unbind..."); 1429 // Delete pending install 1430 if (mPendingInstalls.size() > 0) { 1431 mPendingInstalls.remove(0); 1432 } 1433 if (mPendingInstalls.size() == 0) { 1434 if (mBound) { 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Posting delayed MCS_UNBIND"); 1437 removeMessages(MCS_UNBIND); 1438 Message ubmsg = obtainMessage(MCS_UNBIND); 1439 // Unbind after a little delay, to avoid 1440 // continual thrashing. 1441 sendMessageDelayed(ubmsg, 10000); 1442 } 1443 } else { 1444 // There are more pending requests in queue. 1445 // Just post MCS_BOUND message to trigger processing 1446 // of next pending install. 1447 if (DEBUG_SD_INSTALL) Log.i(TAG, 1448 "Posting MCS_BOUND for next work"); 1449 mHandler.sendEmptyMessage(MCS_BOUND); 1450 } 1451 } 1452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1453 } 1454 } else { 1455 // Should never happen ideally. 1456 Slog.w(TAG, "Empty queue"); 1457 } 1458 break; 1459 } 1460 case MCS_RECONNECT: { 1461 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1462 if (mPendingInstalls.size() > 0) { 1463 if (mBound) { 1464 disconnectService(); 1465 } 1466 if (!connectToService()) { 1467 Slog.e(TAG, "Failed to bind to media container service"); 1468 for (HandlerParams params : mPendingInstalls) { 1469 // Indicate service bind error 1470 params.serviceError(); 1471 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1472 System.identityHashCode(params)); 1473 } 1474 mPendingInstalls.clear(); 1475 } 1476 } 1477 break; 1478 } 1479 case MCS_UNBIND: { 1480 // If there is no actual work left, then time to unbind. 1481 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1482 1483 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1484 if (mBound) { 1485 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1486 1487 disconnectService(); 1488 } 1489 } else if (mPendingInstalls.size() > 0) { 1490 // There are more pending requests in queue. 1491 // Just post MCS_BOUND message to trigger processing 1492 // of next pending install. 1493 mHandler.sendEmptyMessage(MCS_BOUND); 1494 } 1495 1496 break; 1497 } 1498 case MCS_GIVE_UP: { 1499 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1500 HandlerParams params = mPendingInstalls.remove(0); 1501 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1502 System.identityHashCode(params)); 1503 break; 1504 } 1505 case SEND_PENDING_BROADCAST: { 1506 String packages[]; 1507 ArrayList<String> components[]; 1508 int size = 0; 1509 int uids[]; 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1511 synchronized (mPackages) { 1512 if (mPendingBroadcasts == null) { 1513 return; 1514 } 1515 size = mPendingBroadcasts.size(); 1516 if (size <= 0) { 1517 // Nothing to be done. Just return 1518 return; 1519 } 1520 packages = new String[size]; 1521 components = new ArrayList[size]; 1522 uids = new int[size]; 1523 int i = 0; // filling out the above arrays 1524 1525 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1526 int packageUserId = mPendingBroadcasts.userIdAt(n); 1527 Iterator<Map.Entry<String, ArrayList<String>>> it 1528 = mPendingBroadcasts.packagesForUserId(packageUserId) 1529 .entrySet().iterator(); 1530 while (it.hasNext() && i < size) { 1531 Map.Entry<String, ArrayList<String>> ent = it.next(); 1532 packages[i] = ent.getKey(); 1533 components[i] = ent.getValue(); 1534 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1535 uids[i] = (ps != null) 1536 ? UserHandle.getUid(packageUserId, ps.appId) 1537 : -1; 1538 i++; 1539 } 1540 } 1541 size = i; 1542 mPendingBroadcasts.clear(); 1543 } 1544 // Send broadcasts 1545 for (int i = 0; i < size; i++) { 1546 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1547 } 1548 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1549 break; 1550 } 1551 case START_CLEANING_PACKAGE: { 1552 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1553 final String packageName = (String)msg.obj; 1554 final int userId = msg.arg1; 1555 final boolean andCode = msg.arg2 != 0; 1556 synchronized (mPackages) { 1557 if (userId == UserHandle.USER_ALL) { 1558 int[] users = sUserManager.getUserIds(); 1559 for (int user : users) { 1560 mSettings.addPackageToCleanLPw( 1561 new PackageCleanItem(user, packageName, andCode)); 1562 } 1563 } else { 1564 mSettings.addPackageToCleanLPw( 1565 new PackageCleanItem(userId, packageName, andCode)); 1566 } 1567 } 1568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1569 startCleaningPackages(); 1570 } break; 1571 case POST_INSTALL: { 1572 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1573 1574 PostInstallData data = mRunningInstalls.get(msg.arg1); 1575 mRunningInstalls.delete(msg.arg1); 1576 1577 if (data != null) { 1578 InstallArgs args = data.args; 1579 PackageInstalledInfo parentRes = data.res; 1580 1581 final boolean grantPermissions = (args.installFlags 1582 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1583 final boolean killApp = (args.installFlags 1584 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1585 final String[] grantedPermissions = args.installGrantPermissions; 1586 1587 // Handle the parent package 1588 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1589 grantedPermissions, args.observer); 1590 1591 // Handle the child packages 1592 final int childCount = (parentRes.addedChildPackages != null) 1593 ? parentRes.addedChildPackages.size() : 0; 1594 for (int i = 0; i < childCount; i++) { 1595 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1596 handlePackagePostInstall(childRes, grantPermissions, killApp, 1597 grantedPermissions, args.observer); 1598 } 1599 1600 // Log tracing if needed 1601 if (args.traceMethod != null) { 1602 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1603 args.traceCookie); 1604 } 1605 } else { 1606 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1607 } 1608 1609 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1610 } break; 1611 case UPDATED_MEDIA_STATUS: { 1612 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1613 boolean reportStatus = msg.arg1 == 1; 1614 boolean doGc = msg.arg2 == 1; 1615 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1616 if (doGc) { 1617 // Force a gc to clear up stale containers. 1618 Runtime.getRuntime().gc(); 1619 } 1620 if (msg.obj != null) { 1621 @SuppressWarnings("unchecked") 1622 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1624 // Unload containers 1625 unloadAllContainers(args); 1626 } 1627 if (reportStatus) { 1628 try { 1629 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1630 PackageHelper.getMountService().finishMediaUpdate(); 1631 } catch (RemoteException e) { 1632 Log.e(TAG, "MountService not running?"); 1633 } 1634 } 1635 } break; 1636 case WRITE_SETTINGS: { 1637 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1638 synchronized (mPackages) { 1639 removeMessages(WRITE_SETTINGS); 1640 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1641 mSettings.writeLPr(); 1642 mDirtyUsers.clear(); 1643 } 1644 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1645 } break; 1646 case WRITE_PACKAGE_RESTRICTIONS: { 1647 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1648 synchronized (mPackages) { 1649 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1650 for (int userId : mDirtyUsers) { 1651 mSettings.writePackageRestrictionsLPr(userId); 1652 } 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case CHECK_PENDING_VERIFICATION: { 1658 final int verificationId = msg.arg1; 1659 final PackageVerificationState state = mPendingVerification.get(verificationId); 1660 1661 if ((state != null) && !state.timeoutExtended()) { 1662 final InstallArgs args = state.getInstallArgs(); 1663 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1664 1665 Slog.i(TAG, "Verification timed out for " + originUri); 1666 mPendingVerification.remove(verificationId); 1667 1668 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1669 1670 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1671 Slog.i(TAG, "Continuing with installation of " + originUri); 1672 state.setVerifierResponse(Binder.getCallingUid(), 1673 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1674 broadcastPackageVerified(verificationId, originUri, 1675 PackageManager.VERIFICATION_ALLOW, 1676 state.getInstallArgs().getUser()); 1677 try { 1678 ret = args.copyApk(mContainerService, true); 1679 } catch (RemoteException e) { 1680 Slog.e(TAG, "Could not contact the ContainerService"); 1681 } 1682 } else { 1683 broadcastPackageVerified(verificationId, originUri, 1684 PackageManager.VERIFICATION_REJECT, 1685 state.getInstallArgs().getUser()); 1686 } 1687 1688 Trace.asyncTraceEnd( 1689 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1690 1691 processPendingInstall(args, ret); 1692 mHandler.sendEmptyMessage(MCS_UNBIND); 1693 } 1694 break; 1695 } 1696 case PACKAGE_VERIFIED: { 1697 final int verificationId = msg.arg1; 1698 1699 final PackageVerificationState state = mPendingVerification.get(verificationId); 1700 if (state == null) { 1701 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1702 break; 1703 } 1704 1705 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1706 1707 state.setVerifierResponse(response.callerUid, response.code); 1708 1709 if (state.isVerificationComplete()) { 1710 mPendingVerification.remove(verificationId); 1711 1712 final InstallArgs args = state.getInstallArgs(); 1713 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1714 1715 int ret; 1716 if (state.isInstallAllowed()) { 1717 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1718 broadcastPackageVerified(verificationId, originUri, 1719 response.code, state.getInstallArgs().getUser()); 1720 try { 1721 ret = args.copyApk(mContainerService, true); 1722 } catch (RemoteException e) { 1723 Slog.e(TAG, "Could not contact the ContainerService"); 1724 } 1725 } else { 1726 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1727 } 1728 1729 Trace.asyncTraceEnd( 1730 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1731 1732 processPendingInstall(args, ret); 1733 mHandler.sendEmptyMessage(MCS_UNBIND); 1734 } 1735 1736 break; 1737 } 1738 case START_INTENT_FILTER_VERIFICATIONS: { 1739 IFVerificationParams params = (IFVerificationParams) msg.obj; 1740 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1741 params.replacing, params.pkg); 1742 break; 1743 } 1744 case INTENT_FILTER_VERIFIED: { 1745 final int verificationId = msg.arg1; 1746 1747 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1748 verificationId); 1749 if (state == null) { 1750 Slog.w(TAG, "Invalid IntentFilter verification token " 1751 + verificationId + " received"); 1752 break; 1753 } 1754 1755 final int userId = state.getUserId(); 1756 1757 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1758 "Processing IntentFilter verification with token:" 1759 + verificationId + " and userId:" + userId); 1760 1761 final IntentFilterVerificationResponse response = 1762 (IntentFilterVerificationResponse) msg.obj; 1763 1764 state.setVerifierResponse(response.callerUid, response.code); 1765 1766 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1767 "IntentFilter verification with token:" + verificationId 1768 + " and userId:" + userId 1769 + " is settings verifier response with response code:" 1770 + response.code); 1771 1772 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1773 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1774 + response.getFailedDomainsString()); 1775 } 1776 1777 if (state.isVerificationComplete()) { 1778 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1779 } else { 1780 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1781 "IntentFilter verification with token:" + verificationId 1782 + " was not said to be complete"); 1783 } 1784 1785 break; 1786 } 1787 } 1788 } 1789 } 1790 1791 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1792 boolean killApp, String[] grantedPermissions, 1793 IPackageInstallObserver2 installObserver) { 1794 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1795 // Send the removed broadcasts 1796 if (res.removedInfo != null) { 1797 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1798 } 1799 1800 // Now that we successfully installed the package, grant runtime 1801 // permissions if requested before broadcasting the install. 1802 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1803 >= Build.VERSION_CODES.M) { 1804 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1805 } 1806 1807 final boolean update = res.removedInfo != null 1808 && res.removedInfo.removedPackage != null; 1809 1810 // If this is the first time we have child packages for a disabled privileged 1811 // app that had no children, we grant requested runtime permissions to the new 1812 // children if the parent on the system image had them already granted. 1813 if (res.pkg.parentPackage != null) { 1814 synchronized (mPackages) { 1815 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1816 } 1817 } 1818 1819 synchronized (mPackages) { 1820 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1821 } 1822 1823 final String packageName = res.pkg.applicationInfo.packageName; 1824 Bundle extras = new Bundle(1); 1825 extras.putInt(Intent.EXTRA_UID, res.uid); 1826 1827 // Determine the set of users who are adding this package for 1828 // the first time vs. those who are seeing an update. 1829 int[] firstUsers = EMPTY_INT_ARRAY; 1830 int[] updateUsers = EMPTY_INT_ARRAY; 1831 if (res.origUsers == null || res.origUsers.length == 0) { 1832 firstUsers = res.newUsers; 1833 } else { 1834 for (int newUser : res.newUsers) { 1835 boolean isNew = true; 1836 for (int origUser : res.origUsers) { 1837 if (origUser == newUser) { 1838 isNew = false; 1839 break; 1840 } 1841 } 1842 if (isNew) { 1843 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1844 } else { 1845 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1846 } 1847 } 1848 } 1849 1850 // Send installed broadcasts if the install/update is not ephemeral 1851 if (!isEphemeral(res.pkg)) { 1852 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1853 1854 // Send added for users that see the package for the first time 1855 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1856 extras, 0 /*flags*/, null /*targetPackage*/, 1857 null /*finishedReceiver*/, firstUsers); 1858 1859 // Send added for users that don't see the package for the first time 1860 if (update) { 1861 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1862 } 1863 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1864 extras, 0 /*flags*/, null /*targetPackage*/, 1865 null /*finishedReceiver*/, updateUsers); 1866 1867 // Send replaced for users that don't see the package for the first time 1868 if (update) { 1869 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1870 packageName, extras, 0 /*flags*/, 1871 null /*targetPackage*/, null /*finishedReceiver*/, 1872 updateUsers); 1873 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1874 null /*package*/, null /*extras*/, 0 /*flags*/, 1875 packageName /*targetPackage*/, 1876 null /*finishedReceiver*/, updateUsers); 1877 } 1878 1879 // Send broadcast package appeared if forward locked/external for all users 1880 // treat asec-hosted packages like removable media on upgrade 1881 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1882 if (DEBUG_INSTALL) { 1883 Slog.i(TAG, "upgrading pkg " + res.pkg 1884 + " is ASEC-hosted -> AVAILABLE"); 1885 } 1886 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1887 ArrayList<String> pkgList = new ArrayList<>(1); 1888 pkgList.add(packageName); 1889 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1890 } 1891 } 1892 1893 // Work that needs to happen on first install within each user 1894 if (firstUsers != null && firstUsers.length > 0) { 1895 synchronized (mPackages) { 1896 for (int userId : firstUsers) { 1897 // If this app is a browser and it's newly-installed for some 1898 // users, clear any default-browser state in those users. The 1899 // app's nature doesn't depend on the user, so we can just check 1900 // its browser nature in any user and generalize. 1901 if (packageIsBrowser(packageName, userId)) { 1902 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1903 } 1904 1905 // We may also need to apply pending (restored) runtime 1906 // permission grants within these users. 1907 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1908 } 1909 } 1910 } 1911 1912 // Log current value of "unknown sources" setting 1913 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1914 getUnknownSourcesSettings()); 1915 1916 // Force a gc to clear up things 1917 Runtime.getRuntime().gc(); 1918 1919 // Remove the replaced package's older resources safely now 1920 // We delete after a gc for applications on sdcard. 1921 if (res.removedInfo != null && res.removedInfo.args != null) { 1922 synchronized (mInstallLock) { 1923 res.removedInfo.args.doPostDeleteLI(true); 1924 } 1925 } 1926 } 1927 1928 // If someone is watching installs - notify them 1929 if (installObserver != null) { 1930 try { 1931 Bundle extras = extrasForInstallResult(res); 1932 installObserver.onPackageInstalled(res.name, res.returnCode, 1933 res.returnMsg, extras); 1934 } catch (RemoteException e) { 1935 Slog.i(TAG, "Observer no longer exists."); 1936 } 1937 } 1938 } 1939 1940 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1941 PackageParser.Package pkg) { 1942 if (pkg.parentPackage == null) { 1943 return; 1944 } 1945 if (pkg.requestedPermissions == null) { 1946 return; 1947 } 1948 final PackageSetting disabledSysParentPs = mSettings 1949 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1950 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1951 || !disabledSysParentPs.isPrivileged() 1952 || (disabledSysParentPs.childPackageNames != null 1953 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1954 return; 1955 } 1956 final int[] allUserIds = sUserManager.getUserIds(); 1957 final int permCount = pkg.requestedPermissions.size(); 1958 for (int i = 0; i < permCount; i++) { 1959 String permission = pkg.requestedPermissions.get(i); 1960 BasePermission bp = mSettings.mPermissions.get(permission); 1961 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1962 continue; 1963 } 1964 for (int userId : allUserIds) { 1965 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1966 permission, userId)) { 1967 grantRuntimePermission(pkg.packageName, permission, userId); 1968 } 1969 } 1970 } 1971 } 1972 1973 private StorageEventListener mStorageListener = new StorageEventListener() { 1974 @Override 1975 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1976 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1977 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1978 final String volumeUuid = vol.getFsUuid(); 1979 1980 // Clean up any users or apps that were removed or recreated 1981 // while this volume was missing 1982 reconcileUsers(volumeUuid); 1983 reconcileApps(volumeUuid); 1984 1985 // Clean up any install sessions that expired or were 1986 // cancelled while this volume was missing 1987 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1988 1989 loadPrivatePackages(vol); 1990 1991 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1992 unloadPrivatePackages(vol); 1993 } 1994 } 1995 1996 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1997 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1998 updateExternalMediaStatus(true, false); 1999 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2000 updateExternalMediaStatus(false, false); 2001 } 2002 } 2003 } 2004 2005 @Override 2006 public void onVolumeForgotten(String fsUuid) { 2007 if (TextUtils.isEmpty(fsUuid)) { 2008 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2009 return; 2010 } 2011 2012 // Remove any apps installed on the forgotten volume 2013 synchronized (mPackages) { 2014 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2015 for (PackageSetting ps : packages) { 2016 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2017 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2018 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2019 } 2020 2021 mSettings.onVolumeForgotten(fsUuid); 2022 mSettings.writeLPr(); 2023 } 2024 } 2025 }; 2026 2027 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2028 String[] grantedPermissions) { 2029 for (int userId : userIds) { 2030 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2031 } 2032 2033 // We could have touched GID membership, so flush out packages.list 2034 synchronized (mPackages) { 2035 mSettings.writePackageListLPr(); 2036 } 2037 } 2038 2039 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2040 String[] grantedPermissions) { 2041 SettingBase sb = (SettingBase) pkg.mExtras; 2042 if (sb == null) { 2043 return; 2044 } 2045 2046 PermissionsState permissionsState = sb.getPermissionsState(); 2047 2048 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2049 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2050 2051 for (String permission : pkg.requestedPermissions) { 2052 final BasePermission bp; 2053 synchronized (mPackages) { 2054 bp = mSettings.mPermissions.get(permission); 2055 } 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 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2069 Bundle extras = null; 2070 switch (res.returnCode) { 2071 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2072 extras = new Bundle(); 2073 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2074 res.origPermission); 2075 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2076 res.origPackage); 2077 break; 2078 } 2079 case PackageManager.INSTALL_SUCCEEDED: { 2080 extras = new Bundle(); 2081 extras.putBoolean(Intent.EXTRA_REPLACING, 2082 res.removedInfo != null && res.removedInfo.removedPackage != null); 2083 break; 2084 } 2085 } 2086 return extras; 2087 } 2088 2089 void scheduleWriteSettingsLocked() { 2090 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2091 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2092 } 2093 } 2094 2095 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2096 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2097 scheduleWritePackageRestrictionsLocked(userId); 2098 } 2099 2100 void scheduleWritePackageRestrictionsLocked(int userId) { 2101 final int[] userIds = (userId == UserHandle.USER_ALL) 2102 ? sUserManager.getUserIds() : new int[]{userId}; 2103 for (int nextUserId : userIds) { 2104 if (!sUserManager.exists(nextUserId)) return; 2105 mDirtyUsers.add(nextUserId); 2106 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2107 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2108 } 2109 } 2110 } 2111 2112 public static PackageManagerService main(Context context, Installer installer, 2113 boolean factoryTest, boolean onlyCore) { 2114 // Self-check for initial settings. 2115 PackageManagerServiceCompilerMapping.checkProperties(); 2116 2117 PackageManagerService m = new PackageManagerService(context, installer, 2118 factoryTest, onlyCore); 2119 m.enableSystemUserPackages(); 2120 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2121 // disabled after already being started. 2122 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2123 UserHandle.USER_SYSTEM); 2124 ServiceManager.addService("package", m); 2125 return m; 2126 } 2127 2128 private void enableSystemUserPackages() { 2129 if (!UserManager.isSplitSystemUser()) { 2130 return; 2131 } 2132 // For system user, enable apps based on the following conditions: 2133 // - app is whitelisted or belong to one of these groups: 2134 // -- system app which has no launcher icons 2135 // -- system app which has INTERACT_ACROSS_USERS permission 2136 // -- system IME app 2137 // - app is not in the blacklist 2138 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2139 Set<String> enableApps = new ArraySet<>(); 2140 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2141 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2142 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2143 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2144 enableApps.addAll(wlApps); 2145 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2146 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2147 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2148 enableApps.removeAll(blApps); 2149 Log.i(TAG, "Applications installed for system user: " + enableApps); 2150 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2151 UserHandle.SYSTEM); 2152 final int allAppsSize = allAps.size(); 2153 synchronized (mPackages) { 2154 for (int i = 0; i < allAppsSize; i++) { 2155 String pName = allAps.get(i); 2156 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2157 // Should not happen, but we shouldn't be failing if it does 2158 if (pkgSetting == null) { 2159 continue; 2160 } 2161 boolean install = enableApps.contains(pName); 2162 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2163 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2164 + " for system user"); 2165 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2166 } 2167 } 2168 } 2169 } 2170 2171 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2172 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2173 Context.DISPLAY_SERVICE); 2174 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2175 } 2176 2177 public PackageManagerService(Context context, Installer installer, 2178 boolean factoryTest, boolean onlyCore) { 2179 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2180 SystemClock.uptimeMillis()); 2181 2182 if (mSdkVersion <= 0) { 2183 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2184 } 2185 2186 mContext = context; 2187 mFactoryTest = factoryTest; 2188 mOnlyCore = onlyCore; 2189 mMetrics = new DisplayMetrics(); 2190 mSettings = new Settings(mPackages); 2191 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2192 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2193 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2194 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2195 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2196 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2197 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2198 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2199 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2200 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2201 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2202 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2203 2204 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2205 if (separateProcesses != null && separateProcesses.length() > 0) { 2206 if ("*".equals(separateProcesses)) { 2207 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2208 mSeparateProcesses = null; 2209 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2210 } else { 2211 mDefParseFlags = 0; 2212 mSeparateProcesses = separateProcesses.split(","); 2213 Slog.w(TAG, "Running with debug.separate_processes: " 2214 + separateProcesses); 2215 } 2216 } else { 2217 mDefParseFlags = 0; 2218 mSeparateProcesses = null; 2219 } 2220 2221 mInstaller = installer; 2222 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2223 "*dexopt*"); 2224 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2225 2226 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2227 FgThread.get().getLooper()); 2228 2229 getDefaultDisplayMetrics(context, mMetrics); 2230 2231 SystemConfig systemConfig = SystemConfig.getInstance(); 2232 mGlobalGids = systemConfig.getGlobalGids(); 2233 mSystemPermissions = systemConfig.getSystemPermissions(); 2234 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2235 2236 synchronized (mInstallLock) { 2237 // writer 2238 synchronized (mPackages) { 2239 mHandlerThread = new ServiceThread(TAG, 2240 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2241 mHandlerThread.start(); 2242 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2243 mProcessLoggingHandler = new ProcessLoggingHandler(); 2244 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2245 2246 File dataDir = Environment.getDataDirectory(); 2247 mAppInstallDir = new File(dataDir, "app"); 2248 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2249 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2250 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2251 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2252 2253 sUserManager = new UserManagerService(context, this, mPackages); 2254 2255 // Propagate permission configuration in to package manager. 2256 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2257 = systemConfig.getPermissions(); 2258 for (int i=0; i<permConfig.size(); i++) { 2259 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2260 BasePermission bp = mSettings.mPermissions.get(perm.name); 2261 if (bp == null) { 2262 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2263 mSettings.mPermissions.put(perm.name, bp); 2264 } 2265 if (perm.gids != null) { 2266 bp.setGids(perm.gids, perm.perUser); 2267 } 2268 } 2269 2270 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2271 for (int i=0; i<libConfig.size(); i++) { 2272 mSharedLibraries.put(libConfig.keyAt(i), 2273 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2274 } 2275 2276 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2277 2278 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2279 2280 String customResolverActivity = Resources.getSystem().getString( 2281 R.string.config_customResolverActivity); 2282 if (TextUtils.isEmpty(customResolverActivity)) { 2283 customResolverActivity = null; 2284 } else { 2285 mCustomResolverComponentName = ComponentName.unflattenFromString( 2286 customResolverActivity); 2287 } 2288 2289 long startTime = SystemClock.uptimeMillis(); 2290 2291 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2292 startTime); 2293 2294 // Set flag to monitor and not change apk file paths when 2295 // scanning install directories. 2296 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2297 2298 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2299 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2300 2301 if (bootClassPath == null) { 2302 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2303 } 2304 2305 if (systemServerClassPath == null) { 2306 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2307 } 2308 2309 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2310 final String[] dexCodeInstructionSets = 2311 getDexCodeInstructionSets( 2312 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2313 2314 /** 2315 * Ensure all external libraries have had dexopt run on them. 2316 */ 2317 if (mSharedLibraries.size() > 0) { 2318 // NOTE: For now, we're compiling these system "shared libraries" 2319 // (and framework jars) into all available architectures. It's possible 2320 // to compile them only when we come across an app that uses them (there's 2321 // already logic for that in scanPackageLI) but that adds some complexity. 2322 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2323 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2324 final String lib = libEntry.path; 2325 if (lib == null) { 2326 continue; 2327 } 2328 2329 try { 2330 // Shared libraries do not have profiles so we perform a full 2331 // AOT compilation (if needed). 2332 int dexoptNeeded = DexFile.getDexOptNeeded( 2333 lib, dexCodeInstructionSet, 2334 getCompilerFilterForReason(REASON_SHARED_APK), 2335 false /* newProfile */); 2336 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2337 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2338 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2339 getCompilerFilterForReason(REASON_SHARED_APK), 2340 StorageManager.UUID_PRIVATE_INTERNAL, 2341 SPECIAL_SHARED_LIBRARY); 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, null /* sharedLibraries */, instructionSets, 7308 false /* checkProfiles */, 7309 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7310 } 7311 } 7312 7313 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7314 targetCompilerFilter); 7315 } 7316 7317 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7318 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7319 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7320 Set<String> collectedNames = new HashSet<>(); 7321 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7322 7323 retValue.remove(p); 7324 7325 return retValue; 7326 } else { 7327 return Collections.emptyList(); 7328 } 7329 } 7330 7331 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7332 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7333 if (!collectedNames.contains(p.packageName)) { 7334 collectedNames.add(p.packageName); 7335 collected.add(p); 7336 7337 if (p.usesLibraries != null) { 7338 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7339 } 7340 if (p.usesOptionalLibraries != null) { 7341 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7342 collectedNames); 7343 } 7344 } 7345 } 7346 7347 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7348 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7349 for (String libName : libs) { 7350 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7351 if (libPkg != null) { 7352 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7353 } 7354 } 7355 } 7356 7357 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7358 synchronized (mPackages) { 7359 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7360 if (lib != null && lib.apk != null) { 7361 return mPackages.get(lib.apk); 7362 } 7363 } 7364 return null; 7365 } 7366 7367 public void shutdown() { 7368 mPackageUsage.write(true); 7369 } 7370 7371 @Override 7372 public void forceDexOpt(String packageName) { 7373 enforceSystemOrRoot("forceDexOpt"); 7374 7375 PackageParser.Package pkg; 7376 synchronized (mPackages) { 7377 pkg = mPackages.get(packageName); 7378 if (pkg == null) { 7379 throw new IllegalArgumentException("Unknown package: " + packageName); 7380 } 7381 } 7382 7383 synchronized (mInstallLock) { 7384 final String[] instructionSets = new String[] { 7385 getPrimaryInstructionSet(pkg.applicationInfo) }; 7386 7387 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7388 7389 // Whoever is calling forceDexOpt wants a fully compiled package. 7390 // Don't use profiles since that may cause compilation to be skipped. 7391 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7392 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7393 true /* force */); 7394 7395 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7396 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7397 throw new IllegalStateException("Failed to dexopt: " + res); 7398 } 7399 } 7400 } 7401 7402 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7403 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7404 Slog.w(TAG, "Unable to update from " + oldPkg.name 7405 + " to " + newPkg.packageName 7406 + ": old package not in system partition"); 7407 return false; 7408 } else if (mPackages.get(oldPkg.name) != null) { 7409 Slog.w(TAG, "Unable to update from " + oldPkg.name 7410 + " to " + newPkg.packageName 7411 + ": old package still exists"); 7412 return false; 7413 } 7414 return true; 7415 } 7416 7417 void removeCodePathLI(File codePath) { 7418 if (codePath.isDirectory()) { 7419 try { 7420 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7421 } catch (InstallerException e) { 7422 Slog.w(TAG, "Failed to remove code path", e); 7423 } 7424 } else { 7425 codePath.delete(); 7426 } 7427 } 7428 7429 private int[] resolveUserIds(int userId) { 7430 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7431 } 7432 7433 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7434 if (pkg == null) { 7435 Slog.wtf(TAG, "Package was null!", new Throwable()); 7436 return; 7437 } 7438 clearAppDataLeafLIF(pkg, userId, flags); 7439 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7440 for (int i = 0; i < childCount; i++) { 7441 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7442 } 7443 } 7444 7445 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7446 final PackageSetting ps; 7447 synchronized (mPackages) { 7448 ps = mSettings.mPackages.get(pkg.packageName); 7449 } 7450 for (int realUserId : resolveUserIds(userId)) { 7451 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7452 try { 7453 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7454 ceDataInode); 7455 } catch (InstallerException e) { 7456 Slog.w(TAG, String.valueOf(e)); 7457 } 7458 } 7459 } 7460 7461 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7462 if (pkg == null) { 7463 Slog.wtf(TAG, "Package was null!", new Throwable()); 7464 return; 7465 } 7466 destroyAppDataLeafLIF(pkg, userId, flags); 7467 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7468 for (int i = 0; i < childCount; i++) { 7469 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7470 } 7471 } 7472 7473 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7474 final PackageSetting ps; 7475 synchronized (mPackages) { 7476 ps = mSettings.mPackages.get(pkg.packageName); 7477 } 7478 for (int realUserId : resolveUserIds(userId)) { 7479 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7480 try { 7481 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7482 ceDataInode); 7483 } catch (InstallerException e) { 7484 Slog.w(TAG, String.valueOf(e)); 7485 } 7486 } 7487 } 7488 7489 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7490 if (pkg == null) { 7491 Slog.wtf(TAG, "Package was null!", new Throwable()); 7492 return; 7493 } 7494 destroyAppProfilesLeafLIF(pkg); 7495 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7496 for (int i = 0; i < childCount; i++) { 7497 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7498 } 7499 } 7500 7501 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7502 try { 7503 mInstaller.destroyAppProfiles(pkg.packageName); 7504 } catch (InstallerException e) { 7505 Slog.w(TAG, String.valueOf(e)); 7506 } 7507 } 7508 7509 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7510 if (pkg == null) { 7511 Slog.wtf(TAG, "Package was null!", new Throwable()); 7512 return; 7513 } 7514 clearAppProfilesLeafLIF(pkg); 7515 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7516 for (int i = 0; i < childCount; i++) { 7517 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7518 } 7519 } 7520 7521 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7522 try { 7523 mInstaller.clearAppProfiles(pkg.packageName); 7524 } catch (InstallerException e) { 7525 Slog.w(TAG, String.valueOf(e)); 7526 } 7527 } 7528 7529 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7530 long lastUpdateTime) { 7531 // Set parent install/update time 7532 PackageSetting ps = (PackageSetting) pkg.mExtras; 7533 if (ps != null) { 7534 ps.firstInstallTime = firstInstallTime; 7535 ps.lastUpdateTime = lastUpdateTime; 7536 } 7537 // Set children install/update time 7538 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7539 for (int i = 0; i < childCount; i++) { 7540 PackageParser.Package childPkg = pkg.childPackages.get(i); 7541 ps = (PackageSetting) childPkg.mExtras; 7542 if (ps != null) { 7543 ps.firstInstallTime = firstInstallTime; 7544 ps.lastUpdateTime = lastUpdateTime; 7545 } 7546 } 7547 } 7548 7549 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7550 PackageParser.Package changingLib) { 7551 if (file.path != null) { 7552 usesLibraryFiles.add(file.path); 7553 return; 7554 } 7555 PackageParser.Package p = mPackages.get(file.apk); 7556 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7557 // If we are doing this while in the middle of updating a library apk, 7558 // then we need to make sure to use that new apk for determining the 7559 // dependencies here. (We haven't yet finished committing the new apk 7560 // to the package manager state.) 7561 if (p == null || p.packageName.equals(changingLib.packageName)) { 7562 p = changingLib; 7563 } 7564 } 7565 if (p != null) { 7566 usesLibraryFiles.addAll(p.getAllCodePaths()); 7567 } 7568 } 7569 7570 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7571 PackageParser.Package changingLib) throws PackageManagerException { 7572 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7573 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7574 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7575 for (int i=0; i<N; i++) { 7576 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7577 if (file == null) { 7578 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7579 "Package " + pkg.packageName + " requires unavailable shared library " 7580 + pkg.usesLibraries.get(i) + "; failing!"); 7581 } 7582 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7583 } 7584 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7585 for (int i=0; i<N; i++) { 7586 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7587 if (file == null) { 7588 Slog.w(TAG, "Package " + pkg.packageName 7589 + " desires unavailable shared library " 7590 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7591 } else { 7592 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7593 } 7594 } 7595 N = usesLibraryFiles.size(); 7596 if (N > 0) { 7597 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7598 } else { 7599 pkg.usesLibraryFiles = null; 7600 } 7601 } 7602 } 7603 7604 private static boolean hasString(List<String> list, List<String> which) { 7605 if (list == null) { 7606 return false; 7607 } 7608 for (int i=list.size()-1; i>=0; i--) { 7609 for (int j=which.size()-1; j>=0; j--) { 7610 if (which.get(j).equals(list.get(i))) { 7611 return true; 7612 } 7613 } 7614 } 7615 return false; 7616 } 7617 7618 private void updateAllSharedLibrariesLPw() { 7619 for (PackageParser.Package pkg : mPackages.values()) { 7620 try { 7621 updateSharedLibrariesLPw(pkg, null); 7622 } catch (PackageManagerException e) { 7623 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7624 } 7625 } 7626 } 7627 7628 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7629 PackageParser.Package changingPkg) { 7630 ArrayList<PackageParser.Package> res = null; 7631 for (PackageParser.Package pkg : mPackages.values()) { 7632 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7633 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7634 if (res == null) { 7635 res = new ArrayList<PackageParser.Package>(); 7636 } 7637 res.add(pkg); 7638 try { 7639 updateSharedLibrariesLPw(pkg, changingPkg); 7640 } catch (PackageManagerException e) { 7641 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7642 } 7643 } 7644 } 7645 return res; 7646 } 7647 7648 /** 7649 * Derive the value of the {@code cpuAbiOverride} based on the provided 7650 * value and an optional stored value from the package settings. 7651 */ 7652 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7653 String cpuAbiOverride = null; 7654 7655 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7656 cpuAbiOverride = null; 7657 } else if (abiOverride != null) { 7658 cpuAbiOverride = abiOverride; 7659 } else if (settings != null) { 7660 cpuAbiOverride = settings.cpuAbiOverrideString; 7661 } 7662 7663 return cpuAbiOverride; 7664 } 7665 7666 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7667 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7668 throws PackageManagerException { 7669 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7670 // If the package has children and this is the first dive in the function 7671 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7672 // whether all packages (parent and children) would be successfully scanned 7673 // before the actual scan since scanning mutates internal state and we want 7674 // to atomically install the package and its children. 7675 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7676 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7677 scanFlags |= SCAN_CHECK_ONLY; 7678 } 7679 } else { 7680 scanFlags &= ~SCAN_CHECK_ONLY; 7681 } 7682 7683 final PackageParser.Package scannedPkg; 7684 try { 7685 // Scan the parent 7686 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7687 // Scan the children 7688 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7689 for (int i = 0; i < childCount; i++) { 7690 PackageParser.Package childPkg = pkg.childPackages.get(i); 7691 scanPackageLI(childPkg, policyFlags, 7692 scanFlags, currentTime, user); 7693 } 7694 } finally { 7695 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7696 } 7697 7698 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7699 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7700 } 7701 7702 return scannedPkg; 7703 } 7704 7705 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7706 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7707 boolean success = false; 7708 try { 7709 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7710 currentTime, user); 7711 success = true; 7712 return res; 7713 } finally { 7714 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7715 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7716 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7717 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7718 destroyAppProfilesLIF(pkg); 7719 } 7720 } 7721 } 7722 7723 /** 7724 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7725 */ 7726 private static boolean apkHasCode(String fileName) { 7727 StrictJarFile jarFile = null; 7728 try { 7729 jarFile = new StrictJarFile(fileName, 7730 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7731 return jarFile.findEntry("classes.dex") != null; 7732 } catch (IOException ignore) { 7733 } finally { 7734 try { 7735 jarFile.close(); 7736 } catch (IOException ignore) {} 7737 } 7738 return false; 7739 } 7740 7741 /** 7742 * Enforces code policy for the package. This ensures that if an APK has 7743 * declared hasCode="true" in its manifest that the APK actually contains 7744 * code. 7745 * 7746 * @throws PackageManagerException If bytecode could not be found when it should exist 7747 */ 7748 private static void enforceCodePolicy(PackageParser.Package pkg) 7749 throws PackageManagerException { 7750 final boolean shouldHaveCode = 7751 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7752 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7753 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7754 "Package " + pkg.baseCodePath + " code is missing"); 7755 } 7756 7757 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7758 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7759 final boolean splitShouldHaveCode = 7760 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7761 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7762 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7763 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7764 } 7765 } 7766 } 7767 } 7768 7769 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7770 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7771 throws PackageManagerException { 7772 final File scanFile = new File(pkg.codePath); 7773 if (pkg.applicationInfo.getCodePath() == null || 7774 pkg.applicationInfo.getResourcePath() == null) { 7775 // Bail out. The resource and code paths haven't been set. 7776 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7777 "Code and resource paths haven't been set correctly"); 7778 } 7779 7780 // Apply policy 7781 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7782 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7783 if (pkg.applicationInfo.isDirectBootAware()) { 7784 // we're direct boot aware; set for all components 7785 for (PackageParser.Service s : pkg.services) { 7786 s.info.encryptionAware = s.info.directBootAware = true; 7787 } 7788 for (PackageParser.Provider p : pkg.providers) { 7789 p.info.encryptionAware = p.info.directBootAware = true; 7790 } 7791 for (PackageParser.Activity a : pkg.activities) { 7792 a.info.encryptionAware = a.info.directBootAware = true; 7793 } 7794 for (PackageParser.Activity r : pkg.receivers) { 7795 r.info.encryptionAware = r.info.directBootAware = true; 7796 } 7797 } 7798 } else { 7799 // Only allow system apps to be flagged as core apps. 7800 pkg.coreApp = false; 7801 // clear flags not applicable to regular apps 7802 pkg.applicationInfo.privateFlags &= 7803 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7804 pkg.applicationInfo.privateFlags &= 7805 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7806 } 7807 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7808 7809 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7810 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7811 } 7812 7813 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7814 enforceCodePolicy(pkg); 7815 } 7816 7817 if (mCustomResolverComponentName != null && 7818 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7819 setUpCustomResolverActivity(pkg); 7820 } 7821 7822 if (pkg.packageName.equals("android")) { 7823 synchronized (mPackages) { 7824 if (mAndroidApplication != null) { 7825 Slog.w(TAG, "*************************************************"); 7826 Slog.w(TAG, "Core android package being redefined. Skipping."); 7827 Slog.w(TAG, " file=" + scanFile); 7828 Slog.w(TAG, "*************************************************"); 7829 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7830 "Core android package being redefined. Skipping."); 7831 } 7832 7833 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7834 // Set up information for our fall-back user intent resolution activity. 7835 mPlatformPackage = pkg; 7836 pkg.mVersionCode = mSdkVersion; 7837 mAndroidApplication = pkg.applicationInfo; 7838 7839 if (!mResolverReplaced) { 7840 mResolveActivity.applicationInfo = mAndroidApplication; 7841 mResolveActivity.name = ResolverActivity.class.getName(); 7842 mResolveActivity.packageName = mAndroidApplication.packageName; 7843 mResolveActivity.processName = "system:ui"; 7844 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7845 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7846 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7847 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7848 mResolveActivity.exported = true; 7849 mResolveActivity.enabled = true; 7850 mResolveInfo.activityInfo = mResolveActivity; 7851 mResolveInfo.priority = 0; 7852 mResolveInfo.preferredOrder = 0; 7853 mResolveInfo.match = 0; 7854 mResolveComponentName = new ComponentName( 7855 mAndroidApplication.packageName, mResolveActivity.name); 7856 } 7857 } 7858 } 7859 } 7860 7861 if (DEBUG_PACKAGE_SCANNING) { 7862 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7863 Log.d(TAG, "Scanning package " + pkg.packageName); 7864 } 7865 7866 synchronized (mPackages) { 7867 if (mPackages.containsKey(pkg.packageName) 7868 || mSharedLibraries.containsKey(pkg.packageName)) { 7869 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7870 "Application package " + pkg.packageName 7871 + " already installed. Skipping duplicate."); 7872 } 7873 7874 // If we're only installing presumed-existing packages, require that the 7875 // scanned APK is both already known and at the path previously established 7876 // for it. Previously unknown packages we pick up normally, but if we have an 7877 // a priori expectation about this package's install presence, enforce it. 7878 // With a singular exception for new system packages. When an OTA contains 7879 // a new system package, we allow the codepath to change from a system location 7880 // to the user-installed location. If we don't allow this change, any newer, 7881 // user-installed version of the application will be ignored. 7882 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7883 if (mExpectingBetter.containsKey(pkg.packageName)) { 7884 logCriticalInfo(Log.WARN, 7885 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7886 } else { 7887 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7888 if (known != null) { 7889 if (DEBUG_PACKAGE_SCANNING) { 7890 Log.d(TAG, "Examining " + pkg.codePath 7891 + " and requiring known paths " + known.codePathString 7892 + " & " + known.resourcePathString); 7893 } 7894 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7895 || !pkg.applicationInfo.getResourcePath().equals( 7896 known.resourcePathString)) { 7897 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7898 "Application package " + pkg.packageName 7899 + " found at " + pkg.applicationInfo.getCodePath() 7900 + " but expected at " + known.codePathString 7901 + "; ignoring."); 7902 } 7903 } 7904 } 7905 } 7906 } 7907 7908 // Initialize package source and resource directories 7909 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7910 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7911 7912 SharedUserSetting suid = null; 7913 PackageSetting pkgSetting = null; 7914 7915 if (!isSystemApp(pkg)) { 7916 // Only system apps can use these features. 7917 pkg.mOriginalPackages = null; 7918 pkg.mRealPackage = null; 7919 pkg.mAdoptPermissions = null; 7920 } 7921 7922 // Getting the package setting may have a side-effect, so if we 7923 // are only checking if scan would succeed, stash a copy of the 7924 // old setting to restore at the end. 7925 PackageSetting nonMutatedPs = null; 7926 7927 // writer 7928 synchronized (mPackages) { 7929 if (pkg.mSharedUserId != null) { 7930 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7931 if (suid == null) { 7932 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7933 "Creating application package " + pkg.packageName 7934 + " for shared user failed"); 7935 } 7936 if (DEBUG_PACKAGE_SCANNING) { 7937 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7938 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7939 + "): packages=" + suid.packages); 7940 } 7941 } 7942 7943 // Check if we are renaming from an original package name. 7944 PackageSetting origPackage = null; 7945 String realName = null; 7946 if (pkg.mOriginalPackages != null) { 7947 // This package may need to be renamed to a previously 7948 // installed name. Let's check on that... 7949 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7950 if (pkg.mOriginalPackages.contains(renamed)) { 7951 // This package had originally been installed as the 7952 // original name, and we have already taken care of 7953 // transitioning to the new one. Just update the new 7954 // one to continue using the old name. 7955 realName = pkg.mRealPackage; 7956 if (!pkg.packageName.equals(renamed)) { 7957 // Callers into this function may have already taken 7958 // care of renaming the package; only do it here if 7959 // it is not already done. 7960 pkg.setPackageName(renamed); 7961 } 7962 7963 } else { 7964 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7965 if ((origPackage = mSettings.peekPackageLPr( 7966 pkg.mOriginalPackages.get(i))) != null) { 7967 // We do have the package already installed under its 7968 // original name... should we use it? 7969 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7970 // New package is not compatible with original. 7971 origPackage = null; 7972 continue; 7973 } else if (origPackage.sharedUser != null) { 7974 // Make sure uid is compatible between packages. 7975 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7976 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7977 + " to " + pkg.packageName + ": old uid " 7978 + origPackage.sharedUser.name 7979 + " differs from " + pkg.mSharedUserId); 7980 origPackage = null; 7981 continue; 7982 } 7983 // TODO: Add case when shared user id is added [b/28144775] 7984 } else { 7985 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7986 + pkg.packageName + " to old name " + origPackage.name); 7987 } 7988 break; 7989 } 7990 } 7991 } 7992 } 7993 7994 if (mTransferedPackages.contains(pkg.packageName)) { 7995 Slog.w(TAG, "Package " + pkg.packageName 7996 + " was transferred to another, but its .apk remains"); 7997 } 7998 7999 // See comments in nonMutatedPs declaration 8000 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8001 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8002 if (foundPs != null) { 8003 nonMutatedPs = new PackageSetting(foundPs); 8004 } 8005 } 8006 8007 // Just create the setting, don't add it yet. For already existing packages 8008 // the PkgSetting exists already and doesn't have to be created. 8009 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8010 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8011 pkg.applicationInfo.primaryCpuAbi, 8012 pkg.applicationInfo.secondaryCpuAbi, 8013 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8014 user, false); 8015 if (pkgSetting == null) { 8016 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8017 "Creating application package " + pkg.packageName + " failed"); 8018 } 8019 8020 if (pkgSetting.origPackage != null) { 8021 // If we are first transitioning from an original package, 8022 // fix up the new package's name now. We need to do this after 8023 // looking up the package under its new name, so getPackageLP 8024 // can take care of fiddling things correctly. 8025 pkg.setPackageName(origPackage.name); 8026 8027 // File a report about this. 8028 String msg = "New package " + pkgSetting.realName 8029 + " renamed to replace old package " + pkgSetting.name; 8030 reportSettingsProblem(Log.WARN, msg); 8031 8032 // Make a note of it. 8033 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8034 mTransferedPackages.add(origPackage.name); 8035 } 8036 8037 // No longer need to retain this. 8038 pkgSetting.origPackage = null; 8039 } 8040 8041 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8042 // Make a note of it. 8043 mTransferedPackages.add(pkg.packageName); 8044 } 8045 8046 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8047 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8048 } 8049 8050 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8051 // Check all shared libraries and map to their actual file path. 8052 // We only do this here for apps not on a system dir, because those 8053 // are the only ones that can fail an install due to this. We 8054 // will take care of the system apps by updating all of their 8055 // library paths after the scan is done. 8056 updateSharedLibrariesLPw(pkg, null); 8057 } 8058 8059 if (mFoundPolicyFile) { 8060 SELinuxMMAC.assignSeinfoValue(pkg); 8061 } 8062 8063 pkg.applicationInfo.uid = pkgSetting.appId; 8064 pkg.mExtras = pkgSetting; 8065 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8066 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8067 // We just determined the app is signed correctly, so bring 8068 // over the latest parsed certs. 8069 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8070 } else { 8071 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8072 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8073 "Package " + pkg.packageName + " upgrade keys do not match the " 8074 + "previously installed version"); 8075 } else { 8076 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8077 String msg = "System package " + pkg.packageName 8078 + " signature changed; retaining data."; 8079 reportSettingsProblem(Log.WARN, msg); 8080 } 8081 } 8082 } else { 8083 try { 8084 verifySignaturesLP(pkgSetting, pkg); 8085 // We just determined the app is signed correctly, so bring 8086 // over the latest parsed certs. 8087 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8088 } catch (PackageManagerException e) { 8089 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8090 throw e; 8091 } 8092 // The signature has changed, but this package is in the system 8093 // image... let's recover! 8094 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8095 // However... if this package is part of a shared user, but it 8096 // doesn't match the signature of the shared user, let's fail. 8097 // What this means is that you can't change the signatures 8098 // associated with an overall shared user, which doesn't seem all 8099 // that unreasonable. 8100 if (pkgSetting.sharedUser != null) { 8101 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8102 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8103 throw new PackageManagerException( 8104 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8105 "Signature mismatch for shared user: " 8106 + pkgSetting.sharedUser); 8107 } 8108 } 8109 // File a report about this. 8110 String msg = "System package " + pkg.packageName 8111 + " signature changed; retaining data."; 8112 reportSettingsProblem(Log.WARN, msg); 8113 } 8114 } 8115 // Verify that this new package doesn't have any content providers 8116 // that conflict with existing packages. Only do this if the 8117 // package isn't already installed, since we don't want to break 8118 // things that are installed. 8119 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8120 final int N = pkg.providers.size(); 8121 int i; 8122 for (i=0; i<N; i++) { 8123 PackageParser.Provider p = pkg.providers.get(i); 8124 if (p.info.authority != null) { 8125 String names[] = p.info.authority.split(";"); 8126 for (int j = 0; j < names.length; j++) { 8127 if (mProvidersByAuthority.containsKey(names[j])) { 8128 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8129 final String otherPackageName = 8130 ((other != null && other.getComponentName() != null) ? 8131 other.getComponentName().getPackageName() : "?"); 8132 throw new PackageManagerException( 8133 INSTALL_FAILED_CONFLICTING_PROVIDER, 8134 "Can't install because provider name " + names[j] 8135 + " (in package " + pkg.applicationInfo.packageName 8136 + ") is already used by " + otherPackageName); 8137 } 8138 } 8139 } 8140 } 8141 } 8142 8143 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8144 // This package wants to adopt ownership of permissions from 8145 // another package. 8146 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8147 final String origName = pkg.mAdoptPermissions.get(i); 8148 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8149 if (orig != null) { 8150 if (verifyPackageUpdateLPr(orig, pkg)) { 8151 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8152 + pkg.packageName); 8153 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8154 } 8155 } 8156 } 8157 } 8158 } 8159 8160 final String pkgName = pkg.packageName; 8161 8162 final long scanFileTime = scanFile.lastModified(); 8163 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8164 pkg.applicationInfo.processName = fixProcessName( 8165 pkg.applicationInfo.packageName, 8166 pkg.applicationInfo.processName, 8167 pkg.applicationInfo.uid); 8168 8169 if (pkg != mPlatformPackage) { 8170 // Get all of our default paths setup 8171 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8172 } 8173 8174 final String path = scanFile.getPath(); 8175 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8176 8177 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8178 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8179 8180 // Some system apps still use directory structure for native libraries 8181 // in which case we might end up not detecting abi solely based on apk 8182 // structure. Try to detect abi based on directory structure. 8183 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8184 pkg.applicationInfo.primaryCpuAbi == null) { 8185 setBundledAppAbisAndRoots(pkg, pkgSetting); 8186 setNativeLibraryPaths(pkg); 8187 } 8188 8189 } else { 8190 if ((scanFlags & SCAN_MOVE) != 0) { 8191 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8192 // but we already have this packages package info in the PackageSetting. We just 8193 // use that and derive the native library path based on the new codepath. 8194 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8195 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8196 } 8197 8198 // Set native library paths again. For moves, the path will be updated based on the 8199 // ABIs we've determined above. For non-moves, the path will be updated based on the 8200 // ABIs we determined during compilation, but the path will depend on the final 8201 // package path (after the rename away from the stage path). 8202 setNativeLibraryPaths(pkg); 8203 } 8204 8205 // This is a special case for the "system" package, where the ABI is 8206 // dictated by the zygote configuration (and init.rc). We should keep track 8207 // of this ABI so that we can deal with "normal" applications that run under 8208 // the same UID correctly. 8209 if (mPlatformPackage == pkg) { 8210 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8211 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8212 } 8213 8214 // If there's a mismatch between the abi-override in the package setting 8215 // and the abiOverride specified for the install. Warn about this because we 8216 // would've already compiled the app without taking the package setting into 8217 // account. 8218 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8219 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8220 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8221 " for package " + pkg.packageName); 8222 } 8223 } 8224 8225 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8226 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8227 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8228 8229 // Copy the derived override back to the parsed package, so that we can 8230 // update the package settings accordingly. 8231 pkg.cpuAbiOverride = cpuAbiOverride; 8232 8233 if (DEBUG_ABI_SELECTION) { 8234 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8235 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8236 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8237 } 8238 8239 // Push the derived path down into PackageSettings so we know what to 8240 // clean up at uninstall time. 8241 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8242 8243 if (DEBUG_ABI_SELECTION) { 8244 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8245 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8246 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8247 } 8248 8249 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8250 // We don't do this here during boot because we can do it all 8251 // at once after scanning all existing packages. 8252 // 8253 // We also do this *before* we perform dexopt on this package, so that 8254 // we can avoid redundant dexopts, and also to make sure we've got the 8255 // code and package path correct. 8256 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8257 pkg, true /* boot complete */); 8258 } 8259 8260 if (mFactoryTest && pkg.requestedPermissions.contains( 8261 android.Manifest.permission.FACTORY_TEST)) { 8262 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8263 } 8264 8265 ArrayList<PackageParser.Package> clientLibPkgs = null; 8266 8267 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8268 if (nonMutatedPs != null) { 8269 synchronized (mPackages) { 8270 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8271 } 8272 } 8273 return pkg; 8274 } 8275 8276 // Only privileged apps and updated privileged apps can add child packages. 8277 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8278 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8279 throw new PackageManagerException("Only privileged apps and updated " 8280 + "privileged apps can add child packages. Ignoring package " 8281 + pkg.packageName); 8282 } 8283 final int childCount = pkg.childPackages.size(); 8284 for (int i = 0; i < childCount; i++) { 8285 PackageParser.Package childPkg = pkg.childPackages.get(i); 8286 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8287 childPkg.packageName)) { 8288 throw new PackageManagerException("Cannot override a child package of " 8289 + "another disabled system app. Ignoring package " + pkg.packageName); 8290 } 8291 } 8292 } 8293 8294 // writer 8295 synchronized (mPackages) { 8296 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8297 // Only system apps can add new shared libraries. 8298 if (pkg.libraryNames != null) { 8299 for (int i=0; i<pkg.libraryNames.size(); i++) { 8300 String name = pkg.libraryNames.get(i); 8301 boolean allowed = false; 8302 if (pkg.isUpdatedSystemApp()) { 8303 // New library entries can only be added through the 8304 // system image. This is important to get rid of a lot 8305 // of nasty edge cases: for example if we allowed a non- 8306 // system update of the app to add a library, then uninstalling 8307 // the update would make the library go away, and assumptions 8308 // we made such as through app install filtering would now 8309 // have allowed apps on the device which aren't compatible 8310 // with it. Better to just have the restriction here, be 8311 // conservative, and create many fewer cases that can negatively 8312 // impact the user experience. 8313 final PackageSetting sysPs = mSettings 8314 .getDisabledSystemPkgLPr(pkg.packageName); 8315 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8316 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8317 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8318 allowed = true; 8319 break; 8320 } 8321 } 8322 } 8323 } else { 8324 allowed = true; 8325 } 8326 if (allowed) { 8327 if (!mSharedLibraries.containsKey(name)) { 8328 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8329 } else if (!name.equals(pkg.packageName)) { 8330 Slog.w(TAG, "Package " + pkg.packageName + " library " 8331 + name + " already exists; skipping"); 8332 } 8333 } else { 8334 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8335 + name + " that is not declared on system image; skipping"); 8336 } 8337 } 8338 if ((scanFlags & SCAN_BOOTING) == 0) { 8339 // If we are not booting, we need to update any applications 8340 // that are clients of our shared library. If we are booting, 8341 // this will all be done once the scan is complete. 8342 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8343 } 8344 } 8345 } 8346 } 8347 8348 if ((scanFlags & SCAN_BOOTING) != 0) { 8349 // No apps can run during boot scan, so they don't need to be frozen 8350 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8351 // Caller asked to not kill app, so it's probably not frozen 8352 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8353 // Caller asked us to ignore frozen check for some reason; they 8354 // probably didn't know the package name 8355 } else { 8356 // We're doing major surgery on this package, so it better be frozen 8357 // right now to keep it from launching 8358 checkPackageFrozen(pkgName); 8359 } 8360 8361 // Also need to kill any apps that are dependent on the library. 8362 if (clientLibPkgs != null) { 8363 for (int i=0; i<clientLibPkgs.size(); i++) { 8364 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8365 killApplication(clientPkg.applicationInfo.packageName, 8366 clientPkg.applicationInfo.uid, "update lib"); 8367 } 8368 } 8369 8370 // Make sure we're not adding any bogus keyset info 8371 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8372 ksms.assertScannedPackageValid(pkg); 8373 8374 // writer 8375 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8376 8377 boolean createIdmapFailed = false; 8378 synchronized (mPackages) { 8379 // We don't expect installation to fail beyond this point 8380 8381 // Add the new setting to mSettings 8382 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8383 // Add the new setting to mPackages 8384 mPackages.put(pkg.applicationInfo.packageName, pkg); 8385 // Make sure we don't accidentally delete its data. 8386 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8387 while (iter.hasNext()) { 8388 PackageCleanItem item = iter.next(); 8389 if (pkgName.equals(item.packageName)) { 8390 iter.remove(); 8391 } 8392 } 8393 8394 // Take care of first install / last update times. 8395 if (currentTime != 0) { 8396 if (pkgSetting.firstInstallTime == 0) { 8397 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8398 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8399 pkgSetting.lastUpdateTime = currentTime; 8400 } 8401 } else if (pkgSetting.firstInstallTime == 0) { 8402 // We need *something*. Take time time stamp of the file. 8403 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8404 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8405 if (scanFileTime != pkgSetting.timeStamp) { 8406 // A package on the system image has changed; consider this 8407 // to be an update. 8408 pkgSetting.lastUpdateTime = scanFileTime; 8409 } 8410 } 8411 8412 // Add the package's KeySets to the global KeySetManagerService 8413 ksms.addScannedPackageLPw(pkg); 8414 8415 int N = pkg.providers.size(); 8416 StringBuilder r = null; 8417 int i; 8418 for (i=0; i<N; i++) { 8419 PackageParser.Provider p = pkg.providers.get(i); 8420 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8421 p.info.processName, pkg.applicationInfo.uid); 8422 mProviders.addProvider(p); 8423 p.syncable = p.info.isSyncable; 8424 if (p.info.authority != null) { 8425 String names[] = p.info.authority.split(";"); 8426 p.info.authority = null; 8427 for (int j = 0; j < names.length; j++) { 8428 if (j == 1 && p.syncable) { 8429 // We only want the first authority for a provider to possibly be 8430 // syncable, so if we already added this provider using a different 8431 // authority clear the syncable flag. We copy the provider before 8432 // changing it because the mProviders object contains a reference 8433 // to a provider that we don't want to change. 8434 // Only do this for the second authority since the resulting provider 8435 // object can be the same for all future authorities for this provider. 8436 p = new PackageParser.Provider(p); 8437 p.syncable = false; 8438 } 8439 if (!mProvidersByAuthority.containsKey(names[j])) { 8440 mProvidersByAuthority.put(names[j], p); 8441 if (p.info.authority == null) { 8442 p.info.authority = names[j]; 8443 } else { 8444 p.info.authority = p.info.authority + ";" + names[j]; 8445 } 8446 if (DEBUG_PACKAGE_SCANNING) { 8447 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8448 Log.d(TAG, "Registered content provider: " + names[j] 8449 + ", className = " + p.info.name + ", isSyncable = " 8450 + p.info.isSyncable); 8451 } 8452 } else { 8453 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8454 Slog.w(TAG, "Skipping provider name " + names[j] + 8455 " (in package " + pkg.applicationInfo.packageName + 8456 "): name already used by " 8457 + ((other != null && other.getComponentName() != null) 8458 ? other.getComponentName().getPackageName() : "?")); 8459 } 8460 } 8461 } 8462 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8463 if (r == null) { 8464 r = new StringBuilder(256); 8465 } else { 8466 r.append(' '); 8467 } 8468 r.append(p.info.name); 8469 } 8470 } 8471 if (r != null) { 8472 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8473 } 8474 8475 N = pkg.services.size(); 8476 r = null; 8477 for (i=0; i<N; i++) { 8478 PackageParser.Service s = pkg.services.get(i); 8479 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8480 s.info.processName, pkg.applicationInfo.uid); 8481 mServices.addService(s); 8482 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8483 if (r == null) { 8484 r = new StringBuilder(256); 8485 } else { 8486 r.append(' '); 8487 } 8488 r.append(s.info.name); 8489 } 8490 } 8491 if (r != null) { 8492 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8493 } 8494 8495 N = pkg.receivers.size(); 8496 r = null; 8497 for (i=0; i<N; i++) { 8498 PackageParser.Activity a = pkg.receivers.get(i); 8499 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8500 a.info.processName, pkg.applicationInfo.uid); 8501 mReceivers.addActivity(a, "receiver"); 8502 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8503 if (r == null) { 8504 r = new StringBuilder(256); 8505 } else { 8506 r.append(' '); 8507 } 8508 r.append(a.info.name); 8509 } 8510 } 8511 if (r != null) { 8512 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8513 } 8514 8515 N = pkg.activities.size(); 8516 r = null; 8517 for (i=0; i<N; i++) { 8518 PackageParser.Activity a = pkg.activities.get(i); 8519 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8520 a.info.processName, pkg.applicationInfo.uid); 8521 mActivities.addActivity(a, "activity"); 8522 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8523 if (r == null) { 8524 r = new StringBuilder(256); 8525 } else { 8526 r.append(' '); 8527 } 8528 r.append(a.info.name); 8529 } 8530 } 8531 if (r != null) { 8532 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8533 } 8534 8535 N = pkg.permissionGroups.size(); 8536 r = null; 8537 for (i=0; i<N; i++) { 8538 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8539 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8540 if (cur == null) { 8541 mPermissionGroups.put(pg.info.name, pg); 8542 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8543 if (r == null) { 8544 r = new StringBuilder(256); 8545 } else { 8546 r.append(' '); 8547 } 8548 r.append(pg.info.name); 8549 } 8550 } else { 8551 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8552 + pg.info.packageName + " ignored: original from " 8553 + cur.info.packageName); 8554 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8555 if (r == null) { 8556 r = new StringBuilder(256); 8557 } else { 8558 r.append(' '); 8559 } 8560 r.append("DUP:"); 8561 r.append(pg.info.name); 8562 } 8563 } 8564 } 8565 if (r != null) { 8566 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8567 } 8568 8569 N = pkg.permissions.size(); 8570 r = null; 8571 for (i=0; i<N; i++) { 8572 PackageParser.Permission p = pkg.permissions.get(i); 8573 8574 // Assume by default that we did not install this permission into the system. 8575 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8576 8577 // Now that permission groups have a special meaning, we ignore permission 8578 // groups for legacy apps to prevent unexpected behavior. In particular, 8579 // permissions for one app being granted to someone just becase they happen 8580 // to be in a group defined by another app (before this had no implications). 8581 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8582 p.group = mPermissionGroups.get(p.info.group); 8583 // Warn for a permission in an unknown group. 8584 if (p.info.group != null && p.group == null) { 8585 Slog.w(TAG, "Permission " + p.info.name + " from package " 8586 + p.info.packageName + " in an unknown group " + p.info.group); 8587 } 8588 } 8589 8590 ArrayMap<String, BasePermission> permissionMap = 8591 p.tree ? mSettings.mPermissionTrees 8592 : mSettings.mPermissions; 8593 BasePermission bp = permissionMap.get(p.info.name); 8594 8595 // Allow system apps to redefine non-system permissions 8596 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8597 final boolean currentOwnerIsSystem = (bp.perm != null 8598 && isSystemApp(bp.perm.owner)); 8599 if (isSystemApp(p.owner)) { 8600 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8601 // It's a built-in permission and no owner, take ownership now 8602 bp.packageSetting = pkgSetting; 8603 bp.perm = p; 8604 bp.uid = pkg.applicationInfo.uid; 8605 bp.sourcePackage = p.info.packageName; 8606 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8607 } else if (!currentOwnerIsSystem) { 8608 String msg = "New decl " + p.owner + " of permission " 8609 + p.info.name + " is system; overriding " + bp.sourcePackage; 8610 reportSettingsProblem(Log.WARN, msg); 8611 bp = null; 8612 } 8613 } 8614 } 8615 8616 if (bp == null) { 8617 bp = new BasePermission(p.info.name, p.info.packageName, 8618 BasePermission.TYPE_NORMAL); 8619 permissionMap.put(p.info.name, bp); 8620 } 8621 8622 if (bp.perm == null) { 8623 if (bp.sourcePackage == null 8624 || bp.sourcePackage.equals(p.info.packageName)) { 8625 BasePermission tree = findPermissionTreeLP(p.info.name); 8626 if (tree == null 8627 || tree.sourcePackage.equals(p.info.packageName)) { 8628 bp.packageSetting = pkgSetting; 8629 bp.perm = p; 8630 bp.uid = pkg.applicationInfo.uid; 8631 bp.sourcePackage = p.info.packageName; 8632 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8633 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8634 if (r == null) { 8635 r = new StringBuilder(256); 8636 } else { 8637 r.append(' '); 8638 } 8639 r.append(p.info.name); 8640 } 8641 } else { 8642 Slog.w(TAG, "Permission " + p.info.name + " from package " 8643 + p.info.packageName + " ignored: base tree " 8644 + tree.name + " is from package " 8645 + tree.sourcePackage); 8646 } 8647 } else { 8648 Slog.w(TAG, "Permission " + p.info.name + " from package " 8649 + p.info.packageName + " ignored: original from " 8650 + bp.sourcePackage); 8651 } 8652 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8653 if (r == null) { 8654 r = new StringBuilder(256); 8655 } else { 8656 r.append(' '); 8657 } 8658 r.append("DUP:"); 8659 r.append(p.info.name); 8660 } 8661 if (bp.perm == p) { 8662 bp.protectionLevel = p.info.protectionLevel; 8663 } 8664 } 8665 8666 if (r != null) { 8667 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8668 } 8669 8670 N = pkg.instrumentation.size(); 8671 r = null; 8672 for (i=0; i<N; i++) { 8673 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8674 a.info.packageName = pkg.applicationInfo.packageName; 8675 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8676 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8677 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8678 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8679 a.info.dataDir = pkg.applicationInfo.dataDir; 8680 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8681 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8682 8683 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8684 // need other information about the application, like the ABI and what not ? 8685 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8686 mInstrumentation.put(a.getComponentName(), a); 8687 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8688 if (r == null) { 8689 r = new StringBuilder(256); 8690 } else { 8691 r.append(' '); 8692 } 8693 r.append(a.info.name); 8694 } 8695 } 8696 if (r != null) { 8697 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8698 } 8699 8700 if (pkg.protectedBroadcasts != null) { 8701 N = pkg.protectedBroadcasts.size(); 8702 for (i=0; i<N; i++) { 8703 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8704 } 8705 } 8706 8707 pkgSetting.setTimeStamp(scanFileTime); 8708 8709 // Create idmap files for pairs of (packages, overlay packages). 8710 // Note: "android", ie framework-res.apk, is handled by native layers. 8711 if (pkg.mOverlayTarget != null) { 8712 // This is an overlay package. 8713 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8714 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8715 mOverlays.put(pkg.mOverlayTarget, 8716 new ArrayMap<String, PackageParser.Package>()); 8717 } 8718 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8719 map.put(pkg.packageName, pkg); 8720 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8721 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8722 createIdmapFailed = true; 8723 } 8724 } 8725 } else if (mOverlays.containsKey(pkg.packageName) && 8726 !pkg.packageName.equals("android")) { 8727 // This is a regular package, with one or more known overlay packages. 8728 createIdmapsForPackageLI(pkg); 8729 } 8730 } 8731 8732 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8733 8734 if (createIdmapFailed) { 8735 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8736 "scanPackageLI failed to createIdmap"); 8737 } 8738 return pkg; 8739 } 8740 8741 /** 8742 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8743 * is derived purely on the basis of the contents of {@code scanFile} and 8744 * {@code cpuAbiOverride}. 8745 * 8746 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8747 */ 8748 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8749 String cpuAbiOverride, boolean extractLibs) 8750 throws PackageManagerException { 8751 // TODO: We can probably be smarter about this stuff. For installed apps, 8752 // we can calculate this information at install time once and for all. For 8753 // system apps, we can probably assume that this information doesn't change 8754 // after the first boot scan. As things stand, we do lots of unnecessary work. 8755 8756 // Give ourselves some initial paths; we'll come back for another 8757 // pass once we've determined ABI below. 8758 setNativeLibraryPaths(pkg); 8759 8760 // We would never need to extract libs for forward-locked and external packages, 8761 // since the container service will do it for us. We shouldn't attempt to 8762 // extract libs from system app when it was not updated. 8763 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8764 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8765 extractLibs = false; 8766 } 8767 8768 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8769 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8770 8771 NativeLibraryHelper.Handle handle = null; 8772 try { 8773 handle = NativeLibraryHelper.Handle.create(pkg); 8774 // TODO(multiArch): This can be null for apps that didn't go through the 8775 // usual installation process. We can calculate it again, like we 8776 // do during install time. 8777 // 8778 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8779 // unnecessary. 8780 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8781 8782 // Null out the abis so that they can be recalculated. 8783 pkg.applicationInfo.primaryCpuAbi = null; 8784 pkg.applicationInfo.secondaryCpuAbi = null; 8785 if (isMultiArch(pkg.applicationInfo)) { 8786 // Warn if we've set an abiOverride for multi-lib packages.. 8787 // By definition, we need to copy both 32 and 64 bit libraries for 8788 // such packages. 8789 if (pkg.cpuAbiOverride != null 8790 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8791 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8792 } 8793 8794 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8795 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8796 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8797 if (extractLibs) { 8798 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8799 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8800 useIsaSpecificSubdirs); 8801 } else { 8802 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8803 } 8804 } 8805 8806 maybeThrowExceptionForMultiArchCopy( 8807 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8808 8809 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8810 if (extractLibs) { 8811 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8812 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8813 useIsaSpecificSubdirs); 8814 } else { 8815 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8816 } 8817 } 8818 8819 maybeThrowExceptionForMultiArchCopy( 8820 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8821 8822 if (abi64 >= 0) { 8823 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8824 } 8825 8826 if (abi32 >= 0) { 8827 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8828 if (abi64 >= 0) { 8829 if (pkg.use32bitAbi) { 8830 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8831 pkg.applicationInfo.primaryCpuAbi = abi; 8832 } else { 8833 pkg.applicationInfo.secondaryCpuAbi = abi; 8834 } 8835 } else { 8836 pkg.applicationInfo.primaryCpuAbi = abi; 8837 } 8838 } 8839 8840 } else { 8841 String[] abiList = (cpuAbiOverride != null) ? 8842 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8843 8844 // Enable gross and lame hacks for apps that are built with old 8845 // SDK tools. We must scan their APKs for renderscript bitcode and 8846 // not launch them if it's present. Don't bother checking on devices 8847 // that don't have 64 bit support. 8848 boolean needsRenderScriptOverride = false; 8849 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8850 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8851 abiList = Build.SUPPORTED_32_BIT_ABIS; 8852 needsRenderScriptOverride = true; 8853 } 8854 8855 final int copyRet; 8856 if (extractLibs) { 8857 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8858 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8859 } else { 8860 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8861 } 8862 8863 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8864 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8865 "Error unpackaging native libs for app, errorCode=" + copyRet); 8866 } 8867 8868 if (copyRet >= 0) { 8869 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8870 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8871 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8872 } else if (needsRenderScriptOverride) { 8873 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8874 } 8875 } 8876 } catch (IOException ioe) { 8877 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8878 } finally { 8879 IoUtils.closeQuietly(handle); 8880 } 8881 8882 // Now that we've calculated the ABIs and determined if it's an internal app, 8883 // we will go ahead and populate the nativeLibraryPath. 8884 setNativeLibraryPaths(pkg); 8885 } 8886 8887 /** 8888 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8889 * i.e, so that all packages can be run inside a single process if required. 8890 * 8891 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8892 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8893 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8894 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8895 * updating a package that belongs to a shared user. 8896 * 8897 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8898 * adds unnecessary complexity. 8899 */ 8900 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8901 PackageParser.Package scannedPackage, boolean bootComplete) { 8902 String requiredInstructionSet = null; 8903 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8904 requiredInstructionSet = VMRuntime.getInstructionSet( 8905 scannedPackage.applicationInfo.primaryCpuAbi); 8906 } 8907 8908 PackageSetting requirer = null; 8909 for (PackageSetting ps : packagesForUser) { 8910 // If packagesForUser contains scannedPackage, we skip it. This will happen 8911 // when scannedPackage is an update of an existing package. Without this check, 8912 // we will never be able to change the ABI of any package belonging to a shared 8913 // user, even if it's compatible with other packages. 8914 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8915 if (ps.primaryCpuAbiString == null) { 8916 continue; 8917 } 8918 8919 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8920 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8921 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8922 // this but there's not much we can do. 8923 String errorMessage = "Instruction set mismatch, " 8924 + ((requirer == null) ? "[caller]" : requirer) 8925 + " requires " + requiredInstructionSet + " whereas " + ps 8926 + " requires " + instructionSet; 8927 Slog.w(TAG, errorMessage); 8928 } 8929 8930 if (requiredInstructionSet == null) { 8931 requiredInstructionSet = instructionSet; 8932 requirer = ps; 8933 } 8934 } 8935 } 8936 8937 if (requiredInstructionSet != null) { 8938 String adjustedAbi; 8939 if (requirer != null) { 8940 // requirer != null implies that either scannedPackage was null or that scannedPackage 8941 // did not require an ABI, in which case we have to adjust scannedPackage to match 8942 // the ABI of the set (which is the same as requirer's ABI) 8943 adjustedAbi = requirer.primaryCpuAbiString; 8944 if (scannedPackage != null) { 8945 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8946 } 8947 } else { 8948 // requirer == null implies that we're updating all ABIs in the set to 8949 // match scannedPackage. 8950 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8951 } 8952 8953 for (PackageSetting ps : packagesForUser) { 8954 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8955 if (ps.primaryCpuAbiString != null) { 8956 continue; 8957 } 8958 8959 ps.primaryCpuAbiString = adjustedAbi; 8960 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8961 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8962 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8963 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8964 + " (requirer=" 8965 + (requirer == null ? "null" : requirer.pkg.packageName) 8966 + ", scannedPackage=" 8967 + (scannedPackage != null ? scannedPackage.packageName : "null") 8968 + ")"); 8969 try { 8970 mInstaller.rmdex(ps.codePathString, 8971 getDexCodeInstructionSet(getPreferredInstructionSet())); 8972 } catch (InstallerException ignored) { 8973 } 8974 } 8975 } 8976 } 8977 } 8978 } 8979 8980 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8981 synchronized (mPackages) { 8982 mResolverReplaced = true; 8983 // Set up information for custom user intent resolution activity. 8984 mResolveActivity.applicationInfo = pkg.applicationInfo; 8985 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8986 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8987 mResolveActivity.processName = pkg.applicationInfo.packageName; 8988 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8989 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8990 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8991 mResolveActivity.theme = 0; 8992 mResolveActivity.exported = true; 8993 mResolveActivity.enabled = true; 8994 mResolveInfo.activityInfo = mResolveActivity; 8995 mResolveInfo.priority = 0; 8996 mResolveInfo.preferredOrder = 0; 8997 mResolveInfo.match = 0; 8998 mResolveComponentName = mCustomResolverComponentName; 8999 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9000 mResolveComponentName); 9001 } 9002 } 9003 9004 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9005 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9006 9007 // Set up information for ephemeral installer activity 9008 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9009 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9010 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9011 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9012 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9013 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9014 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9015 mEphemeralInstallerActivity.theme = 0; 9016 mEphemeralInstallerActivity.exported = true; 9017 mEphemeralInstallerActivity.enabled = true; 9018 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9019 mEphemeralInstallerInfo.priority = 0; 9020 mEphemeralInstallerInfo.preferredOrder = 0; 9021 mEphemeralInstallerInfo.match = 0; 9022 9023 if (DEBUG_EPHEMERAL) { 9024 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9025 } 9026 } 9027 9028 private static String calculateBundledApkRoot(final String codePathString) { 9029 final File codePath = new File(codePathString); 9030 final File codeRoot; 9031 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9032 codeRoot = Environment.getRootDirectory(); 9033 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9034 codeRoot = Environment.getOemDirectory(); 9035 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9036 codeRoot = Environment.getVendorDirectory(); 9037 } else { 9038 // Unrecognized code path; take its top real segment as the apk root: 9039 // e.g. /something/app/blah.apk => /something 9040 try { 9041 File f = codePath.getCanonicalFile(); 9042 File parent = f.getParentFile(); // non-null because codePath is a file 9043 File tmp; 9044 while ((tmp = parent.getParentFile()) != null) { 9045 f = parent; 9046 parent = tmp; 9047 } 9048 codeRoot = f; 9049 Slog.w(TAG, "Unrecognized code path " 9050 + codePath + " - using " + codeRoot); 9051 } catch (IOException e) { 9052 // Can't canonicalize the code path -- shenanigans? 9053 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9054 return Environment.getRootDirectory().getPath(); 9055 } 9056 } 9057 return codeRoot.getPath(); 9058 } 9059 9060 /** 9061 * Derive and set the location of native libraries for the given package, 9062 * which varies depending on where and how the package was installed. 9063 */ 9064 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9065 final ApplicationInfo info = pkg.applicationInfo; 9066 final String codePath = pkg.codePath; 9067 final File codeFile = new File(codePath); 9068 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9069 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9070 9071 info.nativeLibraryRootDir = null; 9072 info.nativeLibraryRootRequiresIsa = false; 9073 info.nativeLibraryDir = null; 9074 info.secondaryNativeLibraryDir = null; 9075 9076 if (isApkFile(codeFile)) { 9077 // Monolithic install 9078 if (bundledApp) { 9079 // If "/system/lib64/apkname" exists, assume that is the per-package 9080 // native library directory to use; otherwise use "/system/lib/apkname". 9081 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9082 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9083 getPrimaryInstructionSet(info)); 9084 9085 // This is a bundled system app so choose the path based on the ABI. 9086 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9087 // is just the default path. 9088 final String apkName = deriveCodePathName(codePath); 9089 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9090 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9091 apkName).getAbsolutePath(); 9092 9093 if (info.secondaryCpuAbi != null) { 9094 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9095 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9096 secondaryLibDir, apkName).getAbsolutePath(); 9097 } 9098 } else if (asecApp) { 9099 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9100 .getAbsolutePath(); 9101 } else { 9102 final String apkName = deriveCodePathName(codePath); 9103 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9104 .getAbsolutePath(); 9105 } 9106 9107 info.nativeLibraryRootRequiresIsa = false; 9108 info.nativeLibraryDir = info.nativeLibraryRootDir; 9109 } else { 9110 // Cluster install 9111 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9112 info.nativeLibraryRootRequiresIsa = true; 9113 9114 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9115 getPrimaryInstructionSet(info)).getAbsolutePath(); 9116 9117 if (info.secondaryCpuAbi != null) { 9118 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9119 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9120 } 9121 } 9122 } 9123 9124 /** 9125 * Calculate the abis and roots for a bundled app. These can uniquely 9126 * be determined from the contents of the system partition, i.e whether 9127 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9128 * of this information, and instead assume that the system was built 9129 * sensibly. 9130 */ 9131 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9132 PackageSetting pkgSetting) { 9133 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9134 9135 // If "/system/lib64/apkname" exists, assume that is the per-package 9136 // native library directory to use; otherwise use "/system/lib/apkname". 9137 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9138 setBundledAppAbi(pkg, apkRoot, apkName); 9139 // pkgSetting might be null during rescan following uninstall of updates 9140 // to a bundled app, so accommodate that possibility. The settings in 9141 // that case will be established later from the parsed package. 9142 // 9143 // If the settings aren't null, sync them up with what we've just derived. 9144 // note that apkRoot isn't stored in the package settings. 9145 if (pkgSetting != null) { 9146 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9147 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9148 } 9149 } 9150 9151 /** 9152 * Deduces the ABI of a bundled app and sets the relevant fields on the 9153 * parsed pkg object. 9154 * 9155 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9156 * under which system libraries are installed. 9157 * @param apkName the name of the installed package. 9158 */ 9159 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9160 final File codeFile = new File(pkg.codePath); 9161 9162 final boolean has64BitLibs; 9163 final boolean has32BitLibs; 9164 if (isApkFile(codeFile)) { 9165 // Monolithic install 9166 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9167 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9168 } else { 9169 // Cluster install 9170 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9171 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9172 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9173 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9174 has64BitLibs = (new File(rootDir, isa)).exists(); 9175 } else { 9176 has64BitLibs = false; 9177 } 9178 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9179 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9180 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9181 has32BitLibs = (new File(rootDir, isa)).exists(); 9182 } else { 9183 has32BitLibs = false; 9184 } 9185 } 9186 9187 if (has64BitLibs && !has32BitLibs) { 9188 // The package has 64 bit libs, but not 32 bit libs. Its primary 9189 // ABI should be 64 bit. We can safely assume here that the bundled 9190 // native libraries correspond to the most preferred ABI in the list. 9191 9192 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9193 pkg.applicationInfo.secondaryCpuAbi = null; 9194 } else if (has32BitLibs && !has64BitLibs) { 9195 // The package has 32 bit libs but not 64 bit libs. Its primary 9196 // ABI should be 32 bit. 9197 9198 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9199 pkg.applicationInfo.secondaryCpuAbi = null; 9200 } else if (has32BitLibs && has64BitLibs) { 9201 // The application has both 64 and 32 bit bundled libraries. We check 9202 // here that the app declares multiArch support, and warn if it doesn't. 9203 // 9204 // We will be lenient here and record both ABIs. The primary will be the 9205 // ABI that's higher on the list, i.e, a device that's configured to prefer 9206 // 64 bit apps will see a 64 bit primary ABI, 9207 9208 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9209 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9210 } 9211 9212 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9213 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9214 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9215 } else { 9216 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9217 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9218 } 9219 } else { 9220 pkg.applicationInfo.primaryCpuAbi = null; 9221 pkg.applicationInfo.secondaryCpuAbi = null; 9222 } 9223 } 9224 9225 private void killApplication(String pkgName, int appId, String reason) { 9226 // Request the ActivityManager to kill the process(only for existing packages) 9227 // so that we do not end up in a confused state while the user is still using the older 9228 // version of the application while the new one gets installed. 9229 final long token = Binder.clearCallingIdentity(); 9230 try { 9231 IActivityManager am = ActivityManagerNative.getDefault(); 9232 if (am != null) { 9233 try { 9234 am.killApplicationWithAppId(pkgName, appId, reason); 9235 } catch (RemoteException e) { 9236 } 9237 } 9238 } finally { 9239 Binder.restoreCallingIdentity(token); 9240 } 9241 } 9242 9243 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9244 // Remove the parent package setting 9245 PackageSetting ps = (PackageSetting) pkg.mExtras; 9246 if (ps != null) { 9247 removePackageLI(ps, chatty); 9248 } 9249 // Remove the child package setting 9250 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9251 for (int i = 0; i < childCount; i++) { 9252 PackageParser.Package childPkg = pkg.childPackages.get(i); 9253 ps = (PackageSetting) childPkg.mExtras; 9254 if (ps != null) { 9255 removePackageLI(ps, chatty); 9256 } 9257 } 9258 } 9259 9260 void removePackageLI(PackageSetting ps, boolean chatty) { 9261 if (DEBUG_INSTALL) { 9262 if (chatty) 9263 Log.d(TAG, "Removing package " + ps.name); 9264 } 9265 9266 // writer 9267 synchronized (mPackages) { 9268 mPackages.remove(ps.name); 9269 final PackageParser.Package pkg = ps.pkg; 9270 if (pkg != null) { 9271 cleanPackageDataStructuresLILPw(pkg, chatty); 9272 } 9273 } 9274 } 9275 9276 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9277 if (DEBUG_INSTALL) { 9278 if (chatty) 9279 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9280 } 9281 9282 // writer 9283 synchronized (mPackages) { 9284 // Remove the parent package 9285 mPackages.remove(pkg.applicationInfo.packageName); 9286 cleanPackageDataStructuresLILPw(pkg, chatty); 9287 9288 // Remove the child packages 9289 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9290 for (int i = 0; i < childCount; i++) { 9291 PackageParser.Package childPkg = pkg.childPackages.get(i); 9292 mPackages.remove(childPkg.applicationInfo.packageName); 9293 cleanPackageDataStructuresLILPw(childPkg, chatty); 9294 } 9295 } 9296 } 9297 9298 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9299 int N = pkg.providers.size(); 9300 StringBuilder r = null; 9301 int i; 9302 for (i=0; i<N; i++) { 9303 PackageParser.Provider p = pkg.providers.get(i); 9304 mProviders.removeProvider(p); 9305 if (p.info.authority == null) { 9306 9307 /* There was another ContentProvider with this authority when 9308 * this app was installed so this authority is null, 9309 * Ignore it as we don't have to unregister the provider. 9310 */ 9311 continue; 9312 } 9313 String names[] = p.info.authority.split(";"); 9314 for (int j = 0; j < names.length; j++) { 9315 if (mProvidersByAuthority.get(names[j]) == p) { 9316 mProvidersByAuthority.remove(names[j]); 9317 if (DEBUG_REMOVE) { 9318 if (chatty) 9319 Log.d(TAG, "Unregistered content provider: " + names[j] 9320 + ", className = " + p.info.name + ", isSyncable = " 9321 + p.info.isSyncable); 9322 } 9323 } 9324 } 9325 if (DEBUG_REMOVE && chatty) { 9326 if (r == null) { 9327 r = new StringBuilder(256); 9328 } else { 9329 r.append(' '); 9330 } 9331 r.append(p.info.name); 9332 } 9333 } 9334 if (r != null) { 9335 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9336 } 9337 9338 N = pkg.services.size(); 9339 r = null; 9340 for (i=0; i<N; i++) { 9341 PackageParser.Service s = pkg.services.get(i); 9342 mServices.removeService(s); 9343 if (chatty) { 9344 if (r == null) { 9345 r = new StringBuilder(256); 9346 } else { 9347 r.append(' '); 9348 } 9349 r.append(s.info.name); 9350 } 9351 } 9352 if (r != null) { 9353 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9354 } 9355 9356 N = pkg.receivers.size(); 9357 r = null; 9358 for (i=0; i<N; i++) { 9359 PackageParser.Activity a = pkg.receivers.get(i); 9360 mReceivers.removeActivity(a, "receiver"); 9361 if (DEBUG_REMOVE && chatty) { 9362 if (r == null) { 9363 r = new StringBuilder(256); 9364 } else { 9365 r.append(' '); 9366 } 9367 r.append(a.info.name); 9368 } 9369 } 9370 if (r != null) { 9371 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9372 } 9373 9374 N = pkg.activities.size(); 9375 r = null; 9376 for (i=0; i<N; i++) { 9377 PackageParser.Activity a = pkg.activities.get(i); 9378 mActivities.removeActivity(a, "activity"); 9379 if (DEBUG_REMOVE && chatty) { 9380 if (r == null) { 9381 r = new StringBuilder(256); 9382 } else { 9383 r.append(' '); 9384 } 9385 r.append(a.info.name); 9386 } 9387 } 9388 if (r != null) { 9389 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9390 } 9391 9392 N = pkg.permissions.size(); 9393 r = null; 9394 for (i=0; i<N; i++) { 9395 PackageParser.Permission p = pkg.permissions.get(i); 9396 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9397 if (bp == null) { 9398 bp = mSettings.mPermissionTrees.get(p.info.name); 9399 } 9400 if (bp != null && bp.perm == p) { 9401 bp.perm = null; 9402 if (DEBUG_REMOVE && chatty) { 9403 if (r == null) { 9404 r = new StringBuilder(256); 9405 } else { 9406 r.append(' '); 9407 } 9408 r.append(p.info.name); 9409 } 9410 } 9411 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9412 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9413 if (appOpPkgs != null) { 9414 appOpPkgs.remove(pkg.packageName); 9415 } 9416 } 9417 } 9418 if (r != null) { 9419 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9420 } 9421 9422 N = pkg.requestedPermissions.size(); 9423 r = null; 9424 for (i=0; i<N; i++) { 9425 String perm = pkg.requestedPermissions.get(i); 9426 BasePermission bp = mSettings.mPermissions.get(perm); 9427 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9428 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9429 if (appOpPkgs != null) { 9430 appOpPkgs.remove(pkg.packageName); 9431 if (appOpPkgs.isEmpty()) { 9432 mAppOpPermissionPackages.remove(perm); 9433 } 9434 } 9435 } 9436 } 9437 if (r != null) { 9438 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9439 } 9440 9441 N = pkg.instrumentation.size(); 9442 r = null; 9443 for (i=0; i<N; i++) { 9444 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9445 mInstrumentation.remove(a.getComponentName()); 9446 if (DEBUG_REMOVE && chatty) { 9447 if (r == null) { 9448 r = new StringBuilder(256); 9449 } else { 9450 r.append(' '); 9451 } 9452 r.append(a.info.name); 9453 } 9454 } 9455 if (r != null) { 9456 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9457 } 9458 9459 r = null; 9460 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9461 // Only system apps can hold shared libraries. 9462 if (pkg.libraryNames != null) { 9463 for (i=0; i<pkg.libraryNames.size(); i++) { 9464 String name = pkg.libraryNames.get(i); 9465 SharedLibraryEntry cur = mSharedLibraries.get(name); 9466 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9467 mSharedLibraries.remove(name); 9468 if (DEBUG_REMOVE && chatty) { 9469 if (r == null) { 9470 r = new StringBuilder(256); 9471 } else { 9472 r.append(' '); 9473 } 9474 r.append(name); 9475 } 9476 } 9477 } 9478 } 9479 } 9480 if (r != null) { 9481 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9482 } 9483 } 9484 9485 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9486 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9487 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9488 return true; 9489 } 9490 } 9491 return false; 9492 } 9493 9494 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9495 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9496 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9497 9498 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9499 // Update the parent permissions 9500 updatePermissionsLPw(pkg.packageName, pkg, flags); 9501 // Update the child permissions 9502 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9503 for (int i = 0; i < childCount; i++) { 9504 PackageParser.Package childPkg = pkg.childPackages.get(i); 9505 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9506 } 9507 } 9508 9509 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9510 int flags) { 9511 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9512 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9513 } 9514 9515 private void updatePermissionsLPw(String changingPkg, 9516 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9517 // Make sure there are no dangling permission trees. 9518 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9519 while (it.hasNext()) { 9520 final BasePermission bp = it.next(); 9521 if (bp.packageSetting == null) { 9522 // We may not yet have parsed the package, so just see if 9523 // we still know about its settings. 9524 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9525 } 9526 if (bp.packageSetting == null) { 9527 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9528 + " from package " + bp.sourcePackage); 9529 it.remove(); 9530 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9531 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9532 Slog.i(TAG, "Removing old permission tree: " + bp.name 9533 + " from package " + bp.sourcePackage); 9534 flags |= UPDATE_PERMISSIONS_ALL; 9535 it.remove(); 9536 } 9537 } 9538 } 9539 9540 // Make sure all dynamic permissions have been assigned to a package, 9541 // and make sure there are no dangling permissions. 9542 it = mSettings.mPermissions.values().iterator(); 9543 while (it.hasNext()) { 9544 final BasePermission bp = it.next(); 9545 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9546 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9547 + bp.name + " pkg=" + bp.sourcePackage 9548 + " info=" + bp.pendingInfo); 9549 if (bp.packageSetting == null && bp.pendingInfo != null) { 9550 final BasePermission tree = findPermissionTreeLP(bp.name); 9551 if (tree != null && tree.perm != null) { 9552 bp.packageSetting = tree.packageSetting; 9553 bp.perm = new PackageParser.Permission(tree.perm.owner, 9554 new PermissionInfo(bp.pendingInfo)); 9555 bp.perm.info.packageName = tree.perm.info.packageName; 9556 bp.perm.info.name = bp.name; 9557 bp.uid = tree.uid; 9558 } 9559 } 9560 } 9561 if (bp.packageSetting == null) { 9562 // We may not yet have parsed the package, so just see if 9563 // we still know about its settings. 9564 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9565 } 9566 if (bp.packageSetting == null) { 9567 Slog.w(TAG, "Removing dangling permission: " + bp.name 9568 + " from package " + bp.sourcePackage); 9569 it.remove(); 9570 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9571 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9572 Slog.i(TAG, "Removing old permission: " + bp.name 9573 + " from package " + bp.sourcePackage); 9574 flags |= UPDATE_PERMISSIONS_ALL; 9575 it.remove(); 9576 } 9577 } 9578 } 9579 9580 // Now update the permissions for all packages, in particular 9581 // replace the granted permissions of the system packages. 9582 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9583 for (PackageParser.Package pkg : mPackages.values()) { 9584 if (pkg != pkgInfo) { 9585 // Only replace for packages on requested volume 9586 final String volumeUuid = getVolumeUuidForPackage(pkg); 9587 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9588 && Objects.equals(replaceVolumeUuid, volumeUuid); 9589 grantPermissionsLPw(pkg, replace, changingPkg); 9590 } 9591 } 9592 } 9593 9594 if (pkgInfo != null) { 9595 // Only replace for packages on requested volume 9596 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9597 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9598 && Objects.equals(replaceVolumeUuid, volumeUuid); 9599 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9600 } 9601 } 9602 9603 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9604 String packageOfInterest) { 9605 // IMPORTANT: There are two types of permissions: install and runtime. 9606 // Install time permissions are granted when the app is installed to 9607 // all device users and users added in the future. Runtime permissions 9608 // are granted at runtime explicitly to specific users. Normal and signature 9609 // protected permissions are install time permissions. Dangerous permissions 9610 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9611 // otherwise they are runtime permissions. This function does not manage 9612 // runtime permissions except for the case an app targeting Lollipop MR1 9613 // being upgraded to target a newer SDK, in which case dangerous permissions 9614 // are transformed from install time to runtime ones. 9615 9616 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9617 if (ps == null) { 9618 return; 9619 } 9620 9621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9622 9623 PermissionsState permissionsState = ps.getPermissionsState(); 9624 PermissionsState origPermissions = permissionsState; 9625 9626 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9627 9628 boolean runtimePermissionsRevoked = false; 9629 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9630 9631 boolean changedInstallPermission = false; 9632 9633 if (replace) { 9634 ps.installPermissionsFixed = false; 9635 if (!ps.isSharedUser()) { 9636 origPermissions = new PermissionsState(permissionsState); 9637 permissionsState.reset(); 9638 } else { 9639 // We need to know only about runtime permission changes since the 9640 // calling code always writes the install permissions state but 9641 // the runtime ones are written only if changed. The only cases of 9642 // changed runtime permissions here are promotion of an install to 9643 // runtime and revocation of a runtime from a shared user. 9644 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9645 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9646 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9647 runtimePermissionsRevoked = true; 9648 } 9649 } 9650 } 9651 9652 permissionsState.setGlobalGids(mGlobalGids); 9653 9654 final int N = pkg.requestedPermissions.size(); 9655 for (int i=0; i<N; i++) { 9656 final String name = pkg.requestedPermissions.get(i); 9657 final BasePermission bp = mSettings.mPermissions.get(name); 9658 9659 if (DEBUG_INSTALL) { 9660 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9661 } 9662 9663 if (bp == null || bp.packageSetting == null) { 9664 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9665 Slog.w(TAG, "Unknown permission " + name 9666 + " in package " + pkg.packageName); 9667 } 9668 continue; 9669 } 9670 9671 final String perm = bp.name; 9672 boolean allowedSig = false; 9673 int grant = GRANT_DENIED; 9674 9675 // Keep track of app op permissions. 9676 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9677 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9678 if (pkgs == null) { 9679 pkgs = new ArraySet<>(); 9680 mAppOpPermissionPackages.put(bp.name, pkgs); 9681 } 9682 pkgs.add(pkg.packageName); 9683 } 9684 9685 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9686 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9687 >= Build.VERSION_CODES.M; 9688 switch (level) { 9689 case PermissionInfo.PROTECTION_NORMAL: { 9690 // For all apps normal permissions are install time ones. 9691 grant = GRANT_INSTALL; 9692 } break; 9693 9694 case PermissionInfo.PROTECTION_DANGEROUS: { 9695 // If a permission review is required for legacy apps we represent 9696 // their permissions as always granted runtime ones since we need 9697 // to keep the review required permission flag per user while an 9698 // install permission's state is shared across all users. 9699 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9700 // For legacy apps dangerous permissions are install time ones. 9701 grant = GRANT_INSTALL; 9702 } else if (origPermissions.hasInstallPermission(bp.name)) { 9703 // For legacy apps that became modern, install becomes runtime. 9704 grant = GRANT_UPGRADE; 9705 } else if (mPromoteSystemApps 9706 && isSystemApp(ps) 9707 && mExistingSystemPackages.contains(ps.name)) { 9708 // For legacy system apps, install becomes runtime. 9709 // We cannot check hasInstallPermission() for system apps since those 9710 // permissions were granted implicitly and not persisted pre-M. 9711 grant = GRANT_UPGRADE; 9712 } else { 9713 // For modern apps keep runtime permissions unchanged. 9714 grant = GRANT_RUNTIME; 9715 } 9716 } break; 9717 9718 case PermissionInfo.PROTECTION_SIGNATURE: { 9719 // For all apps signature permissions are install time ones. 9720 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9721 if (allowedSig) { 9722 grant = GRANT_INSTALL; 9723 } 9724 } break; 9725 } 9726 9727 if (DEBUG_INSTALL) { 9728 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9729 } 9730 9731 if (grant != GRANT_DENIED) { 9732 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9733 // If this is an existing, non-system package, then 9734 // we can't add any new permissions to it. 9735 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9736 // Except... if this is a permission that was added 9737 // to the platform (note: need to only do this when 9738 // updating the platform). 9739 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9740 grant = GRANT_DENIED; 9741 } 9742 } 9743 } 9744 9745 switch (grant) { 9746 case GRANT_INSTALL: { 9747 // Revoke this as runtime permission to handle the case of 9748 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9749 for (int userId : UserManagerService.getInstance().getUserIds()) { 9750 if (origPermissions.getRuntimePermissionState( 9751 bp.name, userId) != null) { 9752 // Revoke the runtime permission and clear the flags. 9753 origPermissions.revokeRuntimePermission(bp, userId); 9754 origPermissions.updatePermissionFlags(bp, userId, 9755 PackageManager.MASK_PERMISSION_FLAGS, 0); 9756 // If we revoked a permission permission, we have to write. 9757 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9758 changedRuntimePermissionUserIds, userId); 9759 } 9760 } 9761 // Grant an install permission. 9762 if (permissionsState.grantInstallPermission(bp) != 9763 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9764 changedInstallPermission = true; 9765 } 9766 } break; 9767 9768 case GRANT_RUNTIME: { 9769 // Grant previously granted runtime permissions. 9770 for (int userId : UserManagerService.getInstance().getUserIds()) { 9771 PermissionState permissionState = origPermissions 9772 .getRuntimePermissionState(bp.name, userId); 9773 int flags = permissionState != null 9774 ? permissionState.getFlags() : 0; 9775 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9776 if (permissionsState.grantRuntimePermission(bp, userId) == 9777 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9778 // If we cannot put the permission as it was, we have to write. 9779 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9780 changedRuntimePermissionUserIds, userId); 9781 } 9782 // If the app supports runtime permissions no need for a review. 9783 if (Build.PERMISSIONS_REVIEW_REQUIRED 9784 && appSupportsRuntimePermissions 9785 && (flags & PackageManager 9786 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9787 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9788 // Since we changed the flags, we have to write. 9789 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9790 changedRuntimePermissionUserIds, userId); 9791 } 9792 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9793 && !appSupportsRuntimePermissions) { 9794 // For legacy apps that need a permission review, every new 9795 // runtime permission is granted but it is pending a review. 9796 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9797 permissionsState.grantRuntimePermission(bp, userId); 9798 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9799 // We changed the permission and flags, hence have to write. 9800 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9801 changedRuntimePermissionUserIds, userId); 9802 } 9803 } 9804 // Propagate the permission flags. 9805 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9806 } 9807 } break; 9808 9809 case GRANT_UPGRADE: { 9810 // Grant runtime permissions for a previously held install permission. 9811 PermissionState permissionState = origPermissions 9812 .getInstallPermissionState(bp.name); 9813 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9814 9815 if (origPermissions.revokeInstallPermission(bp) 9816 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9817 // We will be transferring the permission flags, so clear them. 9818 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9819 PackageManager.MASK_PERMISSION_FLAGS, 0); 9820 changedInstallPermission = true; 9821 } 9822 9823 // If the permission is not to be promoted to runtime we ignore it and 9824 // also its other flags as they are not applicable to install permissions. 9825 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9826 for (int userId : currentUserIds) { 9827 if (permissionsState.grantRuntimePermission(bp, userId) != 9828 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9829 // Transfer the permission flags. 9830 permissionsState.updatePermissionFlags(bp, userId, 9831 flags, flags); 9832 // If we granted the permission, we have to write. 9833 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9834 changedRuntimePermissionUserIds, userId); 9835 } 9836 } 9837 } 9838 } break; 9839 9840 default: { 9841 if (packageOfInterest == null 9842 || packageOfInterest.equals(pkg.packageName)) { 9843 Slog.w(TAG, "Not granting permission " + perm 9844 + " to package " + pkg.packageName 9845 + " because it was previously installed without"); 9846 } 9847 } break; 9848 } 9849 } else { 9850 if (permissionsState.revokeInstallPermission(bp) != 9851 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9852 // Also drop the permission flags. 9853 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9854 PackageManager.MASK_PERMISSION_FLAGS, 0); 9855 changedInstallPermission = true; 9856 Slog.i(TAG, "Un-granting permission " + perm 9857 + " from package " + pkg.packageName 9858 + " (protectionLevel=" + bp.protectionLevel 9859 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9860 + ")"); 9861 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9862 // Don't print warning for app op permissions, since it is fine for them 9863 // not to be granted, there is a UI for the user to decide. 9864 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9865 Slog.w(TAG, "Not granting permission " + perm 9866 + " to package " + pkg.packageName 9867 + " (protectionLevel=" + bp.protectionLevel 9868 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9869 + ")"); 9870 } 9871 } 9872 } 9873 } 9874 9875 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9876 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9877 // This is the first that we have heard about this package, so the 9878 // permissions we have now selected are fixed until explicitly 9879 // changed. 9880 ps.installPermissionsFixed = true; 9881 } 9882 9883 // Persist the runtime permissions state for users with changes. If permissions 9884 // were revoked because no app in the shared user declares them we have to 9885 // write synchronously to avoid losing runtime permissions state. 9886 for (int userId : changedRuntimePermissionUserIds) { 9887 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9888 } 9889 9890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9891 } 9892 9893 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9894 boolean allowed = false; 9895 final int NP = PackageParser.NEW_PERMISSIONS.length; 9896 for (int ip=0; ip<NP; ip++) { 9897 final PackageParser.NewPermissionInfo npi 9898 = PackageParser.NEW_PERMISSIONS[ip]; 9899 if (npi.name.equals(perm) 9900 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9901 allowed = true; 9902 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9903 + pkg.packageName); 9904 break; 9905 } 9906 } 9907 return allowed; 9908 } 9909 9910 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9911 BasePermission bp, PermissionsState origPermissions) { 9912 boolean allowed; 9913 allowed = (compareSignatures( 9914 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9915 == PackageManager.SIGNATURE_MATCH) 9916 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9917 == PackageManager.SIGNATURE_MATCH); 9918 if (!allowed && (bp.protectionLevel 9919 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9920 if (isSystemApp(pkg)) { 9921 // For updated system applications, a system permission 9922 // is granted only if it had been defined by the original application. 9923 if (pkg.isUpdatedSystemApp()) { 9924 final PackageSetting sysPs = mSettings 9925 .getDisabledSystemPkgLPr(pkg.packageName); 9926 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9927 // If the original was granted this permission, we take 9928 // that grant decision as read and propagate it to the 9929 // update. 9930 if (sysPs.isPrivileged()) { 9931 allowed = true; 9932 } 9933 } else { 9934 // The system apk may have been updated with an older 9935 // version of the one on the data partition, but which 9936 // granted a new system permission that it didn't have 9937 // before. In this case we do want to allow the app to 9938 // now get the new permission if the ancestral apk is 9939 // privileged to get it. 9940 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9941 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9942 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9943 allowed = true; 9944 break; 9945 } 9946 } 9947 } 9948 // Also if a privileged parent package on the system image or any of 9949 // its children requested a privileged permission, the updated child 9950 // packages can also get the permission. 9951 if (pkg.parentPackage != null) { 9952 final PackageSetting disabledSysParentPs = mSettings 9953 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9954 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9955 && disabledSysParentPs.isPrivileged()) { 9956 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9957 allowed = true; 9958 } else if (disabledSysParentPs.pkg.childPackages != null) { 9959 final int count = disabledSysParentPs.pkg.childPackages.size(); 9960 for (int i = 0; i < count; i++) { 9961 PackageParser.Package disabledSysChildPkg = 9962 disabledSysParentPs.pkg.childPackages.get(i); 9963 if (isPackageRequestingPermission(disabledSysChildPkg, 9964 perm)) { 9965 allowed = true; 9966 break; 9967 } 9968 } 9969 } 9970 } 9971 } 9972 } 9973 } else { 9974 allowed = isPrivilegedApp(pkg); 9975 } 9976 } 9977 } 9978 if (!allowed) { 9979 if (!allowed && (bp.protectionLevel 9980 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9981 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9982 // If this was a previously normal/dangerous permission that got moved 9983 // to a system permission as part of the runtime permission redesign, then 9984 // we still want to blindly grant it to old apps. 9985 allowed = true; 9986 } 9987 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9988 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9989 // If this permission is to be granted to the system installer and 9990 // this app is an installer, then it gets the permission. 9991 allowed = true; 9992 } 9993 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9994 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9995 // If this permission is to be granted to the system verifier and 9996 // this app is a verifier, then it gets the permission. 9997 allowed = true; 9998 } 9999 if (!allowed && (bp.protectionLevel 10000 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10001 && isSystemApp(pkg)) { 10002 // Any pre-installed system app is allowed to get this permission. 10003 allowed = true; 10004 } 10005 if (!allowed && (bp.protectionLevel 10006 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10007 // For development permissions, a development permission 10008 // is granted only if it was already granted. 10009 allowed = origPermissions.hasInstallPermission(perm); 10010 } 10011 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10012 && pkg.packageName.equals(mSetupWizardPackage)) { 10013 // If this permission is to be granted to the system setup wizard and 10014 // this app is a setup wizard, then it gets the permission. 10015 allowed = true; 10016 } 10017 } 10018 return allowed; 10019 } 10020 10021 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10022 final int permCount = pkg.requestedPermissions.size(); 10023 for (int j = 0; j < permCount; j++) { 10024 String requestedPermission = pkg.requestedPermissions.get(j); 10025 if (permission.equals(requestedPermission)) { 10026 return true; 10027 } 10028 } 10029 return false; 10030 } 10031 10032 final class ActivityIntentResolver 10033 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10034 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10035 boolean defaultOnly, int userId) { 10036 if (!sUserManager.exists(userId)) return null; 10037 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10038 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10039 } 10040 10041 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10042 int userId) { 10043 if (!sUserManager.exists(userId)) return null; 10044 mFlags = flags; 10045 return super.queryIntent(intent, resolvedType, 10046 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10047 } 10048 10049 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10050 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10051 if (!sUserManager.exists(userId)) return null; 10052 if (packageActivities == null) { 10053 return null; 10054 } 10055 mFlags = flags; 10056 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10057 final int N = packageActivities.size(); 10058 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10059 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10060 10061 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10062 for (int i = 0; i < N; ++i) { 10063 intentFilters = packageActivities.get(i).intents; 10064 if (intentFilters != null && intentFilters.size() > 0) { 10065 PackageParser.ActivityIntentInfo[] array = 10066 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10067 intentFilters.toArray(array); 10068 listCut.add(array); 10069 } 10070 } 10071 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10072 } 10073 10074 /** 10075 * Finds a privileged activity that matches the specified activity names. 10076 */ 10077 private PackageParser.Activity findMatchingActivity( 10078 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10079 for (PackageParser.Activity sysActivity : activityList) { 10080 if (sysActivity.info.name.equals(activityInfo.name)) { 10081 return sysActivity; 10082 } 10083 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10084 return sysActivity; 10085 } 10086 if (sysActivity.info.targetActivity != null) { 10087 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10088 return sysActivity; 10089 } 10090 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10091 return sysActivity; 10092 } 10093 } 10094 } 10095 return null; 10096 } 10097 10098 public class IterGenerator<E> { 10099 public Iterator<E> generate(ActivityIntentInfo info) { 10100 return null; 10101 } 10102 } 10103 10104 public class ActionIterGenerator extends IterGenerator<String> { 10105 @Override 10106 public Iterator<String> generate(ActivityIntentInfo info) { 10107 return info.actionsIterator(); 10108 } 10109 } 10110 10111 public class CategoriesIterGenerator extends IterGenerator<String> { 10112 @Override 10113 public Iterator<String> generate(ActivityIntentInfo info) { 10114 return info.categoriesIterator(); 10115 } 10116 } 10117 10118 public class SchemesIterGenerator extends IterGenerator<String> { 10119 @Override 10120 public Iterator<String> generate(ActivityIntentInfo info) { 10121 return info.schemesIterator(); 10122 } 10123 } 10124 10125 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10126 @Override 10127 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10128 return info.authoritiesIterator(); 10129 } 10130 } 10131 10132 /** 10133 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10134 * MODIFIED. Do not pass in a list that should not be changed. 10135 */ 10136 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10137 IterGenerator<T> generator, Iterator<T> searchIterator) { 10138 // loop through the set of actions; every one must be found in the intent filter 10139 while (searchIterator.hasNext()) { 10140 // we must have at least one filter in the list to consider a match 10141 if (intentList.size() == 0) { 10142 break; 10143 } 10144 10145 final T searchAction = searchIterator.next(); 10146 10147 // loop through the set of intent filters 10148 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10149 while (intentIter.hasNext()) { 10150 final ActivityIntentInfo intentInfo = intentIter.next(); 10151 boolean selectionFound = false; 10152 10153 // loop through the intent filter's selection criteria; at least one 10154 // of them must match the searched criteria 10155 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10156 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10157 final T intentSelection = intentSelectionIter.next(); 10158 if (intentSelection != null && intentSelection.equals(searchAction)) { 10159 selectionFound = true; 10160 break; 10161 } 10162 } 10163 10164 // the selection criteria wasn't found in this filter's set; this filter 10165 // is not a potential match 10166 if (!selectionFound) { 10167 intentIter.remove(); 10168 } 10169 } 10170 } 10171 } 10172 10173 private boolean isProtectedAction(ActivityIntentInfo filter) { 10174 final Iterator<String> actionsIter = filter.actionsIterator(); 10175 while (actionsIter != null && actionsIter.hasNext()) { 10176 final String filterAction = actionsIter.next(); 10177 if (PROTECTED_ACTIONS.contains(filterAction)) { 10178 return true; 10179 } 10180 } 10181 return false; 10182 } 10183 10184 /** 10185 * Adjusts the priority of the given intent filter according to policy. 10186 * <p> 10187 * <ul> 10188 * <li>The priority for non privileged applications is capped to '0'</li> 10189 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10190 * <li>The priority for unbundled updates to privileged applications is capped to the 10191 * priority defined on the system partition</li> 10192 * </ul> 10193 * <p> 10194 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10195 * allowed to obtain any priority on any action. 10196 */ 10197 private void adjustPriority( 10198 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10199 // nothing to do; priority is fine as-is 10200 if (intent.getPriority() <= 0) { 10201 return; 10202 } 10203 10204 final ActivityInfo activityInfo = intent.activity.info; 10205 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10206 10207 final boolean privilegedApp = 10208 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10209 if (!privilegedApp) { 10210 // non-privileged applications can never define a priority >0 10211 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10212 + " package: " + applicationInfo.packageName 10213 + " activity: " + intent.activity.className 10214 + " origPrio: " + intent.getPriority()); 10215 intent.setPriority(0); 10216 return; 10217 } 10218 10219 if (systemActivities == null) { 10220 // the system package is not disabled; we're parsing the system partition 10221 if (isProtectedAction(intent)) { 10222 if (mDeferProtectedFilters) { 10223 // We can't deal with these just yet. No component should ever obtain a 10224 // >0 priority for a protected actions, with ONE exception -- the setup 10225 // wizard. The setup wizard, however, cannot be known until we're able to 10226 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10227 // until all intent filters have been processed. Chicken, meet egg. 10228 // Let the filter temporarily have a high priority and rectify the 10229 // priorities after all system packages have been scanned. 10230 mProtectedFilters.add(intent); 10231 if (DEBUG_FILTERS) { 10232 Slog.i(TAG, "Protected action; save for later;" 10233 + " package: " + applicationInfo.packageName 10234 + " activity: " + intent.activity.className 10235 + " origPrio: " + intent.getPriority()); 10236 } 10237 return; 10238 } else { 10239 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10240 Slog.i(TAG, "No setup wizard;" 10241 + " All protected intents capped to priority 0"); 10242 } 10243 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10244 if (DEBUG_FILTERS) { 10245 Slog.i(TAG, "Found setup wizard;" 10246 + " allow priority " + intent.getPriority() + ";" 10247 + " package: " + intent.activity.info.packageName 10248 + " activity: " + intent.activity.className 10249 + " priority: " + intent.getPriority()); 10250 } 10251 // setup wizard gets whatever it wants 10252 return; 10253 } 10254 Slog.w(TAG, "Protected action; cap priority to 0;" 10255 + " package: " + intent.activity.info.packageName 10256 + " activity: " + intent.activity.className 10257 + " origPrio: " + intent.getPriority()); 10258 intent.setPriority(0); 10259 return; 10260 } 10261 } 10262 // privileged apps on the system image get whatever priority they request 10263 return; 10264 } 10265 10266 // privileged app unbundled update ... try to find the same activity 10267 final PackageParser.Activity foundActivity = 10268 findMatchingActivity(systemActivities, activityInfo); 10269 if (foundActivity == null) { 10270 // this is a new activity; it cannot obtain >0 priority 10271 if (DEBUG_FILTERS) { 10272 Slog.i(TAG, "New activity; cap priority to 0;" 10273 + " package: " + applicationInfo.packageName 10274 + " activity: " + intent.activity.className 10275 + " origPrio: " + intent.getPriority()); 10276 } 10277 intent.setPriority(0); 10278 return; 10279 } 10280 10281 // found activity, now check for filter equivalence 10282 10283 // a shallow copy is enough; we modify the list, not its contents 10284 final List<ActivityIntentInfo> intentListCopy = 10285 new ArrayList<>(foundActivity.intents); 10286 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10287 10288 // find matching action subsets 10289 final Iterator<String> actionsIterator = intent.actionsIterator(); 10290 if (actionsIterator != null) { 10291 getIntentListSubset( 10292 intentListCopy, new ActionIterGenerator(), actionsIterator); 10293 if (intentListCopy.size() == 0) { 10294 // no more intents to match; we're not equivalent 10295 if (DEBUG_FILTERS) { 10296 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10297 + " package: " + applicationInfo.packageName 10298 + " activity: " + intent.activity.className 10299 + " origPrio: " + intent.getPriority()); 10300 } 10301 intent.setPriority(0); 10302 return; 10303 } 10304 } 10305 10306 // find matching category subsets 10307 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10308 if (categoriesIterator != null) { 10309 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10310 categoriesIterator); 10311 if (intentListCopy.size() == 0) { 10312 // no more intents to match; we're not equivalent 10313 if (DEBUG_FILTERS) { 10314 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10315 + " package: " + applicationInfo.packageName 10316 + " activity: " + intent.activity.className 10317 + " origPrio: " + intent.getPriority()); 10318 } 10319 intent.setPriority(0); 10320 return; 10321 } 10322 } 10323 10324 // find matching schemes subsets 10325 final Iterator<String> schemesIterator = intent.schemesIterator(); 10326 if (schemesIterator != null) { 10327 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10328 schemesIterator); 10329 if (intentListCopy.size() == 0) { 10330 // no more intents to match; we're not equivalent 10331 if (DEBUG_FILTERS) { 10332 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10333 + " package: " + applicationInfo.packageName 10334 + " activity: " + intent.activity.className 10335 + " origPrio: " + intent.getPriority()); 10336 } 10337 intent.setPriority(0); 10338 return; 10339 } 10340 } 10341 10342 // find matching authorities subsets 10343 final Iterator<IntentFilter.AuthorityEntry> 10344 authoritiesIterator = intent.authoritiesIterator(); 10345 if (authoritiesIterator != null) { 10346 getIntentListSubset(intentListCopy, 10347 new AuthoritiesIterGenerator(), 10348 authoritiesIterator); 10349 if (intentListCopy.size() == 0) { 10350 // no more intents to match; we're not equivalent 10351 if (DEBUG_FILTERS) { 10352 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10353 + " package: " + applicationInfo.packageName 10354 + " activity: " + intent.activity.className 10355 + " origPrio: " + intent.getPriority()); 10356 } 10357 intent.setPriority(0); 10358 return; 10359 } 10360 } 10361 10362 // we found matching filter(s); app gets the max priority of all intents 10363 int cappedPriority = 0; 10364 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10365 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10366 } 10367 if (intent.getPriority() > cappedPriority) { 10368 if (DEBUG_FILTERS) { 10369 Slog.i(TAG, "Found matching filter(s);" 10370 + " cap priority to " + cappedPriority + ";" 10371 + " package: " + applicationInfo.packageName 10372 + " activity: " + intent.activity.className 10373 + " origPrio: " + intent.getPriority()); 10374 } 10375 intent.setPriority(cappedPriority); 10376 return; 10377 } 10378 // all this for nothing; the requested priority was <= what was on the system 10379 } 10380 10381 public final void addActivity(PackageParser.Activity a, String type) { 10382 mActivities.put(a.getComponentName(), a); 10383 if (DEBUG_SHOW_INFO) 10384 Log.v( 10385 TAG, " " + type + " " + 10386 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10387 if (DEBUG_SHOW_INFO) 10388 Log.v(TAG, " Class=" + a.info.name); 10389 final int NI = a.intents.size(); 10390 for (int j=0; j<NI; j++) { 10391 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10392 if ("activity".equals(type)) { 10393 final PackageSetting ps = 10394 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10395 final List<PackageParser.Activity> systemActivities = 10396 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10397 adjustPriority(systemActivities, intent); 10398 } 10399 if (DEBUG_SHOW_INFO) { 10400 Log.v(TAG, " IntentFilter:"); 10401 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10402 } 10403 if (!intent.debugCheck()) { 10404 Log.w(TAG, "==> For Activity " + a.info.name); 10405 } 10406 addFilter(intent); 10407 } 10408 } 10409 10410 public final void removeActivity(PackageParser.Activity a, String type) { 10411 mActivities.remove(a.getComponentName()); 10412 if (DEBUG_SHOW_INFO) { 10413 Log.v(TAG, " " + type + " " 10414 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10415 : a.info.name) + ":"); 10416 Log.v(TAG, " Class=" + a.info.name); 10417 } 10418 final int NI = a.intents.size(); 10419 for (int j=0; j<NI; j++) { 10420 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10421 if (DEBUG_SHOW_INFO) { 10422 Log.v(TAG, " IntentFilter:"); 10423 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10424 } 10425 removeFilter(intent); 10426 } 10427 } 10428 10429 @Override 10430 protected boolean allowFilterResult( 10431 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10432 ActivityInfo filterAi = filter.activity.info; 10433 for (int i=dest.size()-1; i>=0; i--) { 10434 ActivityInfo destAi = dest.get(i).activityInfo; 10435 if (destAi.name == filterAi.name 10436 && destAi.packageName == filterAi.packageName) { 10437 return false; 10438 } 10439 } 10440 return true; 10441 } 10442 10443 @Override 10444 protected ActivityIntentInfo[] newArray(int size) { 10445 return new ActivityIntentInfo[size]; 10446 } 10447 10448 @Override 10449 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10450 if (!sUserManager.exists(userId)) return true; 10451 PackageParser.Package p = filter.activity.owner; 10452 if (p != null) { 10453 PackageSetting ps = (PackageSetting)p.mExtras; 10454 if (ps != null) { 10455 // System apps are never considered stopped for purposes of 10456 // filtering, because there may be no way for the user to 10457 // actually re-launch them. 10458 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10459 && ps.getStopped(userId); 10460 } 10461 } 10462 return false; 10463 } 10464 10465 @Override 10466 protected boolean isPackageForFilter(String packageName, 10467 PackageParser.ActivityIntentInfo info) { 10468 return packageName.equals(info.activity.owner.packageName); 10469 } 10470 10471 @Override 10472 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10473 int match, int userId) { 10474 if (!sUserManager.exists(userId)) return null; 10475 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10476 return null; 10477 } 10478 final PackageParser.Activity activity = info.activity; 10479 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10480 if (ps == null) { 10481 return null; 10482 } 10483 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10484 ps.readUserState(userId), userId); 10485 if (ai == null) { 10486 return null; 10487 } 10488 final ResolveInfo res = new ResolveInfo(); 10489 res.activityInfo = ai; 10490 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10491 res.filter = info; 10492 } 10493 if (info != null) { 10494 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10495 } 10496 res.priority = info.getPriority(); 10497 res.preferredOrder = activity.owner.mPreferredOrder; 10498 //System.out.println("Result: " + res.activityInfo.className + 10499 // " = " + res.priority); 10500 res.match = match; 10501 res.isDefault = info.hasDefault; 10502 res.labelRes = info.labelRes; 10503 res.nonLocalizedLabel = info.nonLocalizedLabel; 10504 if (userNeedsBadging(userId)) { 10505 res.noResourceId = true; 10506 } else { 10507 res.icon = info.icon; 10508 } 10509 res.iconResourceId = info.icon; 10510 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10511 return res; 10512 } 10513 10514 @Override 10515 protected void sortResults(List<ResolveInfo> results) { 10516 Collections.sort(results, mResolvePrioritySorter); 10517 } 10518 10519 @Override 10520 protected void dumpFilter(PrintWriter out, String prefix, 10521 PackageParser.ActivityIntentInfo filter) { 10522 out.print(prefix); out.print( 10523 Integer.toHexString(System.identityHashCode(filter.activity))); 10524 out.print(' '); 10525 filter.activity.printComponentShortName(out); 10526 out.print(" filter "); 10527 out.println(Integer.toHexString(System.identityHashCode(filter))); 10528 } 10529 10530 @Override 10531 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10532 return filter.activity; 10533 } 10534 10535 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10536 PackageParser.Activity activity = (PackageParser.Activity)label; 10537 out.print(prefix); out.print( 10538 Integer.toHexString(System.identityHashCode(activity))); 10539 out.print(' '); 10540 activity.printComponentShortName(out); 10541 if (count > 1) { 10542 out.print(" ("); out.print(count); out.print(" filters)"); 10543 } 10544 out.println(); 10545 } 10546 10547 // Keys are String (activity class name), values are Activity. 10548 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10549 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10550 private int mFlags; 10551 } 10552 10553 private final class ServiceIntentResolver 10554 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10555 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10556 boolean defaultOnly, int userId) { 10557 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10558 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10559 } 10560 10561 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10562 int userId) { 10563 if (!sUserManager.exists(userId)) return null; 10564 mFlags = flags; 10565 return super.queryIntent(intent, resolvedType, 10566 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10567 } 10568 10569 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10570 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10571 if (!sUserManager.exists(userId)) return null; 10572 if (packageServices == null) { 10573 return null; 10574 } 10575 mFlags = flags; 10576 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10577 final int N = packageServices.size(); 10578 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10579 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10580 10581 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10582 for (int i = 0; i < N; ++i) { 10583 intentFilters = packageServices.get(i).intents; 10584 if (intentFilters != null && intentFilters.size() > 0) { 10585 PackageParser.ServiceIntentInfo[] array = 10586 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10587 intentFilters.toArray(array); 10588 listCut.add(array); 10589 } 10590 } 10591 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10592 } 10593 10594 public final void addService(PackageParser.Service s) { 10595 mServices.put(s.getComponentName(), s); 10596 if (DEBUG_SHOW_INFO) { 10597 Log.v(TAG, " " 10598 + (s.info.nonLocalizedLabel != null 10599 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10600 Log.v(TAG, " Class=" + s.info.name); 10601 } 10602 final int NI = s.intents.size(); 10603 int j; 10604 for (j=0; j<NI; j++) { 10605 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10606 if (DEBUG_SHOW_INFO) { 10607 Log.v(TAG, " IntentFilter:"); 10608 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10609 } 10610 if (!intent.debugCheck()) { 10611 Log.w(TAG, "==> For Service " + s.info.name); 10612 } 10613 addFilter(intent); 10614 } 10615 } 10616 10617 public final void removeService(PackageParser.Service s) { 10618 mServices.remove(s.getComponentName()); 10619 if (DEBUG_SHOW_INFO) { 10620 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10621 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10622 Log.v(TAG, " Class=" + s.info.name); 10623 } 10624 final int NI = s.intents.size(); 10625 int j; 10626 for (j=0; j<NI; j++) { 10627 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10628 if (DEBUG_SHOW_INFO) { 10629 Log.v(TAG, " IntentFilter:"); 10630 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10631 } 10632 removeFilter(intent); 10633 } 10634 } 10635 10636 @Override 10637 protected boolean allowFilterResult( 10638 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10639 ServiceInfo filterSi = filter.service.info; 10640 for (int i=dest.size()-1; i>=0; i--) { 10641 ServiceInfo destAi = dest.get(i).serviceInfo; 10642 if (destAi.name == filterSi.name 10643 && destAi.packageName == filterSi.packageName) { 10644 return false; 10645 } 10646 } 10647 return true; 10648 } 10649 10650 @Override 10651 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10652 return new PackageParser.ServiceIntentInfo[size]; 10653 } 10654 10655 @Override 10656 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10657 if (!sUserManager.exists(userId)) return true; 10658 PackageParser.Package p = filter.service.owner; 10659 if (p != null) { 10660 PackageSetting ps = (PackageSetting)p.mExtras; 10661 if (ps != null) { 10662 // System apps are never considered stopped for purposes of 10663 // filtering, because there may be no way for the user to 10664 // actually re-launch them. 10665 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10666 && ps.getStopped(userId); 10667 } 10668 } 10669 return false; 10670 } 10671 10672 @Override 10673 protected boolean isPackageForFilter(String packageName, 10674 PackageParser.ServiceIntentInfo info) { 10675 return packageName.equals(info.service.owner.packageName); 10676 } 10677 10678 @Override 10679 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10680 int match, int userId) { 10681 if (!sUserManager.exists(userId)) return null; 10682 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10683 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10684 return null; 10685 } 10686 final PackageParser.Service service = info.service; 10687 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10688 if (ps == null) { 10689 return null; 10690 } 10691 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10692 ps.readUserState(userId), userId); 10693 if (si == null) { 10694 return null; 10695 } 10696 final ResolveInfo res = new ResolveInfo(); 10697 res.serviceInfo = si; 10698 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10699 res.filter = filter; 10700 } 10701 res.priority = info.getPriority(); 10702 res.preferredOrder = service.owner.mPreferredOrder; 10703 res.match = match; 10704 res.isDefault = info.hasDefault; 10705 res.labelRes = info.labelRes; 10706 res.nonLocalizedLabel = info.nonLocalizedLabel; 10707 res.icon = info.icon; 10708 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10709 return res; 10710 } 10711 10712 @Override 10713 protected void sortResults(List<ResolveInfo> results) { 10714 Collections.sort(results, mResolvePrioritySorter); 10715 } 10716 10717 @Override 10718 protected void dumpFilter(PrintWriter out, String prefix, 10719 PackageParser.ServiceIntentInfo filter) { 10720 out.print(prefix); out.print( 10721 Integer.toHexString(System.identityHashCode(filter.service))); 10722 out.print(' '); 10723 filter.service.printComponentShortName(out); 10724 out.print(" filter "); 10725 out.println(Integer.toHexString(System.identityHashCode(filter))); 10726 } 10727 10728 @Override 10729 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10730 return filter.service; 10731 } 10732 10733 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10734 PackageParser.Service service = (PackageParser.Service)label; 10735 out.print(prefix); out.print( 10736 Integer.toHexString(System.identityHashCode(service))); 10737 out.print(' '); 10738 service.printComponentShortName(out); 10739 if (count > 1) { 10740 out.print(" ("); out.print(count); out.print(" filters)"); 10741 } 10742 out.println(); 10743 } 10744 10745// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10746// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10747// final List<ResolveInfo> retList = Lists.newArrayList(); 10748// while (i.hasNext()) { 10749// final ResolveInfo resolveInfo = (ResolveInfo) i; 10750// if (isEnabledLP(resolveInfo.serviceInfo)) { 10751// retList.add(resolveInfo); 10752// } 10753// } 10754// return retList; 10755// } 10756 10757 // Keys are String (activity class name), values are Activity. 10758 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10759 = new ArrayMap<ComponentName, PackageParser.Service>(); 10760 private int mFlags; 10761 }; 10762 10763 private final class ProviderIntentResolver 10764 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10765 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10766 boolean defaultOnly, int userId) { 10767 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10768 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10769 } 10770 10771 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10772 int userId) { 10773 if (!sUserManager.exists(userId)) 10774 return null; 10775 mFlags = flags; 10776 return super.queryIntent(intent, resolvedType, 10777 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10778 } 10779 10780 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10781 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10782 if (!sUserManager.exists(userId)) 10783 return null; 10784 if (packageProviders == null) { 10785 return null; 10786 } 10787 mFlags = flags; 10788 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10789 final int N = packageProviders.size(); 10790 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10791 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10792 10793 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10794 for (int i = 0; i < N; ++i) { 10795 intentFilters = packageProviders.get(i).intents; 10796 if (intentFilters != null && intentFilters.size() > 0) { 10797 PackageParser.ProviderIntentInfo[] array = 10798 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10799 intentFilters.toArray(array); 10800 listCut.add(array); 10801 } 10802 } 10803 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10804 } 10805 10806 public final void addProvider(PackageParser.Provider p) { 10807 if (mProviders.containsKey(p.getComponentName())) { 10808 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10809 return; 10810 } 10811 10812 mProviders.put(p.getComponentName(), p); 10813 if (DEBUG_SHOW_INFO) { 10814 Log.v(TAG, " " 10815 + (p.info.nonLocalizedLabel != null 10816 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10817 Log.v(TAG, " Class=" + p.info.name); 10818 } 10819 final int NI = p.intents.size(); 10820 int j; 10821 for (j = 0; j < NI; j++) { 10822 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10823 if (DEBUG_SHOW_INFO) { 10824 Log.v(TAG, " IntentFilter:"); 10825 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10826 } 10827 if (!intent.debugCheck()) { 10828 Log.w(TAG, "==> For Provider " + p.info.name); 10829 } 10830 addFilter(intent); 10831 } 10832 } 10833 10834 public final void removeProvider(PackageParser.Provider p) { 10835 mProviders.remove(p.getComponentName()); 10836 if (DEBUG_SHOW_INFO) { 10837 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10838 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10839 Log.v(TAG, " Class=" + p.info.name); 10840 } 10841 final int NI = p.intents.size(); 10842 int j; 10843 for (j = 0; j < NI; j++) { 10844 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10845 if (DEBUG_SHOW_INFO) { 10846 Log.v(TAG, " IntentFilter:"); 10847 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10848 } 10849 removeFilter(intent); 10850 } 10851 } 10852 10853 @Override 10854 protected boolean allowFilterResult( 10855 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10856 ProviderInfo filterPi = filter.provider.info; 10857 for (int i = dest.size() - 1; i >= 0; i--) { 10858 ProviderInfo destPi = dest.get(i).providerInfo; 10859 if (destPi.name == filterPi.name 10860 && destPi.packageName == filterPi.packageName) { 10861 return false; 10862 } 10863 } 10864 return true; 10865 } 10866 10867 @Override 10868 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10869 return new PackageParser.ProviderIntentInfo[size]; 10870 } 10871 10872 @Override 10873 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10874 if (!sUserManager.exists(userId)) 10875 return true; 10876 PackageParser.Package p = filter.provider.owner; 10877 if (p != null) { 10878 PackageSetting ps = (PackageSetting) p.mExtras; 10879 if (ps != null) { 10880 // System apps are never considered stopped for purposes of 10881 // filtering, because there may be no way for the user to 10882 // actually re-launch them. 10883 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10884 && ps.getStopped(userId); 10885 } 10886 } 10887 return false; 10888 } 10889 10890 @Override 10891 protected boolean isPackageForFilter(String packageName, 10892 PackageParser.ProviderIntentInfo info) { 10893 return packageName.equals(info.provider.owner.packageName); 10894 } 10895 10896 @Override 10897 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10898 int match, int userId) { 10899 if (!sUserManager.exists(userId)) 10900 return null; 10901 final PackageParser.ProviderIntentInfo info = filter; 10902 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10903 return null; 10904 } 10905 final PackageParser.Provider provider = info.provider; 10906 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10907 if (ps == null) { 10908 return null; 10909 } 10910 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10911 ps.readUserState(userId), userId); 10912 if (pi == null) { 10913 return null; 10914 } 10915 final ResolveInfo res = new ResolveInfo(); 10916 res.providerInfo = pi; 10917 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10918 res.filter = filter; 10919 } 10920 res.priority = info.getPriority(); 10921 res.preferredOrder = provider.owner.mPreferredOrder; 10922 res.match = match; 10923 res.isDefault = info.hasDefault; 10924 res.labelRes = info.labelRes; 10925 res.nonLocalizedLabel = info.nonLocalizedLabel; 10926 res.icon = info.icon; 10927 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10928 return res; 10929 } 10930 10931 @Override 10932 protected void sortResults(List<ResolveInfo> results) { 10933 Collections.sort(results, mResolvePrioritySorter); 10934 } 10935 10936 @Override 10937 protected void dumpFilter(PrintWriter out, String prefix, 10938 PackageParser.ProviderIntentInfo filter) { 10939 out.print(prefix); 10940 out.print( 10941 Integer.toHexString(System.identityHashCode(filter.provider))); 10942 out.print(' '); 10943 filter.provider.printComponentShortName(out); 10944 out.print(" filter "); 10945 out.println(Integer.toHexString(System.identityHashCode(filter))); 10946 } 10947 10948 @Override 10949 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10950 return filter.provider; 10951 } 10952 10953 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10954 PackageParser.Provider provider = (PackageParser.Provider)label; 10955 out.print(prefix); out.print( 10956 Integer.toHexString(System.identityHashCode(provider))); 10957 out.print(' '); 10958 provider.printComponentShortName(out); 10959 if (count > 1) { 10960 out.print(" ("); out.print(count); out.print(" filters)"); 10961 } 10962 out.println(); 10963 } 10964 10965 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10966 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10967 private int mFlags; 10968 } 10969 10970 private static final class EphemeralIntentResolver 10971 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10972 @Override 10973 protected EphemeralResolveIntentInfo[] newArray(int size) { 10974 return new EphemeralResolveIntentInfo[size]; 10975 } 10976 10977 @Override 10978 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10979 return true; 10980 } 10981 10982 @Override 10983 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10984 int userId) { 10985 if (!sUserManager.exists(userId)) { 10986 return null; 10987 } 10988 return info.getEphemeralResolveInfo(); 10989 } 10990 } 10991 10992 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10993 new Comparator<ResolveInfo>() { 10994 public int compare(ResolveInfo r1, ResolveInfo r2) { 10995 int v1 = r1.priority; 10996 int v2 = r2.priority; 10997 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10998 if (v1 != v2) { 10999 return (v1 > v2) ? -1 : 1; 11000 } 11001 v1 = r1.preferredOrder; 11002 v2 = r2.preferredOrder; 11003 if (v1 != v2) { 11004 return (v1 > v2) ? -1 : 1; 11005 } 11006 if (r1.isDefault != r2.isDefault) { 11007 return r1.isDefault ? -1 : 1; 11008 } 11009 v1 = r1.match; 11010 v2 = r2.match; 11011 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11012 if (v1 != v2) { 11013 return (v1 > v2) ? -1 : 1; 11014 } 11015 if (r1.system != r2.system) { 11016 return r1.system ? -1 : 1; 11017 } 11018 if (r1.activityInfo != null) { 11019 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11020 } 11021 if (r1.serviceInfo != null) { 11022 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11023 } 11024 if (r1.providerInfo != null) { 11025 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11026 } 11027 return 0; 11028 } 11029 }; 11030 11031 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11032 new Comparator<ProviderInfo>() { 11033 public int compare(ProviderInfo p1, ProviderInfo p2) { 11034 final int v1 = p1.initOrder; 11035 final int v2 = p2.initOrder; 11036 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11037 } 11038 }; 11039 11040 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11041 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11042 final int[] userIds) { 11043 mHandler.post(new Runnable() { 11044 @Override 11045 public void run() { 11046 try { 11047 final IActivityManager am = ActivityManagerNative.getDefault(); 11048 if (am == null) return; 11049 final int[] resolvedUserIds; 11050 if (userIds == null) { 11051 resolvedUserIds = am.getRunningUserIds(); 11052 } else { 11053 resolvedUserIds = userIds; 11054 } 11055 for (int id : resolvedUserIds) { 11056 final Intent intent = new Intent(action, 11057 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11058 if (extras != null) { 11059 intent.putExtras(extras); 11060 } 11061 if (targetPkg != null) { 11062 intent.setPackage(targetPkg); 11063 } 11064 // Modify the UID when posting to other users 11065 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11066 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11067 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11068 intent.putExtra(Intent.EXTRA_UID, uid); 11069 } 11070 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11071 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11072 if (DEBUG_BROADCASTS) { 11073 RuntimeException here = new RuntimeException("here"); 11074 here.fillInStackTrace(); 11075 Slog.d(TAG, "Sending to user " + id + ": " 11076 + intent.toShortString(false, true, false, false) 11077 + " " + intent.getExtras(), here); 11078 } 11079 am.broadcastIntent(null, intent, null, finishedReceiver, 11080 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11081 null, finishedReceiver != null, false, id); 11082 } 11083 } catch (RemoteException ex) { 11084 } 11085 } 11086 }); 11087 } 11088 11089 /** 11090 * Check if the external storage media is available. This is true if there 11091 * is a mounted external storage medium or if the external storage is 11092 * emulated. 11093 */ 11094 private boolean isExternalMediaAvailable() { 11095 return mMediaMounted || Environment.isExternalStorageEmulated(); 11096 } 11097 11098 @Override 11099 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11100 // writer 11101 synchronized (mPackages) { 11102 if (!isExternalMediaAvailable()) { 11103 // If the external storage is no longer mounted at this point, 11104 // the caller may not have been able to delete all of this 11105 // packages files and can not delete any more. Bail. 11106 return null; 11107 } 11108 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11109 if (lastPackage != null) { 11110 pkgs.remove(lastPackage); 11111 } 11112 if (pkgs.size() > 0) { 11113 return pkgs.get(0); 11114 } 11115 } 11116 return null; 11117 } 11118 11119 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11120 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11121 userId, andCode ? 1 : 0, packageName); 11122 if (mSystemReady) { 11123 msg.sendToTarget(); 11124 } else { 11125 if (mPostSystemReadyMessages == null) { 11126 mPostSystemReadyMessages = new ArrayList<>(); 11127 } 11128 mPostSystemReadyMessages.add(msg); 11129 } 11130 } 11131 11132 void startCleaningPackages() { 11133 // reader 11134 if (!isExternalMediaAvailable()) { 11135 return; 11136 } 11137 synchronized (mPackages) { 11138 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11139 return; 11140 } 11141 } 11142 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11143 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11144 IActivityManager am = ActivityManagerNative.getDefault(); 11145 if (am != null) { 11146 try { 11147 am.startService(null, intent, null, mContext.getOpPackageName(), 11148 UserHandle.USER_SYSTEM); 11149 } catch (RemoteException e) { 11150 } 11151 } 11152 } 11153 11154 @Override 11155 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11156 int installFlags, String installerPackageName, int userId) { 11157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11158 11159 final int callingUid = Binder.getCallingUid(); 11160 enforceCrossUserPermission(callingUid, userId, 11161 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11162 11163 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11164 try { 11165 if (observer != null) { 11166 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11167 } 11168 } catch (RemoteException re) { 11169 } 11170 return; 11171 } 11172 11173 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11174 installFlags |= PackageManager.INSTALL_FROM_ADB; 11175 11176 } else { 11177 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11178 // about installerPackageName. 11179 11180 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11181 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11182 } 11183 11184 UserHandle user; 11185 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11186 user = UserHandle.ALL; 11187 } else { 11188 user = new UserHandle(userId); 11189 } 11190 11191 // Only system components can circumvent runtime permissions when installing. 11192 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11193 && mContext.checkCallingOrSelfPermission(Manifest.permission 11194 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11195 throw new SecurityException("You need the " 11196 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11197 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11198 } 11199 11200 final File originFile = new File(originPath); 11201 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11202 11203 final Message msg = mHandler.obtainMessage(INIT_COPY); 11204 final VerificationInfo verificationInfo = new VerificationInfo( 11205 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11206 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11207 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11208 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11209 null /*certificates*/); 11210 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11211 msg.obj = params; 11212 11213 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11214 System.identityHashCode(msg.obj)); 11215 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11216 System.identityHashCode(msg.obj)); 11217 11218 mHandler.sendMessage(msg); 11219 } 11220 11221 void installStage(String packageName, File stagedDir, String stagedCid, 11222 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11223 String installerPackageName, int installerUid, UserHandle user, 11224 Certificate[][] certificates) { 11225 if (DEBUG_EPHEMERAL) { 11226 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11227 Slog.d(TAG, "Ephemeral install of " + packageName); 11228 } 11229 } 11230 final VerificationInfo verificationInfo = new VerificationInfo( 11231 sessionParams.originatingUri, sessionParams.referrerUri, 11232 sessionParams.originatingUid, installerUid); 11233 11234 final OriginInfo origin; 11235 if (stagedDir != null) { 11236 origin = OriginInfo.fromStagedFile(stagedDir); 11237 } else { 11238 origin = OriginInfo.fromStagedContainer(stagedCid); 11239 } 11240 11241 final Message msg = mHandler.obtainMessage(INIT_COPY); 11242 final InstallParams params = new InstallParams(origin, null, observer, 11243 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11244 verificationInfo, user, sessionParams.abiOverride, 11245 sessionParams.grantedRuntimePermissions, certificates); 11246 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11247 msg.obj = params; 11248 11249 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11250 System.identityHashCode(msg.obj)); 11251 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11252 System.identityHashCode(msg.obj)); 11253 11254 mHandler.sendMessage(msg); 11255 } 11256 11257 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11258 int userId) { 11259 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11260 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11261 } 11262 11263 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11264 int appId, int userId) { 11265 Bundle extras = new Bundle(1); 11266 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11267 11268 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11269 packageName, extras, 0, null, null, new int[] {userId}); 11270 try { 11271 IActivityManager am = ActivityManagerNative.getDefault(); 11272 if (isSystem && am.isUserRunning(userId, 0)) { 11273 // The just-installed/enabled app is bundled on the system, so presumed 11274 // to be able to run automatically without needing an explicit launch. 11275 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11276 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11277 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11278 .setPackage(packageName); 11279 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11280 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11281 } 11282 } catch (RemoteException e) { 11283 // shouldn't happen 11284 Slog.w(TAG, "Unable to bootstrap installed package", e); 11285 } 11286 } 11287 11288 @Override 11289 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11290 int userId) { 11291 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11292 PackageSetting pkgSetting; 11293 final int uid = Binder.getCallingUid(); 11294 enforceCrossUserPermission(uid, userId, 11295 true /* requireFullPermission */, true /* checkShell */, 11296 "setApplicationHiddenSetting for user " + userId); 11297 11298 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11299 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11300 return false; 11301 } 11302 11303 long callingId = Binder.clearCallingIdentity(); 11304 try { 11305 boolean sendAdded = false; 11306 boolean sendRemoved = false; 11307 // writer 11308 synchronized (mPackages) { 11309 pkgSetting = mSettings.mPackages.get(packageName); 11310 if (pkgSetting == null) { 11311 return false; 11312 } 11313 if (pkgSetting.getHidden(userId) != hidden) { 11314 pkgSetting.setHidden(hidden, userId); 11315 mSettings.writePackageRestrictionsLPr(userId); 11316 if (hidden) { 11317 sendRemoved = true; 11318 } else { 11319 sendAdded = true; 11320 } 11321 } 11322 } 11323 if (sendAdded) { 11324 sendPackageAddedForUser(packageName, pkgSetting, userId); 11325 return true; 11326 } 11327 if (sendRemoved) { 11328 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11329 "hiding pkg"); 11330 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11331 return true; 11332 } 11333 } finally { 11334 Binder.restoreCallingIdentity(callingId); 11335 } 11336 return false; 11337 } 11338 11339 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11340 int userId) { 11341 final PackageRemovedInfo info = new PackageRemovedInfo(); 11342 info.removedPackage = packageName; 11343 info.removedUsers = new int[] {userId}; 11344 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11345 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11346 } 11347 11348 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11349 if (pkgList.length > 0) { 11350 Bundle extras = new Bundle(1); 11351 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11352 11353 sendPackageBroadcast( 11354 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11355 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11356 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11357 new int[] {userId}); 11358 } 11359 } 11360 11361 /** 11362 * Returns true if application is not found or there was an error. Otherwise it returns 11363 * the hidden state of the package for the given user. 11364 */ 11365 @Override 11366 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11368 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11369 true /* requireFullPermission */, false /* checkShell */, 11370 "getApplicationHidden for user " + userId); 11371 PackageSetting pkgSetting; 11372 long callingId = Binder.clearCallingIdentity(); 11373 try { 11374 // writer 11375 synchronized (mPackages) { 11376 pkgSetting = mSettings.mPackages.get(packageName); 11377 if (pkgSetting == null) { 11378 return true; 11379 } 11380 return pkgSetting.getHidden(userId); 11381 } 11382 } finally { 11383 Binder.restoreCallingIdentity(callingId); 11384 } 11385 } 11386 11387 /** 11388 * @hide 11389 */ 11390 @Override 11391 public int installExistingPackageAsUser(String packageName, int userId) { 11392 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11393 null); 11394 PackageSetting pkgSetting; 11395 final int uid = Binder.getCallingUid(); 11396 enforceCrossUserPermission(uid, userId, 11397 true /* requireFullPermission */, true /* checkShell */, 11398 "installExistingPackage for user " + userId); 11399 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11400 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11401 } 11402 11403 long callingId = Binder.clearCallingIdentity(); 11404 try { 11405 boolean installed = false; 11406 11407 // writer 11408 synchronized (mPackages) { 11409 pkgSetting = mSettings.mPackages.get(packageName); 11410 if (pkgSetting == null) { 11411 return PackageManager.INSTALL_FAILED_INVALID_URI; 11412 } 11413 if (!pkgSetting.getInstalled(userId)) { 11414 pkgSetting.setInstalled(true, userId); 11415 pkgSetting.setHidden(false, userId); 11416 mSettings.writePackageRestrictionsLPr(userId); 11417 installed = true; 11418 } 11419 } 11420 11421 if (installed) { 11422 if (pkgSetting.pkg != null) { 11423 synchronized (mInstallLock) { 11424 // We don't need to freeze for a brand new install 11425 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11426 } 11427 } 11428 sendPackageAddedForUser(packageName, pkgSetting, userId); 11429 } 11430 } finally { 11431 Binder.restoreCallingIdentity(callingId); 11432 } 11433 11434 return PackageManager.INSTALL_SUCCEEDED; 11435 } 11436 11437 boolean isUserRestricted(int userId, String restrictionKey) { 11438 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11439 if (restrictions.getBoolean(restrictionKey, false)) { 11440 Log.w(TAG, "User is restricted: " + restrictionKey); 11441 return true; 11442 } 11443 return false; 11444 } 11445 11446 @Override 11447 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11448 int userId) { 11449 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11450 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11451 true /* requireFullPermission */, true /* checkShell */, 11452 "setPackagesSuspended for user " + userId); 11453 11454 if (ArrayUtils.isEmpty(packageNames)) { 11455 return packageNames; 11456 } 11457 11458 // List of package names for whom the suspended state has changed. 11459 List<String> changedPackages = new ArrayList<>(packageNames.length); 11460 // List of package names for whom the suspended state is not set as requested in this 11461 // method. 11462 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11463 for (int i = 0; i < packageNames.length; i++) { 11464 String packageName = packageNames[i]; 11465 long callingId = Binder.clearCallingIdentity(); 11466 try { 11467 boolean changed = false; 11468 final int appId; 11469 synchronized (mPackages) { 11470 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11471 if (pkgSetting == null) { 11472 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11473 + "\". Skipping suspending/un-suspending."); 11474 unactionedPackages.add(packageName); 11475 continue; 11476 } 11477 appId = pkgSetting.appId; 11478 if (pkgSetting.getSuspended(userId) != suspended) { 11479 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11480 unactionedPackages.add(packageName); 11481 continue; 11482 } 11483 pkgSetting.setSuspended(suspended, userId); 11484 mSettings.writePackageRestrictionsLPr(userId); 11485 changed = true; 11486 changedPackages.add(packageName); 11487 } 11488 } 11489 11490 if (changed && suspended) { 11491 killApplication(packageName, UserHandle.getUid(userId, appId), 11492 "suspending package"); 11493 } 11494 } finally { 11495 Binder.restoreCallingIdentity(callingId); 11496 } 11497 } 11498 11499 if (!changedPackages.isEmpty()) { 11500 sendPackagesSuspendedForUser(changedPackages.toArray( 11501 new String[changedPackages.size()]), userId, suspended); 11502 } 11503 11504 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11505 } 11506 11507 @Override 11508 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11509 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11510 true /* requireFullPermission */, false /* checkShell */, 11511 "isPackageSuspendedForUser for user " + userId); 11512 synchronized (mPackages) { 11513 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11514 if (pkgSetting == null) { 11515 throw new IllegalArgumentException("Unknown target package: " + packageName); 11516 } 11517 return pkgSetting.getSuspended(userId); 11518 } 11519 } 11520 11521 /** 11522 * TODO: cache and disallow blocking the active dialer. 11523 * 11524 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11525 */ 11526 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11527 if (isPackageDeviceAdmin(packageName, userId)) { 11528 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11529 + "\": has an active device admin"); 11530 return false; 11531 } 11532 11533 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11534 if (packageName.equals(activeLauncherPackageName)) { 11535 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11536 + "\": contains the active launcher"); 11537 return false; 11538 } 11539 11540 if (packageName.equals(mRequiredInstallerPackage)) { 11541 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11542 + "\": required for package installation"); 11543 return false; 11544 } 11545 11546 if (packageName.equals(mRequiredVerifierPackage)) { 11547 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11548 + "\": required for package verification"); 11549 return false; 11550 } 11551 11552 final PackageParser.Package pkg = mPackages.get(packageName); 11553 if (pkg != null && isPrivilegedApp(pkg)) { 11554 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11555 + "\": is a privileged app"); 11556 return false; 11557 } 11558 11559 return true; 11560 } 11561 11562 private String getActiveLauncherPackageName(int userId) { 11563 Intent intent = new Intent(Intent.ACTION_MAIN); 11564 intent.addCategory(Intent.CATEGORY_HOME); 11565 ResolveInfo resolveInfo = resolveIntent( 11566 intent, 11567 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11568 PackageManager.MATCH_DEFAULT_ONLY, 11569 userId); 11570 11571 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11572 } 11573 11574 @Override 11575 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11576 mContext.enforceCallingOrSelfPermission( 11577 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11578 "Only package verification agents can verify applications"); 11579 11580 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11581 final PackageVerificationResponse response = new PackageVerificationResponse( 11582 verificationCode, Binder.getCallingUid()); 11583 msg.arg1 = id; 11584 msg.obj = response; 11585 mHandler.sendMessage(msg); 11586 } 11587 11588 @Override 11589 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11590 long millisecondsToDelay) { 11591 mContext.enforceCallingOrSelfPermission( 11592 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11593 "Only package verification agents can extend verification timeouts"); 11594 11595 final PackageVerificationState state = mPendingVerification.get(id); 11596 final PackageVerificationResponse response = new PackageVerificationResponse( 11597 verificationCodeAtTimeout, Binder.getCallingUid()); 11598 11599 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11600 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11601 } 11602 if (millisecondsToDelay < 0) { 11603 millisecondsToDelay = 0; 11604 } 11605 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11606 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11607 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11608 } 11609 11610 if ((state != null) && !state.timeoutExtended()) { 11611 state.extendTimeout(); 11612 11613 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11614 msg.arg1 = id; 11615 msg.obj = response; 11616 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11617 } 11618 } 11619 11620 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11621 int verificationCode, UserHandle user) { 11622 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11623 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11624 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11625 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11626 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11627 11628 mContext.sendBroadcastAsUser(intent, user, 11629 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11630 } 11631 11632 private ComponentName matchComponentForVerifier(String packageName, 11633 List<ResolveInfo> receivers) { 11634 ActivityInfo targetReceiver = null; 11635 11636 final int NR = receivers.size(); 11637 for (int i = 0; i < NR; i++) { 11638 final ResolveInfo info = receivers.get(i); 11639 if (info.activityInfo == null) { 11640 continue; 11641 } 11642 11643 if (packageName.equals(info.activityInfo.packageName)) { 11644 targetReceiver = info.activityInfo; 11645 break; 11646 } 11647 } 11648 11649 if (targetReceiver == null) { 11650 return null; 11651 } 11652 11653 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11654 } 11655 11656 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11657 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11658 if (pkgInfo.verifiers.length == 0) { 11659 return null; 11660 } 11661 11662 final int N = pkgInfo.verifiers.length; 11663 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11664 for (int i = 0; i < N; i++) { 11665 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11666 11667 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11668 receivers); 11669 if (comp == null) { 11670 continue; 11671 } 11672 11673 final int verifierUid = getUidForVerifier(verifierInfo); 11674 if (verifierUid == -1) { 11675 continue; 11676 } 11677 11678 if (DEBUG_VERIFY) { 11679 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11680 + " with the correct signature"); 11681 } 11682 sufficientVerifiers.add(comp); 11683 verificationState.addSufficientVerifier(verifierUid); 11684 } 11685 11686 return sufficientVerifiers; 11687 } 11688 11689 private int getUidForVerifier(VerifierInfo verifierInfo) { 11690 synchronized (mPackages) { 11691 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11692 if (pkg == null) { 11693 return -1; 11694 } else if (pkg.mSignatures.length != 1) { 11695 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11696 + " has more than one signature; ignoring"); 11697 return -1; 11698 } 11699 11700 /* 11701 * If the public key of the package's signature does not match 11702 * our expected public key, then this is a different package and 11703 * we should skip. 11704 */ 11705 11706 final byte[] expectedPublicKey; 11707 try { 11708 final Signature verifierSig = pkg.mSignatures[0]; 11709 final PublicKey publicKey = verifierSig.getPublicKey(); 11710 expectedPublicKey = publicKey.getEncoded(); 11711 } catch (CertificateException e) { 11712 return -1; 11713 } 11714 11715 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11716 11717 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11718 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11719 + " does not have the expected public key; ignoring"); 11720 return -1; 11721 } 11722 11723 return pkg.applicationInfo.uid; 11724 } 11725 } 11726 11727 @Override 11728 public void finishPackageInstall(int token) { 11729 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11730 11731 if (DEBUG_INSTALL) { 11732 Slog.v(TAG, "BM finishing package install for " + token); 11733 } 11734 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11735 11736 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11737 mHandler.sendMessage(msg); 11738 } 11739 11740 /** 11741 * Get the verification agent timeout. 11742 * 11743 * @return verification timeout in milliseconds 11744 */ 11745 private long getVerificationTimeout() { 11746 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11747 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11748 DEFAULT_VERIFICATION_TIMEOUT); 11749 } 11750 11751 /** 11752 * Get the default verification agent response code. 11753 * 11754 * @return default verification response code 11755 */ 11756 private int getDefaultVerificationResponse() { 11757 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11758 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11759 DEFAULT_VERIFICATION_RESPONSE); 11760 } 11761 11762 /** 11763 * Check whether or not package verification has been enabled. 11764 * 11765 * @return true if verification should be performed 11766 */ 11767 private boolean isVerificationEnabled(int userId, int installFlags) { 11768 if (!DEFAULT_VERIFY_ENABLE) { 11769 return false; 11770 } 11771 // Ephemeral apps don't get the full verification treatment 11772 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11773 if (DEBUG_EPHEMERAL) { 11774 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11775 } 11776 return false; 11777 } 11778 11779 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11780 11781 // Check if installing from ADB 11782 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11783 // Do not run verification in a test harness environment 11784 if (ActivityManager.isRunningInTestHarness()) { 11785 return false; 11786 } 11787 if (ensureVerifyAppsEnabled) { 11788 return true; 11789 } 11790 // Check if the developer does not want package verification for ADB installs 11791 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11792 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11793 return false; 11794 } 11795 } 11796 11797 if (ensureVerifyAppsEnabled) { 11798 return true; 11799 } 11800 11801 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11802 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11803 } 11804 11805 @Override 11806 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11807 throws RemoteException { 11808 mContext.enforceCallingOrSelfPermission( 11809 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11810 "Only intentfilter verification agents can verify applications"); 11811 11812 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11813 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11814 Binder.getCallingUid(), verificationCode, failedDomains); 11815 msg.arg1 = id; 11816 msg.obj = response; 11817 mHandler.sendMessage(msg); 11818 } 11819 11820 @Override 11821 public int getIntentVerificationStatus(String packageName, int userId) { 11822 synchronized (mPackages) { 11823 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11824 } 11825 } 11826 11827 @Override 11828 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11829 mContext.enforceCallingOrSelfPermission( 11830 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11831 11832 boolean result = false; 11833 synchronized (mPackages) { 11834 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11835 } 11836 if (result) { 11837 scheduleWritePackageRestrictionsLocked(userId); 11838 } 11839 return result; 11840 } 11841 11842 @Override 11843 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11844 String packageName) { 11845 synchronized (mPackages) { 11846 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11847 } 11848 } 11849 11850 @Override 11851 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11852 if (TextUtils.isEmpty(packageName)) { 11853 return ParceledListSlice.emptyList(); 11854 } 11855 synchronized (mPackages) { 11856 PackageParser.Package pkg = mPackages.get(packageName); 11857 if (pkg == null || pkg.activities == null) { 11858 return ParceledListSlice.emptyList(); 11859 } 11860 final int count = pkg.activities.size(); 11861 ArrayList<IntentFilter> result = new ArrayList<>(); 11862 for (int n=0; n<count; n++) { 11863 PackageParser.Activity activity = pkg.activities.get(n); 11864 if (activity.intents != null && activity.intents.size() > 0) { 11865 result.addAll(activity.intents); 11866 } 11867 } 11868 return new ParceledListSlice<>(result); 11869 } 11870 } 11871 11872 @Override 11873 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11874 mContext.enforceCallingOrSelfPermission( 11875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11876 11877 synchronized (mPackages) { 11878 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11879 if (packageName != null) { 11880 result |= updateIntentVerificationStatus(packageName, 11881 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11882 userId); 11883 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11884 packageName, userId); 11885 } 11886 return result; 11887 } 11888 } 11889 11890 @Override 11891 public String getDefaultBrowserPackageName(int userId) { 11892 synchronized (mPackages) { 11893 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11894 } 11895 } 11896 11897 /** 11898 * Get the "allow unknown sources" setting. 11899 * 11900 * @return the current "allow unknown sources" setting 11901 */ 11902 private int getUnknownSourcesSettings() { 11903 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11904 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11905 -1); 11906 } 11907 11908 @Override 11909 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11910 final int uid = Binder.getCallingUid(); 11911 // writer 11912 synchronized (mPackages) { 11913 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11914 if (targetPackageSetting == null) { 11915 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11916 } 11917 11918 PackageSetting installerPackageSetting; 11919 if (installerPackageName != null) { 11920 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11921 if (installerPackageSetting == null) { 11922 throw new IllegalArgumentException("Unknown installer package: " 11923 + installerPackageName); 11924 } 11925 } else { 11926 installerPackageSetting = null; 11927 } 11928 11929 Signature[] callerSignature; 11930 Object obj = mSettings.getUserIdLPr(uid); 11931 if (obj != null) { 11932 if (obj instanceof SharedUserSetting) { 11933 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11934 } else if (obj instanceof PackageSetting) { 11935 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11936 } else { 11937 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11938 } 11939 } else { 11940 throw new SecurityException("Unknown calling UID: " + uid); 11941 } 11942 11943 // Verify: can't set installerPackageName to a package that is 11944 // not signed with the same cert as the caller. 11945 if (installerPackageSetting != null) { 11946 if (compareSignatures(callerSignature, 11947 installerPackageSetting.signatures.mSignatures) 11948 != PackageManager.SIGNATURE_MATCH) { 11949 throw new SecurityException( 11950 "Caller does not have same cert as new installer package " 11951 + installerPackageName); 11952 } 11953 } 11954 11955 // Verify: if target already has an installer package, it must 11956 // be signed with the same cert as the caller. 11957 if (targetPackageSetting.installerPackageName != null) { 11958 PackageSetting setting = mSettings.mPackages.get( 11959 targetPackageSetting.installerPackageName); 11960 // If the currently set package isn't valid, then it's always 11961 // okay to change it. 11962 if (setting != null) { 11963 if (compareSignatures(callerSignature, 11964 setting.signatures.mSignatures) 11965 != PackageManager.SIGNATURE_MATCH) { 11966 throw new SecurityException( 11967 "Caller does not have same cert as old installer package " 11968 + targetPackageSetting.installerPackageName); 11969 } 11970 } 11971 } 11972 11973 // Okay! 11974 targetPackageSetting.installerPackageName = installerPackageName; 11975 if (installerPackageName != null) { 11976 mSettings.mInstallerPackages.add(installerPackageName); 11977 } 11978 scheduleWriteSettingsLocked(); 11979 } 11980 } 11981 11982 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11983 // Queue up an async operation since the package installation may take a little while. 11984 mHandler.post(new Runnable() { 11985 public void run() { 11986 mHandler.removeCallbacks(this); 11987 // Result object to be returned 11988 PackageInstalledInfo res = new PackageInstalledInfo(); 11989 res.setReturnCode(currentStatus); 11990 res.uid = -1; 11991 res.pkg = null; 11992 res.removedInfo = null; 11993 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11994 args.doPreInstall(res.returnCode); 11995 synchronized (mInstallLock) { 11996 installPackageTracedLI(args, res); 11997 } 11998 args.doPostInstall(res.returnCode, res.uid); 11999 } 12000 12001 // A restore should be performed at this point if (a) the install 12002 // succeeded, (b) the operation is not an update, and (c) the new 12003 // package has not opted out of backup participation. 12004 final boolean update = res.removedInfo != null 12005 && res.removedInfo.removedPackage != null; 12006 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12007 boolean doRestore = !update 12008 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12009 12010 // Set up the post-install work request bookkeeping. This will be used 12011 // and cleaned up by the post-install event handling regardless of whether 12012 // there's a restore pass performed. Token values are >= 1. 12013 int token; 12014 if (mNextInstallToken < 0) mNextInstallToken = 1; 12015 token = mNextInstallToken++; 12016 12017 PostInstallData data = new PostInstallData(args, res); 12018 mRunningInstalls.put(token, data); 12019 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12020 12021 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12022 // Pass responsibility to the Backup Manager. It will perform a 12023 // restore if appropriate, then pass responsibility back to the 12024 // Package Manager to run the post-install observer callbacks 12025 // and broadcasts. 12026 IBackupManager bm = IBackupManager.Stub.asInterface( 12027 ServiceManager.getService(Context.BACKUP_SERVICE)); 12028 if (bm != null) { 12029 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12030 + " to BM for possible restore"); 12031 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12032 try { 12033 // TODO: http://b/22388012 12034 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12035 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12036 } else { 12037 doRestore = false; 12038 } 12039 } catch (RemoteException e) { 12040 // can't happen; the backup manager is local 12041 } catch (Exception e) { 12042 Slog.e(TAG, "Exception trying to enqueue restore", e); 12043 doRestore = false; 12044 } 12045 } else { 12046 Slog.e(TAG, "Backup Manager not found!"); 12047 doRestore = false; 12048 } 12049 } 12050 12051 if (!doRestore) { 12052 // No restore possible, or the Backup Manager was mysteriously not 12053 // available -- just fire the post-install work request directly. 12054 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12055 12056 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12057 12058 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12059 mHandler.sendMessage(msg); 12060 } 12061 } 12062 }); 12063 } 12064 12065 private abstract class HandlerParams { 12066 private static final int MAX_RETRIES = 4; 12067 12068 /** 12069 * Number of times startCopy() has been attempted and had a non-fatal 12070 * error. 12071 */ 12072 private int mRetries = 0; 12073 12074 /** User handle for the user requesting the information or installation. */ 12075 private final UserHandle mUser; 12076 String traceMethod; 12077 int traceCookie; 12078 12079 HandlerParams(UserHandle user) { 12080 mUser = user; 12081 } 12082 12083 UserHandle getUser() { 12084 return mUser; 12085 } 12086 12087 HandlerParams setTraceMethod(String traceMethod) { 12088 this.traceMethod = traceMethod; 12089 return this; 12090 } 12091 12092 HandlerParams setTraceCookie(int traceCookie) { 12093 this.traceCookie = traceCookie; 12094 return this; 12095 } 12096 12097 final boolean startCopy() { 12098 boolean res; 12099 try { 12100 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12101 12102 if (++mRetries > MAX_RETRIES) { 12103 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12104 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12105 handleServiceError(); 12106 return false; 12107 } else { 12108 handleStartCopy(); 12109 res = true; 12110 } 12111 } catch (RemoteException e) { 12112 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12113 mHandler.sendEmptyMessage(MCS_RECONNECT); 12114 res = false; 12115 } 12116 handleReturnCode(); 12117 return res; 12118 } 12119 12120 final void serviceError() { 12121 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12122 handleServiceError(); 12123 handleReturnCode(); 12124 } 12125 12126 abstract void handleStartCopy() throws RemoteException; 12127 abstract void handleServiceError(); 12128 abstract void handleReturnCode(); 12129 } 12130 12131 class MeasureParams extends HandlerParams { 12132 private final PackageStats mStats; 12133 private boolean mSuccess; 12134 12135 private final IPackageStatsObserver mObserver; 12136 12137 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12138 super(new UserHandle(stats.userHandle)); 12139 mObserver = observer; 12140 mStats = stats; 12141 } 12142 12143 @Override 12144 public String toString() { 12145 return "MeasureParams{" 12146 + Integer.toHexString(System.identityHashCode(this)) 12147 + " " + mStats.packageName + "}"; 12148 } 12149 12150 @Override 12151 void handleStartCopy() throws RemoteException { 12152 synchronized (mInstallLock) { 12153 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12154 } 12155 12156 if (mSuccess) { 12157 final boolean mounted; 12158 if (Environment.isExternalStorageEmulated()) { 12159 mounted = true; 12160 } else { 12161 final String status = Environment.getExternalStorageState(); 12162 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12163 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12164 } 12165 12166 if (mounted) { 12167 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12168 12169 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12170 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12171 12172 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12173 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12174 12175 // Always subtract cache size, since it's a subdirectory 12176 mStats.externalDataSize -= mStats.externalCacheSize; 12177 12178 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12179 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12180 12181 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12182 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12183 } 12184 } 12185 } 12186 12187 @Override 12188 void handleReturnCode() { 12189 if (mObserver != null) { 12190 try { 12191 mObserver.onGetStatsCompleted(mStats, mSuccess); 12192 } catch (RemoteException e) { 12193 Slog.i(TAG, "Observer no longer exists."); 12194 } 12195 } 12196 } 12197 12198 @Override 12199 void handleServiceError() { 12200 Slog.e(TAG, "Could not measure application " + mStats.packageName 12201 + " external storage"); 12202 } 12203 } 12204 12205 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12206 throws RemoteException { 12207 long result = 0; 12208 for (File path : paths) { 12209 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12210 } 12211 return result; 12212 } 12213 12214 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12215 for (File path : paths) { 12216 try { 12217 mcs.clearDirectory(path.getAbsolutePath()); 12218 } catch (RemoteException e) { 12219 } 12220 } 12221 } 12222 12223 static class OriginInfo { 12224 /** 12225 * Location where install is coming from, before it has been 12226 * copied/renamed into place. This could be a single monolithic APK 12227 * file, or a cluster directory. This location may be untrusted. 12228 */ 12229 final File file; 12230 final String cid; 12231 12232 /** 12233 * Flag indicating that {@link #file} or {@link #cid} has already been 12234 * staged, meaning downstream users don't need to defensively copy the 12235 * contents. 12236 */ 12237 final boolean staged; 12238 12239 /** 12240 * Flag indicating that {@link #file} or {@link #cid} is an already 12241 * installed app that is being moved. 12242 */ 12243 final boolean existing; 12244 12245 final String resolvedPath; 12246 final File resolvedFile; 12247 12248 static OriginInfo fromNothing() { 12249 return new OriginInfo(null, null, false, false); 12250 } 12251 12252 static OriginInfo fromUntrustedFile(File file) { 12253 return new OriginInfo(file, null, false, false); 12254 } 12255 12256 static OriginInfo fromExistingFile(File file) { 12257 return new OriginInfo(file, null, false, true); 12258 } 12259 12260 static OriginInfo fromStagedFile(File file) { 12261 return new OriginInfo(file, null, true, false); 12262 } 12263 12264 static OriginInfo fromStagedContainer(String cid) { 12265 return new OriginInfo(null, cid, true, false); 12266 } 12267 12268 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12269 this.file = file; 12270 this.cid = cid; 12271 this.staged = staged; 12272 this.existing = existing; 12273 12274 if (cid != null) { 12275 resolvedPath = PackageHelper.getSdDir(cid); 12276 resolvedFile = new File(resolvedPath); 12277 } else if (file != null) { 12278 resolvedPath = file.getAbsolutePath(); 12279 resolvedFile = file; 12280 } else { 12281 resolvedPath = null; 12282 resolvedFile = null; 12283 } 12284 } 12285 } 12286 12287 static class MoveInfo { 12288 final int moveId; 12289 final String fromUuid; 12290 final String toUuid; 12291 final String packageName; 12292 final String dataAppName; 12293 final int appId; 12294 final String seinfo; 12295 final int targetSdkVersion; 12296 12297 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12298 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12299 this.moveId = moveId; 12300 this.fromUuid = fromUuid; 12301 this.toUuid = toUuid; 12302 this.packageName = packageName; 12303 this.dataAppName = dataAppName; 12304 this.appId = appId; 12305 this.seinfo = seinfo; 12306 this.targetSdkVersion = targetSdkVersion; 12307 } 12308 } 12309 12310 static class VerificationInfo { 12311 /** A constant used to indicate that a uid value is not present. */ 12312 public static final int NO_UID = -1; 12313 12314 /** URI referencing where the package was downloaded from. */ 12315 final Uri originatingUri; 12316 12317 /** HTTP referrer URI associated with the originatingURI. */ 12318 final Uri referrer; 12319 12320 /** UID of the application that the install request originated from. */ 12321 final int originatingUid; 12322 12323 /** UID of application requesting the install */ 12324 final int installerUid; 12325 12326 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12327 this.originatingUri = originatingUri; 12328 this.referrer = referrer; 12329 this.originatingUid = originatingUid; 12330 this.installerUid = installerUid; 12331 } 12332 } 12333 12334 class InstallParams extends HandlerParams { 12335 final OriginInfo origin; 12336 final MoveInfo move; 12337 final IPackageInstallObserver2 observer; 12338 int installFlags; 12339 final String installerPackageName; 12340 final String volumeUuid; 12341 private InstallArgs mArgs; 12342 private int mRet; 12343 final String packageAbiOverride; 12344 final String[] grantedRuntimePermissions; 12345 final VerificationInfo verificationInfo; 12346 final Certificate[][] certificates; 12347 12348 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12349 int installFlags, String installerPackageName, String volumeUuid, 12350 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12351 String[] grantedPermissions, Certificate[][] certificates) { 12352 super(user); 12353 this.origin = origin; 12354 this.move = move; 12355 this.observer = observer; 12356 this.installFlags = installFlags; 12357 this.installerPackageName = installerPackageName; 12358 this.volumeUuid = volumeUuid; 12359 this.verificationInfo = verificationInfo; 12360 this.packageAbiOverride = packageAbiOverride; 12361 this.grantedRuntimePermissions = grantedPermissions; 12362 this.certificates = certificates; 12363 } 12364 12365 @Override 12366 public String toString() { 12367 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12368 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12369 } 12370 12371 private int installLocationPolicy(PackageInfoLite pkgLite) { 12372 String packageName = pkgLite.packageName; 12373 int installLocation = pkgLite.installLocation; 12374 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12375 // reader 12376 synchronized (mPackages) { 12377 // Currently installed package which the new package is attempting to replace or 12378 // null if no such package is installed. 12379 PackageParser.Package installedPkg = mPackages.get(packageName); 12380 // Package which currently owns the data which the new package will own if installed. 12381 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12382 // will be null whereas dataOwnerPkg will contain information about the package 12383 // which was uninstalled while keeping its data. 12384 PackageParser.Package dataOwnerPkg = installedPkg; 12385 if (dataOwnerPkg == null) { 12386 PackageSetting ps = mSettings.mPackages.get(packageName); 12387 if (ps != null) { 12388 dataOwnerPkg = ps.pkg; 12389 } 12390 } 12391 12392 if (dataOwnerPkg != null) { 12393 // If installed, the package will get access to data left on the device by its 12394 // predecessor. As a security measure, this is permited only if this is not a 12395 // version downgrade or if the predecessor package is marked as debuggable and 12396 // a downgrade is explicitly requested. 12397 // 12398 // On debuggable platform builds, downgrades are permitted even for 12399 // non-debuggable packages to make testing easier. Debuggable platform builds do 12400 // not offer security guarantees and thus it's OK to disable some security 12401 // mechanisms to make debugging/testing easier on those builds. However, even on 12402 // debuggable builds downgrades of packages are permitted only if requested via 12403 // installFlags. This is because we aim to keep the behavior of debuggable 12404 // platform builds as close as possible to the behavior of non-debuggable 12405 // platform builds. 12406 final boolean downgradeRequested = 12407 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12408 final boolean packageDebuggable = 12409 (dataOwnerPkg.applicationInfo.flags 12410 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12411 final boolean downgradePermitted = 12412 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12413 if (!downgradePermitted) { 12414 try { 12415 checkDowngrade(dataOwnerPkg, pkgLite); 12416 } catch (PackageManagerException e) { 12417 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12418 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12419 } 12420 } 12421 } 12422 12423 if (installedPkg != null) { 12424 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12425 // Check for updated system application. 12426 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12427 if (onSd) { 12428 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12429 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12430 } 12431 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12432 } else { 12433 if (onSd) { 12434 // Install flag overrides everything. 12435 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12436 } 12437 // If current upgrade specifies particular preference 12438 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12439 // Application explicitly specified internal. 12440 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12441 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12442 // App explictly prefers external. Let policy decide 12443 } else { 12444 // Prefer previous location 12445 if (isExternal(installedPkg)) { 12446 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12447 } 12448 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12449 } 12450 } 12451 } else { 12452 // Invalid install. Return error code 12453 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12454 } 12455 } 12456 } 12457 // All the special cases have been taken care of. 12458 // Return result based on recommended install location. 12459 if (onSd) { 12460 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12461 } 12462 return pkgLite.recommendedInstallLocation; 12463 } 12464 12465 /* 12466 * Invoke remote method to get package information and install 12467 * location values. Override install location based on default 12468 * policy if needed and then create install arguments based 12469 * on the install location. 12470 */ 12471 public void handleStartCopy() throws RemoteException { 12472 int ret = PackageManager.INSTALL_SUCCEEDED; 12473 12474 // If we're already staged, we've firmly committed to an install location 12475 if (origin.staged) { 12476 if (origin.file != null) { 12477 installFlags |= PackageManager.INSTALL_INTERNAL; 12478 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12479 } else if (origin.cid != null) { 12480 installFlags |= PackageManager.INSTALL_EXTERNAL; 12481 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12482 } else { 12483 throw new IllegalStateException("Invalid stage location"); 12484 } 12485 } 12486 12487 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12488 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12489 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12490 PackageInfoLite pkgLite = null; 12491 12492 if (onInt && onSd) { 12493 // Check if both bits are set. 12494 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12495 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12496 } else if (onSd && ephemeral) { 12497 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12498 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12499 } else { 12500 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12501 packageAbiOverride); 12502 12503 if (DEBUG_EPHEMERAL && ephemeral) { 12504 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12505 } 12506 12507 /* 12508 * If we have too little free space, try to free cache 12509 * before giving up. 12510 */ 12511 if (!origin.staged && pkgLite.recommendedInstallLocation 12512 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12513 // TODO: focus freeing disk space on the target device 12514 final StorageManager storage = StorageManager.from(mContext); 12515 final long lowThreshold = storage.getStorageLowBytes( 12516 Environment.getDataDirectory()); 12517 12518 final long sizeBytes = mContainerService.calculateInstalledSize( 12519 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12520 12521 try { 12522 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12523 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12524 installFlags, packageAbiOverride); 12525 } catch (InstallerException e) { 12526 Slog.w(TAG, "Failed to free cache", e); 12527 } 12528 12529 /* 12530 * The cache free must have deleted the file we 12531 * downloaded to install. 12532 * 12533 * TODO: fix the "freeCache" call to not delete 12534 * the file we care about. 12535 */ 12536 if (pkgLite.recommendedInstallLocation 12537 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12538 pkgLite.recommendedInstallLocation 12539 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12540 } 12541 } 12542 } 12543 12544 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12545 int loc = pkgLite.recommendedInstallLocation; 12546 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12547 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12548 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12549 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12550 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12551 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12552 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12553 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12554 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12555 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12556 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12557 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12558 } else { 12559 // Override with defaults if needed. 12560 loc = installLocationPolicy(pkgLite); 12561 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12562 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12563 } else if (!onSd && !onInt) { 12564 // Override install location with flags 12565 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12566 // Set the flag to install on external media. 12567 installFlags |= PackageManager.INSTALL_EXTERNAL; 12568 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12569 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12570 if (DEBUG_EPHEMERAL) { 12571 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12572 } 12573 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12574 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12575 |PackageManager.INSTALL_INTERNAL); 12576 } else { 12577 // Make sure the flag for installing on external 12578 // media is unset 12579 installFlags |= PackageManager.INSTALL_INTERNAL; 12580 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12581 } 12582 } 12583 } 12584 } 12585 12586 final InstallArgs args = createInstallArgs(this); 12587 mArgs = args; 12588 12589 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12590 // TODO: http://b/22976637 12591 // Apps installed for "all" users use the device owner to verify the app 12592 UserHandle verifierUser = getUser(); 12593 if (verifierUser == UserHandle.ALL) { 12594 verifierUser = UserHandle.SYSTEM; 12595 } 12596 12597 /* 12598 * Determine if we have any installed package verifiers. If we 12599 * do, then we'll defer to them to verify the packages. 12600 */ 12601 final int requiredUid = mRequiredVerifierPackage == null ? -1 12602 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12603 verifierUser.getIdentifier()); 12604 if (!origin.existing && requiredUid != -1 12605 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12606 final Intent verification = new Intent( 12607 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12608 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12609 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12610 PACKAGE_MIME_TYPE); 12611 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12612 12613 // Query all live verifiers based on current user state 12614 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12615 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12616 12617 if (DEBUG_VERIFY) { 12618 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12619 + verification.toString() + " with " + pkgLite.verifiers.length 12620 + " optional verifiers"); 12621 } 12622 12623 final int verificationId = mPendingVerificationToken++; 12624 12625 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12626 12627 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12628 installerPackageName); 12629 12630 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12631 installFlags); 12632 12633 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12634 pkgLite.packageName); 12635 12636 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12637 pkgLite.versionCode); 12638 12639 if (verificationInfo != null) { 12640 if (verificationInfo.originatingUri != null) { 12641 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12642 verificationInfo.originatingUri); 12643 } 12644 if (verificationInfo.referrer != null) { 12645 verification.putExtra(Intent.EXTRA_REFERRER, 12646 verificationInfo.referrer); 12647 } 12648 if (verificationInfo.originatingUid >= 0) { 12649 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12650 verificationInfo.originatingUid); 12651 } 12652 if (verificationInfo.installerUid >= 0) { 12653 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12654 verificationInfo.installerUid); 12655 } 12656 } 12657 12658 final PackageVerificationState verificationState = new PackageVerificationState( 12659 requiredUid, args); 12660 12661 mPendingVerification.append(verificationId, verificationState); 12662 12663 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12664 receivers, verificationState); 12665 12666 /* 12667 * If any sufficient verifiers were listed in the package 12668 * manifest, attempt to ask them. 12669 */ 12670 if (sufficientVerifiers != null) { 12671 final int N = sufficientVerifiers.size(); 12672 if (N == 0) { 12673 Slog.i(TAG, "Additional verifiers required, but none installed."); 12674 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12675 } else { 12676 for (int i = 0; i < N; i++) { 12677 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12678 12679 final Intent sufficientIntent = new Intent(verification); 12680 sufficientIntent.setComponent(verifierComponent); 12681 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12682 } 12683 } 12684 } 12685 12686 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12687 mRequiredVerifierPackage, receivers); 12688 if (ret == PackageManager.INSTALL_SUCCEEDED 12689 && mRequiredVerifierPackage != null) { 12690 Trace.asyncTraceBegin( 12691 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12692 /* 12693 * Send the intent to the required verification agent, 12694 * but only start the verification timeout after the 12695 * target BroadcastReceivers have run. 12696 */ 12697 verification.setComponent(requiredVerifierComponent); 12698 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12699 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12700 new BroadcastReceiver() { 12701 @Override 12702 public void onReceive(Context context, Intent intent) { 12703 final Message msg = mHandler 12704 .obtainMessage(CHECK_PENDING_VERIFICATION); 12705 msg.arg1 = verificationId; 12706 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12707 } 12708 }, null, 0, null, null); 12709 12710 /* 12711 * We don't want the copy to proceed until verification 12712 * succeeds, so null out this field. 12713 */ 12714 mArgs = null; 12715 } 12716 } else { 12717 /* 12718 * No package verification is enabled, so immediately start 12719 * the remote call to initiate copy using temporary file. 12720 */ 12721 ret = args.copyApk(mContainerService, true); 12722 } 12723 } 12724 12725 mRet = ret; 12726 } 12727 12728 @Override 12729 void handleReturnCode() { 12730 // If mArgs is null, then MCS couldn't be reached. When it 12731 // reconnects, it will try again to install. At that point, this 12732 // will succeed. 12733 if (mArgs != null) { 12734 processPendingInstall(mArgs, mRet); 12735 } 12736 } 12737 12738 @Override 12739 void handleServiceError() { 12740 mArgs = createInstallArgs(this); 12741 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12742 } 12743 12744 public boolean isForwardLocked() { 12745 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12746 } 12747 } 12748 12749 /** 12750 * Used during creation of InstallArgs 12751 * 12752 * @param installFlags package installation flags 12753 * @return true if should be installed on external storage 12754 */ 12755 private static boolean installOnExternalAsec(int installFlags) { 12756 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12757 return false; 12758 } 12759 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12760 return true; 12761 } 12762 return false; 12763 } 12764 12765 /** 12766 * Used during creation of InstallArgs 12767 * 12768 * @param installFlags package installation flags 12769 * @return true if should be installed as forward locked 12770 */ 12771 private static boolean installForwardLocked(int installFlags) { 12772 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12773 } 12774 12775 private InstallArgs createInstallArgs(InstallParams params) { 12776 if (params.move != null) { 12777 return new MoveInstallArgs(params); 12778 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12779 return new AsecInstallArgs(params); 12780 } else { 12781 return new FileInstallArgs(params); 12782 } 12783 } 12784 12785 /** 12786 * Create args that describe an existing installed package. Typically used 12787 * when cleaning up old installs, or used as a move source. 12788 */ 12789 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12790 String resourcePath, String[] instructionSets) { 12791 final boolean isInAsec; 12792 if (installOnExternalAsec(installFlags)) { 12793 /* Apps on SD card are always in ASEC containers. */ 12794 isInAsec = true; 12795 } else if (installForwardLocked(installFlags) 12796 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12797 /* 12798 * Forward-locked apps are only in ASEC containers if they're the 12799 * new style 12800 */ 12801 isInAsec = true; 12802 } else { 12803 isInAsec = false; 12804 } 12805 12806 if (isInAsec) { 12807 return new AsecInstallArgs(codePath, instructionSets, 12808 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12809 } else { 12810 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12811 } 12812 } 12813 12814 static abstract class InstallArgs { 12815 /** @see InstallParams#origin */ 12816 final OriginInfo origin; 12817 /** @see InstallParams#move */ 12818 final MoveInfo move; 12819 12820 final IPackageInstallObserver2 observer; 12821 // Always refers to PackageManager flags only 12822 final int installFlags; 12823 final String installerPackageName; 12824 final String volumeUuid; 12825 final UserHandle user; 12826 final String abiOverride; 12827 final String[] installGrantPermissions; 12828 /** If non-null, drop an async trace when the install completes */ 12829 final String traceMethod; 12830 final int traceCookie; 12831 final Certificate[][] certificates; 12832 12833 // The list of instruction sets supported by this app. This is currently 12834 // only used during the rmdex() phase to clean up resources. We can get rid of this 12835 // if we move dex files under the common app path. 12836 /* nullable */ String[] instructionSets; 12837 12838 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12839 int installFlags, String installerPackageName, String volumeUuid, 12840 UserHandle user, String[] instructionSets, 12841 String abiOverride, String[] installGrantPermissions, 12842 String traceMethod, int traceCookie, Certificate[][] certificates) { 12843 this.origin = origin; 12844 this.move = move; 12845 this.installFlags = installFlags; 12846 this.observer = observer; 12847 this.installerPackageName = installerPackageName; 12848 this.volumeUuid = volumeUuid; 12849 this.user = user; 12850 this.instructionSets = instructionSets; 12851 this.abiOverride = abiOverride; 12852 this.installGrantPermissions = installGrantPermissions; 12853 this.traceMethod = traceMethod; 12854 this.traceCookie = traceCookie; 12855 this.certificates = certificates; 12856 } 12857 12858 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12859 abstract int doPreInstall(int status); 12860 12861 /** 12862 * Rename package into final resting place. All paths on the given 12863 * scanned package should be updated to reflect the rename. 12864 */ 12865 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12866 abstract int doPostInstall(int status, int uid); 12867 12868 /** @see PackageSettingBase#codePathString */ 12869 abstract String getCodePath(); 12870 /** @see PackageSettingBase#resourcePathString */ 12871 abstract String getResourcePath(); 12872 12873 // Need installer lock especially for dex file removal. 12874 abstract void cleanUpResourcesLI(); 12875 abstract boolean doPostDeleteLI(boolean delete); 12876 12877 /** 12878 * Called before the source arguments are copied. This is used mostly 12879 * for MoveParams when it needs to read the source file to put it in the 12880 * destination. 12881 */ 12882 int doPreCopy() { 12883 return PackageManager.INSTALL_SUCCEEDED; 12884 } 12885 12886 /** 12887 * Called after the source arguments are copied. This is used mostly for 12888 * MoveParams when it needs to read the source file to put it in the 12889 * destination. 12890 */ 12891 int doPostCopy(int uid) { 12892 return PackageManager.INSTALL_SUCCEEDED; 12893 } 12894 12895 protected boolean isFwdLocked() { 12896 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12897 } 12898 12899 protected boolean isExternalAsec() { 12900 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12901 } 12902 12903 protected boolean isEphemeral() { 12904 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12905 } 12906 12907 UserHandle getUser() { 12908 return user; 12909 } 12910 } 12911 12912 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12913 if (!allCodePaths.isEmpty()) { 12914 if (instructionSets == null) { 12915 throw new IllegalStateException("instructionSet == null"); 12916 } 12917 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12918 for (String codePath : allCodePaths) { 12919 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12920 try { 12921 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12922 } catch (InstallerException ignored) { 12923 } 12924 } 12925 } 12926 } 12927 } 12928 12929 /** 12930 * Logic to handle installation of non-ASEC applications, including copying 12931 * and renaming logic. 12932 */ 12933 class FileInstallArgs extends InstallArgs { 12934 private File codeFile; 12935 private File resourceFile; 12936 12937 // Example topology: 12938 // /data/app/com.example/base.apk 12939 // /data/app/com.example/split_foo.apk 12940 // /data/app/com.example/lib/arm/libfoo.so 12941 // /data/app/com.example/lib/arm64/libfoo.so 12942 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12943 12944 /** New install */ 12945 FileInstallArgs(InstallParams params) { 12946 super(params.origin, params.move, params.observer, params.installFlags, 12947 params.installerPackageName, params.volumeUuid, 12948 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12949 params.grantedRuntimePermissions, 12950 params.traceMethod, params.traceCookie, params.certificates); 12951 if (isFwdLocked()) { 12952 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12953 } 12954 } 12955 12956 /** Existing install */ 12957 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12958 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12959 null, null, null, 0, null /*certificates*/); 12960 this.codeFile = (codePath != null) ? new File(codePath) : null; 12961 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12962 } 12963 12964 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12965 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12966 try { 12967 return doCopyApk(imcs, temp); 12968 } finally { 12969 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12970 } 12971 } 12972 12973 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12974 if (origin.staged) { 12975 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12976 codeFile = origin.file; 12977 resourceFile = origin.file; 12978 return PackageManager.INSTALL_SUCCEEDED; 12979 } 12980 12981 try { 12982 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12983 final File tempDir = 12984 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12985 codeFile = tempDir; 12986 resourceFile = tempDir; 12987 } catch (IOException e) { 12988 Slog.w(TAG, "Failed to create copy file: " + e); 12989 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12990 } 12991 12992 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12993 @Override 12994 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12995 if (!FileUtils.isValidExtFilename(name)) { 12996 throw new IllegalArgumentException("Invalid filename: " + name); 12997 } 12998 try { 12999 final File file = new File(codeFile, name); 13000 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13001 O_RDWR | O_CREAT, 0644); 13002 Os.chmod(file.getAbsolutePath(), 0644); 13003 return new ParcelFileDescriptor(fd); 13004 } catch (ErrnoException e) { 13005 throw new RemoteException("Failed to open: " + e.getMessage()); 13006 } 13007 } 13008 }; 13009 13010 int ret = PackageManager.INSTALL_SUCCEEDED; 13011 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13012 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13013 Slog.e(TAG, "Failed to copy package"); 13014 return ret; 13015 } 13016 13017 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13018 NativeLibraryHelper.Handle handle = null; 13019 try { 13020 handle = NativeLibraryHelper.Handle.create(codeFile); 13021 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13022 abiOverride); 13023 } catch (IOException e) { 13024 Slog.e(TAG, "Copying native libraries failed", e); 13025 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13026 } finally { 13027 IoUtils.closeQuietly(handle); 13028 } 13029 13030 return ret; 13031 } 13032 13033 int doPreInstall(int status) { 13034 if (status != PackageManager.INSTALL_SUCCEEDED) { 13035 cleanUp(); 13036 } 13037 return status; 13038 } 13039 13040 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13041 if (status != PackageManager.INSTALL_SUCCEEDED) { 13042 cleanUp(); 13043 return false; 13044 } 13045 13046 final File targetDir = codeFile.getParentFile(); 13047 final File beforeCodeFile = codeFile; 13048 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13049 13050 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13051 try { 13052 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13053 } catch (ErrnoException e) { 13054 Slog.w(TAG, "Failed to rename", e); 13055 return false; 13056 } 13057 13058 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13059 Slog.w(TAG, "Failed to restorecon"); 13060 return false; 13061 } 13062 13063 // Reflect the rename internally 13064 codeFile = afterCodeFile; 13065 resourceFile = afterCodeFile; 13066 13067 // Reflect the rename in scanned details 13068 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13069 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13070 afterCodeFile, pkg.baseCodePath)); 13071 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13072 afterCodeFile, pkg.splitCodePaths)); 13073 13074 // Reflect the rename in app info 13075 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13076 pkg.setApplicationInfoCodePath(pkg.codePath); 13077 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13078 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13079 pkg.setApplicationInfoResourcePath(pkg.codePath); 13080 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13081 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13082 13083 return true; 13084 } 13085 13086 int doPostInstall(int status, int uid) { 13087 if (status != PackageManager.INSTALL_SUCCEEDED) { 13088 cleanUp(); 13089 } 13090 return status; 13091 } 13092 13093 @Override 13094 String getCodePath() { 13095 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13096 } 13097 13098 @Override 13099 String getResourcePath() { 13100 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13101 } 13102 13103 private boolean cleanUp() { 13104 if (codeFile == null || !codeFile.exists()) { 13105 return false; 13106 } 13107 13108 removeCodePathLI(codeFile); 13109 13110 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13111 resourceFile.delete(); 13112 } 13113 13114 return true; 13115 } 13116 13117 void cleanUpResourcesLI() { 13118 // Try enumerating all code paths before deleting 13119 List<String> allCodePaths = Collections.EMPTY_LIST; 13120 if (codeFile != null && codeFile.exists()) { 13121 try { 13122 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13123 allCodePaths = pkg.getAllCodePaths(); 13124 } catch (PackageParserException e) { 13125 // Ignored; we tried our best 13126 } 13127 } 13128 13129 cleanUp(); 13130 removeDexFiles(allCodePaths, instructionSets); 13131 } 13132 13133 boolean doPostDeleteLI(boolean delete) { 13134 // XXX err, shouldn't we respect the delete flag? 13135 cleanUpResourcesLI(); 13136 return true; 13137 } 13138 } 13139 13140 private boolean isAsecExternal(String cid) { 13141 final String asecPath = PackageHelper.getSdFilesystem(cid); 13142 return !asecPath.startsWith(mAsecInternalPath); 13143 } 13144 13145 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13146 PackageManagerException { 13147 if (copyRet < 0) { 13148 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13149 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13150 throw new PackageManagerException(copyRet, message); 13151 } 13152 } 13153 } 13154 13155 /** 13156 * Extract the MountService "container ID" from the full code path of an 13157 * .apk. 13158 */ 13159 static String cidFromCodePath(String fullCodePath) { 13160 int eidx = fullCodePath.lastIndexOf("/"); 13161 String subStr1 = fullCodePath.substring(0, eidx); 13162 int sidx = subStr1.lastIndexOf("/"); 13163 return subStr1.substring(sidx+1, eidx); 13164 } 13165 13166 /** 13167 * Logic to handle installation of ASEC applications, including copying and 13168 * renaming logic. 13169 */ 13170 class AsecInstallArgs extends InstallArgs { 13171 static final String RES_FILE_NAME = "pkg.apk"; 13172 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13173 13174 String cid; 13175 String packagePath; 13176 String resourcePath; 13177 13178 /** New install */ 13179 AsecInstallArgs(InstallParams params) { 13180 super(params.origin, params.move, params.observer, params.installFlags, 13181 params.installerPackageName, params.volumeUuid, 13182 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13183 params.grantedRuntimePermissions, 13184 params.traceMethod, params.traceCookie, params.certificates); 13185 } 13186 13187 /** Existing install */ 13188 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13189 boolean isExternal, boolean isForwardLocked) { 13190 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13191 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13192 instructionSets, null, null, null, 0, null /*certificates*/); 13193 // Hackily pretend we're still looking at a full code path 13194 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13195 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13196 } 13197 13198 // Extract cid from fullCodePath 13199 int eidx = fullCodePath.lastIndexOf("/"); 13200 String subStr1 = fullCodePath.substring(0, eidx); 13201 int sidx = subStr1.lastIndexOf("/"); 13202 cid = subStr1.substring(sidx+1, eidx); 13203 setMountPath(subStr1); 13204 } 13205 13206 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13207 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13208 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13209 instructionSets, null, null, null, 0, null /*certificates*/); 13210 this.cid = cid; 13211 setMountPath(PackageHelper.getSdDir(cid)); 13212 } 13213 13214 void createCopyFile() { 13215 cid = mInstallerService.allocateExternalStageCidLegacy(); 13216 } 13217 13218 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13219 if (origin.staged && origin.cid != null) { 13220 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13221 cid = origin.cid; 13222 setMountPath(PackageHelper.getSdDir(cid)); 13223 return PackageManager.INSTALL_SUCCEEDED; 13224 } 13225 13226 if (temp) { 13227 createCopyFile(); 13228 } else { 13229 /* 13230 * Pre-emptively destroy the container since it's destroyed if 13231 * copying fails due to it existing anyway. 13232 */ 13233 PackageHelper.destroySdDir(cid); 13234 } 13235 13236 final String newMountPath = imcs.copyPackageToContainer( 13237 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13238 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13239 13240 if (newMountPath != null) { 13241 setMountPath(newMountPath); 13242 return PackageManager.INSTALL_SUCCEEDED; 13243 } else { 13244 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13245 } 13246 } 13247 13248 @Override 13249 String getCodePath() { 13250 return packagePath; 13251 } 13252 13253 @Override 13254 String getResourcePath() { 13255 return resourcePath; 13256 } 13257 13258 int doPreInstall(int status) { 13259 if (status != PackageManager.INSTALL_SUCCEEDED) { 13260 // Destroy container 13261 PackageHelper.destroySdDir(cid); 13262 } else { 13263 boolean mounted = PackageHelper.isContainerMounted(cid); 13264 if (!mounted) { 13265 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13266 Process.SYSTEM_UID); 13267 if (newMountPath != null) { 13268 setMountPath(newMountPath); 13269 } else { 13270 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13271 } 13272 } 13273 } 13274 return status; 13275 } 13276 13277 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13278 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13279 String newMountPath = null; 13280 if (PackageHelper.isContainerMounted(cid)) { 13281 // Unmount the container 13282 if (!PackageHelper.unMountSdDir(cid)) { 13283 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13284 return false; 13285 } 13286 } 13287 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13288 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13289 " which might be stale. Will try to clean up."); 13290 // Clean up the stale container and proceed to recreate. 13291 if (!PackageHelper.destroySdDir(newCacheId)) { 13292 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13293 return false; 13294 } 13295 // Successfully cleaned up stale container. Try to rename again. 13296 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13297 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13298 + " inspite of cleaning it up."); 13299 return false; 13300 } 13301 } 13302 if (!PackageHelper.isContainerMounted(newCacheId)) { 13303 Slog.w(TAG, "Mounting container " + newCacheId); 13304 newMountPath = PackageHelper.mountSdDir(newCacheId, 13305 getEncryptKey(), Process.SYSTEM_UID); 13306 } else { 13307 newMountPath = PackageHelper.getSdDir(newCacheId); 13308 } 13309 if (newMountPath == null) { 13310 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13311 return false; 13312 } 13313 Log.i(TAG, "Succesfully renamed " + cid + 13314 " to " + newCacheId + 13315 " at new path: " + newMountPath); 13316 cid = newCacheId; 13317 13318 final File beforeCodeFile = new File(packagePath); 13319 setMountPath(newMountPath); 13320 final File afterCodeFile = new File(packagePath); 13321 13322 // Reflect the rename in scanned details 13323 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13324 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13325 afterCodeFile, pkg.baseCodePath)); 13326 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13327 afterCodeFile, pkg.splitCodePaths)); 13328 13329 // Reflect the rename in app info 13330 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13331 pkg.setApplicationInfoCodePath(pkg.codePath); 13332 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13333 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13334 pkg.setApplicationInfoResourcePath(pkg.codePath); 13335 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13336 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13337 13338 return true; 13339 } 13340 13341 private void setMountPath(String mountPath) { 13342 final File mountFile = new File(mountPath); 13343 13344 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13345 if (monolithicFile.exists()) { 13346 packagePath = monolithicFile.getAbsolutePath(); 13347 if (isFwdLocked()) { 13348 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13349 } else { 13350 resourcePath = packagePath; 13351 } 13352 } else { 13353 packagePath = mountFile.getAbsolutePath(); 13354 resourcePath = packagePath; 13355 } 13356 } 13357 13358 int doPostInstall(int status, int uid) { 13359 if (status != PackageManager.INSTALL_SUCCEEDED) { 13360 cleanUp(); 13361 } else { 13362 final int groupOwner; 13363 final String protectedFile; 13364 if (isFwdLocked()) { 13365 groupOwner = UserHandle.getSharedAppGid(uid); 13366 protectedFile = RES_FILE_NAME; 13367 } else { 13368 groupOwner = -1; 13369 protectedFile = null; 13370 } 13371 13372 if (uid < Process.FIRST_APPLICATION_UID 13373 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13374 Slog.e(TAG, "Failed to finalize " + cid); 13375 PackageHelper.destroySdDir(cid); 13376 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13377 } 13378 13379 boolean mounted = PackageHelper.isContainerMounted(cid); 13380 if (!mounted) { 13381 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13382 } 13383 } 13384 return status; 13385 } 13386 13387 private void cleanUp() { 13388 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13389 13390 // Destroy secure container 13391 PackageHelper.destroySdDir(cid); 13392 } 13393 13394 private List<String> getAllCodePaths() { 13395 final File codeFile = new File(getCodePath()); 13396 if (codeFile != null && codeFile.exists()) { 13397 try { 13398 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13399 return pkg.getAllCodePaths(); 13400 } catch (PackageParserException e) { 13401 // Ignored; we tried our best 13402 } 13403 } 13404 return Collections.EMPTY_LIST; 13405 } 13406 13407 void cleanUpResourcesLI() { 13408 // Enumerate all code paths before deleting 13409 cleanUpResourcesLI(getAllCodePaths()); 13410 } 13411 13412 private void cleanUpResourcesLI(List<String> allCodePaths) { 13413 cleanUp(); 13414 removeDexFiles(allCodePaths, instructionSets); 13415 } 13416 13417 String getPackageName() { 13418 return getAsecPackageName(cid); 13419 } 13420 13421 boolean doPostDeleteLI(boolean delete) { 13422 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13423 final List<String> allCodePaths = getAllCodePaths(); 13424 boolean mounted = PackageHelper.isContainerMounted(cid); 13425 if (mounted) { 13426 // Unmount first 13427 if (PackageHelper.unMountSdDir(cid)) { 13428 mounted = false; 13429 } 13430 } 13431 if (!mounted && delete) { 13432 cleanUpResourcesLI(allCodePaths); 13433 } 13434 return !mounted; 13435 } 13436 13437 @Override 13438 int doPreCopy() { 13439 if (isFwdLocked()) { 13440 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13441 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13442 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13443 } 13444 } 13445 13446 return PackageManager.INSTALL_SUCCEEDED; 13447 } 13448 13449 @Override 13450 int doPostCopy(int uid) { 13451 if (isFwdLocked()) { 13452 if (uid < Process.FIRST_APPLICATION_UID 13453 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13454 RES_FILE_NAME)) { 13455 Slog.e(TAG, "Failed to finalize " + cid); 13456 PackageHelper.destroySdDir(cid); 13457 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13458 } 13459 } 13460 13461 return PackageManager.INSTALL_SUCCEEDED; 13462 } 13463 } 13464 13465 /** 13466 * Logic to handle movement of existing installed applications. 13467 */ 13468 class MoveInstallArgs extends InstallArgs { 13469 private File codeFile; 13470 private File resourceFile; 13471 13472 /** New install */ 13473 MoveInstallArgs(InstallParams params) { 13474 super(params.origin, params.move, params.observer, params.installFlags, 13475 params.installerPackageName, params.volumeUuid, 13476 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13477 params.grantedRuntimePermissions, 13478 params.traceMethod, params.traceCookie, params.certificates); 13479 } 13480 13481 int copyApk(IMediaContainerService imcs, boolean temp) { 13482 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13483 + move.fromUuid + " to " + move.toUuid); 13484 synchronized (mInstaller) { 13485 try { 13486 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13487 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13488 } catch (InstallerException e) { 13489 Slog.w(TAG, "Failed to move app", e); 13490 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13491 } 13492 } 13493 13494 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13495 resourceFile = codeFile; 13496 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13497 13498 return PackageManager.INSTALL_SUCCEEDED; 13499 } 13500 13501 int doPreInstall(int status) { 13502 if (status != PackageManager.INSTALL_SUCCEEDED) { 13503 cleanUp(move.toUuid); 13504 } 13505 return status; 13506 } 13507 13508 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13509 if (status != PackageManager.INSTALL_SUCCEEDED) { 13510 cleanUp(move.toUuid); 13511 return false; 13512 } 13513 13514 // Reflect the move in app info 13515 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13516 pkg.setApplicationInfoCodePath(pkg.codePath); 13517 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13518 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13519 pkg.setApplicationInfoResourcePath(pkg.codePath); 13520 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13521 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13522 13523 return true; 13524 } 13525 13526 int doPostInstall(int status, int uid) { 13527 if (status == PackageManager.INSTALL_SUCCEEDED) { 13528 cleanUp(move.fromUuid); 13529 } else { 13530 cleanUp(move.toUuid); 13531 } 13532 return status; 13533 } 13534 13535 @Override 13536 String getCodePath() { 13537 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13538 } 13539 13540 @Override 13541 String getResourcePath() { 13542 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13543 } 13544 13545 private boolean cleanUp(String volumeUuid) { 13546 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13547 move.dataAppName); 13548 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13549 final int[] userIds = sUserManager.getUserIds(); 13550 synchronized (mInstallLock) { 13551 // Clean up both app data and code 13552 // All package moves are frozen until finished 13553 for (int userId : userIds) { 13554 try { 13555 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13556 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13557 } catch (InstallerException e) { 13558 Slog.w(TAG, String.valueOf(e)); 13559 } 13560 } 13561 removeCodePathLI(codeFile); 13562 } 13563 return true; 13564 } 13565 13566 void cleanUpResourcesLI() { 13567 throw new UnsupportedOperationException(); 13568 } 13569 13570 boolean doPostDeleteLI(boolean delete) { 13571 throw new UnsupportedOperationException(); 13572 } 13573 } 13574 13575 static String getAsecPackageName(String packageCid) { 13576 int idx = packageCid.lastIndexOf("-"); 13577 if (idx == -1) { 13578 return packageCid; 13579 } 13580 return packageCid.substring(0, idx); 13581 } 13582 13583 // Utility method used to create code paths based on package name and available index. 13584 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13585 String idxStr = ""; 13586 int idx = 1; 13587 // Fall back to default value of idx=1 if prefix is not 13588 // part of oldCodePath 13589 if (oldCodePath != null) { 13590 String subStr = oldCodePath; 13591 // Drop the suffix right away 13592 if (suffix != null && subStr.endsWith(suffix)) { 13593 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13594 } 13595 // If oldCodePath already contains prefix find out the 13596 // ending index to either increment or decrement. 13597 int sidx = subStr.lastIndexOf(prefix); 13598 if (sidx != -1) { 13599 subStr = subStr.substring(sidx + prefix.length()); 13600 if (subStr != null) { 13601 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13602 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13603 } 13604 try { 13605 idx = Integer.parseInt(subStr); 13606 if (idx <= 1) { 13607 idx++; 13608 } else { 13609 idx--; 13610 } 13611 } catch(NumberFormatException e) { 13612 } 13613 } 13614 } 13615 } 13616 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13617 return prefix + idxStr; 13618 } 13619 13620 private File getNextCodePath(File targetDir, String packageName) { 13621 int suffix = 1; 13622 File result; 13623 do { 13624 result = new File(targetDir, packageName + "-" + suffix); 13625 suffix++; 13626 } while (result.exists()); 13627 return result; 13628 } 13629 13630 // Utility method that returns the relative package path with respect 13631 // to the installation directory. Like say for /data/data/com.test-1.apk 13632 // string com.test-1 is returned. 13633 static String deriveCodePathName(String codePath) { 13634 if (codePath == null) { 13635 return null; 13636 } 13637 final File codeFile = new File(codePath); 13638 final String name = codeFile.getName(); 13639 if (codeFile.isDirectory()) { 13640 return name; 13641 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13642 final int lastDot = name.lastIndexOf('.'); 13643 return name.substring(0, lastDot); 13644 } else { 13645 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13646 return null; 13647 } 13648 } 13649 13650 static class PackageInstalledInfo { 13651 String name; 13652 int uid; 13653 // The set of users that originally had this package installed. 13654 int[] origUsers; 13655 // The set of users that now have this package installed. 13656 int[] newUsers; 13657 PackageParser.Package pkg; 13658 int returnCode; 13659 String returnMsg; 13660 PackageRemovedInfo removedInfo; 13661 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13662 13663 public void setError(int code, String msg) { 13664 setReturnCode(code); 13665 setReturnMessage(msg); 13666 Slog.w(TAG, msg); 13667 } 13668 13669 public void setError(String msg, PackageParserException e) { 13670 setReturnCode(e.error); 13671 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13672 Slog.w(TAG, msg, e); 13673 } 13674 13675 public void setError(String msg, PackageManagerException e) { 13676 returnCode = e.error; 13677 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13678 Slog.w(TAG, msg, e); 13679 } 13680 13681 public void setReturnCode(int returnCode) { 13682 this.returnCode = returnCode; 13683 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13684 for (int i = 0; i < childCount; i++) { 13685 addedChildPackages.valueAt(i).returnCode = returnCode; 13686 } 13687 } 13688 13689 private void setReturnMessage(String returnMsg) { 13690 this.returnMsg = returnMsg; 13691 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13692 for (int i = 0; i < childCount; i++) { 13693 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13694 } 13695 } 13696 13697 // In some error cases we want to convey more info back to the observer 13698 String origPackage; 13699 String origPermission; 13700 } 13701 13702 /* 13703 * Install a non-existing package. 13704 */ 13705 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13706 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13707 PackageInstalledInfo res) { 13708 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13709 13710 // Remember this for later, in case we need to rollback this install 13711 String pkgName = pkg.packageName; 13712 13713 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13714 13715 synchronized(mPackages) { 13716 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13717 // A package with the same name is already installed, though 13718 // it has been renamed to an older name. The package we 13719 // are trying to install should be installed as an update to 13720 // the existing one, but that has not been requested, so bail. 13721 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13722 + " without first uninstalling package running as " 13723 + mSettings.mRenamedPackages.get(pkgName)); 13724 return; 13725 } 13726 if (mPackages.containsKey(pkgName)) { 13727 // Don't allow installation over an existing package with the same name. 13728 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13729 + " without first uninstalling."); 13730 return; 13731 } 13732 } 13733 13734 try { 13735 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13736 System.currentTimeMillis(), user); 13737 13738 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13739 13740 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13741 prepareAppDataAfterInstallLIF(newPackage); 13742 13743 } else { 13744 // Remove package from internal structures, but keep around any 13745 // data that might have already existed 13746 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13747 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13748 } 13749 } catch (PackageManagerException e) { 13750 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13751 } 13752 13753 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13754 } 13755 13756 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13757 // Can't rotate keys during boot or if sharedUser. 13758 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13759 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13760 return false; 13761 } 13762 // app is using upgradeKeySets; make sure all are valid 13763 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13764 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13765 for (int i = 0; i < upgradeKeySets.length; i++) { 13766 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13767 Slog.wtf(TAG, "Package " 13768 + (oldPs.name != null ? oldPs.name : "<null>") 13769 + " contains upgrade-key-set reference to unknown key-set: " 13770 + upgradeKeySets[i] 13771 + " reverting to signatures check."); 13772 return false; 13773 } 13774 } 13775 return true; 13776 } 13777 13778 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13779 // Upgrade keysets are being used. Determine if new package has a superset of the 13780 // required keys. 13781 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13782 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13783 for (int i = 0; i < upgradeKeySets.length; i++) { 13784 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13785 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13786 return true; 13787 } 13788 } 13789 return false; 13790 } 13791 13792 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13793 try (DigestInputStream digestStream = 13794 new DigestInputStream(new FileInputStream(file), digest)) { 13795 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13796 } 13797 } 13798 13799 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13800 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13801 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13802 13803 final PackageParser.Package oldPackage; 13804 final String pkgName = pkg.packageName; 13805 final int[] allUsers; 13806 final int[] installedUsers; 13807 13808 synchronized(mPackages) { 13809 oldPackage = mPackages.get(pkgName); 13810 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13811 13812 // don't allow upgrade to target a release SDK from a pre-release SDK 13813 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13814 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13815 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13816 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13817 if (oldTargetsPreRelease 13818 && !newTargetsPreRelease 13819 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13820 Slog.w(TAG, "Can't install package targeting released sdk"); 13821 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13822 return; 13823 } 13824 13825 // don't allow an upgrade from full to ephemeral 13826 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13827 if (isEphemeral && !oldIsEphemeral) { 13828 // can't downgrade from full to ephemeral 13829 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13830 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13831 return; 13832 } 13833 13834 // verify signatures are valid 13835 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13836 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13837 if (!checkUpgradeKeySetLP(ps, pkg)) { 13838 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13839 "New package not signed by keys specified by upgrade-keysets: " 13840 + pkgName); 13841 return; 13842 } 13843 } else { 13844 // default to original signature matching 13845 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13846 != PackageManager.SIGNATURE_MATCH) { 13847 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13848 "New package has a different signature: " + pkgName); 13849 return; 13850 } 13851 } 13852 13853 // don't allow a system upgrade unless the upgrade hash matches 13854 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13855 byte[] digestBytes = null; 13856 try { 13857 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13858 updateDigest(digest, new File(pkg.baseCodePath)); 13859 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13860 for (String path : pkg.splitCodePaths) { 13861 updateDigest(digest, new File(path)); 13862 } 13863 } 13864 digestBytes = digest.digest(); 13865 } catch (NoSuchAlgorithmException | IOException e) { 13866 res.setError(INSTALL_FAILED_INVALID_APK, 13867 "Could not compute hash: " + pkgName); 13868 return; 13869 } 13870 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13871 res.setError(INSTALL_FAILED_INVALID_APK, 13872 "New package fails restrict-update check: " + pkgName); 13873 return; 13874 } 13875 // retain upgrade restriction 13876 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13877 } 13878 13879 // Check for shared user id changes 13880 String invalidPackageName = 13881 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13882 if (invalidPackageName != null) { 13883 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13884 "Package " + invalidPackageName + " tried to change user " 13885 + oldPackage.mSharedUserId); 13886 return; 13887 } 13888 13889 // In case of rollback, remember per-user/profile install state 13890 allUsers = sUserManager.getUserIds(); 13891 installedUsers = ps.queryInstalledUsers(allUsers, true); 13892 } 13893 13894 // Update what is removed 13895 res.removedInfo = new PackageRemovedInfo(); 13896 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13897 res.removedInfo.removedPackage = oldPackage.packageName; 13898 res.removedInfo.isUpdate = true; 13899 res.removedInfo.origUsers = installedUsers; 13900 final int childCount = (oldPackage.childPackages != null) 13901 ? oldPackage.childPackages.size() : 0; 13902 for (int i = 0; i < childCount; i++) { 13903 boolean childPackageUpdated = false; 13904 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13905 if (res.addedChildPackages != null) { 13906 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13907 if (childRes != null) { 13908 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13909 childRes.removedInfo.removedPackage = childPkg.packageName; 13910 childRes.removedInfo.isUpdate = true; 13911 childPackageUpdated = true; 13912 } 13913 } 13914 if (!childPackageUpdated) { 13915 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13916 childRemovedRes.removedPackage = childPkg.packageName; 13917 childRemovedRes.isUpdate = false; 13918 childRemovedRes.dataRemoved = true; 13919 synchronized (mPackages) { 13920 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13921 if (childPs != null) { 13922 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13923 } 13924 } 13925 if (res.removedInfo.removedChildPackages == null) { 13926 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13927 } 13928 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13929 } 13930 } 13931 13932 boolean sysPkg = (isSystemApp(oldPackage)); 13933 if (sysPkg) { 13934 // Set the system/privileged flags as needed 13935 final boolean privileged = 13936 (oldPackage.applicationInfo.privateFlags 13937 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13938 final int systemPolicyFlags = policyFlags 13939 | PackageParser.PARSE_IS_SYSTEM 13940 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13941 13942 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13943 user, allUsers, installerPackageName, res); 13944 } else { 13945 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13946 user, allUsers, installerPackageName, res); 13947 } 13948 } 13949 13950 public List<String> getPreviousCodePaths(String packageName) { 13951 final PackageSetting ps = mSettings.mPackages.get(packageName); 13952 final List<String> result = new ArrayList<String>(); 13953 if (ps != null && ps.oldCodePaths != null) { 13954 result.addAll(ps.oldCodePaths); 13955 } 13956 return result; 13957 } 13958 13959 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13960 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13961 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13962 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13963 + deletedPackage); 13964 13965 String pkgName = deletedPackage.packageName; 13966 boolean deletedPkg = true; 13967 boolean addedPkg = false; 13968 boolean updatedSettings = false; 13969 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13970 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13971 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13972 13973 final long origUpdateTime = (pkg.mExtras != null) 13974 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13975 13976 // First delete the existing package while retaining the data directory 13977 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13978 res.removedInfo, true, pkg)) { 13979 // If the existing package wasn't successfully deleted 13980 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13981 deletedPkg = false; 13982 } else { 13983 // Successfully deleted the old package; proceed with replace. 13984 13985 // If deleted package lived in a container, give users a chance to 13986 // relinquish resources before killing. 13987 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13988 if (DEBUG_INSTALL) { 13989 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13990 } 13991 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13992 final ArrayList<String> pkgList = new ArrayList<String>(1); 13993 pkgList.add(deletedPackage.applicationInfo.packageName); 13994 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13995 } 13996 13997 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13998 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13999 clearAppProfilesLIF(pkg); 14000 14001 try { 14002 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14003 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14004 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14005 14006 // Update the in-memory copy of the previous code paths. 14007 PackageSetting ps = mSettings.mPackages.get(pkgName); 14008 if (!killApp) { 14009 if (ps.oldCodePaths == null) { 14010 ps.oldCodePaths = new ArraySet<>(); 14011 } 14012 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14013 if (deletedPackage.splitCodePaths != null) { 14014 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14015 } 14016 } else { 14017 ps.oldCodePaths = null; 14018 } 14019 if (ps.childPackageNames != null) { 14020 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14021 final String childPkgName = ps.childPackageNames.get(i); 14022 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14023 childPs.oldCodePaths = ps.oldCodePaths; 14024 } 14025 } 14026 prepareAppDataAfterInstallLIF(newPackage); 14027 addedPkg = true; 14028 } catch (PackageManagerException e) { 14029 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14030 } 14031 } 14032 14033 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14034 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14035 14036 // Revert all internal state mutations and added folders for the failed install 14037 if (addedPkg) { 14038 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14039 res.removedInfo, true, null); 14040 } 14041 14042 // Restore the old package 14043 if (deletedPkg) { 14044 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14045 File restoreFile = new File(deletedPackage.codePath); 14046 // Parse old package 14047 boolean oldExternal = isExternal(deletedPackage); 14048 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14049 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14050 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14051 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14052 try { 14053 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14054 null); 14055 } catch (PackageManagerException e) { 14056 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14057 + e.getMessage()); 14058 return; 14059 } 14060 14061 synchronized (mPackages) { 14062 // Ensure the installer package name up to date 14063 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14064 14065 // Update permissions for restored package 14066 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14067 14068 mSettings.writeLPr(); 14069 } 14070 14071 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14072 } 14073 } else { 14074 synchronized (mPackages) { 14075 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14076 if (ps != null) { 14077 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14078 if (res.removedInfo.removedChildPackages != null) { 14079 final int childCount = res.removedInfo.removedChildPackages.size(); 14080 // Iterate in reverse as we may modify the collection 14081 for (int i = childCount - 1; i >= 0; i--) { 14082 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14083 if (res.addedChildPackages.containsKey(childPackageName)) { 14084 res.removedInfo.removedChildPackages.removeAt(i); 14085 } else { 14086 PackageRemovedInfo childInfo = res.removedInfo 14087 .removedChildPackages.valueAt(i); 14088 childInfo.removedForAllUsers = mPackages.get( 14089 childInfo.removedPackage) == null; 14090 } 14091 } 14092 } 14093 } 14094 } 14095 } 14096 } 14097 14098 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14099 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14100 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14101 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14102 + ", old=" + deletedPackage); 14103 14104 final boolean disabledSystem; 14105 14106 // Remove existing system package 14107 removePackageLI(deletedPackage, true); 14108 14109 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14110 if (!disabledSystem) { 14111 // We didn't need to disable the .apk as a current system package, 14112 // which means we are replacing another update that is already 14113 // installed. We need to make sure to delete the older one's .apk. 14114 res.removedInfo.args = createInstallArgsForExisting(0, 14115 deletedPackage.applicationInfo.getCodePath(), 14116 deletedPackage.applicationInfo.getResourcePath(), 14117 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14118 } else { 14119 res.removedInfo.args = null; 14120 } 14121 14122 // Successfully disabled the old package. Now proceed with re-installation 14123 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14124 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14125 clearAppProfilesLIF(pkg); 14126 14127 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14128 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14129 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14130 14131 PackageParser.Package newPackage = null; 14132 try { 14133 // Add the package to the internal data structures 14134 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14135 14136 // Set the update and install times 14137 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14138 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14139 System.currentTimeMillis()); 14140 14141 // Update the package dynamic state if succeeded 14142 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14143 // Now that the install succeeded make sure we remove data 14144 // directories for any child package the update removed. 14145 final int deletedChildCount = (deletedPackage.childPackages != null) 14146 ? deletedPackage.childPackages.size() : 0; 14147 final int newChildCount = (newPackage.childPackages != null) 14148 ? newPackage.childPackages.size() : 0; 14149 for (int i = 0; i < deletedChildCount; i++) { 14150 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14151 boolean childPackageDeleted = true; 14152 for (int j = 0; j < newChildCount; j++) { 14153 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14154 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14155 childPackageDeleted = false; 14156 break; 14157 } 14158 } 14159 if (childPackageDeleted) { 14160 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14161 deletedChildPkg.packageName); 14162 if (ps != null && res.removedInfo.removedChildPackages != null) { 14163 PackageRemovedInfo removedChildRes = res.removedInfo 14164 .removedChildPackages.get(deletedChildPkg.packageName); 14165 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14166 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14167 } 14168 } 14169 } 14170 14171 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14172 prepareAppDataAfterInstallLIF(newPackage); 14173 } 14174 } catch (PackageManagerException e) { 14175 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14176 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14177 } 14178 14179 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14180 // Re installation failed. Restore old information 14181 // Remove new pkg information 14182 if (newPackage != null) { 14183 removeInstalledPackageLI(newPackage, true); 14184 } 14185 // Add back the old system package 14186 try { 14187 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14188 } catch (PackageManagerException e) { 14189 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14190 } 14191 14192 synchronized (mPackages) { 14193 if (disabledSystem) { 14194 enableSystemPackageLPw(deletedPackage); 14195 } 14196 14197 // Ensure the installer package name up to date 14198 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14199 14200 // Update permissions for restored package 14201 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14202 14203 mSettings.writeLPr(); 14204 } 14205 14206 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14207 + " after failed upgrade"); 14208 } 14209 } 14210 14211 /** 14212 * Checks whether the parent or any of the child packages have a change shared 14213 * user. For a package to be a valid update the shred users of the parent and 14214 * the children should match. We may later support changing child shared users. 14215 * @param oldPkg The updated package. 14216 * @param newPkg The update package. 14217 * @return The shared user that change between the versions. 14218 */ 14219 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14220 PackageParser.Package newPkg) { 14221 // Check parent shared user 14222 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14223 return newPkg.packageName; 14224 } 14225 // Check child shared users 14226 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14227 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14228 for (int i = 0; i < newChildCount; i++) { 14229 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14230 // If this child was present, did it have the same shared user? 14231 for (int j = 0; j < oldChildCount; j++) { 14232 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14233 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14234 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14235 return newChildPkg.packageName; 14236 } 14237 } 14238 } 14239 return null; 14240 } 14241 14242 private void removeNativeBinariesLI(PackageSetting ps) { 14243 // Remove the lib path for the parent package 14244 if (ps != null) { 14245 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14246 // Remove the lib path for the child packages 14247 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14248 for (int i = 0; i < childCount; i++) { 14249 PackageSetting childPs = null; 14250 synchronized (mPackages) { 14251 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14252 } 14253 if (childPs != null) { 14254 NativeLibraryHelper.removeNativeBinariesLI(childPs 14255 .legacyNativeLibraryPathString); 14256 } 14257 } 14258 } 14259 } 14260 14261 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14262 // Enable the parent package 14263 mSettings.enableSystemPackageLPw(pkg.packageName); 14264 // Enable the child packages 14265 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14266 for (int i = 0; i < childCount; i++) { 14267 PackageParser.Package childPkg = pkg.childPackages.get(i); 14268 mSettings.enableSystemPackageLPw(childPkg.packageName); 14269 } 14270 } 14271 14272 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14273 PackageParser.Package newPkg) { 14274 // Disable the parent package (parent always replaced) 14275 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14276 // Disable the child packages 14277 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14278 for (int i = 0; i < childCount; i++) { 14279 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14280 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14281 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14282 } 14283 return disabled; 14284 } 14285 14286 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14287 String installerPackageName) { 14288 // Enable the parent package 14289 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14290 // Enable the child packages 14291 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14292 for (int i = 0; i < childCount; i++) { 14293 PackageParser.Package childPkg = pkg.childPackages.get(i); 14294 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14295 } 14296 } 14297 14298 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14299 // Collect all used permissions in the UID 14300 ArraySet<String> usedPermissions = new ArraySet<>(); 14301 final int packageCount = su.packages.size(); 14302 for (int i = 0; i < packageCount; i++) { 14303 PackageSetting ps = su.packages.valueAt(i); 14304 if (ps.pkg == null) { 14305 continue; 14306 } 14307 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14308 for (int j = 0; j < requestedPermCount; j++) { 14309 String permission = ps.pkg.requestedPermissions.get(j); 14310 BasePermission bp = mSettings.mPermissions.get(permission); 14311 if (bp != null) { 14312 usedPermissions.add(permission); 14313 } 14314 } 14315 } 14316 14317 PermissionsState permissionsState = su.getPermissionsState(); 14318 // Prune install permissions 14319 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14320 final int installPermCount = installPermStates.size(); 14321 for (int i = installPermCount - 1; i >= 0; i--) { 14322 PermissionState permissionState = installPermStates.get(i); 14323 if (!usedPermissions.contains(permissionState.getName())) { 14324 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14325 if (bp != null) { 14326 permissionsState.revokeInstallPermission(bp); 14327 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14328 PackageManager.MASK_PERMISSION_FLAGS, 0); 14329 } 14330 } 14331 } 14332 14333 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14334 14335 // Prune runtime permissions 14336 for (int userId : allUserIds) { 14337 List<PermissionState> runtimePermStates = permissionsState 14338 .getRuntimePermissionStates(userId); 14339 final int runtimePermCount = runtimePermStates.size(); 14340 for (int i = runtimePermCount - 1; i >= 0; i--) { 14341 PermissionState permissionState = runtimePermStates.get(i); 14342 if (!usedPermissions.contains(permissionState.getName())) { 14343 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14344 if (bp != null) { 14345 permissionsState.revokeRuntimePermission(bp, userId); 14346 permissionsState.updatePermissionFlags(bp, userId, 14347 PackageManager.MASK_PERMISSION_FLAGS, 0); 14348 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14349 runtimePermissionChangedUserIds, userId); 14350 } 14351 } 14352 } 14353 } 14354 14355 return runtimePermissionChangedUserIds; 14356 } 14357 14358 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14359 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14360 // Update the parent package setting 14361 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14362 res, user); 14363 // Update the child packages setting 14364 final int childCount = (newPackage.childPackages != null) 14365 ? newPackage.childPackages.size() : 0; 14366 for (int i = 0; i < childCount; i++) { 14367 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14368 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14369 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14370 childRes.origUsers, childRes, user); 14371 } 14372 } 14373 14374 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14375 String installerPackageName, int[] allUsers, int[] installedForUsers, 14376 PackageInstalledInfo res, UserHandle user) { 14377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14378 14379 String pkgName = newPackage.packageName; 14380 synchronized (mPackages) { 14381 //write settings. the installStatus will be incomplete at this stage. 14382 //note that the new package setting would have already been 14383 //added to mPackages. It hasn't been persisted yet. 14384 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14386 mSettings.writeLPr(); 14387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14388 } 14389 14390 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14391 synchronized (mPackages) { 14392 updatePermissionsLPw(newPackage.packageName, newPackage, 14393 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14394 ? UPDATE_PERMISSIONS_ALL : 0)); 14395 // For system-bundled packages, we assume that installing an upgraded version 14396 // of the package implies that the user actually wants to run that new code, 14397 // so we enable the package. 14398 PackageSetting ps = mSettings.mPackages.get(pkgName); 14399 final int userId = user.getIdentifier(); 14400 if (ps != null) { 14401 if (isSystemApp(newPackage)) { 14402 if (DEBUG_INSTALL) { 14403 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14404 } 14405 // Enable system package for requested users 14406 if (res.origUsers != null) { 14407 for (int origUserId : res.origUsers) { 14408 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14409 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14410 origUserId, installerPackageName); 14411 } 14412 } 14413 } 14414 // Also convey the prior install/uninstall state 14415 if (allUsers != null && installedForUsers != null) { 14416 for (int currentUserId : allUsers) { 14417 final boolean installed = ArrayUtils.contains( 14418 installedForUsers, currentUserId); 14419 if (DEBUG_INSTALL) { 14420 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14421 } 14422 ps.setInstalled(installed, currentUserId); 14423 } 14424 // these install state changes will be persisted in the 14425 // upcoming call to mSettings.writeLPr(). 14426 } 14427 } 14428 // It's implied that when a user requests installation, they want the app to be 14429 // installed and enabled. 14430 if (userId != UserHandle.USER_ALL) { 14431 ps.setInstalled(true, userId); 14432 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14433 } 14434 } 14435 res.name = pkgName; 14436 res.uid = newPackage.applicationInfo.uid; 14437 res.pkg = newPackage; 14438 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14439 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14440 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14441 //to update install status 14442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14443 mSettings.writeLPr(); 14444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14445 } 14446 14447 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14448 } 14449 14450 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14451 try { 14452 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14453 installPackageLI(args, res); 14454 } finally { 14455 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14456 } 14457 } 14458 14459 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14460 final int installFlags = args.installFlags; 14461 final String installerPackageName = args.installerPackageName; 14462 final String volumeUuid = args.volumeUuid; 14463 final File tmpPackageFile = new File(args.getCodePath()); 14464 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14465 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14466 || (args.volumeUuid != null)); 14467 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14468 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14469 boolean replace = false; 14470 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14471 if (args.move != null) { 14472 // moving a complete application; perform an initial scan on the new install location 14473 scanFlags |= SCAN_INITIAL; 14474 } 14475 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14476 scanFlags |= SCAN_DONT_KILL_APP; 14477 } 14478 14479 // Result object to be returned 14480 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14481 14482 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14483 14484 // Sanity check 14485 if (ephemeral && (forwardLocked || onExternal)) { 14486 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14487 + " external=" + onExternal); 14488 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14489 return; 14490 } 14491 14492 // Retrieve PackageSettings and parse package 14493 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14494 | PackageParser.PARSE_ENFORCE_CODE 14495 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14496 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14497 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14498 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14499 PackageParser pp = new PackageParser(); 14500 pp.setSeparateProcesses(mSeparateProcesses); 14501 pp.setDisplayMetrics(mMetrics); 14502 14503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14504 final PackageParser.Package pkg; 14505 try { 14506 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14507 } catch (PackageParserException e) { 14508 res.setError("Failed parse during installPackageLI", e); 14509 return; 14510 } finally { 14511 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14512 } 14513 14514 // If we are installing a clustered package add results for the children 14515 if (pkg.childPackages != null) { 14516 synchronized (mPackages) { 14517 final int childCount = pkg.childPackages.size(); 14518 for (int i = 0; i < childCount; i++) { 14519 PackageParser.Package childPkg = pkg.childPackages.get(i); 14520 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14521 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14522 childRes.pkg = childPkg; 14523 childRes.name = childPkg.packageName; 14524 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14525 if (childPs != null) { 14526 childRes.origUsers = childPs.queryInstalledUsers( 14527 sUserManager.getUserIds(), true); 14528 } 14529 if ((mPackages.containsKey(childPkg.packageName))) { 14530 childRes.removedInfo = new PackageRemovedInfo(); 14531 childRes.removedInfo.removedPackage = childPkg.packageName; 14532 } 14533 if (res.addedChildPackages == null) { 14534 res.addedChildPackages = new ArrayMap<>(); 14535 } 14536 res.addedChildPackages.put(childPkg.packageName, childRes); 14537 } 14538 } 14539 } 14540 14541 // If package doesn't declare API override, mark that we have an install 14542 // time CPU ABI override. 14543 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14544 pkg.cpuAbiOverride = args.abiOverride; 14545 } 14546 14547 String pkgName = res.name = pkg.packageName; 14548 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14549 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14550 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14551 return; 14552 } 14553 } 14554 14555 try { 14556 // either use what we've been given or parse directly from the APK 14557 if (args.certificates != null) { 14558 try { 14559 PackageParser.populateCertificates(pkg, args.certificates); 14560 } catch (PackageParserException e) { 14561 // there was something wrong with the certificates we were given; 14562 // try to pull them from the APK 14563 PackageParser.collectCertificates(pkg, parseFlags); 14564 } 14565 } else { 14566 PackageParser.collectCertificates(pkg, parseFlags); 14567 } 14568 } catch (PackageParserException e) { 14569 res.setError("Failed collect during installPackageLI", e); 14570 return; 14571 } 14572 14573 // Get rid of all references to package scan path via parser. 14574 pp = null; 14575 String oldCodePath = null; 14576 boolean systemApp = false; 14577 synchronized (mPackages) { 14578 // Check if installing already existing package 14579 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14580 String oldName = mSettings.mRenamedPackages.get(pkgName); 14581 if (pkg.mOriginalPackages != null 14582 && pkg.mOriginalPackages.contains(oldName) 14583 && mPackages.containsKey(oldName)) { 14584 // This package is derived from an original package, 14585 // and this device has been updating from that original 14586 // name. We must continue using the original name, so 14587 // rename the new package here. 14588 pkg.setPackageName(oldName); 14589 pkgName = pkg.packageName; 14590 replace = true; 14591 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14592 + oldName + " pkgName=" + pkgName); 14593 } else if (mPackages.containsKey(pkgName)) { 14594 // This package, under its official name, already exists 14595 // on the device; we should replace it. 14596 replace = true; 14597 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14598 } 14599 14600 // Child packages are installed through the parent package 14601 if (pkg.parentPackage != null) { 14602 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14603 "Package " + pkg.packageName + " is child of package " 14604 + pkg.parentPackage.parentPackage + ". Child packages " 14605 + "can be updated only through the parent package."); 14606 return; 14607 } 14608 14609 if (replace) { 14610 // Prevent apps opting out from runtime permissions 14611 PackageParser.Package oldPackage = mPackages.get(pkgName); 14612 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14613 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14614 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14615 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14616 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14617 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14618 + " doesn't support runtime permissions but the old" 14619 + " target SDK " + oldTargetSdk + " does."); 14620 return; 14621 } 14622 14623 // Prevent installing of child packages 14624 if (oldPackage.parentPackage != null) { 14625 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14626 "Package " + pkg.packageName + " is child of package " 14627 + oldPackage.parentPackage + ". Child packages " 14628 + "can be updated only through the parent package."); 14629 return; 14630 } 14631 } 14632 } 14633 14634 PackageSetting ps = mSettings.mPackages.get(pkgName); 14635 if (ps != null) { 14636 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14637 14638 // Quick sanity check that we're signed correctly if updating; 14639 // we'll check this again later when scanning, but we want to 14640 // bail early here before tripping over redefined permissions. 14641 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14642 if (!checkUpgradeKeySetLP(ps, pkg)) { 14643 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14644 + pkg.packageName + " upgrade keys do not match the " 14645 + "previously installed version"); 14646 return; 14647 } 14648 } else { 14649 try { 14650 verifySignaturesLP(ps, pkg); 14651 } catch (PackageManagerException e) { 14652 res.setError(e.error, e.getMessage()); 14653 return; 14654 } 14655 } 14656 14657 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14658 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14659 systemApp = (ps.pkg.applicationInfo.flags & 14660 ApplicationInfo.FLAG_SYSTEM) != 0; 14661 } 14662 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14663 } 14664 14665 // Check whether the newly-scanned package wants to define an already-defined perm 14666 int N = pkg.permissions.size(); 14667 for (int i = N-1; i >= 0; i--) { 14668 PackageParser.Permission perm = pkg.permissions.get(i); 14669 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14670 if (bp != null) { 14671 // If the defining package is signed with our cert, it's okay. This 14672 // also includes the "updating the same package" case, of course. 14673 // "updating same package" could also involve key-rotation. 14674 final boolean sigsOk; 14675 if (bp.sourcePackage.equals(pkg.packageName) 14676 && (bp.packageSetting instanceof PackageSetting) 14677 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14678 scanFlags))) { 14679 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14680 } else { 14681 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14682 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14683 } 14684 if (!sigsOk) { 14685 // If the owning package is the system itself, we log but allow 14686 // install to proceed; we fail the install on all other permission 14687 // redefinitions. 14688 if (!bp.sourcePackage.equals("android")) { 14689 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14690 + pkg.packageName + " attempting to redeclare permission " 14691 + perm.info.name + " already owned by " + bp.sourcePackage); 14692 res.origPermission = perm.info.name; 14693 res.origPackage = bp.sourcePackage; 14694 return; 14695 } else { 14696 Slog.w(TAG, "Package " + pkg.packageName 14697 + " attempting to redeclare system permission " 14698 + perm.info.name + "; ignoring new declaration"); 14699 pkg.permissions.remove(i); 14700 } 14701 } 14702 } 14703 } 14704 } 14705 14706 if (systemApp) { 14707 if (onExternal) { 14708 // Abort update; system app can't be replaced with app on sdcard 14709 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14710 "Cannot install updates to system apps on sdcard"); 14711 return; 14712 } else if (ephemeral) { 14713 // Abort update; system app can't be replaced with an ephemeral app 14714 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14715 "Cannot update a system app with an ephemeral app"); 14716 return; 14717 } 14718 } 14719 14720 if (args.move != null) { 14721 // We did an in-place move, so dex is ready to roll 14722 scanFlags |= SCAN_NO_DEX; 14723 scanFlags |= SCAN_MOVE; 14724 14725 synchronized (mPackages) { 14726 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14727 if (ps == null) { 14728 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14729 "Missing settings for moved package " + pkgName); 14730 } 14731 14732 // We moved the entire application as-is, so bring over the 14733 // previously derived ABI information. 14734 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14735 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14736 } 14737 14738 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14739 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14740 scanFlags |= SCAN_NO_DEX; 14741 14742 try { 14743 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14744 args.abiOverride : pkg.cpuAbiOverride); 14745 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14746 true /* extract libs */); 14747 } catch (PackageManagerException pme) { 14748 Slog.e(TAG, "Error deriving application ABI", pme); 14749 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14750 return; 14751 } 14752 14753 // Shared libraries for the package need to be updated. 14754 synchronized (mPackages) { 14755 try { 14756 updateSharedLibrariesLPw(pkg, null); 14757 } catch (PackageManagerException e) { 14758 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14759 } 14760 } 14761 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14762 // Do not run PackageDexOptimizer through the local performDexOpt 14763 // method because `pkg` is not in `mPackages` yet. 14764 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14765 null /* instructionSets */, false /* checkProfiles */, 14766 getCompilerFilterForReason(REASON_INSTALL)); 14767 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14768 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14769 String msg = "Extracting package failed for " + pkgName; 14770 res.setError(INSTALL_FAILED_DEXOPT, msg); 14771 return; 14772 } 14773 14774 // Notify BackgroundDexOptService that the package has been changed. 14775 // If this is an update of a package which used to fail to compile, 14776 // BDOS will remove it from its blacklist. 14777 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14778 } 14779 14780 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14781 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14782 return; 14783 } 14784 14785 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14786 14787 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14788 "installPackageLI")) { 14789 if (replace) { 14790 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14791 installerPackageName, res); 14792 } else { 14793 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14794 args.user, installerPackageName, volumeUuid, res); 14795 } 14796 } 14797 synchronized (mPackages) { 14798 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14799 if (ps != null) { 14800 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14801 } 14802 14803 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14804 for (int i = 0; i < childCount; i++) { 14805 PackageParser.Package childPkg = pkg.childPackages.get(i); 14806 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14807 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14808 if (childPs != null) { 14809 childRes.newUsers = childPs.queryInstalledUsers( 14810 sUserManager.getUserIds(), true); 14811 } 14812 } 14813 } 14814 } 14815 14816 private void startIntentFilterVerifications(int userId, boolean replacing, 14817 PackageParser.Package pkg) { 14818 if (mIntentFilterVerifierComponent == null) { 14819 Slog.w(TAG, "No IntentFilter verification will not be done as " 14820 + "there is no IntentFilterVerifier available!"); 14821 return; 14822 } 14823 14824 final int verifierUid = getPackageUid( 14825 mIntentFilterVerifierComponent.getPackageName(), 14826 MATCH_DEBUG_TRIAGED_MISSING, 14827 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14828 14829 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14830 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14831 mHandler.sendMessage(msg); 14832 14833 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14834 for (int i = 0; i < childCount; i++) { 14835 PackageParser.Package childPkg = pkg.childPackages.get(i); 14836 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14837 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14838 mHandler.sendMessage(msg); 14839 } 14840 } 14841 14842 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14843 PackageParser.Package pkg) { 14844 int size = pkg.activities.size(); 14845 if (size == 0) { 14846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14847 "No activity, so no need to verify any IntentFilter!"); 14848 return; 14849 } 14850 14851 final boolean hasDomainURLs = hasDomainURLs(pkg); 14852 if (!hasDomainURLs) { 14853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14854 "No domain URLs, so no need to verify any IntentFilter!"); 14855 return; 14856 } 14857 14858 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14859 + " if any IntentFilter from the " + size 14860 + " Activities needs verification ..."); 14861 14862 int count = 0; 14863 final String packageName = pkg.packageName; 14864 14865 synchronized (mPackages) { 14866 // If this is a new install and we see that we've already run verification for this 14867 // package, we have nothing to do: it means the state was restored from backup. 14868 if (!replacing) { 14869 IntentFilterVerificationInfo ivi = 14870 mSettings.getIntentFilterVerificationLPr(packageName); 14871 if (ivi != null) { 14872 if (DEBUG_DOMAIN_VERIFICATION) { 14873 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14874 + ivi.getStatusString()); 14875 } 14876 return; 14877 } 14878 } 14879 14880 // If any filters need to be verified, then all need to be. 14881 boolean needToVerify = false; 14882 for (PackageParser.Activity a : pkg.activities) { 14883 for (ActivityIntentInfo filter : a.intents) { 14884 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14885 if (DEBUG_DOMAIN_VERIFICATION) { 14886 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14887 } 14888 needToVerify = true; 14889 break; 14890 } 14891 } 14892 } 14893 14894 if (needToVerify) { 14895 final int verificationId = mIntentFilterVerificationToken++; 14896 for (PackageParser.Activity a : pkg.activities) { 14897 for (ActivityIntentInfo filter : a.intents) { 14898 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14899 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14900 "Verification needed for IntentFilter:" + filter.toString()); 14901 mIntentFilterVerifier.addOneIntentFilterVerification( 14902 verifierUid, userId, verificationId, filter, packageName); 14903 count++; 14904 } 14905 } 14906 } 14907 } 14908 } 14909 14910 if (count > 0) { 14911 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14912 + " IntentFilter verification" + (count > 1 ? "s" : "") 14913 + " for userId:" + userId); 14914 mIntentFilterVerifier.startVerifications(userId); 14915 } else { 14916 if (DEBUG_DOMAIN_VERIFICATION) { 14917 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14918 } 14919 } 14920 } 14921 14922 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14923 final ComponentName cn = filter.activity.getComponentName(); 14924 final String packageName = cn.getPackageName(); 14925 14926 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14927 packageName); 14928 if (ivi == null) { 14929 return true; 14930 } 14931 int status = ivi.getStatus(); 14932 switch (status) { 14933 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14934 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14935 return true; 14936 14937 default: 14938 // Nothing to do 14939 return false; 14940 } 14941 } 14942 14943 private static boolean isMultiArch(ApplicationInfo info) { 14944 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14945 } 14946 14947 private static boolean isExternal(PackageParser.Package pkg) { 14948 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14949 } 14950 14951 private static boolean isExternal(PackageSetting ps) { 14952 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14953 } 14954 14955 private static boolean isEphemeral(PackageParser.Package pkg) { 14956 return pkg.applicationInfo.isEphemeralApp(); 14957 } 14958 14959 private static boolean isEphemeral(PackageSetting ps) { 14960 return ps.pkg != null && isEphemeral(ps.pkg); 14961 } 14962 14963 private static boolean isSystemApp(PackageParser.Package pkg) { 14964 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14965 } 14966 14967 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14968 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14969 } 14970 14971 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14972 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14973 } 14974 14975 private static boolean isSystemApp(PackageSetting ps) { 14976 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14977 } 14978 14979 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14980 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14981 } 14982 14983 private int packageFlagsToInstallFlags(PackageSetting ps) { 14984 int installFlags = 0; 14985 if (isEphemeral(ps)) { 14986 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14987 } 14988 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14989 // This existing package was an external ASEC install when we have 14990 // the external flag without a UUID 14991 installFlags |= PackageManager.INSTALL_EXTERNAL; 14992 } 14993 if (ps.isForwardLocked()) { 14994 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14995 } 14996 return installFlags; 14997 } 14998 14999 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15000 if (isExternal(pkg)) { 15001 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15002 return StorageManager.UUID_PRIMARY_PHYSICAL; 15003 } else { 15004 return pkg.volumeUuid; 15005 } 15006 } else { 15007 return StorageManager.UUID_PRIVATE_INTERNAL; 15008 } 15009 } 15010 15011 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15012 if (isExternal(pkg)) { 15013 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15014 return mSettings.getExternalVersion(); 15015 } else { 15016 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15017 } 15018 } else { 15019 return mSettings.getInternalVersion(); 15020 } 15021 } 15022 15023 private void deleteTempPackageFiles() { 15024 final FilenameFilter filter = new FilenameFilter() { 15025 public boolean accept(File dir, String name) { 15026 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15027 } 15028 }; 15029 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15030 file.delete(); 15031 } 15032 } 15033 15034 @Override 15035 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15036 int flags) { 15037 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15038 flags); 15039 } 15040 15041 @Override 15042 public void deletePackage(final String packageName, 15043 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15044 mContext.enforceCallingOrSelfPermission( 15045 android.Manifest.permission.DELETE_PACKAGES, null); 15046 Preconditions.checkNotNull(packageName); 15047 Preconditions.checkNotNull(observer); 15048 final int uid = Binder.getCallingUid(); 15049 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15050 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15051 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15052 mContext.enforceCallingOrSelfPermission( 15053 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15054 "deletePackage for user " + userId); 15055 } 15056 15057 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15058 try { 15059 observer.onPackageDeleted(packageName, 15060 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15061 } catch (RemoteException re) { 15062 } 15063 return; 15064 } 15065 15066 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15067 try { 15068 observer.onPackageDeleted(packageName, 15069 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15070 } catch (RemoteException re) { 15071 } 15072 return; 15073 } 15074 15075 if (DEBUG_REMOVE) { 15076 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15077 + " deleteAllUsers: " + deleteAllUsers ); 15078 } 15079 // Queue up an async operation since the package deletion may take a little while. 15080 mHandler.post(new Runnable() { 15081 public void run() { 15082 mHandler.removeCallbacks(this); 15083 int returnCode; 15084 if (!deleteAllUsers) { 15085 returnCode = deletePackageX(packageName, userId, deleteFlags); 15086 } else { 15087 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15088 // If nobody is blocking uninstall, proceed with delete for all users 15089 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15090 returnCode = deletePackageX(packageName, userId, deleteFlags); 15091 } else { 15092 // Otherwise uninstall individually for users with blockUninstalls=false 15093 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15094 for (int userId : users) { 15095 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15096 returnCode = deletePackageX(packageName, userId, userFlags); 15097 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15098 Slog.w(TAG, "Package delete failed for user " + userId 15099 + ", returnCode " + returnCode); 15100 } 15101 } 15102 } 15103 // The app has only been marked uninstalled for certain users. 15104 // We still need to report that delete was blocked 15105 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15106 } 15107 } 15108 try { 15109 observer.onPackageDeleted(packageName, returnCode, null); 15110 } catch (RemoteException e) { 15111 Log.i(TAG, "Observer no longer exists."); 15112 } //end catch 15113 } //end run 15114 }); 15115 } 15116 15117 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15118 int[] result = EMPTY_INT_ARRAY; 15119 for (int userId : userIds) { 15120 if (getBlockUninstallForUser(packageName, userId)) { 15121 result = ArrayUtils.appendInt(result, userId); 15122 } 15123 } 15124 return result; 15125 } 15126 15127 @Override 15128 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15129 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15130 } 15131 15132 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15133 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15134 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15135 try { 15136 if (dpm != null) { 15137 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15138 /* callingUserOnly =*/ false); 15139 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15140 : deviceOwnerComponentName.getPackageName(); 15141 // Does the package contains the device owner? 15142 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15143 // this check is probably not needed, since DO should be registered as a device 15144 // admin on some user too. (Original bug for this: b/17657954) 15145 if (packageName.equals(deviceOwnerPackageName)) { 15146 return true; 15147 } 15148 // Does it contain a device admin for any user? 15149 int[] users; 15150 if (userId == UserHandle.USER_ALL) { 15151 users = sUserManager.getUserIds(); 15152 } else { 15153 users = new int[]{userId}; 15154 } 15155 for (int i = 0; i < users.length; ++i) { 15156 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15157 return true; 15158 } 15159 } 15160 } 15161 } catch (RemoteException e) { 15162 } 15163 return false; 15164 } 15165 15166 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15167 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15168 } 15169 15170 /** 15171 * This method is an internal method that could be get invoked either 15172 * to delete an installed package or to clean up a failed installation. 15173 * After deleting an installed package, a broadcast is sent to notify any 15174 * listeners that the package has been removed. For cleaning up a failed 15175 * installation, the broadcast is not necessary since the package's 15176 * installation wouldn't have sent the initial broadcast either 15177 * The key steps in deleting a package are 15178 * deleting the package information in internal structures like mPackages, 15179 * deleting the packages base directories through installd 15180 * updating mSettings to reflect current status 15181 * persisting settings for later use 15182 * sending a broadcast if necessary 15183 */ 15184 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15185 final PackageRemovedInfo info = new PackageRemovedInfo(); 15186 final boolean res; 15187 15188 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15189 ? UserHandle.ALL : new UserHandle(userId); 15190 15191 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15192 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15193 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15194 } 15195 15196 PackageSetting uninstalledPs = null; 15197 15198 // for the uninstall-updates case and restricted profiles, remember the per- 15199 // user handle installed state 15200 int[] allUsers; 15201 synchronized (mPackages) { 15202 uninstalledPs = mSettings.mPackages.get(packageName); 15203 if (uninstalledPs == null) { 15204 Slog.w(TAG, "Not removing non-existent package " + packageName); 15205 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15206 } 15207 allUsers = sUserManager.getUserIds(); 15208 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15209 } 15210 15211 synchronized (mInstallLock) { 15212 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15213 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15214 "deletePackageX")) { 15215 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15216 deleteFlags | REMOVE_CHATTY, info, true, null); 15217 } 15218 synchronized (mPackages) { 15219 if (res) { 15220 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15221 } 15222 } 15223 } 15224 15225 if (res) { 15226 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15227 info.sendPackageRemovedBroadcasts(killApp); 15228 info.sendSystemPackageUpdatedBroadcasts(); 15229 info.sendSystemPackageAppearedBroadcasts(); 15230 } 15231 // Force a gc here. 15232 Runtime.getRuntime().gc(); 15233 // Delete the resources here after sending the broadcast to let 15234 // other processes clean up before deleting resources. 15235 if (info.args != null) { 15236 synchronized (mInstallLock) { 15237 info.args.doPostDeleteLI(true); 15238 } 15239 } 15240 15241 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15242 } 15243 15244 class PackageRemovedInfo { 15245 String removedPackage; 15246 int uid = -1; 15247 int removedAppId = -1; 15248 int[] origUsers; 15249 int[] removedUsers = null; 15250 boolean isRemovedPackageSystemUpdate = false; 15251 boolean isUpdate; 15252 boolean dataRemoved; 15253 boolean removedForAllUsers; 15254 // Clean up resources deleted packages. 15255 InstallArgs args = null; 15256 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15257 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15258 15259 void sendPackageRemovedBroadcasts(boolean killApp) { 15260 sendPackageRemovedBroadcastInternal(killApp); 15261 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15262 for (int i = 0; i < childCount; i++) { 15263 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15264 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15265 } 15266 } 15267 15268 void sendSystemPackageUpdatedBroadcasts() { 15269 if (isRemovedPackageSystemUpdate) { 15270 sendSystemPackageUpdatedBroadcastsInternal(); 15271 final int childCount = (removedChildPackages != null) 15272 ? removedChildPackages.size() : 0; 15273 for (int i = 0; i < childCount; i++) { 15274 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15275 if (childInfo.isRemovedPackageSystemUpdate) { 15276 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15277 } 15278 } 15279 } 15280 } 15281 15282 void sendSystemPackageAppearedBroadcasts() { 15283 final int packageCount = (appearedChildPackages != null) 15284 ? appearedChildPackages.size() : 0; 15285 for (int i = 0; i < packageCount; i++) { 15286 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15287 for (int userId : installedInfo.newUsers) { 15288 sendPackageAddedForUser(installedInfo.name, true, 15289 UserHandle.getAppId(installedInfo.uid), userId); 15290 } 15291 } 15292 } 15293 15294 private void sendSystemPackageUpdatedBroadcastsInternal() { 15295 Bundle extras = new Bundle(2); 15296 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15297 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15298 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15299 extras, 0, null, null, null); 15300 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15301 extras, 0, null, null, null); 15302 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15303 null, 0, removedPackage, null, null); 15304 } 15305 15306 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15307 Bundle extras = new Bundle(2); 15308 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15309 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15310 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15311 if (isUpdate || isRemovedPackageSystemUpdate) { 15312 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15313 } 15314 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15315 if (removedPackage != null) { 15316 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15317 extras, 0, null, null, removedUsers); 15318 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15319 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15320 removedPackage, extras, 0, null, null, removedUsers); 15321 } 15322 } 15323 if (removedAppId >= 0) { 15324 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15325 removedUsers); 15326 } 15327 } 15328 } 15329 15330 /* 15331 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15332 * flag is not set, the data directory is removed as well. 15333 * make sure this flag is set for partially installed apps. If not its meaningless to 15334 * delete a partially installed application. 15335 */ 15336 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15337 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15338 String packageName = ps.name; 15339 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15340 // Retrieve object to delete permissions for shared user later on 15341 final PackageParser.Package deletedPkg; 15342 final PackageSetting deletedPs; 15343 // reader 15344 synchronized (mPackages) { 15345 deletedPkg = mPackages.get(packageName); 15346 deletedPs = mSettings.mPackages.get(packageName); 15347 if (outInfo != null) { 15348 outInfo.removedPackage = packageName; 15349 outInfo.removedUsers = deletedPs != null 15350 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15351 : null; 15352 } 15353 } 15354 15355 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15356 15357 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15358 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15359 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15360 destroyAppProfilesLIF(deletedPkg); 15361 if (outInfo != null) { 15362 outInfo.dataRemoved = true; 15363 } 15364 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15365 } 15366 15367 // writer 15368 synchronized (mPackages) { 15369 if (deletedPs != null) { 15370 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15371 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15372 clearDefaultBrowserIfNeeded(packageName); 15373 if (outInfo != null) { 15374 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15375 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15376 } 15377 updatePermissionsLPw(deletedPs.name, null, 0); 15378 if (deletedPs.sharedUser != null) { 15379 // Remove permissions associated with package. Since runtime 15380 // permissions are per user we have to kill the removed package 15381 // or packages running under the shared user of the removed 15382 // package if revoking the permissions requested only by the removed 15383 // package is successful and this causes a change in gids. 15384 for (int userId : UserManagerService.getInstance().getUserIds()) { 15385 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15386 userId); 15387 if (userIdToKill == UserHandle.USER_ALL 15388 || userIdToKill >= UserHandle.USER_SYSTEM) { 15389 // If gids changed for this user, kill all affected packages. 15390 mHandler.post(new Runnable() { 15391 @Override 15392 public void run() { 15393 // This has to happen with no lock held. 15394 killApplication(deletedPs.name, deletedPs.appId, 15395 KILL_APP_REASON_GIDS_CHANGED); 15396 } 15397 }); 15398 break; 15399 } 15400 } 15401 } 15402 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15403 } 15404 // make sure to preserve per-user disabled state if this removal was just 15405 // a downgrade of a system app to the factory package 15406 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15407 if (DEBUG_REMOVE) { 15408 Slog.d(TAG, "Propagating install state across downgrade"); 15409 } 15410 for (int userId : allUserHandles) { 15411 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15412 if (DEBUG_REMOVE) { 15413 Slog.d(TAG, " user " + userId + " => " + installed); 15414 } 15415 ps.setInstalled(installed, userId); 15416 } 15417 } 15418 } 15419 // can downgrade to reader 15420 if (writeSettings) { 15421 // Save settings now 15422 mSettings.writeLPr(); 15423 } 15424 } 15425 if (outInfo != null) { 15426 // A user ID was deleted here. Go through all users and remove it 15427 // from KeyStore. 15428 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15429 } 15430 } 15431 15432 static boolean locationIsPrivileged(File path) { 15433 try { 15434 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15435 .getCanonicalPath(); 15436 return path.getCanonicalPath().startsWith(privilegedAppDir); 15437 } catch (IOException e) { 15438 Slog.e(TAG, "Unable to access code path " + path); 15439 } 15440 return false; 15441 } 15442 15443 /* 15444 * Tries to delete system package. 15445 */ 15446 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15447 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15448 boolean writeSettings) { 15449 if (deletedPs.parentPackageName != null) { 15450 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15451 return false; 15452 } 15453 15454 final boolean applyUserRestrictions 15455 = (allUserHandles != null) && (outInfo.origUsers != null); 15456 final PackageSetting disabledPs; 15457 // Confirm if the system package has been updated 15458 // An updated system app can be deleted. This will also have to restore 15459 // the system pkg from system partition 15460 // reader 15461 synchronized (mPackages) { 15462 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15463 } 15464 15465 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15466 + " disabledPs=" + disabledPs); 15467 15468 if (disabledPs == null) { 15469 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15470 return false; 15471 } else if (DEBUG_REMOVE) { 15472 Slog.d(TAG, "Deleting system pkg from data partition"); 15473 } 15474 15475 if (DEBUG_REMOVE) { 15476 if (applyUserRestrictions) { 15477 Slog.d(TAG, "Remembering install states:"); 15478 for (int userId : allUserHandles) { 15479 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15480 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15481 } 15482 } 15483 } 15484 15485 // Delete the updated package 15486 outInfo.isRemovedPackageSystemUpdate = true; 15487 if (outInfo.removedChildPackages != null) { 15488 final int childCount = (deletedPs.childPackageNames != null) 15489 ? deletedPs.childPackageNames.size() : 0; 15490 for (int i = 0; i < childCount; i++) { 15491 String childPackageName = deletedPs.childPackageNames.get(i); 15492 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15493 .contains(childPackageName)) { 15494 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15495 childPackageName); 15496 if (childInfo != null) { 15497 childInfo.isRemovedPackageSystemUpdate = true; 15498 } 15499 } 15500 } 15501 } 15502 15503 if (disabledPs.versionCode < deletedPs.versionCode) { 15504 // Delete data for downgrades 15505 flags &= ~PackageManager.DELETE_KEEP_DATA; 15506 } else { 15507 // Preserve data by setting flag 15508 flags |= PackageManager.DELETE_KEEP_DATA; 15509 } 15510 15511 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15512 outInfo, writeSettings, disabledPs.pkg); 15513 if (!ret) { 15514 return false; 15515 } 15516 15517 // writer 15518 synchronized (mPackages) { 15519 // Reinstate the old system package 15520 enableSystemPackageLPw(disabledPs.pkg); 15521 // Remove any native libraries from the upgraded package. 15522 removeNativeBinariesLI(deletedPs); 15523 } 15524 15525 // Install the system package 15526 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15527 int parseFlags = mDefParseFlags 15528 | PackageParser.PARSE_MUST_BE_APK 15529 | PackageParser.PARSE_IS_SYSTEM 15530 | PackageParser.PARSE_IS_SYSTEM_DIR; 15531 if (locationIsPrivileged(disabledPs.codePath)) { 15532 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15533 } 15534 15535 final PackageParser.Package newPkg; 15536 try { 15537 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15538 } catch (PackageManagerException e) { 15539 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15540 + e.getMessage()); 15541 return false; 15542 } 15543 15544 prepareAppDataAfterInstallLIF(newPkg); 15545 15546 // writer 15547 synchronized (mPackages) { 15548 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15549 15550 // Propagate the permissions state as we do not want to drop on the floor 15551 // runtime permissions. The update permissions method below will take 15552 // care of removing obsolete permissions and grant install permissions. 15553 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15554 updatePermissionsLPw(newPkg.packageName, newPkg, 15555 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15556 15557 if (applyUserRestrictions) { 15558 if (DEBUG_REMOVE) { 15559 Slog.d(TAG, "Propagating install state across reinstall"); 15560 } 15561 for (int userId : allUserHandles) { 15562 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15563 if (DEBUG_REMOVE) { 15564 Slog.d(TAG, " user " + userId + " => " + installed); 15565 } 15566 ps.setInstalled(installed, userId); 15567 15568 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15569 } 15570 // Regardless of writeSettings we need to ensure that this restriction 15571 // state propagation is persisted 15572 mSettings.writeAllUsersPackageRestrictionsLPr(); 15573 } 15574 // can downgrade to reader here 15575 if (writeSettings) { 15576 mSettings.writeLPr(); 15577 } 15578 } 15579 return true; 15580 } 15581 15582 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15583 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15584 PackageRemovedInfo outInfo, boolean writeSettings, 15585 PackageParser.Package replacingPackage) { 15586 synchronized (mPackages) { 15587 if (outInfo != null) { 15588 outInfo.uid = ps.appId; 15589 } 15590 15591 if (outInfo != null && outInfo.removedChildPackages != null) { 15592 final int childCount = (ps.childPackageNames != null) 15593 ? ps.childPackageNames.size() : 0; 15594 for (int i = 0; i < childCount; i++) { 15595 String childPackageName = ps.childPackageNames.get(i); 15596 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15597 if (childPs == null) { 15598 return false; 15599 } 15600 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15601 childPackageName); 15602 if (childInfo != null) { 15603 childInfo.uid = childPs.appId; 15604 } 15605 } 15606 } 15607 } 15608 15609 // Delete package data from internal structures and also remove data if flag is set 15610 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15611 15612 // Delete the child packages data 15613 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15614 for (int i = 0; i < childCount; i++) { 15615 PackageSetting childPs; 15616 synchronized (mPackages) { 15617 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15618 } 15619 if (childPs != null) { 15620 PackageRemovedInfo childOutInfo = (outInfo != null 15621 && outInfo.removedChildPackages != null) 15622 ? outInfo.removedChildPackages.get(childPs.name) : null; 15623 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15624 && (replacingPackage != null 15625 && !replacingPackage.hasChildPackage(childPs.name)) 15626 ? flags & ~DELETE_KEEP_DATA : flags; 15627 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15628 deleteFlags, writeSettings); 15629 } 15630 } 15631 15632 // Delete application code and resources only for parent packages 15633 if (ps.parentPackageName == null) { 15634 if (deleteCodeAndResources && (outInfo != null)) { 15635 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15636 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15637 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15638 } 15639 } 15640 15641 return true; 15642 } 15643 15644 @Override 15645 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15646 int userId) { 15647 mContext.enforceCallingOrSelfPermission( 15648 android.Manifest.permission.DELETE_PACKAGES, null); 15649 synchronized (mPackages) { 15650 PackageSetting ps = mSettings.mPackages.get(packageName); 15651 if (ps == null) { 15652 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15653 return false; 15654 } 15655 if (!ps.getInstalled(userId)) { 15656 // Can't block uninstall for an app that is not installed or enabled. 15657 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15658 return false; 15659 } 15660 ps.setBlockUninstall(blockUninstall, userId); 15661 mSettings.writePackageRestrictionsLPr(userId); 15662 } 15663 return true; 15664 } 15665 15666 @Override 15667 public boolean getBlockUninstallForUser(String packageName, int userId) { 15668 synchronized (mPackages) { 15669 PackageSetting ps = mSettings.mPackages.get(packageName); 15670 if (ps == null) { 15671 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15672 return false; 15673 } 15674 return ps.getBlockUninstall(userId); 15675 } 15676 } 15677 15678 @Override 15679 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15680 int callingUid = Binder.getCallingUid(); 15681 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15682 throw new SecurityException( 15683 "setRequiredForSystemUser can only be run by the system or root"); 15684 } 15685 synchronized (mPackages) { 15686 PackageSetting ps = mSettings.mPackages.get(packageName); 15687 if (ps == null) { 15688 Log.w(TAG, "Package doesn't exist: " + packageName); 15689 return false; 15690 } 15691 if (systemUserApp) { 15692 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15693 } else { 15694 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15695 } 15696 mSettings.writeLPr(); 15697 } 15698 return true; 15699 } 15700 15701 /* 15702 * This method handles package deletion in general 15703 */ 15704 private boolean deletePackageLIF(String packageName, UserHandle user, 15705 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15706 PackageRemovedInfo outInfo, boolean writeSettings, 15707 PackageParser.Package replacingPackage) { 15708 if (packageName == null) { 15709 Slog.w(TAG, "Attempt to delete null packageName."); 15710 return false; 15711 } 15712 15713 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15714 15715 PackageSetting ps; 15716 15717 synchronized (mPackages) { 15718 ps = mSettings.mPackages.get(packageName); 15719 if (ps == null) { 15720 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15721 return false; 15722 } 15723 15724 if (ps.parentPackageName != null && (!isSystemApp(ps) 15725 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15726 if (DEBUG_REMOVE) { 15727 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15728 + ((user == null) ? UserHandle.USER_ALL : user)); 15729 } 15730 final int removedUserId = (user != null) ? user.getIdentifier() 15731 : UserHandle.USER_ALL; 15732 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15733 return false; 15734 } 15735 markPackageUninstalledForUserLPw(ps, user); 15736 scheduleWritePackageRestrictionsLocked(user); 15737 return true; 15738 } 15739 } 15740 15741 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15742 && user.getIdentifier() != UserHandle.USER_ALL)) { 15743 // The caller is asking that the package only be deleted for a single 15744 // user. To do this, we just mark its uninstalled state and delete 15745 // its data. If this is a system app, we only allow this to happen if 15746 // they have set the special DELETE_SYSTEM_APP which requests different 15747 // semantics than normal for uninstalling system apps. 15748 markPackageUninstalledForUserLPw(ps, user); 15749 15750 if (!isSystemApp(ps)) { 15751 // Do not uninstall the APK if an app should be cached 15752 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15753 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15754 // Other user still have this package installed, so all 15755 // we need to do is clear this user's data and save that 15756 // it is uninstalled. 15757 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15758 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15759 return false; 15760 } 15761 scheduleWritePackageRestrictionsLocked(user); 15762 return true; 15763 } else { 15764 // We need to set it back to 'installed' so the uninstall 15765 // broadcasts will be sent correctly. 15766 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15767 ps.setInstalled(true, user.getIdentifier()); 15768 } 15769 } else { 15770 // This is a system app, so we assume that the 15771 // other users still have this package installed, so all 15772 // we need to do is clear this user's data and save that 15773 // it is uninstalled. 15774 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15775 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15776 return false; 15777 } 15778 scheduleWritePackageRestrictionsLocked(user); 15779 return true; 15780 } 15781 } 15782 15783 // If we are deleting a composite package for all users, keep track 15784 // of result for each child. 15785 if (ps.childPackageNames != null && outInfo != null) { 15786 synchronized (mPackages) { 15787 final int childCount = ps.childPackageNames.size(); 15788 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15789 for (int i = 0; i < childCount; i++) { 15790 String childPackageName = ps.childPackageNames.get(i); 15791 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15792 childInfo.removedPackage = childPackageName; 15793 outInfo.removedChildPackages.put(childPackageName, childInfo); 15794 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15795 if (childPs != null) { 15796 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15797 } 15798 } 15799 } 15800 } 15801 15802 boolean ret = false; 15803 if (isSystemApp(ps)) { 15804 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15805 // When an updated system application is deleted we delete the existing resources 15806 // as well and fall back to existing code in system partition 15807 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15808 } else { 15809 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15810 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15811 outInfo, writeSettings, replacingPackage); 15812 } 15813 15814 // Take a note whether we deleted the package for all users 15815 if (outInfo != null) { 15816 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15817 if (outInfo.removedChildPackages != null) { 15818 synchronized (mPackages) { 15819 final int childCount = outInfo.removedChildPackages.size(); 15820 for (int i = 0; i < childCount; i++) { 15821 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15822 if (childInfo != null) { 15823 childInfo.removedForAllUsers = mPackages.get( 15824 childInfo.removedPackage) == null; 15825 } 15826 } 15827 } 15828 } 15829 // If we uninstalled an update to a system app there may be some 15830 // child packages that appeared as they are declared in the system 15831 // app but were not declared in the update. 15832 if (isSystemApp(ps)) { 15833 synchronized (mPackages) { 15834 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15835 final int childCount = (updatedPs.childPackageNames != null) 15836 ? updatedPs.childPackageNames.size() : 0; 15837 for (int i = 0; i < childCount; i++) { 15838 String childPackageName = updatedPs.childPackageNames.get(i); 15839 if (outInfo.removedChildPackages == null 15840 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15841 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15842 if (childPs == null) { 15843 continue; 15844 } 15845 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15846 installRes.name = childPackageName; 15847 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15848 installRes.pkg = mPackages.get(childPackageName); 15849 installRes.uid = childPs.pkg.applicationInfo.uid; 15850 if (outInfo.appearedChildPackages == null) { 15851 outInfo.appearedChildPackages = new ArrayMap<>(); 15852 } 15853 outInfo.appearedChildPackages.put(childPackageName, installRes); 15854 } 15855 } 15856 } 15857 } 15858 } 15859 15860 return ret; 15861 } 15862 15863 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15864 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15865 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15866 for (int nextUserId : userIds) { 15867 if (DEBUG_REMOVE) { 15868 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15869 } 15870 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15871 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15872 false /*hidden*/, false /*suspended*/, null, null, null, 15873 false /*blockUninstall*/, 15874 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15875 } 15876 } 15877 15878 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15879 PackageRemovedInfo outInfo) { 15880 final PackageParser.Package pkg; 15881 synchronized (mPackages) { 15882 pkg = mPackages.get(ps.name); 15883 } 15884 15885 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15886 : new int[] {userId}; 15887 for (int nextUserId : userIds) { 15888 if (DEBUG_REMOVE) { 15889 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15890 + nextUserId); 15891 } 15892 15893 destroyAppDataLIF(pkg, userId, 15894 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15895 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15896 schedulePackageCleaning(ps.name, nextUserId, false); 15897 synchronized (mPackages) { 15898 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15899 scheduleWritePackageRestrictionsLocked(nextUserId); 15900 } 15901 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15902 } 15903 } 15904 15905 if (outInfo != null) { 15906 outInfo.removedPackage = ps.name; 15907 outInfo.removedAppId = ps.appId; 15908 outInfo.removedUsers = userIds; 15909 } 15910 15911 return true; 15912 } 15913 15914 private final class ClearStorageConnection implements ServiceConnection { 15915 IMediaContainerService mContainerService; 15916 15917 @Override 15918 public void onServiceConnected(ComponentName name, IBinder service) { 15919 synchronized (this) { 15920 mContainerService = IMediaContainerService.Stub.asInterface(service); 15921 notifyAll(); 15922 } 15923 } 15924 15925 @Override 15926 public void onServiceDisconnected(ComponentName name) { 15927 } 15928 } 15929 15930 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15931 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15932 15933 final boolean mounted; 15934 if (Environment.isExternalStorageEmulated()) { 15935 mounted = true; 15936 } else { 15937 final String status = Environment.getExternalStorageState(); 15938 15939 mounted = status.equals(Environment.MEDIA_MOUNTED) 15940 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15941 } 15942 15943 if (!mounted) { 15944 return; 15945 } 15946 15947 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15948 int[] users; 15949 if (userId == UserHandle.USER_ALL) { 15950 users = sUserManager.getUserIds(); 15951 } else { 15952 users = new int[] { userId }; 15953 } 15954 final ClearStorageConnection conn = new ClearStorageConnection(); 15955 if (mContext.bindServiceAsUser( 15956 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15957 try { 15958 for (int curUser : users) { 15959 long timeout = SystemClock.uptimeMillis() + 5000; 15960 synchronized (conn) { 15961 long now = SystemClock.uptimeMillis(); 15962 while (conn.mContainerService == null && now < timeout) { 15963 try { 15964 conn.wait(timeout - now); 15965 } catch (InterruptedException e) { 15966 } 15967 } 15968 } 15969 if (conn.mContainerService == null) { 15970 return; 15971 } 15972 15973 final UserEnvironment userEnv = new UserEnvironment(curUser); 15974 clearDirectory(conn.mContainerService, 15975 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15976 if (allData) { 15977 clearDirectory(conn.mContainerService, 15978 userEnv.buildExternalStorageAppDataDirs(packageName)); 15979 clearDirectory(conn.mContainerService, 15980 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15981 } 15982 } 15983 } finally { 15984 mContext.unbindService(conn); 15985 } 15986 } 15987 } 15988 15989 @Override 15990 public void clearApplicationProfileData(String packageName) { 15991 enforceSystemOrRoot("Only the system can clear all profile data"); 15992 15993 final PackageParser.Package pkg; 15994 synchronized (mPackages) { 15995 pkg = mPackages.get(packageName); 15996 } 15997 15998 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15999 synchronized (mInstallLock) { 16000 clearAppProfilesLIF(pkg); 16001 } 16002 } 16003 } 16004 16005 @Override 16006 public void clearApplicationUserData(final String packageName, 16007 final IPackageDataObserver observer, final int userId) { 16008 mContext.enforceCallingOrSelfPermission( 16009 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16010 16011 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16012 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16013 16014 final DevicePolicyManagerInternal dpmi = LocalServices 16015 .getService(DevicePolicyManagerInternal.class); 16016 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16017 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16018 } 16019 // Queue up an async operation since the package deletion may take a little while. 16020 mHandler.post(new Runnable() { 16021 public void run() { 16022 mHandler.removeCallbacks(this); 16023 final boolean succeeded; 16024 try (PackageFreezer freezer = freezePackage(packageName, 16025 "clearApplicationUserData")) { 16026 synchronized (mInstallLock) { 16027 succeeded = clearApplicationUserDataLIF(packageName, userId); 16028 } 16029 clearExternalStorageDataSync(packageName, userId, true); 16030 } 16031 if (succeeded) { 16032 // invoke DeviceStorageMonitor's update method to clear any notifications 16033 DeviceStorageMonitorInternal dsm = LocalServices 16034 .getService(DeviceStorageMonitorInternal.class); 16035 if (dsm != null) { 16036 dsm.checkMemory(); 16037 } 16038 } 16039 if(observer != null) { 16040 try { 16041 observer.onRemoveCompleted(packageName, succeeded); 16042 } catch (RemoteException e) { 16043 Log.i(TAG, "Observer no longer exists."); 16044 } 16045 } //end if observer 16046 } //end run 16047 }); 16048 } 16049 16050 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16051 if (packageName == null) { 16052 Slog.w(TAG, "Attempt to delete null packageName."); 16053 return false; 16054 } 16055 16056 // Try finding details about the requested package 16057 PackageParser.Package pkg; 16058 synchronized (mPackages) { 16059 pkg = mPackages.get(packageName); 16060 if (pkg == null) { 16061 final PackageSetting ps = mSettings.mPackages.get(packageName); 16062 if (ps != null) { 16063 pkg = ps.pkg; 16064 } 16065 } 16066 16067 if (pkg == null) { 16068 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16069 return false; 16070 } 16071 16072 PackageSetting ps = (PackageSetting) pkg.mExtras; 16073 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16074 } 16075 16076 clearAppDataLIF(pkg, userId, 16077 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16078 16079 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16080 removeKeystoreDataIfNeeded(userId, appId); 16081 16082 final UserManager um = mContext.getSystemService(UserManager.class); 16083 final int flags; 16084 if (um.isUserUnlocked(userId)) { 16085 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16086 } else if (um.isUserRunning(userId)) { 16087 flags = StorageManager.FLAG_STORAGE_DE; 16088 } else { 16089 flags = 0; 16090 } 16091 prepareAppDataContentsLIF(pkg, userId, flags); 16092 16093 return true; 16094 } 16095 16096 /** 16097 * Reverts user permission state changes (permissions and flags) in 16098 * all packages for a given user. 16099 * 16100 * @param userId The device user for which to do a reset. 16101 */ 16102 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16103 final int packageCount = mPackages.size(); 16104 for (int i = 0; i < packageCount; i++) { 16105 PackageParser.Package pkg = mPackages.valueAt(i); 16106 PackageSetting ps = (PackageSetting) pkg.mExtras; 16107 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16108 } 16109 } 16110 16111 /** 16112 * Reverts user permission state changes (permissions and flags). 16113 * 16114 * @param ps The package for which to reset. 16115 * @param userId The device user for which to do a reset. 16116 */ 16117 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16118 final PackageSetting ps, final int userId) { 16119 if (ps.pkg == null) { 16120 return; 16121 } 16122 16123 // These are flags that can change base on user actions. 16124 final int userSettableMask = FLAG_PERMISSION_USER_SET 16125 | FLAG_PERMISSION_USER_FIXED 16126 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16127 | FLAG_PERMISSION_REVIEW_REQUIRED; 16128 16129 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16130 | FLAG_PERMISSION_POLICY_FIXED; 16131 16132 boolean writeInstallPermissions = false; 16133 boolean writeRuntimePermissions = false; 16134 16135 final int permissionCount = ps.pkg.requestedPermissions.size(); 16136 for (int i = 0; i < permissionCount; i++) { 16137 String permission = ps.pkg.requestedPermissions.get(i); 16138 16139 BasePermission bp = mSettings.mPermissions.get(permission); 16140 if (bp == null) { 16141 continue; 16142 } 16143 16144 // If shared user we just reset the state to which only this app contributed. 16145 if (ps.sharedUser != null) { 16146 boolean used = false; 16147 final int packageCount = ps.sharedUser.packages.size(); 16148 for (int j = 0; j < packageCount; j++) { 16149 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16150 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16151 && pkg.pkg.requestedPermissions.contains(permission)) { 16152 used = true; 16153 break; 16154 } 16155 } 16156 if (used) { 16157 continue; 16158 } 16159 } 16160 16161 PermissionsState permissionsState = ps.getPermissionsState(); 16162 16163 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16164 16165 // Always clear the user settable flags. 16166 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16167 bp.name) != null; 16168 // If permission review is enabled and this is a legacy app, mark the 16169 // permission as requiring a review as this is the initial state. 16170 int flags = 0; 16171 if (Build.PERMISSIONS_REVIEW_REQUIRED 16172 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16173 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16174 } 16175 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16176 if (hasInstallState) { 16177 writeInstallPermissions = true; 16178 } else { 16179 writeRuntimePermissions = true; 16180 } 16181 } 16182 16183 // Below is only runtime permission handling. 16184 if (!bp.isRuntime()) { 16185 continue; 16186 } 16187 16188 // Never clobber system or policy. 16189 if ((oldFlags & policyOrSystemFlags) != 0) { 16190 continue; 16191 } 16192 16193 // If this permission was granted by default, make sure it is. 16194 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16195 if (permissionsState.grantRuntimePermission(bp, userId) 16196 != PERMISSION_OPERATION_FAILURE) { 16197 writeRuntimePermissions = true; 16198 } 16199 // If permission review is enabled the permissions for a legacy apps 16200 // are represented as constantly granted runtime ones, so don't revoke. 16201 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16202 // Otherwise, reset the permission. 16203 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16204 switch (revokeResult) { 16205 case PERMISSION_OPERATION_SUCCESS: 16206 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16207 writeRuntimePermissions = true; 16208 final int appId = ps.appId; 16209 mHandler.post(new Runnable() { 16210 @Override 16211 public void run() { 16212 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16213 } 16214 }); 16215 } break; 16216 } 16217 } 16218 } 16219 16220 // Synchronously write as we are taking permissions away. 16221 if (writeRuntimePermissions) { 16222 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16223 } 16224 16225 // Synchronously write as we are taking permissions away. 16226 if (writeInstallPermissions) { 16227 mSettings.writeLPr(); 16228 } 16229 } 16230 16231 /** 16232 * Remove entries from the keystore daemon. Will only remove it if the 16233 * {@code appId} is valid. 16234 */ 16235 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16236 if (appId < 0) { 16237 return; 16238 } 16239 16240 final KeyStore keyStore = KeyStore.getInstance(); 16241 if (keyStore != null) { 16242 if (userId == UserHandle.USER_ALL) { 16243 for (final int individual : sUserManager.getUserIds()) { 16244 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16245 } 16246 } else { 16247 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16248 } 16249 } else { 16250 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16251 } 16252 } 16253 16254 @Override 16255 public void deleteApplicationCacheFiles(final String packageName, 16256 final IPackageDataObserver observer) { 16257 final int userId = UserHandle.getCallingUserId(); 16258 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16259 } 16260 16261 @Override 16262 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16263 final IPackageDataObserver observer) { 16264 mContext.enforceCallingOrSelfPermission( 16265 android.Manifest.permission.DELETE_CACHE_FILES, null); 16266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16267 /* requireFullPermission= */ true, /* checkShell= */ false, 16268 "delete application cache files"); 16269 16270 final PackageParser.Package pkg; 16271 synchronized (mPackages) { 16272 pkg = mPackages.get(packageName); 16273 } 16274 16275 // Queue up an async operation since the package deletion may take a little while. 16276 mHandler.post(new Runnable() { 16277 public void run() { 16278 synchronized (mInstallLock) { 16279 final int flags = StorageManager.FLAG_STORAGE_DE 16280 | StorageManager.FLAG_STORAGE_CE; 16281 // We're only clearing cache files, so we don't care if the 16282 // app is unfrozen and still able to run 16283 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16284 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16285 } 16286 clearExternalStorageDataSync(packageName, userId, false); 16287 if (observer != null) { 16288 try { 16289 observer.onRemoveCompleted(packageName, true); 16290 } catch (RemoteException e) { 16291 Log.i(TAG, "Observer no longer exists."); 16292 } 16293 } 16294 } 16295 }); 16296 } 16297 16298 @Override 16299 public void getPackageSizeInfo(final String packageName, int userHandle, 16300 final IPackageStatsObserver observer) { 16301 mContext.enforceCallingOrSelfPermission( 16302 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16303 if (packageName == null) { 16304 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16305 } 16306 16307 PackageStats stats = new PackageStats(packageName, userHandle); 16308 16309 /* 16310 * Queue up an async operation since the package measurement may take a 16311 * little while. 16312 */ 16313 Message msg = mHandler.obtainMessage(INIT_COPY); 16314 msg.obj = new MeasureParams(stats, observer); 16315 mHandler.sendMessage(msg); 16316 } 16317 16318 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16319 final PackageSetting ps; 16320 synchronized (mPackages) { 16321 ps = mSettings.mPackages.get(packageName); 16322 if (ps == null) { 16323 Slog.w(TAG, "Failed to find settings for " + packageName); 16324 return false; 16325 } 16326 } 16327 try { 16328 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16329 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16330 ps.getCeDataInode(userId), ps.codePathString, stats); 16331 } catch (InstallerException e) { 16332 Slog.w(TAG, String.valueOf(e)); 16333 return false; 16334 } 16335 16336 // For now, ignore code size of packages on system partition 16337 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16338 stats.codeSize = 0; 16339 } 16340 16341 return true; 16342 } 16343 16344 private int getUidTargetSdkVersionLockedLPr(int uid) { 16345 Object obj = mSettings.getUserIdLPr(uid); 16346 if (obj instanceof SharedUserSetting) { 16347 final SharedUserSetting sus = (SharedUserSetting) obj; 16348 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16349 final Iterator<PackageSetting> it = sus.packages.iterator(); 16350 while (it.hasNext()) { 16351 final PackageSetting ps = it.next(); 16352 if (ps.pkg != null) { 16353 int v = ps.pkg.applicationInfo.targetSdkVersion; 16354 if (v < vers) vers = v; 16355 } 16356 } 16357 return vers; 16358 } else if (obj instanceof PackageSetting) { 16359 final PackageSetting ps = (PackageSetting) obj; 16360 if (ps.pkg != null) { 16361 return ps.pkg.applicationInfo.targetSdkVersion; 16362 } 16363 } 16364 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16365 } 16366 16367 @Override 16368 public void addPreferredActivity(IntentFilter filter, int match, 16369 ComponentName[] set, ComponentName activity, int userId) { 16370 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16371 "Adding preferred"); 16372 } 16373 16374 private void addPreferredActivityInternal(IntentFilter filter, int match, 16375 ComponentName[] set, ComponentName activity, boolean always, int userId, 16376 String opname) { 16377 // writer 16378 int callingUid = Binder.getCallingUid(); 16379 enforceCrossUserPermission(callingUid, userId, 16380 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16381 if (filter.countActions() == 0) { 16382 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16383 return; 16384 } 16385 synchronized (mPackages) { 16386 if (mContext.checkCallingOrSelfPermission( 16387 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16388 != PackageManager.PERMISSION_GRANTED) { 16389 if (getUidTargetSdkVersionLockedLPr(callingUid) 16390 < Build.VERSION_CODES.FROYO) { 16391 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16392 + callingUid); 16393 return; 16394 } 16395 mContext.enforceCallingOrSelfPermission( 16396 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16397 } 16398 16399 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16400 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16401 + userId + ":"); 16402 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16403 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16404 scheduleWritePackageRestrictionsLocked(userId); 16405 } 16406 } 16407 16408 @Override 16409 public void replacePreferredActivity(IntentFilter filter, int match, 16410 ComponentName[] set, ComponentName activity, int userId) { 16411 if (filter.countActions() != 1) { 16412 throw new IllegalArgumentException( 16413 "replacePreferredActivity expects filter to have only 1 action."); 16414 } 16415 if (filter.countDataAuthorities() != 0 16416 || filter.countDataPaths() != 0 16417 || filter.countDataSchemes() > 1 16418 || filter.countDataTypes() != 0) { 16419 throw new IllegalArgumentException( 16420 "replacePreferredActivity expects filter to have no data authorities, " + 16421 "paths, or types; and at most one scheme."); 16422 } 16423 16424 final int callingUid = Binder.getCallingUid(); 16425 enforceCrossUserPermission(callingUid, userId, 16426 true /* requireFullPermission */, false /* checkShell */, 16427 "replace preferred activity"); 16428 synchronized (mPackages) { 16429 if (mContext.checkCallingOrSelfPermission( 16430 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16431 != PackageManager.PERMISSION_GRANTED) { 16432 if (getUidTargetSdkVersionLockedLPr(callingUid) 16433 < Build.VERSION_CODES.FROYO) { 16434 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16435 + Binder.getCallingUid()); 16436 return; 16437 } 16438 mContext.enforceCallingOrSelfPermission( 16439 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16440 } 16441 16442 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16443 if (pir != null) { 16444 // Get all of the existing entries that exactly match this filter. 16445 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16446 if (existing != null && existing.size() == 1) { 16447 PreferredActivity cur = existing.get(0); 16448 if (DEBUG_PREFERRED) { 16449 Slog.i(TAG, "Checking replace of preferred:"); 16450 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16451 if (!cur.mPref.mAlways) { 16452 Slog.i(TAG, " -- CUR; not mAlways!"); 16453 } else { 16454 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16455 Slog.i(TAG, " -- CUR: mSet=" 16456 + Arrays.toString(cur.mPref.mSetComponents)); 16457 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16458 Slog.i(TAG, " -- NEW: mMatch=" 16459 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16460 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16461 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16462 } 16463 } 16464 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16465 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16466 && cur.mPref.sameSet(set)) { 16467 // Setting the preferred activity to what it happens to be already 16468 if (DEBUG_PREFERRED) { 16469 Slog.i(TAG, "Replacing with same preferred activity " 16470 + cur.mPref.mShortComponent + " for user " 16471 + userId + ":"); 16472 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16473 } 16474 return; 16475 } 16476 } 16477 16478 if (existing != null) { 16479 if (DEBUG_PREFERRED) { 16480 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16481 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16482 } 16483 for (int i = 0; i < existing.size(); i++) { 16484 PreferredActivity pa = existing.get(i); 16485 if (DEBUG_PREFERRED) { 16486 Slog.i(TAG, "Removing existing preferred activity " 16487 + pa.mPref.mComponent + ":"); 16488 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16489 } 16490 pir.removeFilter(pa); 16491 } 16492 } 16493 } 16494 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16495 "Replacing preferred"); 16496 } 16497 } 16498 16499 @Override 16500 public void clearPackagePreferredActivities(String packageName) { 16501 final int uid = Binder.getCallingUid(); 16502 // writer 16503 synchronized (mPackages) { 16504 PackageParser.Package pkg = mPackages.get(packageName); 16505 if (pkg == null || pkg.applicationInfo.uid != uid) { 16506 if (mContext.checkCallingOrSelfPermission( 16507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16508 != PackageManager.PERMISSION_GRANTED) { 16509 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16510 < Build.VERSION_CODES.FROYO) { 16511 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16512 + Binder.getCallingUid()); 16513 return; 16514 } 16515 mContext.enforceCallingOrSelfPermission( 16516 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16517 } 16518 } 16519 16520 int user = UserHandle.getCallingUserId(); 16521 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16522 scheduleWritePackageRestrictionsLocked(user); 16523 } 16524 } 16525 } 16526 16527 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16528 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16529 ArrayList<PreferredActivity> removed = null; 16530 boolean changed = false; 16531 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16532 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16533 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16534 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16535 continue; 16536 } 16537 Iterator<PreferredActivity> it = pir.filterIterator(); 16538 while (it.hasNext()) { 16539 PreferredActivity pa = it.next(); 16540 // Mark entry for removal only if it matches the package name 16541 // and the entry is of type "always". 16542 if (packageName == null || 16543 (pa.mPref.mComponent.getPackageName().equals(packageName) 16544 && pa.mPref.mAlways)) { 16545 if (removed == null) { 16546 removed = new ArrayList<PreferredActivity>(); 16547 } 16548 removed.add(pa); 16549 } 16550 } 16551 if (removed != null) { 16552 for (int j=0; j<removed.size(); j++) { 16553 PreferredActivity pa = removed.get(j); 16554 pir.removeFilter(pa); 16555 } 16556 changed = true; 16557 } 16558 } 16559 return changed; 16560 } 16561 16562 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16563 private void clearIntentFilterVerificationsLPw(int userId) { 16564 final int packageCount = mPackages.size(); 16565 for (int i = 0; i < packageCount; i++) { 16566 PackageParser.Package pkg = mPackages.valueAt(i); 16567 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16568 } 16569 } 16570 16571 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16572 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16573 if (userId == UserHandle.USER_ALL) { 16574 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16575 sUserManager.getUserIds())) { 16576 for (int oneUserId : sUserManager.getUserIds()) { 16577 scheduleWritePackageRestrictionsLocked(oneUserId); 16578 } 16579 } 16580 } else { 16581 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16582 scheduleWritePackageRestrictionsLocked(userId); 16583 } 16584 } 16585 } 16586 16587 void clearDefaultBrowserIfNeeded(String packageName) { 16588 for (int oneUserId : sUserManager.getUserIds()) { 16589 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16590 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16591 if (packageName.equals(defaultBrowserPackageName)) { 16592 setDefaultBrowserPackageName(null, oneUserId); 16593 } 16594 } 16595 } 16596 16597 @Override 16598 public void resetApplicationPreferences(int userId) { 16599 mContext.enforceCallingOrSelfPermission( 16600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16601 // writer 16602 synchronized (mPackages) { 16603 final long identity = Binder.clearCallingIdentity(); 16604 try { 16605 clearPackagePreferredActivitiesLPw(null, userId); 16606 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16607 // TODO: We have to reset the default SMS and Phone. This requires 16608 // significant refactoring to keep all default apps in the package 16609 // manager (cleaner but more work) or have the services provide 16610 // callbacks to the package manager to request a default app reset. 16611 applyFactoryDefaultBrowserLPw(userId); 16612 clearIntentFilterVerificationsLPw(userId); 16613 primeDomainVerificationsLPw(userId); 16614 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16615 scheduleWritePackageRestrictionsLocked(userId); 16616 } finally { 16617 Binder.restoreCallingIdentity(identity); 16618 } 16619 } 16620 } 16621 16622 @Override 16623 public int getPreferredActivities(List<IntentFilter> outFilters, 16624 List<ComponentName> outActivities, String packageName) { 16625 16626 int num = 0; 16627 final int userId = UserHandle.getCallingUserId(); 16628 // reader 16629 synchronized (mPackages) { 16630 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16631 if (pir != null) { 16632 final Iterator<PreferredActivity> it = pir.filterIterator(); 16633 while (it.hasNext()) { 16634 final PreferredActivity pa = it.next(); 16635 if (packageName == null 16636 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16637 && pa.mPref.mAlways)) { 16638 if (outFilters != null) { 16639 outFilters.add(new IntentFilter(pa)); 16640 } 16641 if (outActivities != null) { 16642 outActivities.add(pa.mPref.mComponent); 16643 } 16644 } 16645 } 16646 } 16647 } 16648 16649 return num; 16650 } 16651 16652 @Override 16653 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16654 int userId) { 16655 int callingUid = Binder.getCallingUid(); 16656 if (callingUid != Process.SYSTEM_UID) { 16657 throw new SecurityException( 16658 "addPersistentPreferredActivity can only be run by the system"); 16659 } 16660 if (filter.countActions() == 0) { 16661 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16662 return; 16663 } 16664 synchronized (mPackages) { 16665 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16666 ":"); 16667 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16668 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16669 new PersistentPreferredActivity(filter, activity)); 16670 scheduleWritePackageRestrictionsLocked(userId); 16671 } 16672 } 16673 16674 @Override 16675 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16676 int callingUid = Binder.getCallingUid(); 16677 if (callingUid != Process.SYSTEM_UID) { 16678 throw new SecurityException( 16679 "clearPackagePersistentPreferredActivities can only be run by the system"); 16680 } 16681 ArrayList<PersistentPreferredActivity> removed = null; 16682 boolean changed = false; 16683 synchronized (mPackages) { 16684 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16685 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16686 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16687 .valueAt(i); 16688 if (userId != thisUserId) { 16689 continue; 16690 } 16691 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16692 while (it.hasNext()) { 16693 PersistentPreferredActivity ppa = it.next(); 16694 // Mark entry for removal only if it matches the package name. 16695 if (ppa.mComponent.getPackageName().equals(packageName)) { 16696 if (removed == null) { 16697 removed = new ArrayList<PersistentPreferredActivity>(); 16698 } 16699 removed.add(ppa); 16700 } 16701 } 16702 if (removed != null) { 16703 for (int j=0; j<removed.size(); j++) { 16704 PersistentPreferredActivity ppa = removed.get(j); 16705 ppir.removeFilter(ppa); 16706 } 16707 changed = true; 16708 } 16709 } 16710 16711 if (changed) { 16712 scheduleWritePackageRestrictionsLocked(userId); 16713 } 16714 } 16715 } 16716 16717 /** 16718 * Common machinery for picking apart a restored XML blob and passing 16719 * it to a caller-supplied functor to be applied to the running system. 16720 */ 16721 private void restoreFromXml(XmlPullParser parser, int userId, 16722 String expectedStartTag, BlobXmlRestorer functor) 16723 throws IOException, XmlPullParserException { 16724 int type; 16725 while ((type = parser.next()) != XmlPullParser.START_TAG 16726 && type != XmlPullParser.END_DOCUMENT) { 16727 } 16728 if (type != XmlPullParser.START_TAG) { 16729 // oops didn't find a start tag?! 16730 if (DEBUG_BACKUP) { 16731 Slog.e(TAG, "Didn't find start tag during restore"); 16732 } 16733 return; 16734 } 16735Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16736 // this is supposed to be TAG_PREFERRED_BACKUP 16737 if (!expectedStartTag.equals(parser.getName())) { 16738 if (DEBUG_BACKUP) { 16739 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16740 } 16741 return; 16742 } 16743 16744 // skip interfering stuff, then we're aligned with the backing implementation 16745 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16746Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16747 functor.apply(parser, userId); 16748 } 16749 16750 private interface BlobXmlRestorer { 16751 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16752 } 16753 16754 /** 16755 * Non-Binder method, support for the backup/restore mechanism: write the 16756 * full set of preferred activities in its canonical XML format. Returns the 16757 * XML output as a byte array, or null if there is none. 16758 */ 16759 @Override 16760 public byte[] getPreferredActivityBackup(int userId) { 16761 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16762 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16763 } 16764 16765 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16766 try { 16767 final XmlSerializer serializer = new FastXmlSerializer(); 16768 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16769 serializer.startDocument(null, true); 16770 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16771 16772 synchronized (mPackages) { 16773 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16774 } 16775 16776 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16777 serializer.endDocument(); 16778 serializer.flush(); 16779 } catch (Exception e) { 16780 if (DEBUG_BACKUP) { 16781 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16782 } 16783 return null; 16784 } 16785 16786 return dataStream.toByteArray(); 16787 } 16788 16789 @Override 16790 public void restorePreferredActivities(byte[] backup, int userId) { 16791 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16792 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16793 } 16794 16795 try { 16796 final XmlPullParser parser = Xml.newPullParser(); 16797 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16798 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16799 new BlobXmlRestorer() { 16800 @Override 16801 public void apply(XmlPullParser parser, int userId) 16802 throws XmlPullParserException, IOException { 16803 synchronized (mPackages) { 16804 mSettings.readPreferredActivitiesLPw(parser, userId); 16805 } 16806 } 16807 } ); 16808 } catch (Exception e) { 16809 if (DEBUG_BACKUP) { 16810 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16811 } 16812 } 16813 } 16814 16815 /** 16816 * Non-Binder method, support for the backup/restore mechanism: write the 16817 * default browser (etc) settings in its canonical XML format. Returns the default 16818 * browser XML representation as a byte array, or null if there is none. 16819 */ 16820 @Override 16821 public byte[] getDefaultAppsBackup(int userId) { 16822 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16823 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16824 } 16825 16826 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16827 try { 16828 final XmlSerializer serializer = new FastXmlSerializer(); 16829 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16830 serializer.startDocument(null, true); 16831 serializer.startTag(null, TAG_DEFAULT_APPS); 16832 16833 synchronized (mPackages) { 16834 mSettings.writeDefaultAppsLPr(serializer, userId); 16835 } 16836 16837 serializer.endTag(null, TAG_DEFAULT_APPS); 16838 serializer.endDocument(); 16839 serializer.flush(); 16840 } catch (Exception e) { 16841 if (DEBUG_BACKUP) { 16842 Slog.e(TAG, "Unable to write default apps for backup", e); 16843 } 16844 return null; 16845 } 16846 16847 return dataStream.toByteArray(); 16848 } 16849 16850 @Override 16851 public void restoreDefaultApps(byte[] backup, int userId) { 16852 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16853 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16854 } 16855 16856 try { 16857 final XmlPullParser parser = Xml.newPullParser(); 16858 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16859 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16860 new BlobXmlRestorer() { 16861 @Override 16862 public void apply(XmlPullParser parser, int userId) 16863 throws XmlPullParserException, IOException { 16864 synchronized (mPackages) { 16865 mSettings.readDefaultAppsLPw(parser, userId); 16866 } 16867 } 16868 } ); 16869 } catch (Exception e) { 16870 if (DEBUG_BACKUP) { 16871 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16872 } 16873 } 16874 } 16875 16876 @Override 16877 public byte[] getIntentFilterVerificationBackup(int userId) { 16878 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16879 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16880 } 16881 16882 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16883 try { 16884 final XmlSerializer serializer = new FastXmlSerializer(); 16885 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16886 serializer.startDocument(null, true); 16887 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16888 16889 synchronized (mPackages) { 16890 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16891 } 16892 16893 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16894 serializer.endDocument(); 16895 serializer.flush(); 16896 } catch (Exception e) { 16897 if (DEBUG_BACKUP) { 16898 Slog.e(TAG, "Unable to write default apps for backup", e); 16899 } 16900 return null; 16901 } 16902 16903 return dataStream.toByteArray(); 16904 } 16905 16906 @Override 16907 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16908 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16909 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16910 } 16911 16912 try { 16913 final XmlPullParser parser = Xml.newPullParser(); 16914 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16915 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16916 new BlobXmlRestorer() { 16917 @Override 16918 public void apply(XmlPullParser parser, int userId) 16919 throws XmlPullParserException, IOException { 16920 synchronized (mPackages) { 16921 mSettings.readAllDomainVerificationsLPr(parser, userId); 16922 mSettings.writeLPr(); 16923 } 16924 } 16925 } ); 16926 } catch (Exception e) { 16927 if (DEBUG_BACKUP) { 16928 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16929 } 16930 } 16931 } 16932 16933 @Override 16934 public byte[] getPermissionGrantBackup(int userId) { 16935 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16936 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16937 } 16938 16939 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16940 try { 16941 final XmlSerializer serializer = new FastXmlSerializer(); 16942 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16943 serializer.startDocument(null, true); 16944 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16945 16946 synchronized (mPackages) { 16947 serializeRuntimePermissionGrantsLPr(serializer, userId); 16948 } 16949 16950 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16951 serializer.endDocument(); 16952 serializer.flush(); 16953 } catch (Exception e) { 16954 if (DEBUG_BACKUP) { 16955 Slog.e(TAG, "Unable to write default apps for backup", e); 16956 } 16957 return null; 16958 } 16959 16960 return dataStream.toByteArray(); 16961 } 16962 16963 @Override 16964 public void restorePermissionGrants(byte[] backup, int userId) { 16965 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16966 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16967 } 16968 16969 try { 16970 final XmlPullParser parser = Xml.newPullParser(); 16971 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16972 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16973 new BlobXmlRestorer() { 16974 @Override 16975 public void apply(XmlPullParser parser, int userId) 16976 throws XmlPullParserException, IOException { 16977 synchronized (mPackages) { 16978 processRestoredPermissionGrantsLPr(parser, userId); 16979 } 16980 } 16981 } ); 16982 } catch (Exception e) { 16983 if (DEBUG_BACKUP) { 16984 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16985 } 16986 } 16987 } 16988 16989 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16990 throws IOException { 16991 serializer.startTag(null, TAG_ALL_GRANTS); 16992 16993 final int N = mSettings.mPackages.size(); 16994 for (int i = 0; i < N; i++) { 16995 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16996 boolean pkgGrantsKnown = false; 16997 16998 PermissionsState packagePerms = ps.getPermissionsState(); 16999 17000 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17001 final int grantFlags = state.getFlags(); 17002 // only look at grants that are not system/policy fixed 17003 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17004 final boolean isGranted = state.isGranted(); 17005 // And only back up the user-twiddled state bits 17006 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17007 final String packageName = mSettings.mPackages.keyAt(i); 17008 if (!pkgGrantsKnown) { 17009 serializer.startTag(null, TAG_GRANT); 17010 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17011 pkgGrantsKnown = true; 17012 } 17013 17014 final boolean userSet = 17015 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17016 final boolean userFixed = 17017 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17018 final boolean revoke = 17019 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17020 17021 serializer.startTag(null, TAG_PERMISSION); 17022 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17023 if (isGranted) { 17024 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17025 } 17026 if (userSet) { 17027 serializer.attribute(null, ATTR_USER_SET, "true"); 17028 } 17029 if (userFixed) { 17030 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17031 } 17032 if (revoke) { 17033 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17034 } 17035 serializer.endTag(null, TAG_PERMISSION); 17036 } 17037 } 17038 } 17039 17040 if (pkgGrantsKnown) { 17041 serializer.endTag(null, TAG_GRANT); 17042 } 17043 } 17044 17045 serializer.endTag(null, TAG_ALL_GRANTS); 17046 } 17047 17048 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17049 throws XmlPullParserException, IOException { 17050 String pkgName = null; 17051 int outerDepth = parser.getDepth(); 17052 int type; 17053 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17054 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17055 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17056 continue; 17057 } 17058 17059 final String tagName = parser.getName(); 17060 if (tagName.equals(TAG_GRANT)) { 17061 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17062 if (DEBUG_BACKUP) { 17063 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17064 } 17065 } else if (tagName.equals(TAG_PERMISSION)) { 17066 17067 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17068 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17069 17070 int newFlagSet = 0; 17071 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17072 newFlagSet |= FLAG_PERMISSION_USER_SET; 17073 } 17074 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17075 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17076 } 17077 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17078 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17079 } 17080 if (DEBUG_BACKUP) { 17081 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17082 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17083 } 17084 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17085 if (ps != null) { 17086 // Already installed so we apply the grant immediately 17087 if (DEBUG_BACKUP) { 17088 Slog.v(TAG, " + already installed; applying"); 17089 } 17090 PermissionsState perms = ps.getPermissionsState(); 17091 BasePermission bp = mSettings.mPermissions.get(permName); 17092 if (bp != null) { 17093 if (isGranted) { 17094 perms.grantRuntimePermission(bp, userId); 17095 } 17096 if (newFlagSet != 0) { 17097 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17098 } 17099 } 17100 } else { 17101 // Need to wait for post-restore install to apply the grant 17102 if (DEBUG_BACKUP) { 17103 Slog.v(TAG, " - not yet installed; saving for later"); 17104 } 17105 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17106 isGranted, newFlagSet, userId); 17107 } 17108 } else { 17109 PackageManagerService.reportSettingsProblem(Log.WARN, 17110 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17111 XmlUtils.skipCurrentTag(parser); 17112 } 17113 } 17114 17115 scheduleWriteSettingsLocked(); 17116 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17117 } 17118 17119 @Override 17120 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17121 int sourceUserId, int targetUserId, int flags) { 17122 mContext.enforceCallingOrSelfPermission( 17123 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17124 int callingUid = Binder.getCallingUid(); 17125 enforceOwnerRights(ownerPackage, callingUid); 17126 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17127 if (intentFilter.countActions() == 0) { 17128 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17129 return; 17130 } 17131 synchronized (mPackages) { 17132 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17133 ownerPackage, targetUserId, flags); 17134 CrossProfileIntentResolver resolver = 17135 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17136 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17137 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17138 if (existing != null) { 17139 int size = existing.size(); 17140 for (int i = 0; i < size; i++) { 17141 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17142 return; 17143 } 17144 } 17145 } 17146 resolver.addFilter(newFilter); 17147 scheduleWritePackageRestrictionsLocked(sourceUserId); 17148 } 17149 } 17150 17151 @Override 17152 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17153 mContext.enforceCallingOrSelfPermission( 17154 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17155 int callingUid = Binder.getCallingUid(); 17156 enforceOwnerRights(ownerPackage, callingUid); 17157 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17158 synchronized (mPackages) { 17159 CrossProfileIntentResolver resolver = 17160 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17161 ArraySet<CrossProfileIntentFilter> set = 17162 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17163 for (CrossProfileIntentFilter filter : set) { 17164 if (filter.getOwnerPackage().equals(ownerPackage)) { 17165 resolver.removeFilter(filter); 17166 } 17167 } 17168 scheduleWritePackageRestrictionsLocked(sourceUserId); 17169 } 17170 } 17171 17172 // Enforcing that callingUid is owning pkg on userId 17173 private void enforceOwnerRights(String pkg, int callingUid) { 17174 // The system owns everything. 17175 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17176 return; 17177 } 17178 int callingUserId = UserHandle.getUserId(callingUid); 17179 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17180 if (pi == null) { 17181 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17182 + callingUserId); 17183 } 17184 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17185 throw new SecurityException("Calling uid " + callingUid 17186 + " does not own package " + pkg); 17187 } 17188 } 17189 17190 @Override 17191 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17192 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17193 } 17194 17195 private Intent getHomeIntent() { 17196 Intent intent = new Intent(Intent.ACTION_MAIN); 17197 intent.addCategory(Intent.CATEGORY_HOME); 17198 return intent; 17199 } 17200 17201 private IntentFilter getHomeFilter() { 17202 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17203 filter.addCategory(Intent.CATEGORY_HOME); 17204 filter.addCategory(Intent.CATEGORY_DEFAULT); 17205 return filter; 17206 } 17207 17208 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17209 int userId) { 17210 Intent intent = getHomeIntent(); 17211 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17212 PackageManager.GET_META_DATA, userId); 17213 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17214 true, false, false, userId); 17215 17216 allHomeCandidates.clear(); 17217 if (list != null) { 17218 for (ResolveInfo ri : list) { 17219 allHomeCandidates.add(ri); 17220 } 17221 } 17222 return (preferred == null || preferred.activityInfo == null) 17223 ? null 17224 : new ComponentName(preferred.activityInfo.packageName, 17225 preferred.activityInfo.name); 17226 } 17227 17228 @Override 17229 public void setHomeActivity(ComponentName comp, int userId) { 17230 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17231 getHomeActivitiesAsUser(homeActivities, userId); 17232 17233 boolean found = false; 17234 17235 final int size = homeActivities.size(); 17236 final ComponentName[] set = new ComponentName[size]; 17237 for (int i = 0; i < size; i++) { 17238 final ResolveInfo candidate = homeActivities.get(i); 17239 final ActivityInfo info = candidate.activityInfo; 17240 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17241 set[i] = activityName; 17242 if (!found && activityName.equals(comp)) { 17243 found = true; 17244 } 17245 } 17246 if (!found) { 17247 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17248 + userId); 17249 } 17250 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17251 set, comp, userId); 17252 } 17253 17254 private @Nullable String getSetupWizardPackageName() { 17255 final Intent intent = new Intent(Intent.ACTION_MAIN); 17256 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17257 17258 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17259 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17260 | MATCH_DISABLED_COMPONENTS, 17261 UserHandle.myUserId()); 17262 if (matches.size() == 1) { 17263 return matches.get(0).getComponentInfo().packageName; 17264 } else { 17265 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17266 + ": matches=" + matches); 17267 return null; 17268 } 17269 } 17270 17271 @Override 17272 public void setApplicationEnabledSetting(String appPackageName, 17273 int newState, int flags, int userId, String callingPackage) { 17274 if (!sUserManager.exists(userId)) return; 17275 if (callingPackage == null) { 17276 callingPackage = Integer.toString(Binder.getCallingUid()); 17277 } 17278 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17279 } 17280 17281 @Override 17282 public void setComponentEnabledSetting(ComponentName componentName, 17283 int newState, int flags, int userId) { 17284 if (!sUserManager.exists(userId)) return; 17285 setEnabledSetting(componentName.getPackageName(), 17286 componentName.getClassName(), newState, flags, userId, null); 17287 } 17288 17289 private void setEnabledSetting(final String packageName, String className, int newState, 17290 final int flags, int userId, String callingPackage) { 17291 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17292 || newState == COMPONENT_ENABLED_STATE_ENABLED 17293 || newState == COMPONENT_ENABLED_STATE_DISABLED 17294 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17295 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17296 throw new IllegalArgumentException("Invalid new component state: " 17297 + newState); 17298 } 17299 PackageSetting pkgSetting; 17300 final int uid = Binder.getCallingUid(); 17301 final int permission; 17302 if (uid == Process.SYSTEM_UID) { 17303 permission = PackageManager.PERMISSION_GRANTED; 17304 } else { 17305 permission = mContext.checkCallingOrSelfPermission( 17306 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17307 } 17308 enforceCrossUserPermission(uid, userId, 17309 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17310 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17311 boolean sendNow = false; 17312 boolean isApp = (className == null); 17313 String componentName = isApp ? packageName : className; 17314 int packageUid = -1; 17315 ArrayList<String> components; 17316 17317 // writer 17318 synchronized (mPackages) { 17319 pkgSetting = mSettings.mPackages.get(packageName); 17320 if (pkgSetting == null) { 17321 if (className == null) { 17322 throw new IllegalArgumentException("Unknown package: " + packageName); 17323 } 17324 throw new IllegalArgumentException( 17325 "Unknown component: " + packageName + "/" + className); 17326 } 17327 // Allow root and verify that userId is not being specified by a different user 17328 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17329 throw new SecurityException( 17330 "Permission Denial: attempt to change component state from pid=" 17331 + Binder.getCallingPid() 17332 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17333 } 17334 if (className == null) { 17335 // We're dealing with an application/package level state change 17336 if (pkgSetting.getEnabled(userId) == newState) { 17337 // Nothing to do 17338 return; 17339 } 17340 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17341 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17342 // Don't care about who enables an app. 17343 callingPackage = null; 17344 } 17345 pkgSetting.setEnabled(newState, userId, callingPackage); 17346 // pkgSetting.pkg.mSetEnabled = newState; 17347 } else { 17348 // We're dealing with a component level state change 17349 // First, verify that this is a valid class name. 17350 PackageParser.Package pkg = pkgSetting.pkg; 17351 if (pkg == null || !pkg.hasComponentClassName(className)) { 17352 if (pkg != null && 17353 pkg.applicationInfo.targetSdkVersion >= 17354 Build.VERSION_CODES.JELLY_BEAN) { 17355 throw new IllegalArgumentException("Component class " + className 17356 + " does not exist in " + packageName); 17357 } else { 17358 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17359 + className + " does not exist in " + packageName); 17360 } 17361 } 17362 switch (newState) { 17363 case COMPONENT_ENABLED_STATE_ENABLED: 17364 if (!pkgSetting.enableComponentLPw(className, userId)) { 17365 return; 17366 } 17367 break; 17368 case COMPONENT_ENABLED_STATE_DISABLED: 17369 if (!pkgSetting.disableComponentLPw(className, userId)) { 17370 return; 17371 } 17372 break; 17373 case COMPONENT_ENABLED_STATE_DEFAULT: 17374 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17375 return; 17376 } 17377 break; 17378 default: 17379 Slog.e(TAG, "Invalid new component state: " + newState); 17380 return; 17381 } 17382 } 17383 scheduleWritePackageRestrictionsLocked(userId); 17384 components = mPendingBroadcasts.get(userId, packageName); 17385 final boolean newPackage = components == null; 17386 if (newPackage) { 17387 components = new ArrayList<String>(); 17388 } 17389 if (!components.contains(componentName)) { 17390 components.add(componentName); 17391 } 17392 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17393 sendNow = true; 17394 // Purge entry from pending broadcast list if another one exists already 17395 // since we are sending one right away. 17396 mPendingBroadcasts.remove(userId, packageName); 17397 } else { 17398 if (newPackage) { 17399 mPendingBroadcasts.put(userId, packageName, components); 17400 } 17401 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17402 // Schedule a message 17403 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17404 } 17405 } 17406 } 17407 17408 long callingId = Binder.clearCallingIdentity(); 17409 try { 17410 if (sendNow) { 17411 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17412 sendPackageChangedBroadcast(packageName, 17413 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17414 } 17415 } finally { 17416 Binder.restoreCallingIdentity(callingId); 17417 } 17418 } 17419 17420 @Override 17421 public void flushPackageRestrictionsAsUser(int userId) { 17422 if (!sUserManager.exists(userId)) { 17423 return; 17424 } 17425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17426 false /* checkShell */, "flushPackageRestrictions"); 17427 synchronized (mPackages) { 17428 mSettings.writePackageRestrictionsLPr(userId); 17429 mDirtyUsers.remove(userId); 17430 if (mDirtyUsers.isEmpty()) { 17431 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17432 } 17433 } 17434 } 17435 17436 private void sendPackageChangedBroadcast(String packageName, 17437 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17438 if (DEBUG_INSTALL) 17439 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17440 + componentNames); 17441 Bundle extras = new Bundle(4); 17442 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17443 String nameList[] = new String[componentNames.size()]; 17444 componentNames.toArray(nameList); 17445 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17446 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17447 extras.putInt(Intent.EXTRA_UID, packageUid); 17448 // If this is not reporting a change of the overall package, then only send it 17449 // to registered receivers. We don't want to launch a swath of apps for every 17450 // little component state change. 17451 final int flags = !componentNames.contains(packageName) 17452 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17453 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17454 new int[] {UserHandle.getUserId(packageUid)}); 17455 } 17456 17457 @Override 17458 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17459 if (!sUserManager.exists(userId)) return; 17460 final int uid = Binder.getCallingUid(); 17461 final int permission = mContext.checkCallingOrSelfPermission( 17462 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17463 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17464 enforceCrossUserPermission(uid, userId, 17465 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17466 // writer 17467 synchronized (mPackages) { 17468 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17469 allowedByPermission, uid, userId)) { 17470 scheduleWritePackageRestrictionsLocked(userId); 17471 } 17472 } 17473 } 17474 17475 @Override 17476 public String getInstallerPackageName(String packageName) { 17477 // reader 17478 synchronized (mPackages) { 17479 return mSettings.getInstallerPackageNameLPr(packageName); 17480 } 17481 } 17482 17483 @Override 17484 public int getApplicationEnabledSetting(String packageName, int userId) { 17485 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17486 int uid = Binder.getCallingUid(); 17487 enforceCrossUserPermission(uid, userId, 17488 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17489 // reader 17490 synchronized (mPackages) { 17491 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17492 } 17493 } 17494 17495 @Override 17496 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17497 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17498 int uid = Binder.getCallingUid(); 17499 enforceCrossUserPermission(uid, userId, 17500 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17501 // reader 17502 synchronized (mPackages) { 17503 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17504 } 17505 } 17506 17507 @Override 17508 public void enterSafeMode() { 17509 enforceSystemOrRoot("Only the system can request entering safe mode"); 17510 17511 if (!mSystemReady) { 17512 mSafeMode = true; 17513 } 17514 } 17515 17516 @Override 17517 public void systemReady() { 17518 mSystemReady = true; 17519 17520 // Read the compatibilty setting when the system is ready. 17521 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17522 mContext.getContentResolver(), 17523 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17524 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17525 if (DEBUG_SETTINGS) { 17526 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17527 } 17528 17529 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17530 17531 synchronized (mPackages) { 17532 // Verify that all of the preferred activity components actually 17533 // exist. It is possible for applications to be updated and at 17534 // that point remove a previously declared activity component that 17535 // had been set as a preferred activity. We try to clean this up 17536 // the next time we encounter that preferred activity, but it is 17537 // possible for the user flow to never be able to return to that 17538 // situation so here we do a sanity check to make sure we haven't 17539 // left any junk around. 17540 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17541 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17542 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17543 removed.clear(); 17544 for (PreferredActivity pa : pir.filterSet()) { 17545 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17546 removed.add(pa); 17547 } 17548 } 17549 if (removed.size() > 0) { 17550 for (int r=0; r<removed.size(); r++) { 17551 PreferredActivity pa = removed.get(r); 17552 Slog.w(TAG, "Removing dangling preferred activity: " 17553 + pa.mPref.mComponent); 17554 pir.removeFilter(pa); 17555 } 17556 mSettings.writePackageRestrictionsLPr( 17557 mSettings.mPreferredActivities.keyAt(i)); 17558 } 17559 } 17560 17561 for (int userId : UserManagerService.getInstance().getUserIds()) { 17562 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17563 grantPermissionsUserIds = ArrayUtils.appendInt( 17564 grantPermissionsUserIds, userId); 17565 } 17566 } 17567 } 17568 sUserManager.systemReady(); 17569 17570 // If we upgraded grant all default permissions before kicking off. 17571 for (int userId : grantPermissionsUserIds) { 17572 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17573 } 17574 17575 // Kick off any messages waiting for system ready 17576 if (mPostSystemReadyMessages != null) { 17577 for (Message msg : mPostSystemReadyMessages) { 17578 msg.sendToTarget(); 17579 } 17580 mPostSystemReadyMessages = null; 17581 } 17582 17583 // Watch for external volumes that come and go over time 17584 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17585 storage.registerListener(mStorageListener); 17586 17587 mInstallerService.systemReady(); 17588 mPackageDexOptimizer.systemReady(); 17589 17590 MountServiceInternal mountServiceInternal = LocalServices.getService( 17591 MountServiceInternal.class); 17592 mountServiceInternal.addExternalStoragePolicy( 17593 new MountServiceInternal.ExternalStorageMountPolicy() { 17594 @Override 17595 public int getMountMode(int uid, String packageName) { 17596 if (Process.isIsolated(uid)) { 17597 return Zygote.MOUNT_EXTERNAL_NONE; 17598 } 17599 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17600 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17601 } 17602 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17603 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17604 } 17605 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17606 return Zygote.MOUNT_EXTERNAL_READ; 17607 } 17608 return Zygote.MOUNT_EXTERNAL_WRITE; 17609 } 17610 17611 @Override 17612 public boolean hasExternalStorage(int uid, String packageName) { 17613 return true; 17614 } 17615 }); 17616 17617 // Now that we're mostly running, clean up stale users and apps 17618 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17619 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17620 } 17621 17622 @Override 17623 public boolean isSafeMode() { 17624 return mSafeMode; 17625 } 17626 17627 @Override 17628 public boolean hasSystemUidErrors() { 17629 return mHasSystemUidErrors; 17630 } 17631 17632 static String arrayToString(int[] array) { 17633 StringBuffer buf = new StringBuffer(128); 17634 buf.append('['); 17635 if (array != null) { 17636 for (int i=0; i<array.length; i++) { 17637 if (i > 0) buf.append(", "); 17638 buf.append(array[i]); 17639 } 17640 } 17641 buf.append(']'); 17642 return buf.toString(); 17643 } 17644 17645 static class DumpState { 17646 public static final int DUMP_LIBS = 1 << 0; 17647 public static final int DUMP_FEATURES = 1 << 1; 17648 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17649 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17650 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17651 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17652 public static final int DUMP_PERMISSIONS = 1 << 6; 17653 public static final int DUMP_PACKAGES = 1 << 7; 17654 public static final int DUMP_SHARED_USERS = 1 << 8; 17655 public static final int DUMP_MESSAGES = 1 << 9; 17656 public static final int DUMP_PROVIDERS = 1 << 10; 17657 public static final int DUMP_VERIFIERS = 1 << 11; 17658 public static final int DUMP_PREFERRED = 1 << 12; 17659 public static final int DUMP_PREFERRED_XML = 1 << 13; 17660 public static final int DUMP_KEYSETS = 1 << 14; 17661 public static final int DUMP_VERSION = 1 << 15; 17662 public static final int DUMP_INSTALLS = 1 << 16; 17663 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17664 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17665 public static final int DUMP_FROZEN = 1 << 19; 17666 17667 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17668 17669 private int mTypes; 17670 17671 private int mOptions; 17672 17673 private boolean mTitlePrinted; 17674 17675 private SharedUserSetting mSharedUser; 17676 17677 public boolean isDumping(int type) { 17678 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17679 return true; 17680 } 17681 17682 return (mTypes & type) != 0; 17683 } 17684 17685 public void setDump(int type) { 17686 mTypes |= type; 17687 } 17688 17689 public boolean isOptionEnabled(int option) { 17690 return (mOptions & option) != 0; 17691 } 17692 17693 public void setOptionEnabled(int option) { 17694 mOptions |= option; 17695 } 17696 17697 public boolean onTitlePrinted() { 17698 final boolean printed = mTitlePrinted; 17699 mTitlePrinted = true; 17700 return printed; 17701 } 17702 17703 public boolean getTitlePrinted() { 17704 return mTitlePrinted; 17705 } 17706 17707 public void setTitlePrinted(boolean enabled) { 17708 mTitlePrinted = enabled; 17709 } 17710 17711 public SharedUserSetting getSharedUser() { 17712 return mSharedUser; 17713 } 17714 17715 public void setSharedUser(SharedUserSetting user) { 17716 mSharedUser = user; 17717 } 17718 } 17719 17720 @Override 17721 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17722 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17723 (new PackageManagerShellCommand(this)).exec( 17724 this, in, out, err, args, resultReceiver); 17725 } 17726 17727 @Override 17728 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17729 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17730 != PackageManager.PERMISSION_GRANTED) { 17731 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17732 + Binder.getCallingPid() 17733 + ", uid=" + Binder.getCallingUid() 17734 + " without permission " 17735 + android.Manifest.permission.DUMP); 17736 return; 17737 } 17738 17739 DumpState dumpState = new DumpState(); 17740 boolean fullPreferred = false; 17741 boolean checkin = false; 17742 17743 String packageName = null; 17744 ArraySet<String> permissionNames = null; 17745 17746 int opti = 0; 17747 while (opti < args.length) { 17748 String opt = args[opti]; 17749 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17750 break; 17751 } 17752 opti++; 17753 17754 if ("-a".equals(opt)) { 17755 // Right now we only know how to print all. 17756 } else if ("-h".equals(opt)) { 17757 pw.println("Package manager dump options:"); 17758 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17759 pw.println(" --checkin: dump for a checkin"); 17760 pw.println(" -f: print details of intent filters"); 17761 pw.println(" -h: print this help"); 17762 pw.println(" cmd may be one of:"); 17763 pw.println(" l[ibraries]: list known shared libraries"); 17764 pw.println(" f[eatures]: list device features"); 17765 pw.println(" k[eysets]: print known keysets"); 17766 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17767 pw.println(" perm[issions]: dump permissions"); 17768 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17769 pw.println(" pref[erred]: print preferred package settings"); 17770 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17771 pw.println(" prov[iders]: dump content providers"); 17772 pw.println(" p[ackages]: dump installed packages"); 17773 pw.println(" s[hared-users]: dump shared user IDs"); 17774 pw.println(" m[essages]: print collected runtime messages"); 17775 pw.println(" v[erifiers]: print package verifier info"); 17776 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17777 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17778 pw.println(" version: print database version info"); 17779 pw.println(" write: write current settings now"); 17780 pw.println(" installs: details about install sessions"); 17781 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17782 pw.println(" <package.name>: info about given package"); 17783 return; 17784 } else if ("--checkin".equals(opt)) { 17785 checkin = true; 17786 } else if ("-f".equals(opt)) { 17787 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17788 } else { 17789 pw.println("Unknown argument: " + opt + "; use -h for help"); 17790 } 17791 } 17792 17793 // Is the caller requesting to dump a particular piece of data? 17794 if (opti < args.length) { 17795 String cmd = args[opti]; 17796 opti++; 17797 // Is this a package name? 17798 if ("android".equals(cmd) || cmd.contains(".")) { 17799 packageName = cmd; 17800 // When dumping a single package, we always dump all of its 17801 // filter information since the amount of data will be reasonable. 17802 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17803 } else if ("check-permission".equals(cmd)) { 17804 if (opti >= args.length) { 17805 pw.println("Error: check-permission missing permission argument"); 17806 return; 17807 } 17808 String perm = args[opti]; 17809 opti++; 17810 if (opti >= args.length) { 17811 pw.println("Error: check-permission missing package argument"); 17812 return; 17813 } 17814 String pkg = args[opti]; 17815 opti++; 17816 int user = UserHandle.getUserId(Binder.getCallingUid()); 17817 if (opti < args.length) { 17818 try { 17819 user = Integer.parseInt(args[opti]); 17820 } catch (NumberFormatException e) { 17821 pw.println("Error: check-permission user argument is not a number: " 17822 + args[opti]); 17823 return; 17824 } 17825 } 17826 pw.println(checkPermission(perm, pkg, user)); 17827 return; 17828 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17829 dumpState.setDump(DumpState.DUMP_LIBS); 17830 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17831 dumpState.setDump(DumpState.DUMP_FEATURES); 17832 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17833 if (opti >= args.length) { 17834 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17835 | DumpState.DUMP_SERVICE_RESOLVERS 17836 | DumpState.DUMP_RECEIVER_RESOLVERS 17837 | DumpState.DUMP_CONTENT_RESOLVERS); 17838 } else { 17839 while (opti < args.length) { 17840 String name = args[opti]; 17841 if ("a".equals(name) || "activity".equals(name)) { 17842 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17843 } else if ("s".equals(name) || "service".equals(name)) { 17844 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17845 } else if ("r".equals(name) || "receiver".equals(name)) { 17846 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17847 } else if ("c".equals(name) || "content".equals(name)) { 17848 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17849 } else { 17850 pw.println("Error: unknown resolver table type: " + name); 17851 return; 17852 } 17853 opti++; 17854 } 17855 } 17856 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17857 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17858 } else if ("permission".equals(cmd)) { 17859 if (opti >= args.length) { 17860 pw.println("Error: permission requires permission name"); 17861 return; 17862 } 17863 permissionNames = new ArraySet<>(); 17864 while (opti < args.length) { 17865 permissionNames.add(args[opti]); 17866 opti++; 17867 } 17868 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17869 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17870 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17871 dumpState.setDump(DumpState.DUMP_PREFERRED); 17872 } else if ("preferred-xml".equals(cmd)) { 17873 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17874 if (opti < args.length && "--full".equals(args[opti])) { 17875 fullPreferred = true; 17876 opti++; 17877 } 17878 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17879 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17880 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17881 dumpState.setDump(DumpState.DUMP_PACKAGES); 17882 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17883 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17884 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17885 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17886 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17887 dumpState.setDump(DumpState.DUMP_MESSAGES); 17888 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17889 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17890 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17891 || "intent-filter-verifiers".equals(cmd)) { 17892 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17893 } else if ("version".equals(cmd)) { 17894 dumpState.setDump(DumpState.DUMP_VERSION); 17895 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17896 dumpState.setDump(DumpState.DUMP_KEYSETS); 17897 } else if ("installs".equals(cmd)) { 17898 dumpState.setDump(DumpState.DUMP_INSTALLS); 17899 } else if ("frozen".equals(cmd)) { 17900 dumpState.setDump(DumpState.DUMP_FROZEN); 17901 } else if ("write".equals(cmd)) { 17902 synchronized (mPackages) { 17903 mSettings.writeLPr(); 17904 pw.println("Settings written."); 17905 return; 17906 } 17907 } 17908 } 17909 17910 if (checkin) { 17911 pw.println("vers,1"); 17912 } 17913 17914 // reader 17915 synchronized (mPackages) { 17916 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17917 if (!checkin) { 17918 if (dumpState.onTitlePrinted()) 17919 pw.println(); 17920 pw.println("Database versions:"); 17921 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17922 } 17923 } 17924 17925 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17926 if (!checkin) { 17927 if (dumpState.onTitlePrinted()) 17928 pw.println(); 17929 pw.println("Verifiers:"); 17930 pw.print(" Required: "); 17931 pw.print(mRequiredVerifierPackage); 17932 pw.print(" (uid="); 17933 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17934 UserHandle.USER_SYSTEM)); 17935 pw.println(")"); 17936 } else if (mRequiredVerifierPackage != null) { 17937 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17938 pw.print(","); 17939 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17940 UserHandle.USER_SYSTEM)); 17941 } 17942 } 17943 17944 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17945 packageName == null) { 17946 if (mIntentFilterVerifierComponent != null) { 17947 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17948 if (!checkin) { 17949 if (dumpState.onTitlePrinted()) 17950 pw.println(); 17951 pw.println("Intent Filter Verifier:"); 17952 pw.print(" Using: "); 17953 pw.print(verifierPackageName); 17954 pw.print(" (uid="); 17955 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17956 UserHandle.USER_SYSTEM)); 17957 pw.println(")"); 17958 } else if (verifierPackageName != null) { 17959 pw.print("ifv,"); pw.print(verifierPackageName); 17960 pw.print(","); 17961 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17962 UserHandle.USER_SYSTEM)); 17963 } 17964 } else { 17965 pw.println(); 17966 pw.println("No Intent Filter Verifier available!"); 17967 } 17968 } 17969 17970 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17971 boolean printedHeader = false; 17972 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17973 while (it.hasNext()) { 17974 String name = it.next(); 17975 SharedLibraryEntry ent = mSharedLibraries.get(name); 17976 if (!checkin) { 17977 if (!printedHeader) { 17978 if (dumpState.onTitlePrinted()) 17979 pw.println(); 17980 pw.println("Libraries:"); 17981 printedHeader = true; 17982 } 17983 pw.print(" "); 17984 } else { 17985 pw.print("lib,"); 17986 } 17987 pw.print(name); 17988 if (!checkin) { 17989 pw.print(" -> "); 17990 } 17991 if (ent.path != null) { 17992 if (!checkin) { 17993 pw.print("(jar) "); 17994 pw.print(ent.path); 17995 } else { 17996 pw.print(",jar,"); 17997 pw.print(ent.path); 17998 } 17999 } else { 18000 if (!checkin) { 18001 pw.print("(apk) "); 18002 pw.print(ent.apk); 18003 } else { 18004 pw.print(",apk,"); 18005 pw.print(ent.apk); 18006 } 18007 } 18008 pw.println(); 18009 } 18010 } 18011 18012 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18013 if (dumpState.onTitlePrinted()) 18014 pw.println(); 18015 if (!checkin) { 18016 pw.println("Features:"); 18017 } 18018 18019 for (FeatureInfo feat : mAvailableFeatures.values()) { 18020 if (checkin) { 18021 pw.print("feat,"); 18022 pw.print(feat.name); 18023 pw.print(","); 18024 pw.println(feat.version); 18025 } else { 18026 pw.print(" "); 18027 pw.print(feat.name); 18028 if (feat.version > 0) { 18029 pw.print(" version="); 18030 pw.print(feat.version); 18031 } 18032 pw.println(); 18033 } 18034 } 18035 } 18036 18037 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18038 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18039 : "Activity Resolver Table:", " ", packageName, 18040 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18041 dumpState.setTitlePrinted(true); 18042 } 18043 } 18044 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18045 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18046 : "Receiver Resolver Table:", " ", packageName, 18047 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18048 dumpState.setTitlePrinted(true); 18049 } 18050 } 18051 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18052 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18053 : "Service Resolver Table:", " ", packageName, 18054 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18055 dumpState.setTitlePrinted(true); 18056 } 18057 } 18058 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18059 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18060 : "Provider Resolver Table:", " ", packageName, 18061 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18062 dumpState.setTitlePrinted(true); 18063 } 18064 } 18065 18066 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18067 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18068 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18069 int user = mSettings.mPreferredActivities.keyAt(i); 18070 if (pir.dump(pw, 18071 dumpState.getTitlePrinted() 18072 ? "\nPreferred Activities User " + user + ":" 18073 : "Preferred Activities User " + user + ":", " ", 18074 packageName, true, false)) { 18075 dumpState.setTitlePrinted(true); 18076 } 18077 } 18078 } 18079 18080 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18081 pw.flush(); 18082 FileOutputStream fout = new FileOutputStream(fd); 18083 BufferedOutputStream str = new BufferedOutputStream(fout); 18084 XmlSerializer serializer = new FastXmlSerializer(); 18085 try { 18086 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18087 serializer.startDocument(null, true); 18088 serializer.setFeature( 18089 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18090 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18091 serializer.endDocument(); 18092 serializer.flush(); 18093 } catch (IllegalArgumentException e) { 18094 pw.println("Failed writing: " + e); 18095 } catch (IllegalStateException e) { 18096 pw.println("Failed writing: " + e); 18097 } catch (IOException e) { 18098 pw.println("Failed writing: " + e); 18099 } 18100 } 18101 18102 if (!checkin 18103 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18104 && packageName == null) { 18105 pw.println(); 18106 int count = mSettings.mPackages.size(); 18107 if (count == 0) { 18108 pw.println("No applications!"); 18109 pw.println(); 18110 } else { 18111 final String prefix = " "; 18112 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18113 if (allPackageSettings.size() == 0) { 18114 pw.println("No domain preferred apps!"); 18115 pw.println(); 18116 } else { 18117 pw.println("App verification status:"); 18118 pw.println(); 18119 count = 0; 18120 for (PackageSetting ps : allPackageSettings) { 18121 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18122 if (ivi == null || ivi.getPackageName() == null) continue; 18123 pw.println(prefix + "Package: " + ivi.getPackageName()); 18124 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18125 pw.println(prefix + "Status: " + ivi.getStatusString()); 18126 pw.println(); 18127 count++; 18128 } 18129 if (count == 0) { 18130 pw.println(prefix + "No app verification established."); 18131 pw.println(); 18132 } 18133 for (int userId : sUserManager.getUserIds()) { 18134 pw.println("App linkages for user " + userId + ":"); 18135 pw.println(); 18136 count = 0; 18137 for (PackageSetting ps : allPackageSettings) { 18138 final long status = ps.getDomainVerificationStatusForUser(userId); 18139 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18140 continue; 18141 } 18142 pw.println(prefix + "Package: " + ps.name); 18143 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18144 String statusStr = IntentFilterVerificationInfo. 18145 getStatusStringFromValue(status); 18146 pw.println(prefix + "Status: " + statusStr); 18147 pw.println(); 18148 count++; 18149 } 18150 if (count == 0) { 18151 pw.println(prefix + "No configured app linkages."); 18152 pw.println(); 18153 } 18154 } 18155 } 18156 } 18157 } 18158 18159 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18160 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18161 if (packageName == null && permissionNames == null) { 18162 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18163 if (iperm == 0) { 18164 if (dumpState.onTitlePrinted()) 18165 pw.println(); 18166 pw.println("AppOp Permissions:"); 18167 } 18168 pw.print(" AppOp Permission "); 18169 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18170 pw.println(":"); 18171 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18172 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18173 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18174 } 18175 } 18176 } 18177 } 18178 18179 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18180 boolean printedSomething = false; 18181 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18182 if (packageName != null && !packageName.equals(p.info.packageName)) { 18183 continue; 18184 } 18185 if (!printedSomething) { 18186 if (dumpState.onTitlePrinted()) 18187 pw.println(); 18188 pw.println("Registered ContentProviders:"); 18189 printedSomething = true; 18190 } 18191 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18192 pw.print(" "); pw.println(p.toString()); 18193 } 18194 printedSomething = false; 18195 for (Map.Entry<String, PackageParser.Provider> entry : 18196 mProvidersByAuthority.entrySet()) { 18197 PackageParser.Provider p = entry.getValue(); 18198 if (packageName != null && !packageName.equals(p.info.packageName)) { 18199 continue; 18200 } 18201 if (!printedSomething) { 18202 if (dumpState.onTitlePrinted()) 18203 pw.println(); 18204 pw.println("ContentProvider Authorities:"); 18205 printedSomething = true; 18206 } 18207 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18208 pw.print(" "); pw.println(p.toString()); 18209 if (p.info != null && p.info.applicationInfo != null) { 18210 final String appInfo = p.info.applicationInfo.toString(); 18211 pw.print(" applicationInfo="); pw.println(appInfo); 18212 } 18213 } 18214 } 18215 18216 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18217 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18218 } 18219 18220 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18221 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18222 } 18223 18224 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18225 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18226 } 18227 18228 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18229 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18230 } 18231 18232 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18233 // XXX should handle packageName != null by dumping only install data that 18234 // the given package is involved with. 18235 if (dumpState.onTitlePrinted()) pw.println(); 18236 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18237 } 18238 18239 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18240 // XXX should handle packageName != null by dumping only install data that 18241 // the given package is involved with. 18242 if (dumpState.onTitlePrinted()) pw.println(); 18243 18244 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18245 ipw.println(); 18246 ipw.println("Frozen packages:"); 18247 ipw.increaseIndent(); 18248 if (mFrozenPackages.size() == 0) { 18249 ipw.println("(none)"); 18250 } else { 18251 for (int i = 0; i < mFrozenPackages.size(); i++) { 18252 ipw.println(mFrozenPackages.valueAt(i)); 18253 } 18254 } 18255 ipw.decreaseIndent(); 18256 } 18257 18258 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18259 if (dumpState.onTitlePrinted()) pw.println(); 18260 mSettings.dumpReadMessagesLPr(pw, dumpState); 18261 18262 pw.println(); 18263 pw.println("Package warning messages:"); 18264 BufferedReader in = null; 18265 String line = null; 18266 try { 18267 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18268 while ((line = in.readLine()) != null) { 18269 if (line.contains("ignored: updated version")) continue; 18270 pw.println(line); 18271 } 18272 } catch (IOException ignored) { 18273 } finally { 18274 IoUtils.closeQuietly(in); 18275 } 18276 } 18277 18278 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18279 BufferedReader in = null; 18280 String line = null; 18281 try { 18282 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18283 while ((line = in.readLine()) != null) { 18284 if (line.contains("ignored: updated version")) continue; 18285 pw.print("msg,"); 18286 pw.println(line); 18287 } 18288 } catch (IOException ignored) { 18289 } finally { 18290 IoUtils.closeQuietly(in); 18291 } 18292 } 18293 } 18294 } 18295 18296 private String dumpDomainString(String packageName) { 18297 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18298 .getList(); 18299 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18300 18301 ArraySet<String> result = new ArraySet<>(); 18302 if (iviList.size() > 0) { 18303 for (IntentFilterVerificationInfo ivi : iviList) { 18304 for (String host : ivi.getDomains()) { 18305 result.add(host); 18306 } 18307 } 18308 } 18309 if (filters != null && filters.size() > 0) { 18310 for (IntentFilter filter : filters) { 18311 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18312 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18313 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18314 result.addAll(filter.getHostsList()); 18315 } 18316 } 18317 } 18318 18319 StringBuilder sb = new StringBuilder(result.size() * 16); 18320 for (String domain : result) { 18321 if (sb.length() > 0) sb.append(" "); 18322 sb.append(domain); 18323 } 18324 return sb.toString(); 18325 } 18326 18327 // ------- apps on sdcard specific code ------- 18328 static final boolean DEBUG_SD_INSTALL = false; 18329 18330 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18331 18332 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18333 18334 private boolean mMediaMounted = false; 18335 18336 static String getEncryptKey() { 18337 try { 18338 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18339 SD_ENCRYPTION_KEYSTORE_NAME); 18340 if (sdEncKey == null) { 18341 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18342 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18343 if (sdEncKey == null) { 18344 Slog.e(TAG, "Failed to create encryption keys"); 18345 return null; 18346 } 18347 } 18348 return sdEncKey; 18349 } catch (NoSuchAlgorithmException nsae) { 18350 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18351 return null; 18352 } catch (IOException ioe) { 18353 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18354 return null; 18355 } 18356 } 18357 18358 /* 18359 * Update media status on PackageManager. 18360 */ 18361 @Override 18362 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18363 int callingUid = Binder.getCallingUid(); 18364 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18365 throw new SecurityException("Media status can only be updated by the system"); 18366 } 18367 // reader; this apparently protects mMediaMounted, but should probably 18368 // be a different lock in that case. 18369 synchronized (mPackages) { 18370 Log.i(TAG, "Updating external media status from " 18371 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18372 + (mediaStatus ? "mounted" : "unmounted")); 18373 if (DEBUG_SD_INSTALL) 18374 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18375 + ", mMediaMounted=" + mMediaMounted); 18376 if (mediaStatus == mMediaMounted) { 18377 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18378 : 0, -1); 18379 mHandler.sendMessage(msg); 18380 return; 18381 } 18382 mMediaMounted = mediaStatus; 18383 } 18384 // Queue up an async operation since the package installation may take a 18385 // little while. 18386 mHandler.post(new Runnable() { 18387 public void run() { 18388 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18389 } 18390 }); 18391 } 18392 18393 /** 18394 * Called by MountService when the initial ASECs to scan are available. 18395 * Should block until all the ASEC containers are finished being scanned. 18396 */ 18397 public void scanAvailableAsecs() { 18398 updateExternalMediaStatusInner(true, false, false); 18399 } 18400 18401 /* 18402 * Collect information of applications on external media, map them against 18403 * existing containers and update information based on current mount status. 18404 * Please note that we always have to report status if reportStatus has been 18405 * set to true especially when unloading packages. 18406 */ 18407 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18408 boolean externalStorage) { 18409 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18410 int[] uidArr = EmptyArray.INT; 18411 18412 final String[] list = PackageHelper.getSecureContainerList(); 18413 if (ArrayUtils.isEmpty(list)) { 18414 Log.i(TAG, "No secure containers found"); 18415 } else { 18416 // Process list of secure containers and categorize them 18417 // as active or stale based on their package internal state. 18418 18419 // reader 18420 synchronized (mPackages) { 18421 for (String cid : list) { 18422 // Leave stages untouched for now; installer service owns them 18423 if (PackageInstallerService.isStageName(cid)) continue; 18424 18425 if (DEBUG_SD_INSTALL) 18426 Log.i(TAG, "Processing container " + cid); 18427 String pkgName = getAsecPackageName(cid); 18428 if (pkgName == null) { 18429 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18430 continue; 18431 } 18432 if (DEBUG_SD_INSTALL) 18433 Log.i(TAG, "Looking for pkg : " + pkgName); 18434 18435 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18436 if (ps == null) { 18437 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18438 continue; 18439 } 18440 18441 /* 18442 * Skip packages that are not external if we're unmounting 18443 * external storage. 18444 */ 18445 if (externalStorage && !isMounted && !isExternal(ps)) { 18446 continue; 18447 } 18448 18449 final AsecInstallArgs args = new AsecInstallArgs(cid, 18450 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18451 // The package status is changed only if the code path 18452 // matches between settings and the container id. 18453 if (ps.codePathString != null 18454 && ps.codePathString.startsWith(args.getCodePath())) { 18455 if (DEBUG_SD_INSTALL) { 18456 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18457 + " at code path: " + ps.codePathString); 18458 } 18459 18460 // We do have a valid package installed on sdcard 18461 processCids.put(args, ps.codePathString); 18462 final int uid = ps.appId; 18463 if (uid != -1) { 18464 uidArr = ArrayUtils.appendInt(uidArr, uid); 18465 } 18466 } else { 18467 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18468 + ps.codePathString); 18469 } 18470 } 18471 } 18472 18473 Arrays.sort(uidArr); 18474 } 18475 18476 // Process packages with valid entries. 18477 if (isMounted) { 18478 if (DEBUG_SD_INSTALL) 18479 Log.i(TAG, "Loading packages"); 18480 loadMediaPackages(processCids, uidArr, externalStorage); 18481 startCleaningPackages(); 18482 mInstallerService.onSecureContainersAvailable(); 18483 } else { 18484 if (DEBUG_SD_INSTALL) 18485 Log.i(TAG, "Unloading packages"); 18486 unloadMediaPackages(processCids, uidArr, reportStatus); 18487 } 18488 } 18489 18490 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18491 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18492 final int size = infos.size(); 18493 final String[] packageNames = new String[size]; 18494 final int[] packageUids = new int[size]; 18495 for (int i = 0; i < size; i++) { 18496 final ApplicationInfo info = infos.get(i); 18497 packageNames[i] = info.packageName; 18498 packageUids[i] = info.uid; 18499 } 18500 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18501 finishedReceiver); 18502 } 18503 18504 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18505 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18506 sendResourcesChangedBroadcast(mediaStatus, replacing, 18507 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18508 } 18509 18510 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18511 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18512 int size = pkgList.length; 18513 if (size > 0) { 18514 // Send broadcasts here 18515 Bundle extras = new Bundle(); 18516 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18517 if (uidArr != null) { 18518 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18519 } 18520 if (replacing) { 18521 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18522 } 18523 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18524 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18525 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18526 } 18527 } 18528 18529 /* 18530 * Look at potentially valid container ids from processCids If package 18531 * information doesn't match the one on record or package scanning fails, 18532 * the cid is added to list of removeCids. We currently don't delete stale 18533 * containers. 18534 */ 18535 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18536 boolean externalStorage) { 18537 ArrayList<String> pkgList = new ArrayList<String>(); 18538 Set<AsecInstallArgs> keys = processCids.keySet(); 18539 18540 for (AsecInstallArgs args : keys) { 18541 String codePath = processCids.get(args); 18542 if (DEBUG_SD_INSTALL) 18543 Log.i(TAG, "Loading container : " + args.cid); 18544 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18545 try { 18546 // Make sure there are no container errors first. 18547 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18548 Slog.e(TAG, "Failed to mount cid : " + args.cid 18549 + " when installing from sdcard"); 18550 continue; 18551 } 18552 // Check code path here. 18553 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18554 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18555 + " does not match one in settings " + codePath); 18556 continue; 18557 } 18558 // Parse package 18559 int parseFlags = mDefParseFlags; 18560 if (args.isExternalAsec()) { 18561 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18562 } 18563 if (args.isFwdLocked()) { 18564 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18565 } 18566 18567 synchronized (mInstallLock) { 18568 PackageParser.Package pkg = null; 18569 try { 18570 // Sadly we don't know the package name yet to freeze it 18571 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18572 SCAN_IGNORE_FROZEN, 0, null); 18573 } catch (PackageManagerException e) { 18574 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18575 } 18576 // Scan the package 18577 if (pkg != null) { 18578 /* 18579 * TODO why is the lock being held? doPostInstall is 18580 * called in other places without the lock. This needs 18581 * to be straightened out. 18582 */ 18583 // writer 18584 synchronized (mPackages) { 18585 retCode = PackageManager.INSTALL_SUCCEEDED; 18586 pkgList.add(pkg.packageName); 18587 // Post process args 18588 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18589 pkg.applicationInfo.uid); 18590 } 18591 } else { 18592 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18593 } 18594 } 18595 18596 } finally { 18597 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18598 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18599 } 18600 } 18601 } 18602 // writer 18603 synchronized (mPackages) { 18604 // If the platform SDK has changed since the last time we booted, 18605 // we need to re-grant app permission to catch any new ones that 18606 // appear. This is really a hack, and means that apps can in some 18607 // cases get permissions that the user didn't initially explicitly 18608 // allow... it would be nice to have some better way to handle 18609 // this situation. 18610 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18611 : mSettings.getInternalVersion(); 18612 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18613 : StorageManager.UUID_PRIVATE_INTERNAL; 18614 18615 int updateFlags = UPDATE_PERMISSIONS_ALL; 18616 if (ver.sdkVersion != mSdkVersion) { 18617 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18618 + mSdkVersion + "; regranting permissions for external"); 18619 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18620 } 18621 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18622 18623 // Yay, everything is now upgraded 18624 ver.forceCurrent(); 18625 18626 // can downgrade to reader 18627 // Persist settings 18628 mSettings.writeLPr(); 18629 } 18630 // Send a broadcast to let everyone know we are done processing 18631 if (pkgList.size() > 0) { 18632 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18633 } 18634 } 18635 18636 /* 18637 * Utility method to unload a list of specified containers 18638 */ 18639 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18640 // Just unmount all valid containers. 18641 for (AsecInstallArgs arg : cidArgs) { 18642 synchronized (mInstallLock) { 18643 arg.doPostDeleteLI(false); 18644 } 18645 } 18646 } 18647 18648 /* 18649 * Unload packages mounted on external media. This involves deleting package 18650 * data from internal structures, sending broadcasts about disabled packages, 18651 * gc'ing to free up references, unmounting all secure containers 18652 * corresponding to packages on external media, and posting a 18653 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18654 * that we always have to post this message if status has been requested no 18655 * matter what. 18656 */ 18657 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18658 final boolean reportStatus) { 18659 if (DEBUG_SD_INSTALL) 18660 Log.i(TAG, "unloading media packages"); 18661 ArrayList<String> pkgList = new ArrayList<String>(); 18662 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18663 final Set<AsecInstallArgs> keys = processCids.keySet(); 18664 for (AsecInstallArgs args : keys) { 18665 String pkgName = args.getPackageName(); 18666 if (DEBUG_SD_INSTALL) 18667 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18668 // Delete package internally 18669 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18670 synchronized (mInstallLock) { 18671 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18672 final boolean res; 18673 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18674 "unloadMediaPackages")) { 18675 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18676 null); 18677 } 18678 if (res) { 18679 pkgList.add(pkgName); 18680 } else { 18681 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18682 failedList.add(args); 18683 } 18684 } 18685 } 18686 18687 // reader 18688 synchronized (mPackages) { 18689 // We didn't update the settings after removing each package; 18690 // write them now for all packages. 18691 mSettings.writeLPr(); 18692 } 18693 18694 // We have to absolutely send UPDATED_MEDIA_STATUS only 18695 // after confirming that all the receivers processed the ordered 18696 // broadcast when packages get disabled, force a gc to clean things up. 18697 // and unload all the containers. 18698 if (pkgList.size() > 0) { 18699 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18700 new IIntentReceiver.Stub() { 18701 public void performReceive(Intent intent, int resultCode, String data, 18702 Bundle extras, boolean ordered, boolean sticky, 18703 int sendingUser) throws RemoteException { 18704 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18705 reportStatus ? 1 : 0, 1, keys); 18706 mHandler.sendMessage(msg); 18707 } 18708 }); 18709 } else { 18710 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18711 keys); 18712 mHandler.sendMessage(msg); 18713 } 18714 } 18715 18716 private void loadPrivatePackages(final VolumeInfo vol) { 18717 mHandler.post(new Runnable() { 18718 @Override 18719 public void run() { 18720 loadPrivatePackagesInner(vol); 18721 } 18722 }); 18723 } 18724 18725 private void loadPrivatePackagesInner(VolumeInfo vol) { 18726 final String volumeUuid = vol.fsUuid; 18727 if (TextUtils.isEmpty(volumeUuid)) { 18728 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18729 return; 18730 } 18731 18732 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18733 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18734 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18735 18736 final VersionInfo ver; 18737 final List<PackageSetting> packages; 18738 synchronized (mPackages) { 18739 ver = mSettings.findOrCreateVersion(volumeUuid); 18740 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18741 } 18742 18743 for (PackageSetting ps : packages) { 18744 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18745 synchronized (mInstallLock) { 18746 final PackageParser.Package pkg; 18747 try { 18748 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18749 loaded.add(pkg.applicationInfo); 18750 18751 } catch (PackageManagerException e) { 18752 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18753 } 18754 18755 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18756 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18757 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18758 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18759 } 18760 } 18761 } 18762 18763 // Reconcile app data for all started/unlocked users 18764 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18765 final UserManager um = mContext.getSystemService(UserManager.class); 18766 for (UserInfo user : um.getUsers()) { 18767 final int flags; 18768 if (um.isUserUnlocked(user.id)) { 18769 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18770 } else if (um.isUserRunning(user.id)) { 18771 flags = StorageManager.FLAG_STORAGE_DE; 18772 } else { 18773 continue; 18774 } 18775 18776 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18777 synchronized (mInstallLock) { 18778 reconcileAppsDataLI(volumeUuid, user.id, flags); 18779 } 18780 } 18781 18782 synchronized (mPackages) { 18783 int updateFlags = UPDATE_PERMISSIONS_ALL; 18784 if (ver.sdkVersion != mSdkVersion) { 18785 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18786 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18787 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18788 } 18789 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18790 18791 // Yay, everything is now upgraded 18792 ver.forceCurrent(); 18793 18794 mSettings.writeLPr(); 18795 } 18796 18797 for (PackageFreezer freezer : freezers) { 18798 freezer.close(); 18799 } 18800 18801 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18802 sendResourcesChangedBroadcast(true, false, loaded, null); 18803 } 18804 18805 private void unloadPrivatePackages(final VolumeInfo vol) { 18806 mHandler.post(new Runnable() { 18807 @Override 18808 public void run() { 18809 unloadPrivatePackagesInner(vol); 18810 } 18811 }); 18812 } 18813 18814 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18815 final String volumeUuid = vol.fsUuid; 18816 if (TextUtils.isEmpty(volumeUuid)) { 18817 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18818 return; 18819 } 18820 18821 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18822 synchronized (mInstallLock) { 18823 synchronized (mPackages) { 18824 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18825 for (PackageSetting ps : packages) { 18826 if (ps.pkg == null) continue; 18827 18828 final ApplicationInfo info = ps.pkg.applicationInfo; 18829 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18830 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18831 18832 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18833 "unloadPrivatePackagesInner")) { 18834 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18835 false, null)) { 18836 unloaded.add(info); 18837 } else { 18838 Slog.w(TAG, "Failed to unload " + ps.codePath); 18839 } 18840 } 18841 } 18842 18843 mSettings.writeLPr(); 18844 } 18845 } 18846 18847 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18848 sendResourcesChangedBroadcast(false, false, unloaded, null); 18849 } 18850 18851 /** 18852 * Prepare storage areas for given user on all mounted devices. 18853 */ 18854 void prepareUserData(int userId, int userSerial, int flags) { 18855 synchronized (mInstallLock) { 18856 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18857 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18858 final String volumeUuid = vol.getFsUuid(); 18859 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18860 } 18861 } 18862 } 18863 18864 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18865 boolean allowRecover) { 18866 // Prepare storage and verify that serial numbers are consistent; if 18867 // there's a mismatch we need to destroy to avoid leaking data 18868 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18869 try { 18870 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18871 18872 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18873 UserManagerService.enforceSerialNumber( 18874 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18875 } 18876 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18877 UserManagerService.enforceSerialNumber( 18878 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18879 } 18880 18881 synchronized (mInstallLock) { 18882 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18883 } 18884 } catch (Exception e) { 18885 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18886 + " because we failed to prepare: " + e); 18887 destroyUserDataLI(volumeUuid, userId, 18888 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18889 18890 if (allowRecover) { 18891 // Try one last time; if we fail again we're really in trouble 18892 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18893 } 18894 } 18895 } 18896 18897 /** 18898 * Destroy storage areas for given user on all mounted devices. 18899 */ 18900 void destroyUserData(int userId, int flags) { 18901 synchronized (mInstallLock) { 18902 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18903 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18904 final String volumeUuid = vol.getFsUuid(); 18905 destroyUserDataLI(volumeUuid, userId, flags); 18906 } 18907 } 18908 } 18909 18910 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18911 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18912 try { 18913 // Clean up app data, profile data, and media data 18914 mInstaller.destroyUserData(volumeUuid, userId, flags); 18915 18916 // Clean up system data 18917 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18918 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18919 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18920 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18921 } 18922 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18923 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18924 } 18925 } 18926 18927 // Data with special labels is now gone, so finish the job 18928 storage.destroyUserStorage(volumeUuid, userId, flags); 18929 18930 } catch (Exception e) { 18931 logCriticalInfo(Log.WARN, 18932 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18933 } 18934 } 18935 18936 /** 18937 * Examine all users present on given mounted volume, and destroy data 18938 * belonging to users that are no longer valid, or whose user ID has been 18939 * recycled. 18940 */ 18941 private void reconcileUsers(String volumeUuid) { 18942 final List<File> files = new ArrayList<>(); 18943 Collections.addAll(files, FileUtils 18944 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18945 Collections.addAll(files, FileUtils 18946 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18947 for (File file : files) { 18948 if (!file.isDirectory()) continue; 18949 18950 final int userId; 18951 final UserInfo info; 18952 try { 18953 userId = Integer.parseInt(file.getName()); 18954 info = sUserManager.getUserInfo(userId); 18955 } catch (NumberFormatException e) { 18956 Slog.w(TAG, "Invalid user directory " + file); 18957 continue; 18958 } 18959 18960 boolean destroyUser = false; 18961 if (info == null) { 18962 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18963 + " because no matching user was found"); 18964 destroyUser = true; 18965 } else if (!mOnlyCore) { 18966 try { 18967 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18968 } catch (IOException e) { 18969 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18970 + " because we failed to enforce serial number: " + e); 18971 destroyUser = true; 18972 } 18973 } 18974 18975 if (destroyUser) { 18976 synchronized (mInstallLock) { 18977 destroyUserDataLI(volumeUuid, userId, 18978 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18979 } 18980 } 18981 } 18982 } 18983 18984 private void assertPackageKnown(String volumeUuid, String packageName) 18985 throws PackageManagerException { 18986 synchronized (mPackages) { 18987 final PackageSetting ps = mSettings.mPackages.get(packageName); 18988 if (ps == null) { 18989 throw new PackageManagerException("Package " + packageName + " is unknown"); 18990 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18991 throw new PackageManagerException( 18992 "Package " + packageName + " found on unknown volume " + volumeUuid 18993 + "; expected volume " + ps.volumeUuid); 18994 } 18995 } 18996 } 18997 18998 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18999 throws PackageManagerException { 19000 synchronized (mPackages) { 19001 final PackageSetting ps = mSettings.mPackages.get(packageName); 19002 if (ps == null) { 19003 throw new PackageManagerException("Package " + packageName + " is unknown"); 19004 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19005 throw new PackageManagerException( 19006 "Package " + packageName + " found on unknown volume " + volumeUuid 19007 + "; expected volume " + ps.volumeUuid); 19008 } else if (!ps.getInstalled(userId)) { 19009 throw new PackageManagerException( 19010 "Package " + packageName + " not installed for user " + userId); 19011 } 19012 } 19013 } 19014 19015 /** 19016 * Examine all apps present on given mounted volume, and destroy apps that 19017 * aren't expected, either due to uninstallation or reinstallation on 19018 * another volume. 19019 */ 19020 private void reconcileApps(String volumeUuid) { 19021 final File[] files = FileUtils 19022 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19023 for (File file : files) { 19024 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19025 && !PackageInstallerService.isStageName(file.getName()); 19026 if (!isPackage) { 19027 // Ignore entries which are not packages 19028 continue; 19029 } 19030 19031 try { 19032 final PackageLite pkg = PackageParser.parsePackageLite(file, 19033 PackageParser.PARSE_MUST_BE_APK); 19034 assertPackageKnown(volumeUuid, pkg.packageName); 19035 19036 } catch (PackageParserException | PackageManagerException e) { 19037 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19038 synchronized (mInstallLock) { 19039 removeCodePathLI(file); 19040 } 19041 } 19042 } 19043 } 19044 19045 /** 19046 * Reconcile all app data for the given user. 19047 * <p> 19048 * Verifies that directories exist and that ownership and labeling is 19049 * correct for all installed apps on all mounted volumes. 19050 */ 19051 void reconcileAppsData(int userId, int flags) { 19052 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19053 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19054 final String volumeUuid = vol.getFsUuid(); 19055 synchronized (mInstallLock) { 19056 reconcileAppsDataLI(volumeUuid, userId, flags); 19057 } 19058 } 19059 } 19060 19061 /** 19062 * Reconcile all app data on given mounted volume. 19063 * <p> 19064 * Destroys app data that isn't expected, either due to uninstallation or 19065 * reinstallation on another volume. 19066 * <p> 19067 * Verifies that directories exist and that ownership and labeling is 19068 * correct for all installed apps. 19069 */ 19070 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19071 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19072 + Integer.toHexString(flags)); 19073 19074 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19075 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19076 19077 boolean restoreconNeeded = false; 19078 19079 // First look for stale data that doesn't belong, and check if things 19080 // have changed since we did our last restorecon 19081 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19082 if (!isUserKeyUnlocked(userId)) { 19083 throw new RuntimeException( 19084 "Yikes, someone asked us to reconcile CE storage while " + userId 19085 + " was still locked; this would have caused massive data loss!"); 19086 } 19087 19088 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19089 19090 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19091 for (File file : files) { 19092 final String packageName = file.getName(); 19093 try { 19094 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19095 } catch (PackageManagerException e) { 19096 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19097 try { 19098 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19099 StorageManager.FLAG_STORAGE_CE, 0); 19100 } catch (InstallerException e2) { 19101 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19102 } 19103 } 19104 } 19105 } 19106 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19107 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19108 19109 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19110 for (File file : files) { 19111 final String packageName = file.getName(); 19112 try { 19113 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19114 } catch (PackageManagerException e) { 19115 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19116 try { 19117 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19118 StorageManager.FLAG_STORAGE_DE, 0); 19119 } catch (InstallerException e2) { 19120 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19121 } 19122 } 19123 } 19124 } 19125 19126 // Ensure that data directories are ready to roll for all packages 19127 // installed for this volume and user 19128 final List<PackageSetting> packages; 19129 synchronized (mPackages) { 19130 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19131 } 19132 int preparedCount = 0; 19133 for (PackageSetting ps : packages) { 19134 final String packageName = ps.name; 19135 if (ps.pkg == null) { 19136 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19137 // TODO: might be due to legacy ASEC apps; we should circle back 19138 // and reconcile again once they're scanned 19139 continue; 19140 } 19141 19142 if (ps.getInstalled(userId)) { 19143 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19144 19145 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19146 // We may have just shuffled around app data directories, so 19147 // prepare them one more time 19148 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19149 } 19150 19151 preparedCount++; 19152 } 19153 } 19154 19155 if (restoreconNeeded) { 19156 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19157 SELinuxMMAC.setRestoreconDone(ceDir); 19158 } 19159 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19160 SELinuxMMAC.setRestoreconDone(deDir); 19161 } 19162 } 19163 19164 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19165 + " packages; restoreconNeeded was " + restoreconNeeded); 19166 } 19167 19168 /** 19169 * Prepare app data for the given app just after it was installed or 19170 * upgraded. This method carefully only touches users that it's installed 19171 * for, and it forces a restorecon to handle any seinfo changes. 19172 * <p> 19173 * Verifies that directories exist and that ownership and labeling is 19174 * correct for all installed apps. If there is an ownership mismatch, it 19175 * will try recovering system apps by wiping data; third-party app data is 19176 * left intact. 19177 * <p> 19178 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19179 */ 19180 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19181 final PackageSetting ps; 19182 synchronized (mPackages) { 19183 ps = mSettings.mPackages.get(pkg.packageName); 19184 mSettings.writeKernelMappingLPr(ps); 19185 } 19186 19187 final UserManager um = mContext.getSystemService(UserManager.class); 19188 for (UserInfo user : um.getUsers()) { 19189 final int flags; 19190 if (um.isUserUnlocked(user.id)) { 19191 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19192 } else if (um.isUserRunning(user.id)) { 19193 flags = StorageManager.FLAG_STORAGE_DE; 19194 } else { 19195 continue; 19196 } 19197 19198 if (ps.getInstalled(user.id)) { 19199 // Whenever an app changes, force a restorecon of its data 19200 // TODO: when user data is locked, mark that we're still dirty 19201 prepareAppDataLIF(pkg, user.id, flags, true); 19202 } 19203 } 19204 } 19205 19206 /** 19207 * Prepare app data for the given app. 19208 * <p> 19209 * Verifies that directories exist and that ownership and labeling is 19210 * correct for all installed apps. If there is an ownership mismatch, this 19211 * will try recovering system apps by wiping data; third-party app data is 19212 * left intact. 19213 */ 19214 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19215 boolean restoreconNeeded) { 19216 if (pkg == null) { 19217 Slog.wtf(TAG, "Package was null!", new Throwable()); 19218 return; 19219 } 19220 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19221 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19222 for (int i = 0; i < childCount; i++) { 19223 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19224 } 19225 } 19226 19227 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19228 boolean restoreconNeeded) { 19229 if (DEBUG_APP_DATA) { 19230 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19231 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19232 } 19233 19234 final String volumeUuid = pkg.volumeUuid; 19235 final String packageName = pkg.packageName; 19236 final ApplicationInfo app = pkg.applicationInfo; 19237 final int appId = UserHandle.getAppId(app.uid); 19238 19239 Preconditions.checkNotNull(app.seinfo); 19240 19241 try { 19242 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19243 appId, app.seinfo, app.targetSdkVersion); 19244 } catch (InstallerException e) { 19245 if (app.isSystemApp()) { 19246 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19247 + ", but trying to recover: " + e); 19248 destroyAppDataLeafLIF(pkg, userId, flags); 19249 try { 19250 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19251 appId, app.seinfo, app.targetSdkVersion); 19252 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19253 } catch (InstallerException e2) { 19254 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19255 } 19256 } else { 19257 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19258 } 19259 } 19260 19261 if (restoreconNeeded) { 19262 try { 19263 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19264 app.seinfo); 19265 } catch (InstallerException e) { 19266 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19267 } 19268 } 19269 19270 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19271 try { 19272 // CE storage is unlocked right now, so read out the inode and 19273 // remember for use later when it's locked 19274 // TODO: mark this structure as dirty so we persist it! 19275 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19276 StorageManager.FLAG_STORAGE_CE); 19277 synchronized (mPackages) { 19278 final PackageSetting ps = mSettings.mPackages.get(packageName); 19279 if (ps != null) { 19280 ps.setCeDataInode(ceDataInode, userId); 19281 } 19282 } 19283 } catch (InstallerException e) { 19284 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19285 } 19286 } 19287 19288 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19289 } 19290 19291 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19292 if (pkg == null) { 19293 Slog.wtf(TAG, "Package was null!", new Throwable()); 19294 return; 19295 } 19296 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19297 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19298 for (int i = 0; i < childCount; i++) { 19299 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19300 } 19301 } 19302 19303 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19304 final String volumeUuid = pkg.volumeUuid; 19305 final String packageName = pkg.packageName; 19306 final ApplicationInfo app = pkg.applicationInfo; 19307 19308 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19309 // Create a native library symlink only if we have native libraries 19310 // and if the native libraries are 32 bit libraries. We do not provide 19311 // this symlink for 64 bit libraries. 19312 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19313 final String nativeLibPath = app.nativeLibraryDir; 19314 try { 19315 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19316 nativeLibPath, userId); 19317 } catch (InstallerException e) { 19318 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19319 } 19320 } 19321 } 19322 } 19323 19324 /** 19325 * For system apps on non-FBE devices, this method migrates any existing 19326 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19327 * requested by the app. 19328 */ 19329 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19330 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19331 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19332 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19333 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19334 try { 19335 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19336 storageTarget); 19337 } catch (InstallerException e) { 19338 logCriticalInfo(Log.WARN, 19339 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19340 } 19341 return true; 19342 } else { 19343 return false; 19344 } 19345 } 19346 19347 public PackageFreezer freezePackage(String packageName, String killReason) { 19348 return new PackageFreezer(packageName, killReason); 19349 } 19350 19351 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19352 String killReason) { 19353 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19354 return new PackageFreezer(); 19355 } else { 19356 return freezePackage(packageName, killReason); 19357 } 19358 } 19359 19360 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19361 String killReason) { 19362 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19363 return new PackageFreezer(); 19364 } else { 19365 return freezePackage(packageName, killReason); 19366 } 19367 } 19368 19369 /** 19370 * Class that freezes and kills the given package upon creation, and 19371 * unfreezes it upon closing. This is typically used when doing surgery on 19372 * app code/data to prevent the app from running while you're working. 19373 */ 19374 private class PackageFreezer implements AutoCloseable { 19375 private final String mPackageName; 19376 private final PackageFreezer[] mChildren; 19377 19378 private final boolean mWeFroze; 19379 19380 private final AtomicBoolean mClosed = new AtomicBoolean(); 19381 private final CloseGuard mCloseGuard = CloseGuard.get(); 19382 19383 /** 19384 * Create and return a stub freezer that doesn't actually do anything, 19385 * typically used when someone requested 19386 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19387 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19388 */ 19389 public PackageFreezer() { 19390 mPackageName = null; 19391 mChildren = null; 19392 mWeFroze = false; 19393 mCloseGuard.open("close"); 19394 } 19395 19396 public PackageFreezer(String packageName, String killReason) { 19397 synchronized (mPackages) { 19398 mPackageName = packageName; 19399 mWeFroze = mFrozenPackages.add(mPackageName); 19400 19401 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19402 if (ps != null) { 19403 killApplication(ps.name, ps.appId, killReason); 19404 } 19405 19406 final PackageParser.Package p = mPackages.get(packageName); 19407 if (p != null && p.childPackages != null) { 19408 final int N = p.childPackages.size(); 19409 mChildren = new PackageFreezer[N]; 19410 for (int i = 0; i < N; i++) { 19411 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19412 killReason); 19413 } 19414 } else { 19415 mChildren = null; 19416 } 19417 } 19418 mCloseGuard.open("close"); 19419 } 19420 19421 @Override 19422 protected void finalize() throws Throwable { 19423 try { 19424 mCloseGuard.warnIfOpen(); 19425 close(); 19426 } finally { 19427 super.finalize(); 19428 } 19429 } 19430 19431 @Override 19432 public void close() { 19433 mCloseGuard.close(); 19434 if (mClosed.compareAndSet(false, true)) { 19435 synchronized (mPackages) { 19436 if (mWeFroze) { 19437 mFrozenPackages.remove(mPackageName); 19438 } 19439 19440 if (mChildren != null) { 19441 for (PackageFreezer freezer : mChildren) { 19442 freezer.close(); 19443 } 19444 } 19445 } 19446 } 19447 } 19448 } 19449 19450 /** 19451 * Verify that given package is currently frozen. 19452 */ 19453 private void checkPackageFrozen(String packageName) { 19454 synchronized (mPackages) { 19455 if (!mFrozenPackages.contains(packageName)) { 19456 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19457 } 19458 } 19459 } 19460 19461 @Override 19462 public int movePackage(final String packageName, final String volumeUuid) { 19463 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19464 19465 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19466 final int moveId = mNextMoveId.getAndIncrement(); 19467 mHandler.post(new Runnable() { 19468 @Override 19469 public void run() { 19470 try { 19471 movePackageInternal(packageName, volumeUuid, moveId, user); 19472 } catch (PackageManagerException e) { 19473 Slog.w(TAG, "Failed to move " + packageName, e); 19474 mMoveCallbacks.notifyStatusChanged(moveId, 19475 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19476 } 19477 } 19478 }); 19479 return moveId; 19480 } 19481 19482 private void movePackageInternal(final String packageName, final String volumeUuid, 19483 final int moveId, UserHandle user) throws PackageManagerException { 19484 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19485 final PackageManager pm = mContext.getPackageManager(); 19486 19487 final boolean currentAsec; 19488 final String currentVolumeUuid; 19489 final File codeFile; 19490 final String installerPackageName; 19491 final String packageAbiOverride; 19492 final int appId; 19493 final String seinfo; 19494 final String label; 19495 final int targetSdkVersion; 19496 final PackageFreezer freezer; 19497 19498 // reader 19499 synchronized (mPackages) { 19500 final PackageParser.Package pkg = mPackages.get(packageName); 19501 final PackageSetting ps = mSettings.mPackages.get(packageName); 19502 if (pkg == null || ps == null) { 19503 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19504 } 19505 19506 if (pkg.applicationInfo.isSystemApp()) { 19507 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19508 "Cannot move system application"); 19509 } 19510 19511 if (pkg.applicationInfo.isExternalAsec()) { 19512 currentAsec = true; 19513 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19514 } else if (pkg.applicationInfo.isForwardLocked()) { 19515 currentAsec = true; 19516 currentVolumeUuid = "forward_locked"; 19517 } else { 19518 currentAsec = false; 19519 currentVolumeUuid = ps.volumeUuid; 19520 19521 final File probe = new File(pkg.codePath); 19522 final File probeOat = new File(probe, "oat"); 19523 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19524 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19525 "Move only supported for modern cluster style installs"); 19526 } 19527 } 19528 19529 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19530 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19531 "Package already moved to " + volumeUuid); 19532 } 19533 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19534 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19535 "Device admin cannot be moved"); 19536 } 19537 19538 if (mFrozenPackages.contains(packageName)) { 19539 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19540 "Failed to move already frozen package"); 19541 } 19542 19543 codeFile = new File(pkg.codePath); 19544 installerPackageName = ps.installerPackageName; 19545 packageAbiOverride = ps.cpuAbiOverrideString; 19546 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19547 seinfo = pkg.applicationInfo.seinfo; 19548 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19549 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19550 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19551 } 19552 19553 final Bundle extras = new Bundle(); 19554 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19555 extras.putString(Intent.EXTRA_TITLE, label); 19556 mMoveCallbacks.notifyCreated(moveId, extras); 19557 19558 int installFlags; 19559 final boolean moveCompleteApp; 19560 final File measurePath; 19561 19562 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19563 installFlags = INSTALL_INTERNAL; 19564 moveCompleteApp = !currentAsec; 19565 measurePath = Environment.getDataAppDirectory(volumeUuid); 19566 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19567 installFlags = INSTALL_EXTERNAL; 19568 moveCompleteApp = false; 19569 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19570 } else { 19571 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19572 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19573 || !volume.isMountedWritable()) { 19574 freezer.close(); 19575 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19576 "Move location not mounted private volume"); 19577 } 19578 19579 Preconditions.checkState(!currentAsec); 19580 19581 installFlags = INSTALL_INTERNAL; 19582 moveCompleteApp = true; 19583 measurePath = Environment.getDataAppDirectory(volumeUuid); 19584 } 19585 19586 final PackageStats stats = new PackageStats(null, -1); 19587 synchronized (mInstaller) { 19588 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19589 freezer.close(); 19590 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19591 "Failed to measure package size"); 19592 } 19593 } 19594 19595 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19596 + stats.dataSize); 19597 19598 final long startFreeBytes = measurePath.getFreeSpace(); 19599 final long sizeBytes; 19600 if (moveCompleteApp) { 19601 sizeBytes = stats.codeSize + stats.dataSize; 19602 } else { 19603 sizeBytes = stats.codeSize; 19604 } 19605 19606 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19607 freezer.close(); 19608 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19609 "Not enough free space to move"); 19610 } 19611 19612 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19613 19614 final CountDownLatch installedLatch = new CountDownLatch(1); 19615 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19616 @Override 19617 public void onUserActionRequired(Intent intent) throws RemoteException { 19618 throw new IllegalStateException(); 19619 } 19620 19621 @Override 19622 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19623 Bundle extras) throws RemoteException { 19624 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19625 + PackageManager.installStatusToString(returnCode, msg)); 19626 19627 installedLatch.countDown(); 19628 freezer.close(); 19629 19630 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19631 switch (status) { 19632 case PackageInstaller.STATUS_SUCCESS: 19633 mMoveCallbacks.notifyStatusChanged(moveId, 19634 PackageManager.MOVE_SUCCEEDED); 19635 break; 19636 case PackageInstaller.STATUS_FAILURE_STORAGE: 19637 mMoveCallbacks.notifyStatusChanged(moveId, 19638 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19639 break; 19640 default: 19641 mMoveCallbacks.notifyStatusChanged(moveId, 19642 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19643 break; 19644 } 19645 } 19646 }; 19647 19648 final MoveInfo move; 19649 if (moveCompleteApp) { 19650 // Kick off a thread to report progress estimates 19651 new Thread() { 19652 @Override 19653 public void run() { 19654 while (true) { 19655 try { 19656 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19657 break; 19658 } 19659 } catch (InterruptedException ignored) { 19660 } 19661 19662 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19663 final int progress = 10 + (int) MathUtils.constrain( 19664 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19665 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19666 } 19667 } 19668 }.start(); 19669 19670 final String dataAppName = codeFile.getName(); 19671 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19672 dataAppName, appId, seinfo, targetSdkVersion); 19673 } else { 19674 move = null; 19675 } 19676 19677 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19678 19679 final Message msg = mHandler.obtainMessage(INIT_COPY); 19680 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19681 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19682 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19683 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19684 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19685 msg.obj = params; 19686 19687 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19688 System.identityHashCode(msg.obj)); 19689 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19690 System.identityHashCode(msg.obj)); 19691 19692 mHandler.sendMessage(msg); 19693 } 19694 19695 @Override 19696 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19697 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19698 19699 final int realMoveId = mNextMoveId.getAndIncrement(); 19700 final Bundle extras = new Bundle(); 19701 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19702 mMoveCallbacks.notifyCreated(realMoveId, extras); 19703 19704 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19705 @Override 19706 public void onCreated(int moveId, Bundle extras) { 19707 // Ignored 19708 } 19709 19710 @Override 19711 public void onStatusChanged(int moveId, int status, long estMillis) { 19712 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19713 } 19714 }; 19715 19716 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19717 storage.setPrimaryStorageUuid(volumeUuid, callback); 19718 return realMoveId; 19719 } 19720 19721 @Override 19722 public int getMoveStatus(int moveId) { 19723 mContext.enforceCallingOrSelfPermission( 19724 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19725 return mMoveCallbacks.mLastStatus.get(moveId); 19726 } 19727 19728 @Override 19729 public void registerMoveCallback(IPackageMoveObserver callback) { 19730 mContext.enforceCallingOrSelfPermission( 19731 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19732 mMoveCallbacks.register(callback); 19733 } 19734 19735 @Override 19736 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19737 mContext.enforceCallingOrSelfPermission( 19738 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19739 mMoveCallbacks.unregister(callback); 19740 } 19741 19742 @Override 19743 public boolean setInstallLocation(int loc) { 19744 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19745 null); 19746 if (getInstallLocation() == loc) { 19747 return true; 19748 } 19749 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19750 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19751 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19752 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19753 return true; 19754 } 19755 return false; 19756 } 19757 19758 @Override 19759 public int getInstallLocation() { 19760 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19761 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19762 PackageHelper.APP_INSTALL_AUTO); 19763 } 19764 19765 /** Called by UserManagerService */ 19766 void cleanUpUser(UserManagerService userManager, int userHandle) { 19767 synchronized (mPackages) { 19768 mDirtyUsers.remove(userHandle); 19769 mUserNeedsBadging.delete(userHandle); 19770 mSettings.removeUserLPw(userHandle); 19771 mPendingBroadcasts.remove(userHandle); 19772 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19773 removeUnusedPackagesLPw(userManager, userHandle); 19774 } 19775 } 19776 19777 /** 19778 * We're removing userHandle and would like to remove any downloaded packages 19779 * that are no longer in use by any other user. 19780 * @param userHandle the user being removed 19781 */ 19782 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19783 final boolean DEBUG_CLEAN_APKS = false; 19784 int [] users = userManager.getUserIds(); 19785 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19786 while (psit.hasNext()) { 19787 PackageSetting ps = psit.next(); 19788 if (ps.pkg == null) { 19789 continue; 19790 } 19791 final String packageName = ps.pkg.packageName; 19792 // Skip over if system app 19793 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19794 continue; 19795 } 19796 if (DEBUG_CLEAN_APKS) { 19797 Slog.i(TAG, "Checking package " + packageName); 19798 } 19799 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19800 if (keep) { 19801 if (DEBUG_CLEAN_APKS) { 19802 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19803 } 19804 } else { 19805 for (int i = 0; i < users.length; i++) { 19806 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19807 keep = true; 19808 if (DEBUG_CLEAN_APKS) { 19809 Slog.i(TAG, " Keeping package " + packageName + " for user " 19810 + users[i]); 19811 } 19812 break; 19813 } 19814 } 19815 } 19816 if (!keep) { 19817 if (DEBUG_CLEAN_APKS) { 19818 Slog.i(TAG, " Removing package " + packageName); 19819 } 19820 mHandler.post(new Runnable() { 19821 public void run() { 19822 deletePackageX(packageName, userHandle, 0); 19823 } //end run 19824 }); 19825 } 19826 } 19827 } 19828 19829 /** Called by UserManagerService */ 19830 void createNewUser(int userHandle) { 19831 synchronized (mInstallLock) { 19832 mSettings.createNewUserLI(this, mInstaller, userHandle); 19833 } 19834 synchronized (mPackages) { 19835 applyFactoryDefaultBrowserLPw(userHandle); 19836 primeDomainVerificationsLPw(userHandle); 19837 } 19838 } 19839 19840 void newUserCreated(final int userHandle) { 19841 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19842 // If permission review for legacy apps is required, we represent 19843 // dagerous permissions for such apps as always granted runtime 19844 // permissions to keep per user flag state whether review is needed. 19845 // Hence, if a new user is added we have to propagate dangerous 19846 // permission grants for these legacy apps. 19847 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19848 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19849 | UPDATE_PERMISSIONS_REPLACE_ALL); 19850 } 19851 } 19852 19853 @Override 19854 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19855 mContext.enforceCallingOrSelfPermission( 19856 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19857 "Only package verification agents can read the verifier device identity"); 19858 19859 synchronized (mPackages) { 19860 return mSettings.getVerifierDeviceIdentityLPw(); 19861 } 19862 } 19863 19864 @Override 19865 public void setPermissionEnforced(String permission, boolean enforced) { 19866 // TODO: Now that we no longer change GID for storage, this should to away. 19867 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19868 "setPermissionEnforced"); 19869 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19870 synchronized (mPackages) { 19871 if (mSettings.mReadExternalStorageEnforced == null 19872 || mSettings.mReadExternalStorageEnforced != enforced) { 19873 mSettings.mReadExternalStorageEnforced = enforced; 19874 mSettings.writeLPr(); 19875 } 19876 } 19877 // kill any non-foreground processes so we restart them and 19878 // grant/revoke the GID. 19879 final IActivityManager am = ActivityManagerNative.getDefault(); 19880 if (am != null) { 19881 final long token = Binder.clearCallingIdentity(); 19882 try { 19883 am.killProcessesBelowForeground("setPermissionEnforcement"); 19884 } catch (RemoteException e) { 19885 } finally { 19886 Binder.restoreCallingIdentity(token); 19887 } 19888 } 19889 } else { 19890 throw new IllegalArgumentException("No selective enforcement for " + permission); 19891 } 19892 } 19893 19894 @Override 19895 @Deprecated 19896 public boolean isPermissionEnforced(String permission) { 19897 return true; 19898 } 19899 19900 @Override 19901 public boolean isStorageLow() { 19902 final long token = Binder.clearCallingIdentity(); 19903 try { 19904 final DeviceStorageMonitorInternal 19905 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19906 if (dsm != null) { 19907 return dsm.isMemoryLow(); 19908 } else { 19909 return false; 19910 } 19911 } finally { 19912 Binder.restoreCallingIdentity(token); 19913 } 19914 } 19915 19916 @Override 19917 public IPackageInstaller getPackageInstaller() { 19918 return mInstallerService; 19919 } 19920 19921 private boolean userNeedsBadging(int userId) { 19922 int index = mUserNeedsBadging.indexOfKey(userId); 19923 if (index < 0) { 19924 final UserInfo userInfo; 19925 final long token = Binder.clearCallingIdentity(); 19926 try { 19927 userInfo = sUserManager.getUserInfo(userId); 19928 } finally { 19929 Binder.restoreCallingIdentity(token); 19930 } 19931 final boolean b; 19932 if (userInfo != null && userInfo.isManagedProfile()) { 19933 b = true; 19934 } else { 19935 b = false; 19936 } 19937 mUserNeedsBadging.put(userId, b); 19938 return b; 19939 } 19940 return mUserNeedsBadging.valueAt(index); 19941 } 19942 19943 @Override 19944 public KeySet getKeySetByAlias(String packageName, String alias) { 19945 if (packageName == null || alias == null) { 19946 return null; 19947 } 19948 synchronized(mPackages) { 19949 final PackageParser.Package pkg = mPackages.get(packageName); 19950 if (pkg == null) { 19951 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19952 throw new IllegalArgumentException("Unknown package: " + packageName); 19953 } 19954 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19955 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19956 } 19957 } 19958 19959 @Override 19960 public KeySet getSigningKeySet(String packageName) { 19961 if (packageName == null) { 19962 return null; 19963 } 19964 synchronized(mPackages) { 19965 final PackageParser.Package pkg = mPackages.get(packageName); 19966 if (pkg == null) { 19967 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19968 throw new IllegalArgumentException("Unknown package: " + packageName); 19969 } 19970 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19971 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19972 throw new SecurityException("May not access signing KeySet of other apps."); 19973 } 19974 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19975 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19976 } 19977 } 19978 19979 @Override 19980 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19981 if (packageName == null || ks == null) { 19982 return false; 19983 } 19984 synchronized(mPackages) { 19985 final PackageParser.Package pkg = mPackages.get(packageName); 19986 if (pkg == null) { 19987 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19988 throw new IllegalArgumentException("Unknown package: " + packageName); 19989 } 19990 IBinder ksh = ks.getToken(); 19991 if (ksh instanceof KeySetHandle) { 19992 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19993 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19994 } 19995 return false; 19996 } 19997 } 19998 19999 @Override 20000 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20001 if (packageName == null || ks == null) { 20002 return false; 20003 } 20004 synchronized(mPackages) { 20005 final PackageParser.Package pkg = mPackages.get(packageName); 20006 if (pkg == null) { 20007 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20008 throw new IllegalArgumentException("Unknown package: " + packageName); 20009 } 20010 IBinder ksh = ks.getToken(); 20011 if (ksh instanceof KeySetHandle) { 20012 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20013 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20014 } 20015 return false; 20016 } 20017 } 20018 20019 private void deletePackageIfUnusedLPr(final String packageName) { 20020 PackageSetting ps = mSettings.mPackages.get(packageName); 20021 if (ps == null) { 20022 return; 20023 } 20024 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20025 // TODO Implement atomic delete if package is unused 20026 // It is currently possible that the package will be deleted even if it is installed 20027 // after this method returns. 20028 mHandler.post(new Runnable() { 20029 public void run() { 20030 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20031 } 20032 }); 20033 } 20034 } 20035 20036 /** 20037 * Check and throw if the given before/after packages would be considered a 20038 * downgrade. 20039 */ 20040 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20041 throws PackageManagerException { 20042 if (after.versionCode < before.mVersionCode) { 20043 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20044 "Update version code " + after.versionCode + " is older than current " 20045 + before.mVersionCode); 20046 } else if (after.versionCode == before.mVersionCode) { 20047 if (after.baseRevisionCode < before.baseRevisionCode) { 20048 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20049 "Update base revision code " + after.baseRevisionCode 20050 + " is older than current " + before.baseRevisionCode); 20051 } 20052 20053 if (!ArrayUtils.isEmpty(after.splitNames)) { 20054 for (int i = 0; i < after.splitNames.length; i++) { 20055 final String splitName = after.splitNames[i]; 20056 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20057 if (j != -1) { 20058 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20059 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20060 "Update split " + splitName + " revision code " 20061 + after.splitRevisionCodes[i] + " is older than current " 20062 + before.splitRevisionCodes[j]); 20063 } 20064 } 20065 } 20066 } 20067 } 20068 } 20069 20070 private static class MoveCallbacks extends Handler { 20071 private static final int MSG_CREATED = 1; 20072 private static final int MSG_STATUS_CHANGED = 2; 20073 20074 private final RemoteCallbackList<IPackageMoveObserver> 20075 mCallbacks = new RemoteCallbackList<>(); 20076 20077 private final SparseIntArray mLastStatus = new SparseIntArray(); 20078 20079 public MoveCallbacks(Looper looper) { 20080 super(looper); 20081 } 20082 20083 public void register(IPackageMoveObserver callback) { 20084 mCallbacks.register(callback); 20085 } 20086 20087 public void unregister(IPackageMoveObserver callback) { 20088 mCallbacks.unregister(callback); 20089 } 20090 20091 @Override 20092 public void handleMessage(Message msg) { 20093 final SomeArgs args = (SomeArgs) msg.obj; 20094 final int n = mCallbacks.beginBroadcast(); 20095 for (int i = 0; i < n; i++) { 20096 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20097 try { 20098 invokeCallback(callback, msg.what, args); 20099 } catch (RemoteException ignored) { 20100 } 20101 } 20102 mCallbacks.finishBroadcast(); 20103 args.recycle(); 20104 } 20105 20106 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20107 throws RemoteException { 20108 switch (what) { 20109 case MSG_CREATED: { 20110 callback.onCreated(args.argi1, (Bundle) args.arg2); 20111 break; 20112 } 20113 case MSG_STATUS_CHANGED: { 20114 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20115 break; 20116 } 20117 } 20118 } 20119 20120 private void notifyCreated(int moveId, Bundle extras) { 20121 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20122 20123 final SomeArgs args = SomeArgs.obtain(); 20124 args.argi1 = moveId; 20125 args.arg2 = extras; 20126 obtainMessage(MSG_CREATED, args).sendToTarget(); 20127 } 20128 20129 private void notifyStatusChanged(int moveId, int status) { 20130 notifyStatusChanged(moveId, status, -1); 20131 } 20132 20133 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20134 Slog.v(TAG, "Move " + moveId + " status " + status); 20135 20136 final SomeArgs args = SomeArgs.obtain(); 20137 args.argi1 = moveId; 20138 args.argi2 = status; 20139 args.arg3 = estMillis; 20140 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20141 20142 synchronized (mLastStatus) { 20143 mLastStatus.put(moveId, status); 20144 } 20145 } 20146 } 20147 20148 private final static class OnPermissionChangeListeners extends Handler { 20149 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20150 20151 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20152 new RemoteCallbackList<>(); 20153 20154 public OnPermissionChangeListeners(Looper looper) { 20155 super(looper); 20156 } 20157 20158 @Override 20159 public void handleMessage(Message msg) { 20160 switch (msg.what) { 20161 case MSG_ON_PERMISSIONS_CHANGED: { 20162 final int uid = msg.arg1; 20163 handleOnPermissionsChanged(uid); 20164 } break; 20165 } 20166 } 20167 20168 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20169 mPermissionListeners.register(listener); 20170 20171 } 20172 20173 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20174 mPermissionListeners.unregister(listener); 20175 } 20176 20177 public void onPermissionsChanged(int uid) { 20178 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20179 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20180 } 20181 } 20182 20183 private void handleOnPermissionsChanged(int uid) { 20184 final int count = mPermissionListeners.beginBroadcast(); 20185 try { 20186 for (int i = 0; i < count; i++) { 20187 IOnPermissionsChangeListener callback = mPermissionListeners 20188 .getBroadcastItem(i); 20189 try { 20190 callback.onPermissionsChanged(uid); 20191 } catch (RemoteException e) { 20192 Log.e(TAG, "Permission listener is dead", e); 20193 } 20194 } 20195 } finally { 20196 mPermissionListeners.finishBroadcast(); 20197 } 20198 } 20199 } 20200 20201 private class PackageManagerInternalImpl extends PackageManagerInternal { 20202 @Override 20203 public void setLocationPackagesProvider(PackagesProvider provider) { 20204 synchronized (mPackages) { 20205 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20206 } 20207 } 20208 20209 @Override 20210 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20211 synchronized (mPackages) { 20212 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20213 } 20214 } 20215 20216 @Override 20217 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20218 synchronized (mPackages) { 20219 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20220 } 20221 } 20222 20223 @Override 20224 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20225 synchronized (mPackages) { 20226 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20227 } 20228 } 20229 20230 @Override 20231 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20232 synchronized (mPackages) { 20233 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20234 } 20235 } 20236 20237 @Override 20238 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20239 synchronized (mPackages) { 20240 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20241 } 20242 } 20243 20244 @Override 20245 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20246 synchronized (mPackages) { 20247 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20248 packageName, userId); 20249 } 20250 } 20251 20252 @Override 20253 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20254 synchronized (mPackages) { 20255 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20256 packageName, userId); 20257 } 20258 } 20259 20260 @Override 20261 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20262 synchronized (mPackages) { 20263 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20264 packageName, userId); 20265 } 20266 } 20267 20268 @Override 20269 public void setKeepUninstalledPackages(final List<String> packageList) { 20270 Preconditions.checkNotNull(packageList); 20271 List<String> removedFromList = null; 20272 synchronized (mPackages) { 20273 if (mKeepUninstalledPackages != null) { 20274 final int packagesCount = mKeepUninstalledPackages.size(); 20275 for (int i = 0; i < packagesCount; i++) { 20276 String oldPackage = mKeepUninstalledPackages.get(i); 20277 if (packageList != null && packageList.contains(oldPackage)) { 20278 continue; 20279 } 20280 if (removedFromList == null) { 20281 removedFromList = new ArrayList<>(); 20282 } 20283 removedFromList.add(oldPackage); 20284 } 20285 } 20286 mKeepUninstalledPackages = new ArrayList<>(packageList); 20287 if (removedFromList != null) { 20288 final int removedCount = removedFromList.size(); 20289 for (int i = 0; i < removedCount; i++) { 20290 deletePackageIfUnusedLPr(removedFromList.get(i)); 20291 } 20292 } 20293 } 20294 } 20295 20296 @Override 20297 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20298 synchronized (mPackages) { 20299 // If we do not support permission review, done. 20300 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20301 return false; 20302 } 20303 20304 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20305 if (packageSetting == null) { 20306 return false; 20307 } 20308 20309 // Permission review applies only to apps not supporting the new permission model. 20310 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20311 return false; 20312 } 20313 20314 // Legacy apps have the permission and get user consent on launch. 20315 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20316 return permissionsState.isPermissionReviewRequired(userId); 20317 } 20318 } 20319 20320 @Override 20321 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20322 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20323 } 20324 20325 @Override 20326 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20327 int userId) { 20328 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20329 } 20330 } 20331 20332 @Override 20333 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20334 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20335 synchronized (mPackages) { 20336 final long identity = Binder.clearCallingIdentity(); 20337 try { 20338 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20339 packageNames, userId); 20340 } finally { 20341 Binder.restoreCallingIdentity(identity); 20342 } 20343 } 20344 } 20345 20346 private static void enforceSystemOrPhoneCaller(String tag) { 20347 int callingUid = Binder.getCallingUid(); 20348 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20349 throw new SecurityException( 20350 "Cannot call " + tag + " from UID " + callingUid); 20351 } 20352 } 20353 20354 boolean isHistoricalPackageUsageAvailable() { 20355 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20356 } 20357 20358 /** 20359 * Return a <b>copy</b> of the collection of packages known to the package manager. 20360 * @return A copy of the values of mPackages. 20361 */ 20362 Collection<PackageParser.Package> getPackages() { 20363 synchronized (mPackages) { 20364 return new ArrayList<>(mPackages.values()); 20365 } 20366 } 20367 20368 /** 20369 * Logs process start information (including base APK hash) to the security log. 20370 * @hide 20371 */ 20372 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20373 String apkFile, int pid) { 20374 if (!SecurityLog.isLoggingEnabled()) { 20375 return; 20376 } 20377 Bundle data = new Bundle(); 20378 data.putLong("startTimestamp", System.currentTimeMillis()); 20379 data.putString("processName", processName); 20380 data.putInt("uid", uid); 20381 data.putString("seinfo", seinfo); 20382 data.putString("apkFile", apkFile); 20383 data.putInt("pid", pid); 20384 Message msg = mProcessLoggingHandler.obtainMessage( 20385 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20386 msg.setData(data); 20387 mProcessLoggingHandler.sendMessage(msg); 20388 } 20389} 20390