PackageManagerService.java revision d022ac21ebcb441314b80b6d8f0656939f2480e5
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.app.usage.UsageStatsManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.os.IParcelFileDescriptorFactory; 229import com.android.internal.os.InstallerConnection.InstallerException; 230import com.android.internal.os.SomeArgs; 231import com.android.internal.os.Zygote; 232import com.android.internal.telephony.CarrierAppUtils; 233import com.android.internal.util.ArrayUtils; 234import com.android.internal.util.FastPrintWriter; 235import com.android.internal.util.FastXmlSerializer; 236import com.android.internal.util.IndentingPrintWriter; 237import com.android.internal.util.Preconditions; 238import com.android.internal.util.XmlUtils; 239import com.android.server.EventLogTags; 240import com.android.server.FgThread; 241import com.android.server.IntentResolver; 242import com.android.server.LocalServices; 243import com.android.server.ServiceThread; 244import com.android.server.SystemConfig; 245import com.android.server.Watchdog; 246import com.android.server.pm.PermissionsState.PermissionState; 247import com.android.server.pm.Settings.DatabaseVersion; 248import com.android.server.pm.Settings.VersionInfo; 249import com.android.server.storage.DeviceStorageMonitorInternal; 250 251import dalvik.system.CloseGuard; 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.Certificate; 281import java.security.cert.CertificateEncodingException; 282import java.security.cert.CertificateException; 283import java.text.SimpleDateFormat; 284import java.util.ArrayList; 285import java.util.Arrays; 286import java.util.Collection; 287import java.util.Collections; 288import java.util.Comparator; 289import java.util.Date; 290import java.util.HashSet; 291import java.util.Iterator; 292import java.util.List; 293import java.util.Map; 294import java.util.Objects; 295import java.util.Set; 296import java.util.concurrent.CountDownLatch; 297import java.util.concurrent.TimeUnit; 298import java.util.concurrent.atomic.AtomicBoolean; 299import java.util.concurrent.atomic.AtomicInteger; 300import java.util.concurrent.atomic.AtomicLong; 301 302/** 303 * Keep track of all those APKs everywhere. 304 * <p> 305 * Internally there are two important locks: 306 * <ul> 307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 308 * and other related state. It is a fine-grained lock that should only be held 309 * momentarily, as it's one of the most contended locks in the system. 310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 311 * operations typically involve heavy lifting of application data on disk. Since 312 * {@code installd} is single-threaded, and it's operations can often be slow, 313 * this lock should never be acquired while already holding {@link #mPackages}. 314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 315 * holding {@link #mInstallLock}. 316 * </ul> 317 * Many internal methods rely on the caller to hold the appropriate locks, and 318 * this contract is expressed through method name suffixes: 319 * <ul> 320 * <li>fooLI(): the caller must hold {@link #mInstallLock} 321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 322 * being modified must be frozen 323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 325 * </ul> 326 * <p> 327 * Because this class is very central to the platform's security; please run all 328 * CTS and unit tests whenever making modifications: 329 * 330 * <pre> 331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 333 * </pre> 334 */ 335public class PackageManagerService extends IPackageManager.Stub { 336 static final String TAG = "PackageManager"; 337 static final boolean DEBUG_SETTINGS = false; 338 static final boolean DEBUG_PREFERRED = false; 339 static final boolean DEBUG_UPGRADE = false; 340 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 341 private static final boolean DEBUG_BACKUP = false; 342 private static final boolean DEBUG_INSTALL = false; 343 private static final boolean DEBUG_REMOVE = false; 344 private static final boolean DEBUG_BROADCASTS = false; 345 private static final boolean DEBUG_SHOW_INFO = false; 346 private static final boolean DEBUG_PACKAGE_INFO = false; 347 private static final boolean DEBUG_INTENT_MATCHING = false; 348 private static final boolean DEBUG_PACKAGE_SCANNING = false; 349 private static final boolean DEBUG_VERIFY = false; 350 private static final boolean DEBUG_FILTERS = false; 351 352 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 353 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 354 // user, but by default initialize to this. 355 static final boolean DEBUG_DEXOPT = false; 356 357 private static final boolean DEBUG_ABI_SELECTION = false; 358 private static final boolean DEBUG_EPHEMERAL = false; 359 private static final boolean DEBUG_TRIAGED_MISSING = false; 360 private static final boolean DEBUG_APP_DATA = false; 361 362 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 363 364 private static final boolean DISABLE_EPHEMERAL_APPS = true; 365 366 private static final int RADIO_UID = Process.PHONE_UID; 367 private static final int LOG_UID = Process.LOG_UID; 368 private static final int NFC_UID = Process.NFC_UID; 369 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 370 private static final int SHELL_UID = Process.SHELL_UID; 371 372 // Cap the size of permission trees that 3rd party apps can define 373 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 374 375 // Suffix used during package installation when copying/moving 376 // package apks to install directory. 377 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 378 379 static final int SCAN_NO_DEX = 1<<1; 380 static final int SCAN_FORCE_DEX = 1<<2; 381 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 382 static final int SCAN_NEW_INSTALL = 1<<4; 383 static final int SCAN_NO_PATHS = 1<<5; 384 static final int SCAN_UPDATE_TIME = 1<<6; 385 static final int SCAN_DEFER_DEX = 1<<7; 386 static final int SCAN_BOOTING = 1<<8; 387 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 388 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 389 static final int SCAN_REPLACING = 1<<11; 390 static final int SCAN_REQUIRE_KNOWN = 1<<12; 391 static final int SCAN_MOVE = 1<<13; 392 static final int SCAN_INITIAL = 1<<14; 393 static final int SCAN_CHECK_ONLY = 1<<15; 394 static final int SCAN_DONT_KILL_APP = 1<<17; 395 static final int SCAN_IGNORE_FROZEN = 1<<18; 396 397 static final int REMOVE_CHATTY = 1<<16; 398 399 private static final int[] EMPTY_INT_ARRAY = new int[0]; 400 401 /** 402 * Timeout (in milliseconds) after which the watchdog should declare that 403 * our handler thread is wedged. The usual default for such things is one 404 * minute but we sometimes do very lengthy I/O operations on this thread, 405 * such as installing multi-gigabyte applications, so ours needs to be longer. 406 */ 407 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 408 409 /** 410 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 411 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 412 * settings entry if available, otherwise we use the hardcoded default. If it's been 413 * more than this long since the last fstrim, we force one during the boot sequence. 414 * 415 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 416 * one gets run at the next available charging+idle time. This final mandatory 417 * no-fstrim check kicks in only of the other scheduling criteria is never met. 418 */ 419 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 420 421 /** 422 * Whether verification is enabled by default. 423 */ 424 private static final boolean DEFAULT_VERIFY_ENABLE = true; 425 426 /** 427 * The default maximum time to wait for the verification agent to return in 428 * milliseconds. 429 */ 430 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 431 432 /** 433 * The default response for package verification timeout. 434 * 435 * This can be either PackageManager.VERIFICATION_ALLOW or 436 * PackageManager.VERIFICATION_REJECT. 437 */ 438 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 439 440 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 441 442 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 443 DEFAULT_CONTAINER_PACKAGE, 444 "com.android.defcontainer.DefaultContainerService"); 445 446 private static final String KILL_APP_REASON_GIDS_CHANGED = 447 "permission grant or revoke changed gids"; 448 449 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 450 "permissions revoked"; 451 452 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 453 454 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 455 456 /** Permission grant: not grant the permission. */ 457 private static final int GRANT_DENIED = 1; 458 459 /** Permission grant: grant the permission as an install permission. */ 460 private static final int GRANT_INSTALL = 2; 461 462 /** Permission grant: grant the permission as a runtime one. */ 463 private static final int GRANT_RUNTIME = 3; 464 465 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 466 private static final int GRANT_UPGRADE = 4; 467 468 /** Canonical intent used to identify what counts as a "web browser" app */ 469 private static final Intent sBrowserIntent; 470 static { 471 sBrowserIntent = new Intent(); 472 sBrowserIntent.setAction(Intent.ACTION_VIEW); 473 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 474 sBrowserIntent.setData(Uri.parse("http:")); 475 } 476 477 /** 478 * The set of all protected actions [i.e. those actions for which a high priority 479 * intent filter is disallowed]. 480 */ 481 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 482 static { 483 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 485 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 486 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 487 } 488 489 // Compilation reasons. 490 public static final int REASON_FIRST_BOOT = 0; 491 public static final int REASON_BOOT = 1; 492 public static final int REASON_INSTALL = 2; 493 public static final int REASON_BACKGROUND_DEXOPT = 3; 494 public static final int REASON_AB_OTA = 4; 495 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 496 public static final int REASON_SHARED_APK = 6; 497 public static final int REASON_FORCED_DEXOPT = 7; 498 499 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 500 501 final ServiceThread mHandlerThread; 502 503 final PackageHandler mHandler; 504 505 private final ProcessLoggingHandler mProcessLoggingHandler; 506 507 /** 508 * Messages for {@link #mHandler} that need to wait for system ready before 509 * being dispatched. 510 */ 511 private ArrayList<Message> mPostSystemReadyMessages; 512 513 final int mSdkVersion = Build.VERSION.SDK_INT; 514 515 final Context mContext; 516 final boolean mFactoryTest; 517 final boolean mOnlyCore; 518 final DisplayMetrics mMetrics; 519 final int mDefParseFlags; 520 final String[] mSeparateProcesses; 521 final boolean mIsUpgrade; 522 final boolean mIsPreNUpgrade; 523 524 /** The location for ASEC container files on internal storage. */ 525 final String mAsecInternalPath; 526 527 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 528 // LOCK HELD. Can be called with mInstallLock held. 529 @GuardedBy("mInstallLock") 530 final Installer mInstaller; 531 532 /** Directory where installed third-party apps stored */ 533 final File mAppInstallDir; 534 final File mEphemeralInstallDir; 535 536 /** 537 * Directory to which applications installed internally have their 538 * 32 bit native libraries copied. 539 */ 540 private File mAppLib32InstallDir; 541 542 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 543 // apps. 544 final File mDrmAppPrivateInstallDir; 545 546 // ---------------------------------------------------------------- 547 548 // Lock for state used when installing and doing other long running 549 // operations. Methods that must be called with this lock held have 550 // the suffix "LI". 551 final Object mInstallLock = new Object(); 552 553 // ---------------------------------------------------------------- 554 555 // Keys are String (package name), values are Package. This also serves 556 // as the lock for the global state. Methods that must be called with 557 // this lock held have the prefix "LP". 558 @GuardedBy("mPackages") 559 final ArrayMap<String, PackageParser.Package> mPackages = 560 new ArrayMap<String, PackageParser.Package>(); 561 562 final ArrayMap<String, Set<String>> mKnownCodebase = 563 new ArrayMap<String, Set<String>>(); 564 565 // Tracks available target package names -> overlay package paths. 566 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 567 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 568 569 /** 570 * Tracks new system packages [received in an OTA] that we expect to 571 * find updated user-installed versions. Keys are package name, values 572 * are package location. 573 */ 574 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 575 /** 576 * Tracks high priority intent filters for protected actions. During boot, certain 577 * filter actions are protected and should never be allowed to have a high priority 578 * intent filter for them. However, there is one, and only one exception -- the 579 * setup wizard. It must be able to define a high priority intent filter for these 580 * actions to ensure there are no escapes from the wizard. We need to delay processing 581 * of these during boot as we need to look at all of the system packages in order 582 * to know which component is the setup wizard. 583 */ 584 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 585 /** 586 * Whether or not processing protected filters should be deferred. 587 */ 588 private boolean mDeferProtectedFilters = true; 589 590 /** 591 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 592 */ 593 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 594 /** 595 * Whether or not system app permissions should be promoted from install to runtime. 596 */ 597 boolean mPromoteSystemApps; 598 599 @GuardedBy("mPackages") 600 final Settings mSettings; 601 602 /** 603 * Set of package names that are currently "frozen", which means active 604 * surgery is being done on the code/data for that package. The platform 605 * will refuse to launch frozen packages to avoid race conditions. 606 * 607 * @see PackageFreezer 608 */ 609 @GuardedBy("mPackages") 610 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 611 612 boolean mRestoredSettings; 613 614 // System configuration read by SystemConfig. 615 final int[] mGlobalGids; 616 final SparseArray<ArraySet<String>> mSystemPermissions; 617 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 618 619 // If mac_permissions.xml was found for seinfo labeling. 620 boolean mFoundPolicyFile; 621 622 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 623 624 public static final class SharedLibraryEntry { 625 public final String path; 626 public final String apk; 627 628 SharedLibraryEntry(String _path, String _apk) { 629 path = _path; 630 apk = _apk; 631 } 632 } 633 634 // Currently known shared libraries. 635 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 636 new ArrayMap<String, SharedLibraryEntry>(); 637 638 // All available activities, for your resolving pleasure. 639 final ActivityIntentResolver mActivities = 640 new ActivityIntentResolver(); 641 642 // All available receivers, for your resolving pleasure. 643 final ActivityIntentResolver mReceivers = 644 new ActivityIntentResolver(); 645 646 // All available services, for your resolving pleasure. 647 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 648 649 // All available providers, for your resolving pleasure. 650 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 651 652 // Mapping from provider base names (first directory in content URI codePath) 653 // to the provider information. 654 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 655 new ArrayMap<String, PackageParser.Provider>(); 656 657 // Mapping from instrumentation class names to info about them. 658 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 659 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 660 661 // Mapping from permission names to info about them. 662 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 663 new ArrayMap<String, PackageParser.PermissionGroup>(); 664 665 // Packages whose data we have transfered into another package, thus 666 // should no longer exist. 667 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 668 669 // Broadcast actions that are only available to the system. 670 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 671 672 /** List of packages waiting for verification. */ 673 final SparseArray<PackageVerificationState> mPendingVerification 674 = new SparseArray<PackageVerificationState>(); 675 676 /** Set of packages associated with each app op permission. */ 677 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 678 679 final PackageInstallerService mInstallerService; 680 681 private final PackageDexOptimizer mPackageDexOptimizer; 682 683 private AtomicInteger mNextMoveId = new AtomicInteger(); 684 private final MoveCallbacks mMoveCallbacks; 685 686 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 687 688 // Cache of users who need badging. 689 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 690 691 /** Token for keys in mPendingVerification. */ 692 private int mPendingVerificationToken = 0; 693 694 volatile boolean mSystemReady; 695 volatile boolean mSafeMode; 696 volatile boolean mHasSystemUidErrors; 697 698 ApplicationInfo mAndroidApplication; 699 final ActivityInfo mResolveActivity = new ActivityInfo(); 700 final ResolveInfo mResolveInfo = new ResolveInfo(); 701 ComponentName mResolveComponentName; 702 PackageParser.Package mPlatformPackage; 703 ComponentName mCustomResolverComponentName; 704 705 boolean mResolverReplaced = false; 706 707 private final @Nullable ComponentName mIntentFilterVerifierComponent; 708 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 709 710 private int mIntentFilterVerificationToken = 0; 711 712 /** Component that knows whether or not an ephemeral application exists */ 713 final ComponentName mEphemeralResolverComponent; 714 /** The service connection to the ephemeral resolver */ 715 final EphemeralResolverConnection mEphemeralResolverConnection; 716 717 /** Component used to install ephemeral applications */ 718 final ComponentName mEphemeralInstallerComponent; 719 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 720 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 721 722 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 723 = new SparseArray<IntentFilterVerificationState>(); 724 725 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 726 new DefaultPermissionGrantPolicy(this); 727 728 // List of packages names to keep cached, even if they are uninstalled for all users 729 private List<String> mKeepUninstalledPackages; 730 731 private static class IFVerificationParams { 732 PackageParser.Package pkg; 733 boolean replacing; 734 int userId; 735 int verifierUid; 736 737 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 738 int _userId, int _verifierUid) { 739 pkg = _pkg; 740 replacing = _replacing; 741 userId = _userId; 742 replacing = _replacing; 743 verifierUid = _verifierUid; 744 } 745 } 746 747 private interface IntentFilterVerifier<T extends IntentFilter> { 748 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 749 T filter, String packageName); 750 void startVerifications(int userId); 751 void receiveVerificationResponse(int verificationId); 752 } 753 754 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 755 private Context mContext; 756 private ComponentName mIntentFilterVerifierComponent; 757 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 758 759 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 760 mContext = context; 761 mIntentFilterVerifierComponent = verifierComponent; 762 } 763 764 private String getDefaultScheme() { 765 return IntentFilter.SCHEME_HTTPS; 766 } 767 768 @Override 769 public void startVerifications(int userId) { 770 // Launch verifications requests 771 int count = mCurrentIntentFilterVerifications.size(); 772 for (int n=0; n<count; n++) { 773 int verificationId = mCurrentIntentFilterVerifications.get(n); 774 final IntentFilterVerificationState ivs = 775 mIntentFilterVerificationStates.get(verificationId); 776 777 String packageName = ivs.getPackageName(); 778 779 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 780 final int filterCount = filters.size(); 781 ArraySet<String> domainsSet = new ArraySet<>(); 782 for (int m=0; m<filterCount; m++) { 783 PackageParser.ActivityIntentInfo filter = filters.get(m); 784 domainsSet.addAll(filter.getHostsList()); 785 } 786 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 787 synchronized (mPackages) { 788 if (mSettings.createIntentFilterVerificationIfNeededLPw( 789 packageName, domainsList) != null) { 790 scheduleWriteSettingsLocked(); 791 } 792 } 793 sendVerificationRequest(userId, verificationId, ivs); 794 } 795 mCurrentIntentFilterVerifications.clear(); 796 } 797 798 private void sendVerificationRequest(int userId, int verificationId, 799 IntentFilterVerificationState ivs) { 800 801 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 802 verificationIntent.putExtra( 803 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 804 verificationId); 805 verificationIntent.putExtra( 806 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 807 getDefaultScheme()); 808 verificationIntent.putExtra( 809 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 810 ivs.getHostsString()); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 813 ivs.getPackageName()); 814 verificationIntent.setComponent(mIntentFilterVerifierComponent); 815 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 816 817 UserHandle user = new UserHandle(userId); 818 mContext.sendBroadcastAsUser(verificationIntent, user); 819 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 820 "Sending IntentFilter verification broadcast"); 821 } 822 823 public void receiveVerificationResponse(int verificationId) { 824 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 825 826 final boolean verified = ivs.isVerified(); 827 828 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 829 final int count = filters.size(); 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.i(TAG, "Received verification response " + verificationId 832 + " for " + count + " filters, verified=" + verified); 833 } 834 for (int n=0; n<count; n++) { 835 PackageParser.ActivityIntentInfo filter = filters.get(n); 836 filter.setVerified(verified); 837 838 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 839 + " verified with result:" + verified + " and hosts:" 840 + ivs.getHostsString()); 841 } 842 843 mIntentFilterVerificationStates.remove(verificationId); 844 845 final String packageName = ivs.getPackageName(); 846 IntentFilterVerificationInfo ivi = null; 847 848 synchronized (mPackages) { 849 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 850 } 851 if (ivi == null) { 852 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 853 + verificationId + " packageName:" + packageName); 854 return; 855 } 856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 857 "Updating IntentFilterVerificationInfo for package " + packageName 858 +" verificationId:" + verificationId); 859 860 synchronized (mPackages) { 861 if (verified) { 862 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 863 } else { 864 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 865 } 866 scheduleWriteSettingsLocked(); 867 868 final int userId = ivs.getUserId(); 869 if (userId != UserHandle.USER_ALL) { 870 final int userStatus = 871 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 872 873 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 874 boolean needUpdate = false; 875 876 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 877 // already been set by the User thru the Disambiguation dialog 878 switch (userStatus) { 879 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 880 if (verified) { 881 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 882 } else { 883 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 884 } 885 needUpdate = true; 886 break; 887 888 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 889 if (verified) { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 891 needUpdate = true; 892 } 893 break; 894 895 default: 896 // Nothing to do 897 } 898 899 if (needUpdate) { 900 mSettings.updateIntentFilterVerificationStatusLPw( 901 packageName, updatedStatus, userId); 902 scheduleWritePackageRestrictionsLocked(userId); 903 } 904 } 905 } 906 } 907 908 @Override 909 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 910 ActivityIntentInfo filter, String packageName) { 911 if (!hasValidDomains(filter)) { 912 return false; 913 } 914 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 915 if (ivs == null) { 916 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 917 packageName); 918 } 919 if (DEBUG_DOMAIN_VERIFICATION) { 920 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 921 } 922 ivs.addFilter(filter); 923 return true; 924 } 925 926 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 927 int userId, int verificationId, String packageName) { 928 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 929 verifierUid, userId, packageName); 930 ivs.setPendingState(); 931 synchronized (mPackages) { 932 mIntentFilterVerificationStates.append(verificationId, ivs); 933 mCurrentIntentFilterVerifications.add(verificationId); 934 } 935 return ivs; 936 } 937 } 938 939 private static boolean hasValidDomains(ActivityIntentInfo filter) { 940 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 941 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 942 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 943 } 944 945 // Set of pending broadcasts for aggregating enable/disable of components. 946 static class PendingPackageBroadcasts { 947 // for each user id, a map of <package name -> components within that package> 948 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 949 950 public PendingPackageBroadcasts() { 951 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 952 } 953 954 public ArrayList<String> get(int userId, String packageName) { 955 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 956 return packages.get(packageName); 957 } 958 959 public void put(int userId, String packageName, ArrayList<String> components) { 960 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 961 packages.put(packageName, components); 962 } 963 964 public void remove(int userId, String packageName) { 965 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 966 if (packages != null) { 967 packages.remove(packageName); 968 } 969 } 970 971 public void remove(int userId) { 972 mUidMap.remove(userId); 973 } 974 975 public int userIdCount() { 976 return mUidMap.size(); 977 } 978 979 public int userIdAt(int n) { 980 return mUidMap.keyAt(n); 981 } 982 983 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 984 return mUidMap.get(userId); 985 } 986 987 public int size() { 988 // total number of pending broadcast entries across all userIds 989 int num = 0; 990 for (int i = 0; i< mUidMap.size(); i++) { 991 num += mUidMap.valueAt(i).size(); 992 } 993 return num; 994 } 995 996 public void clear() { 997 mUidMap.clear(); 998 } 999 1000 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1001 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1002 if (map == null) { 1003 map = new ArrayMap<String, ArrayList<String>>(); 1004 mUidMap.put(userId, map); 1005 } 1006 return map; 1007 } 1008 } 1009 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1010 1011 // Service Connection to remote media container service to copy 1012 // package uri's from external media onto secure containers 1013 // or internal storage. 1014 private IMediaContainerService mContainerService = null; 1015 1016 static final int SEND_PENDING_BROADCAST = 1; 1017 static final int MCS_BOUND = 3; 1018 static final int END_COPY = 4; 1019 static final int INIT_COPY = 5; 1020 static final int MCS_UNBIND = 6; 1021 static final int START_CLEANING_PACKAGE = 7; 1022 static final int FIND_INSTALL_LOC = 8; 1023 static final int POST_INSTALL = 9; 1024 static final int MCS_RECONNECT = 10; 1025 static final int MCS_GIVE_UP = 11; 1026 static final int UPDATED_MEDIA_STATUS = 12; 1027 static final int WRITE_SETTINGS = 13; 1028 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1029 static final int PACKAGE_VERIFIED = 15; 1030 static final int CHECK_PENDING_VERIFICATION = 16; 1031 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1032 static final int INTENT_FILTER_VERIFIED = 18; 1033 1034 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1035 1036 // Delay time in millisecs 1037 static final int BROADCAST_DELAY = 10 * 1000; 1038 1039 static UserManagerService sUserManager; 1040 1041 // Stores a list of users whose package restrictions file needs to be updated 1042 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1043 1044 final private DefaultContainerConnection mDefContainerConn = 1045 new DefaultContainerConnection(); 1046 class DefaultContainerConnection implements ServiceConnection { 1047 public void onServiceConnected(ComponentName name, IBinder service) { 1048 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1049 IMediaContainerService imcs = 1050 IMediaContainerService.Stub.asInterface(service); 1051 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1052 } 1053 1054 public void onServiceDisconnected(ComponentName name) { 1055 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1056 } 1057 } 1058 1059 // Recordkeeping of restore-after-install operations that are currently in flight 1060 // between the Package Manager and the Backup Manager 1061 static class PostInstallData { 1062 public InstallArgs args; 1063 public PackageInstalledInfo res; 1064 1065 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1066 args = _a; 1067 res = _r; 1068 } 1069 } 1070 1071 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1072 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1073 1074 // XML tags for backup/restore of various bits of state 1075 private static final String TAG_PREFERRED_BACKUP = "pa"; 1076 private static final String TAG_DEFAULT_APPS = "da"; 1077 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1078 1079 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1080 private static final String TAG_ALL_GRANTS = "rt-grants"; 1081 private static final String TAG_GRANT = "grant"; 1082 private static final String ATTR_PACKAGE_NAME = "pkg"; 1083 1084 private static final String TAG_PERMISSION = "perm"; 1085 private static final String ATTR_PERMISSION_NAME = "name"; 1086 private static final String ATTR_IS_GRANTED = "g"; 1087 private static final String ATTR_USER_SET = "set"; 1088 private static final String ATTR_USER_FIXED = "fixed"; 1089 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1090 1091 // System/policy permission grants are not backed up 1092 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1093 FLAG_PERMISSION_POLICY_FIXED 1094 | FLAG_PERMISSION_SYSTEM_FIXED 1095 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1096 1097 // And we back up these user-adjusted states 1098 private static final int USER_RUNTIME_GRANT_MASK = 1099 FLAG_PERMISSION_USER_SET 1100 | FLAG_PERMISSION_USER_FIXED 1101 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1102 1103 final @Nullable String mRequiredVerifierPackage; 1104 final @NonNull String mRequiredInstallerPackage; 1105 final @Nullable String mSetupWizardPackage; 1106 final @NonNull String mServicesSystemSharedLibraryPackageName; 1107 1108 private final PackageUsage mPackageUsage = new PackageUsage(); 1109 1110 private class PackageUsage { 1111 private static final int WRITE_INTERVAL 1112 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1113 1114 private final Object mFileLock = new Object(); 1115 private final AtomicLong mLastWritten = new AtomicLong(0); 1116 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1117 1118 private boolean mIsHistoricalPackageUsageAvailable = true; 1119 1120 boolean isHistoricalPackageUsageAvailable() { 1121 return mIsHistoricalPackageUsageAvailable; 1122 } 1123 1124 void write(boolean force) { 1125 if (force) { 1126 writeInternal(); 1127 return; 1128 } 1129 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1130 && !DEBUG_DEXOPT) { 1131 return; 1132 } 1133 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1134 new Thread("PackageUsage_DiskWriter") { 1135 @Override 1136 public void run() { 1137 try { 1138 writeInternal(); 1139 } finally { 1140 mBackgroundWriteRunning.set(false); 1141 } 1142 } 1143 }.start(); 1144 } 1145 } 1146 1147 private void writeInternal() { 1148 synchronized (mPackages) { 1149 synchronized (mFileLock) { 1150 AtomicFile file = getFile(); 1151 FileOutputStream f = null; 1152 try { 1153 f = file.startWrite(); 1154 BufferedOutputStream out = new BufferedOutputStream(f); 1155 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1156 StringBuilder sb = new StringBuilder(); 1157 for (PackageParser.Package pkg : mPackages.values()) { 1158 if (pkg.mLastPackageUsageTimeInMills == 0) { 1159 continue; 1160 } 1161 sb.setLength(0); 1162 sb.append(pkg.packageName); 1163 sb.append(' '); 1164 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1165 sb.append('\n'); 1166 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1167 } 1168 out.flush(); 1169 file.finishWrite(f); 1170 } catch (IOException e) { 1171 if (f != null) { 1172 file.failWrite(f); 1173 } 1174 Log.e(TAG, "Failed to write package usage times", e); 1175 } 1176 } 1177 } 1178 mLastWritten.set(SystemClock.elapsedRealtime()); 1179 } 1180 1181 void readLP() { 1182 synchronized (mFileLock) { 1183 AtomicFile file = getFile(); 1184 BufferedInputStream in = null; 1185 try { 1186 in = new BufferedInputStream(file.openRead()); 1187 StringBuffer sb = new StringBuffer(); 1188 while (true) { 1189 String packageName = readToken(in, sb, ' '); 1190 if (packageName == null) { 1191 break; 1192 } 1193 String timeInMillisString = readToken(in, sb, '\n'); 1194 if (timeInMillisString == null) { 1195 throw new IOException("Failed to find last usage time for package " 1196 + packageName); 1197 } 1198 PackageParser.Package pkg = mPackages.get(packageName); 1199 if (pkg == null) { 1200 continue; 1201 } 1202 long timeInMillis; 1203 try { 1204 timeInMillis = Long.parseLong(timeInMillisString); 1205 } catch (NumberFormatException e) { 1206 throw new IOException("Failed to parse " + timeInMillisString 1207 + " as a long.", e); 1208 } 1209 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1210 } 1211 } catch (FileNotFoundException expected) { 1212 mIsHistoricalPackageUsageAvailable = false; 1213 } catch (IOException e) { 1214 Log.w(TAG, "Failed to read package usage times", e); 1215 } finally { 1216 IoUtils.closeQuietly(in); 1217 } 1218 } 1219 mLastWritten.set(SystemClock.elapsedRealtime()); 1220 } 1221 1222 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1223 throws IOException { 1224 sb.setLength(0); 1225 while (true) { 1226 int ch = in.read(); 1227 if (ch == -1) { 1228 if (sb.length() == 0) { 1229 return null; 1230 } 1231 throw new IOException("Unexpected EOF"); 1232 } 1233 if (ch == endOfToken) { 1234 return sb.toString(); 1235 } 1236 sb.append((char)ch); 1237 } 1238 } 1239 1240 private AtomicFile getFile() { 1241 File dataDir = Environment.getDataDirectory(); 1242 File systemDir = new File(dataDir, "system"); 1243 File fname = new File(systemDir, "package-usage.list"); 1244 return new AtomicFile(fname); 1245 } 1246 } 1247 1248 class PackageHandler extends Handler { 1249 private boolean mBound = false; 1250 final ArrayList<HandlerParams> mPendingInstalls = 1251 new ArrayList<HandlerParams>(); 1252 1253 private boolean connectToService() { 1254 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1255 " DefaultContainerService"); 1256 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1257 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1258 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1259 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1261 mBound = true; 1262 return true; 1263 } 1264 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1265 return false; 1266 } 1267 1268 private void disconnectService() { 1269 mContainerService = null; 1270 mBound = false; 1271 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1272 mContext.unbindService(mDefContainerConn); 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1274 } 1275 1276 PackageHandler(Looper looper) { 1277 super(looper); 1278 } 1279 1280 public void handleMessage(Message msg) { 1281 try { 1282 doHandleMessage(msg); 1283 } finally { 1284 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1285 } 1286 } 1287 1288 void doHandleMessage(Message msg) { 1289 switch (msg.what) { 1290 case INIT_COPY: { 1291 HandlerParams params = (HandlerParams) msg.obj; 1292 int idx = mPendingInstalls.size(); 1293 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1294 // If a bind was already initiated we dont really 1295 // need to do anything. The pending install 1296 // will be processed later on. 1297 if (!mBound) { 1298 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1299 System.identityHashCode(mHandler)); 1300 // If this is the only one pending we might 1301 // have to bind to the service again. 1302 if (!connectToService()) { 1303 Slog.e(TAG, "Failed to bind to media container service"); 1304 params.serviceError(); 1305 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1306 System.identityHashCode(mHandler)); 1307 if (params.traceMethod != null) { 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1309 params.traceCookie); 1310 } 1311 return; 1312 } else { 1313 // Once we bind to the service, the first 1314 // pending request will be processed. 1315 mPendingInstalls.add(idx, params); 1316 } 1317 } else { 1318 mPendingInstalls.add(idx, params); 1319 // Already bound to the service. Just make 1320 // sure we trigger off processing the first request. 1321 if (idx == 0) { 1322 mHandler.sendEmptyMessage(MCS_BOUND); 1323 } 1324 } 1325 break; 1326 } 1327 case MCS_BOUND: { 1328 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1329 if (msg.obj != null) { 1330 mContainerService = (IMediaContainerService) msg.obj; 1331 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1332 System.identityHashCode(mHandler)); 1333 } 1334 if (mContainerService == null) { 1335 if (!mBound) { 1336 // Something seriously wrong since we are not bound and we are not 1337 // waiting for connection. Bail out. 1338 Slog.e(TAG, "Cannot bind to media container service"); 1339 for (HandlerParams params : mPendingInstalls) { 1340 // Indicate service bind error 1341 params.serviceError(); 1342 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1343 System.identityHashCode(params)); 1344 if (params.traceMethod != null) { 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1346 params.traceMethod, params.traceCookie); 1347 } 1348 return; 1349 } 1350 mPendingInstalls.clear(); 1351 } else { 1352 Slog.w(TAG, "Waiting to connect to media container service"); 1353 } 1354 } else if (mPendingInstalls.size() > 0) { 1355 HandlerParams params = mPendingInstalls.get(0); 1356 if (params != null) { 1357 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1358 System.identityHashCode(params)); 1359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1360 if (params.startCopy()) { 1361 // We are done... look for more work or to 1362 // go idle. 1363 if (DEBUG_SD_INSTALL) Log.i(TAG, 1364 "Checking for more work or unbind..."); 1365 // Delete pending install 1366 if (mPendingInstalls.size() > 0) { 1367 mPendingInstalls.remove(0); 1368 } 1369 if (mPendingInstalls.size() == 0) { 1370 if (mBound) { 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, 1372 "Posting delayed MCS_UNBIND"); 1373 removeMessages(MCS_UNBIND); 1374 Message ubmsg = obtainMessage(MCS_UNBIND); 1375 // Unbind after a little delay, to avoid 1376 // continual thrashing. 1377 sendMessageDelayed(ubmsg, 10000); 1378 } 1379 } else { 1380 // There are more pending requests in queue. 1381 // Just post MCS_BOUND message to trigger processing 1382 // of next pending install. 1383 if (DEBUG_SD_INSTALL) Log.i(TAG, 1384 "Posting MCS_BOUND for next work"); 1385 mHandler.sendEmptyMessage(MCS_BOUND); 1386 } 1387 } 1388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1389 } 1390 } else { 1391 // Should never happen ideally. 1392 Slog.w(TAG, "Empty queue"); 1393 } 1394 break; 1395 } 1396 case MCS_RECONNECT: { 1397 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1398 if (mPendingInstalls.size() > 0) { 1399 if (mBound) { 1400 disconnectService(); 1401 } 1402 if (!connectToService()) { 1403 Slog.e(TAG, "Failed to bind to media container service"); 1404 for (HandlerParams params : mPendingInstalls) { 1405 // Indicate service bind error 1406 params.serviceError(); 1407 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1408 System.identityHashCode(params)); 1409 } 1410 mPendingInstalls.clear(); 1411 } 1412 } 1413 break; 1414 } 1415 case MCS_UNBIND: { 1416 // If there is no actual work left, then time to unbind. 1417 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1418 1419 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1420 if (mBound) { 1421 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1422 1423 disconnectService(); 1424 } 1425 } else if (mPendingInstalls.size() > 0) { 1426 // There are more pending requests in queue. 1427 // Just post MCS_BOUND message to trigger processing 1428 // of next pending install. 1429 mHandler.sendEmptyMessage(MCS_BOUND); 1430 } 1431 1432 break; 1433 } 1434 case MCS_GIVE_UP: { 1435 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1436 HandlerParams params = mPendingInstalls.remove(0); 1437 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1438 System.identityHashCode(params)); 1439 break; 1440 } 1441 case SEND_PENDING_BROADCAST: { 1442 String packages[]; 1443 ArrayList<String> components[]; 1444 int size = 0; 1445 int uids[]; 1446 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1447 synchronized (mPackages) { 1448 if (mPendingBroadcasts == null) { 1449 return; 1450 } 1451 size = mPendingBroadcasts.size(); 1452 if (size <= 0) { 1453 // Nothing to be done. Just return 1454 return; 1455 } 1456 packages = new String[size]; 1457 components = new ArrayList[size]; 1458 uids = new int[size]; 1459 int i = 0; // filling out the above arrays 1460 1461 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1462 int packageUserId = mPendingBroadcasts.userIdAt(n); 1463 Iterator<Map.Entry<String, ArrayList<String>>> it 1464 = mPendingBroadcasts.packagesForUserId(packageUserId) 1465 .entrySet().iterator(); 1466 while (it.hasNext() && i < size) { 1467 Map.Entry<String, ArrayList<String>> ent = it.next(); 1468 packages[i] = ent.getKey(); 1469 components[i] = ent.getValue(); 1470 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1471 uids[i] = (ps != null) 1472 ? UserHandle.getUid(packageUserId, ps.appId) 1473 : -1; 1474 i++; 1475 } 1476 } 1477 size = i; 1478 mPendingBroadcasts.clear(); 1479 } 1480 // Send broadcasts 1481 for (int i = 0; i < size; i++) { 1482 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1483 } 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1485 break; 1486 } 1487 case START_CLEANING_PACKAGE: { 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1489 final String packageName = (String)msg.obj; 1490 final int userId = msg.arg1; 1491 final boolean andCode = msg.arg2 != 0; 1492 synchronized (mPackages) { 1493 if (userId == UserHandle.USER_ALL) { 1494 int[] users = sUserManager.getUserIds(); 1495 for (int user : users) { 1496 mSettings.addPackageToCleanLPw( 1497 new PackageCleanItem(user, packageName, andCode)); 1498 } 1499 } else { 1500 mSettings.addPackageToCleanLPw( 1501 new PackageCleanItem(userId, packageName, andCode)); 1502 } 1503 } 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1505 startCleaningPackages(); 1506 } break; 1507 case POST_INSTALL: { 1508 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1509 1510 PostInstallData data = mRunningInstalls.get(msg.arg1); 1511 mRunningInstalls.delete(msg.arg1); 1512 1513 if (data != null) { 1514 InstallArgs args = data.args; 1515 PackageInstalledInfo parentRes = data.res; 1516 1517 final boolean grantPermissions = (args.installFlags 1518 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1519 final boolean killApp = (args.installFlags 1520 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1521 final String[] grantedPermissions = args.installGrantPermissions; 1522 1523 // Handle the parent package 1524 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1525 grantedPermissions, args.observer); 1526 1527 // Handle the child packages 1528 final int childCount = (parentRes.addedChildPackages != null) 1529 ? parentRes.addedChildPackages.size() : 0; 1530 for (int i = 0; i < childCount; i++) { 1531 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1532 handlePackagePostInstall(childRes, grantPermissions, killApp, 1533 grantedPermissions, args.observer); 1534 } 1535 1536 // Log tracing if needed 1537 if (args.traceMethod != null) { 1538 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1539 args.traceCookie); 1540 } 1541 } else { 1542 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1543 } 1544 1545 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1546 } break; 1547 case UPDATED_MEDIA_STATUS: { 1548 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1549 boolean reportStatus = msg.arg1 == 1; 1550 boolean doGc = msg.arg2 == 1; 1551 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1552 if (doGc) { 1553 // Force a gc to clear up stale containers. 1554 Runtime.getRuntime().gc(); 1555 } 1556 if (msg.obj != null) { 1557 @SuppressWarnings("unchecked") 1558 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1559 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1560 // Unload containers 1561 unloadAllContainers(args); 1562 } 1563 if (reportStatus) { 1564 try { 1565 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1566 PackageHelper.getMountService().finishMediaUpdate(); 1567 } catch (RemoteException e) { 1568 Log.e(TAG, "MountService not running?"); 1569 } 1570 } 1571 } break; 1572 case WRITE_SETTINGS: { 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1574 synchronized (mPackages) { 1575 removeMessages(WRITE_SETTINGS); 1576 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1577 mSettings.writeLPr(); 1578 mDirtyUsers.clear(); 1579 } 1580 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1581 } break; 1582 case WRITE_PACKAGE_RESTRICTIONS: { 1583 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1584 synchronized (mPackages) { 1585 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1586 for (int userId : mDirtyUsers) { 1587 mSettings.writePackageRestrictionsLPr(userId); 1588 } 1589 mDirtyUsers.clear(); 1590 } 1591 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1592 } break; 1593 case CHECK_PENDING_VERIFICATION: { 1594 final int verificationId = msg.arg1; 1595 final PackageVerificationState state = mPendingVerification.get(verificationId); 1596 1597 if ((state != null) && !state.timeoutExtended()) { 1598 final InstallArgs args = state.getInstallArgs(); 1599 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1600 1601 Slog.i(TAG, "Verification timed out for " + originUri); 1602 mPendingVerification.remove(verificationId); 1603 1604 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1605 1606 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1607 Slog.i(TAG, "Continuing with installation of " + originUri); 1608 state.setVerifierResponse(Binder.getCallingUid(), 1609 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1610 broadcastPackageVerified(verificationId, originUri, 1611 PackageManager.VERIFICATION_ALLOW, 1612 state.getInstallArgs().getUser()); 1613 try { 1614 ret = args.copyApk(mContainerService, true); 1615 } catch (RemoteException e) { 1616 Slog.e(TAG, "Could not contact the ContainerService"); 1617 } 1618 } else { 1619 broadcastPackageVerified(verificationId, originUri, 1620 PackageManager.VERIFICATION_REJECT, 1621 state.getInstallArgs().getUser()); 1622 } 1623 1624 Trace.asyncTraceEnd( 1625 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1626 1627 processPendingInstall(args, ret); 1628 mHandler.sendEmptyMessage(MCS_UNBIND); 1629 } 1630 break; 1631 } 1632 case PACKAGE_VERIFIED: { 1633 final int verificationId = msg.arg1; 1634 1635 final PackageVerificationState state = mPendingVerification.get(verificationId); 1636 if (state == null) { 1637 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1638 break; 1639 } 1640 1641 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1642 1643 state.setVerifierResponse(response.callerUid, response.code); 1644 1645 if (state.isVerificationComplete()) { 1646 mPendingVerification.remove(verificationId); 1647 1648 final InstallArgs args = state.getInstallArgs(); 1649 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1650 1651 int ret; 1652 if (state.isInstallAllowed()) { 1653 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1654 broadcastPackageVerified(verificationId, originUri, 1655 response.code, state.getInstallArgs().getUser()); 1656 try { 1657 ret = args.copyApk(mContainerService, true); 1658 } catch (RemoteException e) { 1659 Slog.e(TAG, "Could not contact the ContainerService"); 1660 } 1661 } else { 1662 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1663 } 1664 1665 Trace.asyncTraceEnd( 1666 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1667 1668 processPendingInstall(args, ret); 1669 mHandler.sendEmptyMessage(MCS_UNBIND); 1670 } 1671 1672 break; 1673 } 1674 case START_INTENT_FILTER_VERIFICATIONS: { 1675 IFVerificationParams params = (IFVerificationParams) msg.obj; 1676 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1677 params.replacing, params.pkg); 1678 break; 1679 } 1680 case INTENT_FILTER_VERIFIED: { 1681 final int verificationId = msg.arg1; 1682 1683 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1684 verificationId); 1685 if (state == null) { 1686 Slog.w(TAG, "Invalid IntentFilter verification token " 1687 + verificationId + " received"); 1688 break; 1689 } 1690 1691 final int userId = state.getUserId(); 1692 1693 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1694 "Processing IntentFilter verification with token:" 1695 + verificationId + " and userId:" + userId); 1696 1697 final IntentFilterVerificationResponse response = 1698 (IntentFilterVerificationResponse) msg.obj; 1699 1700 state.setVerifierResponse(response.callerUid, response.code); 1701 1702 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1703 "IntentFilter verification with token:" + verificationId 1704 + " and userId:" + userId 1705 + " is settings verifier response with response code:" 1706 + response.code); 1707 1708 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1710 + response.getFailedDomainsString()); 1711 } 1712 1713 if (state.isVerificationComplete()) { 1714 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1715 } else { 1716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1717 "IntentFilter verification with token:" + verificationId 1718 + " was not said to be complete"); 1719 } 1720 1721 break; 1722 } 1723 } 1724 } 1725 } 1726 1727 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1728 boolean killApp, String[] grantedPermissions, 1729 IPackageInstallObserver2 installObserver) { 1730 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1731 // Send the removed broadcasts 1732 if (res.removedInfo != null) { 1733 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1734 } 1735 1736 // Now that we successfully installed the package, grant runtime 1737 // permissions if requested before broadcasting the install. 1738 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1739 >= Build.VERSION_CODES.M) { 1740 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1741 } 1742 1743 final boolean update = res.removedInfo != null 1744 && res.removedInfo.removedPackage != null; 1745 1746 // If this is the first time we have child packages for a disabled privileged 1747 // app that had no children, we grant requested runtime permissions to the new 1748 // children if the parent on the system image had them already granted. 1749 if (res.pkg.parentPackage != null) { 1750 synchronized (mPackages) { 1751 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1752 } 1753 } 1754 1755 synchronized (mPackages) { 1756 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1757 } 1758 1759 final String packageName = res.pkg.applicationInfo.packageName; 1760 Bundle extras = new Bundle(1); 1761 extras.putInt(Intent.EXTRA_UID, res.uid); 1762 1763 // Determine the set of users who are adding this package for 1764 // the first time vs. those who are seeing an update. 1765 int[] firstUsers = EMPTY_INT_ARRAY; 1766 int[] updateUsers = EMPTY_INT_ARRAY; 1767 if (res.origUsers == null || res.origUsers.length == 0) { 1768 firstUsers = res.newUsers; 1769 } else { 1770 for (int newUser : res.newUsers) { 1771 boolean isNew = true; 1772 for (int origUser : res.origUsers) { 1773 if (origUser == newUser) { 1774 isNew = false; 1775 break; 1776 } 1777 } 1778 if (isNew) { 1779 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1780 } else { 1781 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1782 } 1783 } 1784 } 1785 1786 // Send installed broadcasts if the install/update is not ephemeral 1787 if (!isEphemeral(res.pkg)) { 1788 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1789 1790 // Send added for users that see the package for the first time 1791 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1792 extras, 0 /*flags*/, null /*targetPackage*/, 1793 null /*finishedReceiver*/, firstUsers); 1794 1795 // Send added for users that don't see the package for the first time 1796 if (update) { 1797 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1798 } 1799 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1800 extras, 0 /*flags*/, null /*targetPackage*/, 1801 null /*finishedReceiver*/, updateUsers); 1802 1803 // Send replaced for users that don't see the package for the first time 1804 if (update) { 1805 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1806 packageName, extras, 0 /*flags*/, 1807 null /*targetPackage*/, null /*finishedReceiver*/, 1808 updateUsers); 1809 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1810 null /*package*/, null /*extras*/, 0 /*flags*/, 1811 packageName /*targetPackage*/, 1812 null /*finishedReceiver*/, updateUsers); 1813 } 1814 1815 // Send broadcast package appeared if forward locked/external for all users 1816 // treat asec-hosted packages like removable media on upgrade 1817 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1818 if (DEBUG_INSTALL) { 1819 Slog.i(TAG, "upgrading pkg " + res.pkg 1820 + " is ASEC-hosted -> AVAILABLE"); 1821 } 1822 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1823 ArrayList<String> pkgList = new ArrayList<>(1); 1824 pkgList.add(packageName); 1825 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1826 } 1827 } 1828 1829 // Work that needs to happen on first install within each user 1830 if (firstUsers != null && firstUsers.length > 0) { 1831 synchronized (mPackages) { 1832 for (int userId : firstUsers) { 1833 // If this app is a browser and it's newly-installed for some 1834 // users, clear any default-browser state in those users. The 1835 // app's nature doesn't depend on the user, so we can just check 1836 // its browser nature in any user and generalize. 1837 if (packageIsBrowser(packageName, userId)) { 1838 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1839 } 1840 1841 // We may also need to apply pending (restored) runtime 1842 // permission grants within these users. 1843 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1844 } 1845 } 1846 } 1847 1848 // Log current value of "unknown sources" setting 1849 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1850 getUnknownSourcesSettings()); 1851 1852 // Force a gc to clear up things 1853 Runtime.getRuntime().gc(); 1854 1855 // Remove the replaced package's older resources safely now 1856 // We delete after a gc for applications on sdcard. 1857 if (res.removedInfo != null && res.removedInfo.args != null) { 1858 synchronized (mInstallLock) { 1859 res.removedInfo.args.doPostDeleteLI(true); 1860 } 1861 } 1862 } 1863 1864 // If someone is watching installs - notify them 1865 if (installObserver != null) { 1866 try { 1867 Bundle extras = extrasForInstallResult(res); 1868 installObserver.onPackageInstalled(res.name, res.returnCode, 1869 res.returnMsg, extras); 1870 } catch (RemoteException e) { 1871 Slog.i(TAG, "Observer no longer exists."); 1872 } 1873 } 1874 } 1875 1876 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1877 PackageParser.Package pkg) { 1878 if (pkg.parentPackage == null) { 1879 return; 1880 } 1881 if (pkg.requestedPermissions == null) { 1882 return; 1883 } 1884 final PackageSetting disabledSysParentPs = mSettings 1885 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1886 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1887 || !disabledSysParentPs.isPrivileged() 1888 || (disabledSysParentPs.childPackageNames != null 1889 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1890 return; 1891 } 1892 final int[] allUserIds = sUserManager.getUserIds(); 1893 final int permCount = pkg.requestedPermissions.size(); 1894 for (int i = 0; i < permCount; i++) { 1895 String permission = pkg.requestedPermissions.get(i); 1896 BasePermission bp = mSettings.mPermissions.get(permission); 1897 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1898 continue; 1899 } 1900 for (int userId : allUserIds) { 1901 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1902 permission, userId)) { 1903 grantRuntimePermission(pkg.packageName, permission, userId); 1904 } 1905 } 1906 } 1907 } 1908 1909 private StorageEventListener mStorageListener = new StorageEventListener() { 1910 @Override 1911 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1912 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1913 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1914 final String volumeUuid = vol.getFsUuid(); 1915 1916 // Clean up any users or apps that were removed or recreated 1917 // while this volume was missing 1918 reconcileUsers(volumeUuid); 1919 reconcileApps(volumeUuid); 1920 1921 // Clean up any install sessions that expired or were 1922 // cancelled while this volume was missing 1923 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1924 1925 loadPrivatePackages(vol); 1926 1927 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1928 unloadPrivatePackages(vol); 1929 } 1930 } 1931 1932 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1933 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1934 updateExternalMediaStatus(true, false); 1935 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1936 updateExternalMediaStatus(false, false); 1937 } 1938 } 1939 } 1940 1941 @Override 1942 public void onVolumeForgotten(String fsUuid) { 1943 if (TextUtils.isEmpty(fsUuid)) { 1944 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1945 return; 1946 } 1947 1948 // Remove any apps installed on the forgotten volume 1949 synchronized (mPackages) { 1950 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1951 for (PackageSetting ps : packages) { 1952 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1953 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1954 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1955 } 1956 1957 mSettings.onVolumeForgotten(fsUuid); 1958 mSettings.writeLPr(); 1959 } 1960 } 1961 }; 1962 1963 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1964 String[] grantedPermissions) { 1965 for (int userId : userIds) { 1966 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1967 } 1968 1969 // We could have touched GID membership, so flush out packages.list 1970 synchronized (mPackages) { 1971 mSettings.writePackageListLPr(); 1972 } 1973 } 1974 1975 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1976 String[] grantedPermissions) { 1977 SettingBase sb = (SettingBase) pkg.mExtras; 1978 if (sb == null) { 1979 return; 1980 } 1981 1982 PermissionsState permissionsState = sb.getPermissionsState(); 1983 1984 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1985 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1986 1987 synchronized (mPackages) { 1988 for (String permission : pkg.requestedPermissions) { 1989 BasePermission bp = mSettings.mPermissions.get(permission); 1990 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1991 && (grantedPermissions == null 1992 || ArrayUtils.contains(grantedPermissions, permission))) { 1993 final int flags = permissionsState.getPermissionFlags(permission, userId); 1994 // Installer cannot change immutable permissions. 1995 if ((flags & immutableFlags) == 0) { 1996 grantRuntimePermission(pkg.packageName, permission, userId); 1997 } 1998 } 1999 } 2000 } 2001 } 2002 2003 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2004 Bundle extras = null; 2005 switch (res.returnCode) { 2006 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2007 extras = new Bundle(); 2008 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2009 res.origPermission); 2010 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2011 res.origPackage); 2012 break; 2013 } 2014 case PackageManager.INSTALL_SUCCEEDED: { 2015 extras = new Bundle(); 2016 extras.putBoolean(Intent.EXTRA_REPLACING, 2017 res.removedInfo != null && res.removedInfo.removedPackage != null); 2018 break; 2019 } 2020 } 2021 return extras; 2022 } 2023 2024 void scheduleWriteSettingsLocked() { 2025 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2026 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2027 } 2028 } 2029 2030 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2031 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2032 scheduleWritePackageRestrictionsLocked(userId); 2033 } 2034 2035 void scheduleWritePackageRestrictionsLocked(int userId) { 2036 final int[] userIds = (userId == UserHandle.USER_ALL) 2037 ? sUserManager.getUserIds() : new int[]{userId}; 2038 for (int nextUserId : userIds) { 2039 if (!sUserManager.exists(nextUserId)) return; 2040 mDirtyUsers.add(nextUserId); 2041 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2042 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2043 } 2044 } 2045 } 2046 2047 public static PackageManagerService main(Context context, Installer installer, 2048 boolean factoryTest, boolean onlyCore) { 2049 // Self-check for initial settings. 2050 PackageManagerServiceCompilerMapping.checkProperties(); 2051 2052 PackageManagerService m = new PackageManagerService(context, installer, 2053 factoryTest, onlyCore); 2054 m.enableSystemUserPackages(); 2055 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2056 // disabled after already being started. 2057 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2058 UserHandle.USER_SYSTEM); 2059 ServiceManager.addService("package", m); 2060 return m; 2061 } 2062 2063 private void enableSystemUserPackages() { 2064 if (!UserManager.isSplitSystemUser()) { 2065 return; 2066 } 2067 // For system user, enable apps based on the following conditions: 2068 // - app is whitelisted or belong to one of these groups: 2069 // -- system app which has no launcher icons 2070 // -- system app which has INTERACT_ACROSS_USERS permission 2071 // -- system IME app 2072 // - app is not in the blacklist 2073 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2074 Set<String> enableApps = new ArraySet<>(); 2075 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2076 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2077 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2078 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2079 enableApps.addAll(wlApps); 2080 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2081 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2082 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2083 enableApps.removeAll(blApps); 2084 Log.i(TAG, "Applications installed for system user: " + enableApps); 2085 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2086 UserHandle.SYSTEM); 2087 final int allAppsSize = allAps.size(); 2088 synchronized (mPackages) { 2089 for (int i = 0; i < allAppsSize; i++) { 2090 String pName = allAps.get(i); 2091 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2092 // Should not happen, but we shouldn't be failing if it does 2093 if (pkgSetting == null) { 2094 continue; 2095 } 2096 boolean install = enableApps.contains(pName); 2097 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2098 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2099 + " for system user"); 2100 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2101 } 2102 } 2103 } 2104 } 2105 2106 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2107 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2108 Context.DISPLAY_SERVICE); 2109 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2110 } 2111 2112 public PackageManagerService(Context context, Installer installer, 2113 boolean factoryTest, boolean onlyCore) { 2114 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2115 SystemClock.uptimeMillis()); 2116 2117 if (mSdkVersion <= 0) { 2118 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2119 } 2120 2121 mContext = context; 2122 mFactoryTest = factoryTest; 2123 mOnlyCore = onlyCore; 2124 mMetrics = new DisplayMetrics(); 2125 mSettings = new Settings(mPackages); 2126 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2127 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2128 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2129 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2130 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2131 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2132 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2133 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2134 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2135 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2136 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2137 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2138 2139 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2140 if (separateProcesses != null && separateProcesses.length() > 0) { 2141 if ("*".equals(separateProcesses)) { 2142 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2143 mSeparateProcesses = null; 2144 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2145 } else { 2146 mDefParseFlags = 0; 2147 mSeparateProcesses = separateProcesses.split(","); 2148 Slog.w(TAG, "Running with debug.separate_processes: " 2149 + separateProcesses); 2150 } 2151 } else { 2152 mDefParseFlags = 0; 2153 mSeparateProcesses = null; 2154 } 2155 2156 mInstaller = installer; 2157 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2158 "*dexopt*"); 2159 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2160 2161 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2162 FgThread.get().getLooper()); 2163 2164 getDefaultDisplayMetrics(context, mMetrics); 2165 2166 SystemConfig systemConfig = SystemConfig.getInstance(); 2167 mGlobalGids = systemConfig.getGlobalGids(); 2168 mSystemPermissions = systemConfig.getSystemPermissions(); 2169 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2170 2171 synchronized (mInstallLock) { 2172 // writer 2173 synchronized (mPackages) { 2174 mHandlerThread = new ServiceThread(TAG, 2175 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2176 mHandlerThread.start(); 2177 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2178 mProcessLoggingHandler = new ProcessLoggingHandler(); 2179 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2180 2181 File dataDir = Environment.getDataDirectory(); 2182 mAppInstallDir = new File(dataDir, "app"); 2183 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2184 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2185 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2186 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2187 2188 sUserManager = new UserManagerService(context, this, mPackages); 2189 2190 // Propagate permission configuration in to package manager. 2191 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2192 = systemConfig.getPermissions(); 2193 for (int i=0; i<permConfig.size(); i++) { 2194 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2195 BasePermission bp = mSettings.mPermissions.get(perm.name); 2196 if (bp == null) { 2197 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2198 mSettings.mPermissions.put(perm.name, bp); 2199 } 2200 if (perm.gids != null) { 2201 bp.setGids(perm.gids, perm.perUser); 2202 } 2203 } 2204 2205 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2206 for (int i=0; i<libConfig.size(); i++) { 2207 mSharedLibraries.put(libConfig.keyAt(i), 2208 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2209 } 2210 2211 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2212 2213 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2214 2215 String customResolverActivity = Resources.getSystem().getString( 2216 R.string.config_customResolverActivity); 2217 if (TextUtils.isEmpty(customResolverActivity)) { 2218 customResolverActivity = null; 2219 } else { 2220 mCustomResolverComponentName = ComponentName.unflattenFromString( 2221 customResolverActivity); 2222 } 2223 2224 long startTime = SystemClock.uptimeMillis(); 2225 2226 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2227 startTime); 2228 2229 // Set flag to monitor and not change apk file paths when 2230 // scanning install directories. 2231 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2232 2233 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2234 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2235 2236 if (bootClassPath == null) { 2237 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2238 } 2239 2240 if (systemServerClassPath == null) { 2241 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2242 } 2243 2244 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2245 final String[] dexCodeInstructionSets = 2246 getDexCodeInstructionSets( 2247 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2248 2249 /** 2250 * Ensure all external libraries have had dexopt run on them. 2251 */ 2252 if (mSharedLibraries.size() > 0) { 2253 // NOTE: For now, we're compiling these system "shared libraries" 2254 // (and framework jars) into all available architectures. It's possible 2255 // to compile them only when we come across an app that uses them (there's 2256 // already logic for that in scanPackageLI) but that adds some complexity. 2257 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2258 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2259 final String lib = libEntry.path; 2260 if (lib == null) { 2261 continue; 2262 } 2263 2264 try { 2265 // Shared libraries do not have profiles so we perform a full 2266 // AOT compilation (if needed). 2267 int dexoptNeeded = DexFile.getDexOptNeeded( 2268 lib, dexCodeInstructionSet, 2269 getCompilerFilterForReason(REASON_SHARED_APK), 2270 false /* newProfile */); 2271 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2272 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2273 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2274 getCompilerFilterForReason(REASON_SHARED_APK), 2275 StorageManager.UUID_PRIVATE_INTERNAL); 2276 } 2277 } catch (FileNotFoundException e) { 2278 Slog.w(TAG, "Library not found: " + lib); 2279 } catch (IOException | InstallerException e) { 2280 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2281 + e.getMessage()); 2282 } 2283 } 2284 } 2285 } 2286 2287 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2288 2289 final VersionInfo ver = mSettings.getInternalVersion(); 2290 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2291 2292 // when upgrading from pre-M, promote system app permissions from install to runtime 2293 mPromoteSystemApps = 2294 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2295 2296 // save off the names of pre-existing system packages prior to scanning; we don't 2297 // want to automatically grant runtime permissions for new system apps 2298 if (mPromoteSystemApps) { 2299 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2300 while (pkgSettingIter.hasNext()) { 2301 PackageSetting ps = pkgSettingIter.next(); 2302 if (isSystemApp(ps)) { 2303 mExistingSystemPackages.add(ps.name); 2304 } 2305 } 2306 } 2307 2308 // When upgrading from pre-N, we need to handle package extraction like first boot, 2309 // as there is no profiling data available. 2310 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2311 mSettings.setNWorkDone(); 2312 2313 // Collect vendor overlay packages. 2314 // (Do this before scanning any apps.) 2315 // For security and version matching reason, only consider 2316 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2317 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2318 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2319 | PackageParser.PARSE_IS_SYSTEM 2320 | PackageParser.PARSE_IS_SYSTEM_DIR 2321 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2322 2323 // Find base frameworks (resource packages without code). 2324 scanDirTracedLI(frameworkDir, mDefParseFlags 2325 | PackageParser.PARSE_IS_SYSTEM 2326 | PackageParser.PARSE_IS_SYSTEM_DIR 2327 | PackageParser.PARSE_IS_PRIVILEGED, 2328 scanFlags | SCAN_NO_DEX, 0); 2329 2330 // Collected privileged system packages. 2331 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2332 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2333 | PackageParser.PARSE_IS_SYSTEM 2334 | PackageParser.PARSE_IS_SYSTEM_DIR 2335 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2336 2337 // Collect ordinary system packages. 2338 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2339 scanDirTracedLI(systemAppDir, mDefParseFlags 2340 | PackageParser.PARSE_IS_SYSTEM 2341 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2342 2343 // Collect all vendor packages. 2344 File vendorAppDir = new File("/vendor/app"); 2345 try { 2346 vendorAppDir = vendorAppDir.getCanonicalFile(); 2347 } catch (IOException e) { 2348 // failed to look up canonical path, continue with original one 2349 } 2350 scanDirTracedLI(vendorAppDir, mDefParseFlags 2351 | PackageParser.PARSE_IS_SYSTEM 2352 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2353 2354 // Collect all OEM packages. 2355 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2356 scanDirTracedLI(oemAppDir, mDefParseFlags 2357 | PackageParser.PARSE_IS_SYSTEM 2358 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2359 2360 // Prune any system packages that no longer exist. 2361 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2362 if (!mOnlyCore) { 2363 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2364 while (psit.hasNext()) { 2365 PackageSetting ps = psit.next(); 2366 2367 /* 2368 * If this is not a system app, it can't be a 2369 * disable system app. 2370 */ 2371 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2372 continue; 2373 } 2374 2375 /* 2376 * If the package is scanned, it's not erased. 2377 */ 2378 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2379 if (scannedPkg != null) { 2380 /* 2381 * If the system app is both scanned and in the 2382 * disabled packages list, then it must have been 2383 * added via OTA. Remove it from the currently 2384 * scanned package so the previously user-installed 2385 * application can be scanned. 2386 */ 2387 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2388 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2389 + ps.name + "; removing system app. Last known codePath=" 2390 + ps.codePathString + ", installStatus=" + ps.installStatus 2391 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2392 + scannedPkg.mVersionCode); 2393 removePackageLI(scannedPkg, true); 2394 mExpectingBetter.put(ps.name, ps.codePath); 2395 } 2396 2397 continue; 2398 } 2399 2400 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2401 psit.remove(); 2402 logCriticalInfo(Log.WARN, "System package " + ps.name 2403 + " no longer exists; it's data will be wiped"); 2404 // Actual deletion of code and data will be handled by later 2405 // reconciliation step 2406 } else { 2407 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2408 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2409 possiblyDeletedUpdatedSystemApps.add(ps.name); 2410 } 2411 } 2412 } 2413 } 2414 2415 //look for any incomplete package installations 2416 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2417 for (int i = 0; i < deletePkgsList.size(); i++) { 2418 // Actual deletion of code and data will be handled by later 2419 // reconciliation step 2420 final String packageName = deletePkgsList.get(i).name; 2421 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2422 synchronized (mPackages) { 2423 mSettings.removePackageLPw(packageName); 2424 } 2425 } 2426 2427 //delete tmp files 2428 deleteTempPackageFiles(); 2429 2430 // Remove any shared userIDs that have no associated packages 2431 mSettings.pruneSharedUsersLPw(); 2432 2433 if (!mOnlyCore) { 2434 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2435 SystemClock.uptimeMillis()); 2436 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2437 2438 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2439 | PackageParser.PARSE_FORWARD_LOCK, 2440 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2441 2442 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_EPHEMERAL, 2444 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2445 2446 /** 2447 * Remove disable package settings for any updated system 2448 * apps that were removed via an OTA. If they're not a 2449 * previously-updated app, remove them completely. 2450 * Otherwise, just revoke their system-level permissions. 2451 */ 2452 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2453 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2454 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2455 2456 String msg; 2457 if (deletedPkg == null) { 2458 msg = "Updated system package " + deletedAppName 2459 + " no longer exists; it's data will be wiped"; 2460 // Actual deletion of code and data will be handled by later 2461 // reconciliation step 2462 } else { 2463 msg = "Updated system app + " + deletedAppName 2464 + " no longer present; removing system privileges for " 2465 + deletedAppName; 2466 2467 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2468 2469 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2470 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2471 } 2472 logCriticalInfo(Log.WARN, msg); 2473 } 2474 2475 /** 2476 * Make sure all system apps that we expected to appear on 2477 * the userdata partition actually showed up. If they never 2478 * appeared, crawl back and revive the system version. 2479 */ 2480 for (int i = 0; i < mExpectingBetter.size(); i++) { 2481 final String packageName = mExpectingBetter.keyAt(i); 2482 if (!mPackages.containsKey(packageName)) { 2483 final File scanFile = mExpectingBetter.valueAt(i); 2484 2485 logCriticalInfo(Log.WARN, "Expected better " + packageName 2486 + " but never showed up; reverting to system"); 2487 2488 int reparseFlags = mDefParseFlags; 2489 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2490 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2491 | PackageParser.PARSE_IS_SYSTEM_DIR 2492 | PackageParser.PARSE_IS_PRIVILEGED; 2493 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2494 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2495 | PackageParser.PARSE_IS_SYSTEM_DIR; 2496 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2497 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2498 | PackageParser.PARSE_IS_SYSTEM_DIR; 2499 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2500 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2501 | PackageParser.PARSE_IS_SYSTEM_DIR; 2502 } else { 2503 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2504 continue; 2505 } 2506 2507 mSettings.enableSystemPackageLPw(packageName); 2508 2509 try { 2510 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2511 } catch (PackageManagerException e) { 2512 Slog.e(TAG, "Failed to parse original system package: " 2513 + e.getMessage()); 2514 } 2515 } 2516 } 2517 } 2518 mExpectingBetter.clear(); 2519 2520 // Resolve protected action filters. Only the setup wizard is allowed to 2521 // have a high priority filter for these actions. 2522 mSetupWizardPackage = getSetupWizardPackageName(); 2523 if (mProtectedFilters.size() > 0) { 2524 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2525 Slog.i(TAG, "No setup wizard;" 2526 + " All protected intents capped to priority 0"); 2527 } 2528 for (ActivityIntentInfo filter : mProtectedFilters) { 2529 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2530 if (DEBUG_FILTERS) { 2531 Slog.i(TAG, "Found setup wizard;" 2532 + " allow priority " + filter.getPriority() + ";" 2533 + " package: " + filter.activity.info.packageName 2534 + " activity: " + filter.activity.className 2535 + " priority: " + filter.getPriority()); 2536 } 2537 // skip setup wizard; allow it to keep the high priority filter 2538 continue; 2539 } 2540 Slog.w(TAG, "Protected action; cap priority to 0;" 2541 + " package: " + filter.activity.info.packageName 2542 + " activity: " + filter.activity.className 2543 + " origPrio: " + filter.getPriority()); 2544 filter.setPriority(0); 2545 } 2546 } 2547 mDeferProtectedFilters = false; 2548 mProtectedFilters.clear(); 2549 2550 // Now that we know all of the shared libraries, update all clients to have 2551 // the correct library paths. 2552 updateAllSharedLibrariesLPw(); 2553 2554 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2555 // NOTE: We ignore potential failures here during a system scan (like 2556 // the rest of the commands above) because there's precious little we 2557 // can do about it. A settings error is reported, though. 2558 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2559 false /* boot complete */); 2560 } 2561 2562 // Now that we know all the packages we are keeping, 2563 // read and update their last usage times. 2564 mPackageUsage.readLP(); 2565 2566 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2567 SystemClock.uptimeMillis()); 2568 Slog.i(TAG, "Time to scan packages: " 2569 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2570 + " seconds"); 2571 2572 // If the platform SDK has changed since the last time we booted, 2573 // we need to re-grant app permission to catch any new ones that 2574 // appear. This is really a hack, and means that apps can in some 2575 // cases get permissions that the user didn't initially explicitly 2576 // allow... it would be nice to have some better way to handle 2577 // this situation. 2578 int updateFlags = UPDATE_PERMISSIONS_ALL; 2579 if (ver.sdkVersion != mSdkVersion) { 2580 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2581 + mSdkVersion + "; regranting permissions for internal storage"); 2582 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2583 } 2584 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2585 ver.sdkVersion = mSdkVersion; 2586 2587 // If this is the first boot or an update from pre-M, and it is a normal 2588 // boot, then we need to initialize the default preferred apps across 2589 // all defined users. 2590 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2591 for (UserInfo user : sUserManager.getUsers(true)) { 2592 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2593 applyFactoryDefaultBrowserLPw(user.id); 2594 primeDomainVerificationsLPw(user.id); 2595 } 2596 } 2597 2598 // Prepare storage for system user really early during boot, 2599 // since core system apps like SettingsProvider and SystemUI 2600 // can't wait for user to start 2601 final int storageFlags; 2602 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2603 storageFlags = StorageManager.FLAG_STORAGE_DE; 2604 } else { 2605 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2606 } 2607 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2608 storageFlags); 2609 2610 // If this is first boot after an OTA, and a normal boot, then 2611 // we need to clear code cache directories. 2612 if (mIsUpgrade && !onlyCore) { 2613 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2614 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2615 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2616 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2617 // No apps are running this early, so no need to freeze 2618 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2619 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2620 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2621 } 2622 clearAppProfilesLIF(ps.pkg); 2623 } 2624 ver.fingerprint = Build.FINGERPRINT; 2625 } 2626 2627 checkDefaultBrowser(); 2628 2629 // clear only after permissions and other defaults have been updated 2630 mExistingSystemPackages.clear(); 2631 mPromoteSystemApps = false; 2632 2633 // All the changes are done during package scanning. 2634 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2635 2636 // can downgrade to reader 2637 mSettings.writeLPr(); 2638 2639 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2640 SystemClock.uptimeMillis()); 2641 2642 if (!mOnlyCore) { 2643 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2644 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2645 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2646 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2647 mIntentFilterVerifierComponent); 2648 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2649 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2650 getRequiredSharedLibraryLPr( 2651 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2652 } else { 2653 mRequiredVerifierPackage = null; 2654 mRequiredInstallerPackage = null; 2655 mIntentFilterVerifierComponent = null; 2656 mIntentFilterVerifier = null; 2657 mServicesSystemSharedLibraryPackageName = null; 2658 } 2659 2660 mInstallerService = new PackageInstallerService(context, this); 2661 2662 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2663 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2664 // both the installer and resolver must be present to enable ephemeral 2665 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2666 if (DEBUG_EPHEMERAL) { 2667 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2668 + " installer:" + ephemeralInstallerComponent); 2669 } 2670 mEphemeralResolverComponent = ephemeralResolverComponent; 2671 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2672 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2673 mEphemeralResolverConnection = 2674 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2675 } else { 2676 if (DEBUG_EPHEMERAL) { 2677 final String missingComponent = 2678 (ephemeralResolverComponent == null) 2679 ? (ephemeralInstallerComponent == null) 2680 ? "resolver and installer" 2681 : "resolver" 2682 : "installer"; 2683 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2684 } 2685 mEphemeralResolverComponent = null; 2686 mEphemeralInstallerComponent = null; 2687 mEphemeralResolverConnection = null; 2688 } 2689 2690 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2691 } // synchronized (mPackages) 2692 } // synchronized (mInstallLock) 2693 2694 // Now after opening every single application zip, make sure they 2695 // are all flushed. Not really needed, but keeps things nice and 2696 // tidy. 2697 Runtime.getRuntime().gc(); 2698 2699 // The initial scanning above does many calls into installd while 2700 // holding the mPackages lock, but we're mostly interested in yelling 2701 // once we have a booted system. 2702 mInstaller.setWarnIfHeld(mPackages); 2703 2704 // Expose private service for system components to use. 2705 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2706 } 2707 2708 @Override 2709 public boolean isFirstBoot() { 2710 return !mRestoredSettings; 2711 } 2712 2713 @Override 2714 public boolean isOnlyCoreApps() { 2715 return mOnlyCore; 2716 } 2717 2718 @Override 2719 public boolean isUpgrade() { 2720 return mIsUpgrade; 2721 } 2722 2723 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2724 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2725 2726 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2727 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2728 UserHandle.USER_SYSTEM); 2729 if (matches.size() == 1) { 2730 return matches.get(0).getComponentInfo().packageName; 2731 } else { 2732 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2733 return null; 2734 } 2735 } 2736 2737 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2738 synchronized (mPackages) { 2739 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2740 if (libraryEntry == null) { 2741 throw new IllegalStateException("Missing required shared library:" + libraryName); 2742 } 2743 return libraryEntry.apk; 2744 } 2745 } 2746 2747 private @NonNull String getRequiredInstallerLPr() { 2748 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2749 intent.addCategory(Intent.CATEGORY_DEFAULT); 2750 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2751 2752 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2753 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2754 UserHandle.USER_SYSTEM); 2755 if (matches.size() == 1) { 2756 ResolveInfo resolveInfo = matches.get(0); 2757 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2758 throw new RuntimeException("The installer must be a privileged app"); 2759 } 2760 return matches.get(0).getComponentInfo().packageName; 2761 } else { 2762 throw new RuntimeException("There must be exactly one installer; found " + matches); 2763 } 2764 } 2765 2766 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2767 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2768 2769 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2770 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2771 UserHandle.USER_SYSTEM); 2772 ResolveInfo best = null; 2773 final int N = matches.size(); 2774 for (int i = 0; i < N; i++) { 2775 final ResolveInfo cur = matches.get(i); 2776 final String packageName = cur.getComponentInfo().packageName; 2777 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2778 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2779 continue; 2780 } 2781 2782 if (best == null || cur.priority > best.priority) { 2783 best = cur; 2784 } 2785 } 2786 2787 if (best != null) { 2788 return best.getComponentInfo().getComponentName(); 2789 } else { 2790 throw new RuntimeException("There must be at least one intent filter verifier"); 2791 } 2792 } 2793 2794 private @Nullable ComponentName getEphemeralResolverLPr() { 2795 final String[] packageArray = 2796 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2797 if (packageArray.length == 0) { 2798 if (DEBUG_EPHEMERAL) { 2799 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2800 } 2801 return null; 2802 } 2803 2804 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2805 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2806 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2807 UserHandle.USER_SYSTEM); 2808 2809 final int N = resolvers.size(); 2810 if (N == 0) { 2811 if (DEBUG_EPHEMERAL) { 2812 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2813 } 2814 return null; 2815 } 2816 2817 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2818 for (int i = 0; i < N; i++) { 2819 final ResolveInfo info = resolvers.get(i); 2820 2821 if (info.serviceInfo == null) { 2822 continue; 2823 } 2824 2825 final String packageName = info.serviceInfo.packageName; 2826 if (!possiblePackages.contains(packageName)) { 2827 if (DEBUG_EPHEMERAL) { 2828 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2829 + " pkg: " + packageName + ", info:" + info); 2830 } 2831 continue; 2832 } 2833 2834 if (DEBUG_EPHEMERAL) { 2835 Slog.v(TAG, "Ephemeral resolver found;" 2836 + " pkg: " + packageName + ", info:" + info); 2837 } 2838 return new ComponentName(packageName, info.serviceInfo.name); 2839 } 2840 if (DEBUG_EPHEMERAL) { 2841 Slog.v(TAG, "Ephemeral resolver NOT found"); 2842 } 2843 return null; 2844 } 2845 2846 private @Nullable ComponentName getEphemeralInstallerLPr() { 2847 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2848 intent.addCategory(Intent.CATEGORY_DEFAULT); 2849 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2850 2851 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2852 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2853 UserHandle.USER_SYSTEM); 2854 if (matches.size() == 0) { 2855 return null; 2856 } else if (matches.size() == 1) { 2857 return matches.get(0).getComponentInfo().getComponentName(); 2858 } else { 2859 throw new RuntimeException( 2860 "There must be at most one ephemeral installer; found " + matches); 2861 } 2862 } 2863 2864 private void primeDomainVerificationsLPw(int userId) { 2865 if (DEBUG_DOMAIN_VERIFICATION) { 2866 Slog.d(TAG, "Priming domain verifications in user " + userId); 2867 } 2868 2869 SystemConfig systemConfig = SystemConfig.getInstance(); 2870 ArraySet<String> packages = systemConfig.getLinkedApps(); 2871 ArraySet<String> domains = new ArraySet<String>(); 2872 2873 for (String packageName : packages) { 2874 PackageParser.Package pkg = mPackages.get(packageName); 2875 if (pkg != null) { 2876 if (!pkg.isSystemApp()) { 2877 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2878 continue; 2879 } 2880 2881 domains.clear(); 2882 for (PackageParser.Activity a : pkg.activities) { 2883 for (ActivityIntentInfo filter : a.intents) { 2884 if (hasValidDomains(filter)) { 2885 domains.addAll(filter.getHostsList()); 2886 } 2887 } 2888 } 2889 2890 if (domains.size() > 0) { 2891 if (DEBUG_DOMAIN_VERIFICATION) { 2892 Slog.v(TAG, " + " + packageName); 2893 } 2894 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2895 // state w.r.t. the formal app-linkage "no verification attempted" state; 2896 // and then 'always' in the per-user state actually used for intent resolution. 2897 final IntentFilterVerificationInfo ivi; 2898 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2899 new ArrayList<String>(domains)); 2900 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2901 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2902 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2903 } else { 2904 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2905 + "' does not handle web links"); 2906 } 2907 } else { 2908 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2909 } 2910 } 2911 2912 scheduleWritePackageRestrictionsLocked(userId); 2913 scheduleWriteSettingsLocked(); 2914 } 2915 2916 private void applyFactoryDefaultBrowserLPw(int userId) { 2917 // The default browser app's package name is stored in a string resource, 2918 // with a product-specific overlay used for vendor customization. 2919 String browserPkg = mContext.getResources().getString( 2920 com.android.internal.R.string.default_browser); 2921 if (!TextUtils.isEmpty(browserPkg)) { 2922 // non-empty string => required to be a known package 2923 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2924 if (ps == null) { 2925 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2926 browserPkg = null; 2927 } else { 2928 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2929 } 2930 } 2931 2932 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2933 // default. If there's more than one, just leave everything alone. 2934 if (browserPkg == null) { 2935 calculateDefaultBrowserLPw(userId); 2936 } 2937 } 2938 2939 private void calculateDefaultBrowserLPw(int userId) { 2940 List<String> allBrowsers = resolveAllBrowserApps(userId); 2941 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2942 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2943 } 2944 2945 private List<String> resolveAllBrowserApps(int userId) { 2946 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2947 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2948 PackageManager.MATCH_ALL, userId); 2949 2950 final int count = list.size(); 2951 List<String> result = new ArrayList<String>(count); 2952 for (int i=0; i<count; i++) { 2953 ResolveInfo info = list.get(i); 2954 if (info.activityInfo == null 2955 || !info.handleAllWebDataURI 2956 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2957 || result.contains(info.activityInfo.packageName)) { 2958 continue; 2959 } 2960 result.add(info.activityInfo.packageName); 2961 } 2962 2963 return result; 2964 } 2965 2966 private boolean packageIsBrowser(String packageName, int userId) { 2967 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2968 PackageManager.MATCH_ALL, userId); 2969 final int N = list.size(); 2970 for (int i = 0; i < N; i++) { 2971 ResolveInfo info = list.get(i); 2972 if (packageName.equals(info.activityInfo.packageName)) { 2973 return true; 2974 } 2975 } 2976 return false; 2977 } 2978 2979 private void checkDefaultBrowser() { 2980 final int myUserId = UserHandle.myUserId(); 2981 final String packageName = getDefaultBrowserPackageName(myUserId); 2982 if (packageName != null) { 2983 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2984 if (info == null) { 2985 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2986 synchronized (mPackages) { 2987 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2988 } 2989 } 2990 } 2991 } 2992 2993 @Override 2994 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2995 throws RemoteException { 2996 try { 2997 return super.onTransact(code, data, reply, flags); 2998 } catch (RuntimeException e) { 2999 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3000 Slog.wtf(TAG, "Package Manager Crash", e); 3001 } 3002 throw e; 3003 } 3004 } 3005 3006 static int[] appendInts(int[] cur, int[] add) { 3007 if (add == null) return cur; 3008 if (cur == null) return add; 3009 final int N = add.length; 3010 for (int i=0; i<N; i++) { 3011 cur = appendInt(cur, add[i]); 3012 } 3013 return cur; 3014 } 3015 3016 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3017 if (!sUserManager.exists(userId)) return null; 3018 if (ps == null) { 3019 return null; 3020 } 3021 final PackageParser.Package p = ps.pkg; 3022 if (p == null) { 3023 return null; 3024 } 3025 3026 final PermissionsState permissionsState = ps.getPermissionsState(); 3027 3028 final int[] gids = permissionsState.computeGids(userId); 3029 final Set<String> permissions = permissionsState.getPermissions(userId); 3030 final PackageUserState state = ps.readUserState(userId); 3031 3032 return PackageParser.generatePackageInfo(p, gids, flags, 3033 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3034 } 3035 3036 @Override 3037 public void checkPackageStartable(String packageName, int userId) { 3038 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3039 3040 synchronized (mPackages) { 3041 final PackageSetting ps = mSettings.mPackages.get(packageName); 3042 if (ps == null) { 3043 throw new SecurityException("Package " + packageName + " was not found!"); 3044 } 3045 3046 if (!ps.getInstalled(userId)) { 3047 throw new SecurityException( 3048 "Package " + packageName + " was not installed for user " + userId + "!"); 3049 } 3050 3051 if (mSafeMode && !ps.isSystem()) { 3052 throw new SecurityException("Package " + packageName + " not a system app!"); 3053 } 3054 3055 if (mFrozenPackages.contains(packageName)) { 3056 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3057 } 3058 3059 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3060 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3061 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3062 } 3063 } 3064 } 3065 3066 @Override 3067 public boolean isPackageAvailable(String packageName, int userId) { 3068 if (!sUserManager.exists(userId)) return false; 3069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3070 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3071 synchronized (mPackages) { 3072 PackageParser.Package p = mPackages.get(packageName); 3073 if (p != null) { 3074 final PackageSetting ps = (PackageSetting) p.mExtras; 3075 if (ps != null) { 3076 final PackageUserState state = ps.readUserState(userId); 3077 if (state != null) { 3078 return PackageParser.isAvailable(state); 3079 } 3080 } 3081 } 3082 } 3083 return false; 3084 } 3085 3086 @Override 3087 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3088 if (!sUserManager.exists(userId)) return null; 3089 flags = updateFlagsForPackage(flags, userId, packageName); 3090 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3091 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3092 // reader 3093 synchronized (mPackages) { 3094 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3095 PackageParser.Package p = null; 3096 if (matchFactoryOnly) { 3097 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3098 if (ps != null) { 3099 return generatePackageInfo(ps, flags, userId); 3100 } 3101 } 3102 if (p == null) { 3103 p = mPackages.get(packageName); 3104 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3105 return null; 3106 } 3107 } 3108 if (DEBUG_PACKAGE_INFO) 3109 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3110 if (p != null) { 3111 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3112 } 3113 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3114 final PackageSetting ps = mSettings.mPackages.get(packageName); 3115 return generatePackageInfo(ps, flags, userId); 3116 } 3117 } 3118 return null; 3119 } 3120 3121 @Override 3122 public String[] currentToCanonicalPackageNames(String[] names) { 3123 String[] out = new String[names.length]; 3124 // reader 3125 synchronized (mPackages) { 3126 for (int i=names.length-1; i>=0; i--) { 3127 PackageSetting ps = mSettings.mPackages.get(names[i]); 3128 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3129 } 3130 } 3131 return out; 3132 } 3133 3134 @Override 3135 public String[] canonicalToCurrentPackageNames(String[] names) { 3136 String[] out = new String[names.length]; 3137 // reader 3138 synchronized (mPackages) { 3139 for (int i=names.length-1; i>=0; i--) { 3140 String cur = mSettings.mRenamedPackages.get(names[i]); 3141 out[i] = cur != null ? cur : names[i]; 3142 } 3143 } 3144 return out; 3145 } 3146 3147 @Override 3148 public int getPackageUid(String packageName, int flags, int userId) { 3149 if (!sUserManager.exists(userId)) return -1; 3150 flags = updateFlagsForPackage(flags, userId, packageName); 3151 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3152 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3153 3154 // reader 3155 synchronized (mPackages) { 3156 final PackageParser.Package p = mPackages.get(packageName); 3157 if (p != null && p.isMatch(flags)) { 3158 return UserHandle.getUid(userId, p.applicationInfo.uid); 3159 } 3160 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3161 final PackageSetting ps = mSettings.mPackages.get(packageName); 3162 if (ps != null && ps.isMatch(flags)) { 3163 return UserHandle.getUid(userId, ps.appId); 3164 } 3165 } 3166 } 3167 3168 return -1; 3169 } 3170 3171 @Override 3172 public int[] getPackageGids(String packageName, int flags, int userId) { 3173 if (!sUserManager.exists(userId)) return null; 3174 flags = updateFlagsForPackage(flags, userId, packageName); 3175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3176 false /* requireFullPermission */, false /* checkShell */, 3177 "getPackageGids"); 3178 3179 // reader 3180 synchronized (mPackages) { 3181 final PackageParser.Package p = mPackages.get(packageName); 3182 if (p != null && p.isMatch(flags)) { 3183 PackageSetting ps = (PackageSetting) p.mExtras; 3184 return ps.getPermissionsState().computeGids(userId); 3185 } 3186 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3187 final PackageSetting ps = mSettings.mPackages.get(packageName); 3188 if (ps != null && ps.isMatch(flags)) { 3189 return ps.getPermissionsState().computeGids(userId); 3190 } 3191 } 3192 } 3193 3194 return null; 3195 } 3196 3197 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3198 if (bp.perm != null) { 3199 return PackageParser.generatePermissionInfo(bp.perm, flags); 3200 } 3201 PermissionInfo pi = new PermissionInfo(); 3202 pi.name = bp.name; 3203 pi.packageName = bp.sourcePackage; 3204 pi.nonLocalizedLabel = bp.name; 3205 pi.protectionLevel = bp.protectionLevel; 3206 return pi; 3207 } 3208 3209 @Override 3210 public PermissionInfo getPermissionInfo(String name, int flags) { 3211 // reader 3212 synchronized (mPackages) { 3213 final BasePermission p = mSettings.mPermissions.get(name); 3214 if (p != null) { 3215 return generatePermissionInfo(p, flags); 3216 } 3217 return null; 3218 } 3219 } 3220 3221 @Override 3222 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3223 int flags) { 3224 // reader 3225 synchronized (mPackages) { 3226 if (group != null && !mPermissionGroups.containsKey(group)) { 3227 // This is thrown as NameNotFoundException 3228 return null; 3229 } 3230 3231 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3232 for (BasePermission p : mSettings.mPermissions.values()) { 3233 if (group == null) { 3234 if (p.perm == null || p.perm.info.group == null) { 3235 out.add(generatePermissionInfo(p, flags)); 3236 } 3237 } else { 3238 if (p.perm != null && group.equals(p.perm.info.group)) { 3239 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3240 } 3241 } 3242 } 3243 return new ParceledListSlice<>(out); 3244 } 3245 } 3246 3247 @Override 3248 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3249 // reader 3250 synchronized (mPackages) { 3251 return PackageParser.generatePermissionGroupInfo( 3252 mPermissionGroups.get(name), flags); 3253 } 3254 } 3255 3256 @Override 3257 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3258 // reader 3259 synchronized (mPackages) { 3260 final int N = mPermissionGroups.size(); 3261 ArrayList<PermissionGroupInfo> out 3262 = new ArrayList<PermissionGroupInfo>(N); 3263 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3264 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3265 } 3266 return new ParceledListSlice<>(out); 3267 } 3268 } 3269 3270 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3271 int userId) { 3272 if (!sUserManager.exists(userId)) return null; 3273 PackageSetting ps = mSettings.mPackages.get(packageName); 3274 if (ps != null) { 3275 if (ps.pkg == null) { 3276 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3277 if (pInfo != null) { 3278 return pInfo.applicationInfo; 3279 } 3280 return null; 3281 } 3282 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3283 ps.readUserState(userId), userId); 3284 } 3285 return null; 3286 } 3287 3288 @Override 3289 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3290 if (!sUserManager.exists(userId)) return null; 3291 flags = updateFlagsForApplication(flags, userId, packageName); 3292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3293 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3294 // writer 3295 synchronized (mPackages) { 3296 PackageParser.Package p = mPackages.get(packageName); 3297 if (DEBUG_PACKAGE_INFO) Log.v( 3298 TAG, "getApplicationInfo " + packageName 3299 + ": " + p); 3300 if (p != null) { 3301 PackageSetting ps = mSettings.mPackages.get(packageName); 3302 if (ps == null) return null; 3303 // Note: isEnabledLP() does not apply here - always return info 3304 return PackageParser.generateApplicationInfo( 3305 p, flags, ps.readUserState(userId), userId); 3306 } 3307 if ("android".equals(packageName)||"system".equals(packageName)) { 3308 return mAndroidApplication; 3309 } 3310 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3311 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3312 } 3313 } 3314 return null; 3315 } 3316 3317 @Override 3318 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3319 final IPackageDataObserver observer) { 3320 mContext.enforceCallingOrSelfPermission( 3321 android.Manifest.permission.CLEAR_APP_CACHE, null); 3322 // Queue up an async operation since clearing cache may take a little while. 3323 mHandler.post(new Runnable() { 3324 public void run() { 3325 mHandler.removeCallbacks(this); 3326 boolean success = true; 3327 synchronized (mInstallLock) { 3328 try { 3329 mInstaller.freeCache(volumeUuid, freeStorageSize); 3330 } catch (InstallerException e) { 3331 Slog.w(TAG, "Couldn't clear application caches: " + e); 3332 success = false; 3333 } 3334 } 3335 if (observer != null) { 3336 try { 3337 observer.onRemoveCompleted(null, success); 3338 } catch (RemoteException e) { 3339 Slog.w(TAG, "RemoveException when invoking call back"); 3340 } 3341 } 3342 } 3343 }); 3344 } 3345 3346 @Override 3347 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3348 final IntentSender pi) { 3349 mContext.enforceCallingOrSelfPermission( 3350 android.Manifest.permission.CLEAR_APP_CACHE, null); 3351 // Queue up an async operation since clearing cache may take a little while. 3352 mHandler.post(new Runnable() { 3353 public void run() { 3354 mHandler.removeCallbacks(this); 3355 boolean success = true; 3356 synchronized (mInstallLock) { 3357 try { 3358 mInstaller.freeCache(volumeUuid, freeStorageSize); 3359 } catch (InstallerException e) { 3360 Slog.w(TAG, "Couldn't clear application caches: " + e); 3361 success = false; 3362 } 3363 } 3364 if(pi != null) { 3365 try { 3366 // Callback via pending intent 3367 int code = success ? 1 : 0; 3368 pi.sendIntent(null, code, null, 3369 null, null); 3370 } catch (SendIntentException e1) { 3371 Slog.i(TAG, "Failed to send pending intent"); 3372 } 3373 } 3374 } 3375 }); 3376 } 3377 3378 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3379 synchronized (mInstallLock) { 3380 try { 3381 mInstaller.freeCache(volumeUuid, freeStorageSize); 3382 } catch (InstallerException e) { 3383 throw new IOException("Failed to free enough space", e); 3384 } 3385 } 3386 } 3387 3388 /** 3389 * Return if the user key is currently unlocked. 3390 */ 3391 private boolean isUserKeyUnlocked(int userId) { 3392 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3393 final IMountService mount = IMountService.Stub 3394 .asInterface(ServiceManager.getService("mount")); 3395 if (mount == null) { 3396 Slog.w(TAG, "Early during boot, assuming locked"); 3397 return false; 3398 } 3399 final long token = Binder.clearCallingIdentity(); 3400 try { 3401 return mount.isUserKeyUnlocked(userId); 3402 } catch (RemoteException e) { 3403 throw e.rethrowAsRuntimeException(); 3404 } finally { 3405 Binder.restoreCallingIdentity(token); 3406 } 3407 } else { 3408 return true; 3409 } 3410 } 3411 3412 /** 3413 * Update given flags based on encryption status of current user. 3414 */ 3415 private int updateFlags(int flags, int userId) { 3416 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3417 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3418 // Caller expressed an explicit opinion about what encryption 3419 // aware/unaware components they want to see, so fall through and 3420 // give them what they want 3421 } else { 3422 // Caller expressed no opinion, so match based on user state 3423 if (isUserKeyUnlocked(userId)) { 3424 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3425 } else { 3426 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3427 } 3428 } 3429 return flags; 3430 } 3431 3432 /** 3433 * Update given flags when being used to request {@link PackageInfo}. 3434 */ 3435 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3436 boolean triaged = true; 3437 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3438 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3439 // Caller is asking for component details, so they'd better be 3440 // asking for specific encryption matching behavior, or be triaged 3441 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3442 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3443 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3444 triaged = false; 3445 } 3446 } 3447 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3448 | PackageManager.MATCH_SYSTEM_ONLY 3449 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3450 triaged = false; 3451 } 3452 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3453 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3454 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3455 } 3456 return updateFlags(flags, userId); 3457 } 3458 3459 /** 3460 * Update given flags when being used to request {@link ApplicationInfo}. 3461 */ 3462 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3463 return updateFlagsForPackage(flags, userId, cookie); 3464 } 3465 3466 /** 3467 * Update given flags when being used to request {@link ComponentInfo}. 3468 */ 3469 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3470 if (cookie instanceof Intent) { 3471 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3472 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3473 } 3474 } 3475 3476 boolean triaged = true; 3477 // Caller is asking for component details, so they'd better be 3478 // asking for specific encryption matching behavior, or be triaged 3479 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3480 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3481 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3482 triaged = false; 3483 } 3484 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3485 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3486 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3487 } 3488 3489 return updateFlags(flags, userId); 3490 } 3491 3492 /** 3493 * Update given flags when being used to request {@link ResolveInfo}. 3494 */ 3495 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3496 // Safe mode means we shouldn't match any third-party components 3497 if (mSafeMode) { 3498 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3499 } 3500 3501 return updateFlagsForComponent(flags, userId, cookie); 3502 } 3503 3504 @Override 3505 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3506 if (!sUserManager.exists(userId)) return null; 3507 flags = updateFlagsForComponent(flags, userId, component); 3508 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3509 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3510 synchronized (mPackages) { 3511 PackageParser.Activity a = mActivities.mActivities.get(component); 3512 3513 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3514 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3515 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3516 if (ps == null) return null; 3517 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3518 userId); 3519 } 3520 if (mResolveComponentName.equals(component)) { 3521 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3522 new PackageUserState(), userId); 3523 } 3524 } 3525 return null; 3526 } 3527 3528 @Override 3529 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3530 String resolvedType) { 3531 synchronized (mPackages) { 3532 if (component.equals(mResolveComponentName)) { 3533 // The resolver supports EVERYTHING! 3534 return true; 3535 } 3536 PackageParser.Activity a = mActivities.mActivities.get(component); 3537 if (a == null) { 3538 return false; 3539 } 3540 for (int i=0; i<a.intents.size(); i++) { 3541 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3542 intent.getData(), intent.getCategories(), TAG) >= 0) { 3543 return true; 3544 } 3545 } 3546 return false; 3547 } 3548 } 3549 3550 @Override 3551 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3552 if (!sUserManager.exists(userId)) return null; 3553 flags = updateFlagsForComponent(flags, userId, component); 3554 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3555 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3556 synchronized (mPackages) { 3557 PackageParser.Activity a = mReceivers.mActivities.get(component); 3558 if (DEBUG_PACKAGE_INFO) Log.v( 3559 TAG, "getReceiverInfo " + component + ": " + a); 3560 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3561 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3562 if (ps == null) return null; 3563 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3564 userId); 3565 } 3566 } 3567 return null; 3568 } 3569 3570 @Override 3571 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3572 if (!sUserManager.exists(userId)) return null; 3573 flags = updateFlagsForComponent(flags, userId, component); 3574 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3575 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3576 synchronized (mPackages) { 3577 PackageParser.Service s = mServices.mServices.get(component); 3578 if (DEBUG_PACKAGE_INFO) Log.v( 3579 TAG, "getServiceInfo " + component + ": " + s); 3580 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3581 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3582 if (ps == null) return null; 3583 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3584 userId); 3585 } 3586 } 3587 return null; 3588 } 3589 3590 @Override 3591 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3592 if (!sUserManager.exists(userId)) return null; 3593 flags = updateFlagsForComponent(flags, userId, component); 3594 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3595 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3596 synchronized (mPackages) { 3597 PackageParser.Provider p = mProviders.mProviders.get(component); 3598 if (DEBUG_PACKAGE_INFO) Log.v( 3599 TAG, "getProviderInfo " + component + ": " + p); 3600 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3601 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3602 if (ps == null) return null; 3603 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3604 userId); 3605 } 3606 } 3607 return null; 3608 } 3609 3610 @Override 3611 public String[] getSystemSharedLibraryNames() { 3612 Set<String> libSet; 3613 synchronized (mPackages) { 3614 libSet = mSharedLibraries.keySet(); 3615 int size = libSet.size(); 3616 if (size > 0) { 3617 String[] libs = new String[size]; 3618 libSet.toArray(libs); 3619 return libs; 3620 } 3621 } 3622 return null; 3623 } 3624 3625 @Override 3626 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3627 synchronized (mPackages) { 3628 return mServicesSystemSharedLibraryPackageName; 3629 } 3630 } 3631 3632 @Override 3633 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3634 synchronized (mPackages) { 3635 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3636 3637 final FeatureInfo fi = new FeatureInfo(); 3638 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3639 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3640 res.add(fi); 3641 3642 return new ParceledListSlice<>(res); 3643 } 3644 } 3645 3646 @Override 3647 public boolean hasSystemFeature(String name, int version) { 3648 synchronized (mPackages) { 3649 final FeatureInfo feat = mAvailableFeatures.get(name); 3650 if (feat == null) { 3651 return false; 3652 } else { 3653 return feat.version >= version; 3654 } 3655 } 3656 } 3657 3658 @Override 3659 public int checkPermission(String permName, String pkgName, int userId) { 3660 if (!sUserManager.exists(userId)) { 3661 return PackageManager.PERMISSION_DENIED; 3662 } 3663 3664 synchronized (mPackages) { 3665 final PackageParser.Package p = mPackages.get(pkgName); 3666 if (p != null && p.mExtras != null) { 3667 final PackageSetting ps = (PackageSetting) p.mExtras; 3668 final PermissionsState permissionsState = ps.getPermissionsState(); 3669 if (permissionsState.hasPermission(permName, userId)) { 3670 return PackageManager.PERMISSION_GRANTED; 3671 } 3672 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3673 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3674 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3675 return PackageManager.PERMISSION_GRANTED; 3676 } 3677 } 3678 } 3679 3680 return PackageManager.PERMISSION_DENIED; 3681 } 3682 3683 @Override 3684 public int checkUidPermission(String permName, int uid) { 3685 final int userId = UserHandle.getUserId(uid); 3686 3687 if (!sUserManager.exists(userId)) { 3688 return PackageManager.PERMISSION_DENIED; 3689 } 3690 3691 synchronized (mPackages) { 3692 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3693 if (obj != null) { 3694 final SettingBase ps = (SettingBase) obj; 3695 final PermissionsState permissionsState = ps.getPermissionsState(); 3696 if (permissionsState.hasPermission(permName, userId)) { 3697 return PackageManager.PERMISSION_GRANTED; 3698 } 3699 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3700 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3701 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3702 return PackageManager.PERMISSION_GRANTED; 3703 } 3704 } else { 3705 ArraySet<String> perms = mSystemPermissions.get(uid); 3706 if (perms != null) { 3707 if (perms.contains(permName)) { 3708 return PackageManager.PERMISSION_GRANTED; 3709 } 3710 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3711 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3712 return PackageManager.PERMISSION_GRANTED; 3713 } 3714 } 3715 } 3716 } 3717 3718 return PackageManager.PERMISSION_DENIED; 3719 } 3720 3721 @Override 3722 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3723 if (UserHandle.getCallingUserId() != userId) { 3724 mContext.enforceCallingPermission( 3725 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3726 "isPermissionRevokedByPolicy for user " + userId); 3727 } 3728 3729 if (checkPermission(permission, packageName, userId) 3730 == PackageManager.PERMISSION_GRANTED) { 3731 return false; 3732 } 3733 3734 final long identity = Binder.clearCallingIdentity(); 3735 try { 3736 final int flags = getPermissionFlags(permission, packageName, userId); 3737 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3738 } finally { 3739 Binder.restoreCallingIdentity(identity); 3740 } 3741 } 3742 3743 @Override 3744 public String getPermissionControllerPackageName() { 3745 synchronized (mPackages) { 3746 return mRequiredInstallerPackage; 3747 } 3748 } 3749 3750 /** 3751 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3752 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3753 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3754 * @param message the message to log on security exception 3755 */ 3756 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3757 boolean checkShell, String message) { 3758 if (userId < 0) { 3759 throw new IllegalArgumentException("Invalid userId " + userId); 3760 } 3761 if (checkShell) { 3762 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3763 } 3764 if (userId == UserHandle.getUserId(callingUid)) return; 3765 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3766 if (requireFullPermission) { 3767 mContext.enforceCallingOrSelfPermission( 3768 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3769 } else { 3770 try { 3771 mContext.enforceCallingOrSelfPermission( 3772 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3773 } catch (SecurityException se) { 3774 mContext.enforceCallingOrSelfPermission( 3775 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3776 } 3777 } 3778 } 3779 } 3780 3781 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3782 if (callingUid == Process.SHELL_UID) { 3783 if (userHandle >= 0 3784 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3785 throw new SecurityException("Shell does not have permission to access user " 3786 + userHandle); 3787 } else if (userHandle < 0) { 3788 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3789 + Debug.getCallers(3)); 3790 } 3791 } 3792 } 3793 3794 private BasePermission findPermissionTreeLP(String permName) { 3795 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3796 if (permName.startsWith(bp.name) && 3797 permName.length() > bp.name.length() && 3798 permName.charAt(bp.name.length()) == '.') { 3799 return bp; 3800 } 3801 } 3802 return null; 3803 } 3804 3805 private BasePermission checkPermissionTreeLP(String permName) { 3806 if (permName != null) { 3807 BasePermission bp = findPermissionTreeLP(permName); 3808 if (bp != null) { 3809 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3810 return bp; 3811 } 3812 throw new SecurityException("Calling uid " 3813 + Binder.getCallingUid() 3814 + " is not allowed to add to permission tree " 3815 + bp.name + " owned by uid " + bp.uid); 3816 } 3817 } 3818 throw new SecurityException("No permission tree found for " + permName); 3819 } 3820 3821 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3822 if (s1 == null) { 3823 return s2 == null; 3824 } 3825 if (s2 == null) { 3826 return false; 3827 } 3828 if (s1.getClass() != s2.getClass()) { 3829 return false; 3830 } 3831 return s1.equals(s2); 3832 } 3833 3834 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3835 if (pi1.icon != pi2.icon) return false; 3836 if (pi1.logo != pi2.logo) return false; 3837 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3838 if (!compareStrings(pi1.name, pi2.name)) return false; 3839 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3840 // We'll take care of setting this one. 3841 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3842 // These are not currently stored in settings. 3843 //if (!compareStrings(pi1.group, pi2.group)) return false; 3844 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3845 //if (pi1.labelRes != pi2.labelRes) return false; 3846 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3847 return true; 3848 } 3849 3850 int permissionInfoFootprint(PermissionInfo info) { 3851 int size = info.name.length(); 3852 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3853 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3854 return size; 3855 } 3856 3857 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3858 int size = 0; 3859 for (BasePermission perm : mSettings.mPermissions.values()) { 3860 if (perm.uid == tree.uid) { 3861 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3862 } 3863 } 3864 return size; 3865 } 3866 3867 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3868 // We calculate the max size of permissions defined by this uid and throw 3869 // if that plus the size of 'info' would exceed our stated maximum. 3870 if (tree.uid != Process.SYSTEM_UID) { 3871 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3872 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3873 throw new SecurityException("Permission tree size cap exceeded"); 3874 } 3875 } 3876 } 3877 3878 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3879 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3880 throw new SecurityException("Label must be specified in permission"); 3881 } 3882 BasePermission tree = checkPermissionTreeLP(info.name); 3883 BasePermission bp = mSettings.mPermissions.get(info.name); 3884 boolean added = bp == null; 3885 boolean changed = true; 3886 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3887 if (added) { 3888 enforcePermissionCapLocked(info, tree); 3889 bp = new BasePermission(info.name, tree.sourcePackage, 3890 BasePermission.TYPE_DYNAMIC); 3891 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3892 throw new SecurityException( 3893 "Not allowed to modify non-dynamic permission " 3894 + info.name); 3895 } else { 3896 if (bp.protectionLevel == fixedLevel 3897 && bp.perm.owner.equals(tree.perm.owner) 3898 && bp.uid == tree.uid 3899 && comparePermissionInfos(bp.perm.info, info)) { 3900 changed = false; 3901 } 3902 } 3903 bp.protectionLevel = fixedLevel; 3904 info = new PermissionInfo(info); 3905 info.protectionLevel = fixedLevel; 3906 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3907 bp.perm.info.packageName = tree.perm.info.packageName; 3908 bp.uid = tree.uid; 3909 if (added) { 3910 mSettings.mPermissions.put(info.name, bp); 3911 } 3912 if (changed) { 3913 if (!async) { 3914 mSettings.writeLPr(); 3915 } else { 3916 scheduleWriteSettingsLocked(); 3917 } 3918 } 3919 return added; 3920 } 3921 3922 @Override 3923 public boolean addPermission(PermissionInfo info) { 3924 synchronized (mPackages) { 3925 return addPermissionLocked(info, false); 3926 } 3927 } 3928 3929 @Override 3930 public boolean addPermissionAsync(PermissionInfo info) { 3931 synchronized (mPackages) { 3932 return addPermissionLocked(info, true); 3933 } 3934 } 3935 3936 @Override 3937 public void removePermission(String name) { 3938 synchronized (mPackages) { 3939 checkPermissionTreeLP(name); 3940 BasePermission bp = mSettings.mPermissions.get(name); 3941 if (bp != null) { 3942 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3943 throw new SecurityException( 3944 "Not allowed to modify non-dynamic permission " 3945 + name); 3946 } 3947 mSettings.mPermissions.remove(name); 3948 mSettings.writeLPr(); 3949 } 3950 } 3951 } 3952 3953 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3954 BasePermission bp) { 3955 int index = pkg.requestedPermissions.indexOf(bp.name); 3956 if (index == -1) { 3957 throw new SecurityException("Package " + pkg.packageName 3958 + " has not requested permission " + bp.name); 3959 } 3960 if (!bp.isRuntime() && !bp.isDevelopment()) { 3961 throw new SecurityException("Permission " + bp.name 3962 + " is not a changeable permission type"); 3963 } 3964 } 3965 3966 @Override 3967 public void grantRuntimePermission(String packageName, String name, final int userId) { 3968 if (!sUserManager.exists(userId)) { 3969 Log.e(TAG, "No such user:" + userId); 3970 return; 3971 } 3972 3973 mContext.enforceCallingOrSelfPermission( 3974 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3975 "grantRuntimePermission"); 3976 3977 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3978 true /* requireFullPermission */, true /* checkShell */, 3979 "grantRuntimePermission"); 3980 3981 final int uid; 3982 final SettingBase sb; 3983 3984 synchronized (mPackages) { 3985 final PackageParser.Package pkg = mPackages.get(packageName); 3986 if (pkg == null) { 3987 throw new IllegalArgumentException("Unknown package: " + packageName); 3988 } 3989 3990 final BasePermission bp = mSettings.mPermissions.get(name); 3991 if (bp == null) { 3992 throw new IllegalArgumentException("Unknown permission: " + name); 3993 } 3994 3995 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3996 3997 // If a permission review is required for legacy apps we represent 3998 // their permissions as always granted runtime ones since we need 3999 // to keep the review required permission flag per user while an 4000 // install permission's state is shared across all users. 4001 if (Build.PERMISSIONS_REVIEW_REQUIRED 4002 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4003 && bp.isRuntime()) { 4004 return; 4005 } 4006 4007 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4008 sb = (SettingBase) pkg.mExtras; 4009 if (sb == null) { 4010 throw new IllegalArgumentException("Unknown package: " + packageName); 4011 } 4012 4013 final PermissionsState permissionsState = sb.getPermissionsState(); 4014 4015 final int flags = permissionsState.getPermissionFlags(name, userId); 4016 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4017 throw new SecurityException("Cannot grant system fixed permission " 4018 + name + " for package " + packageName); 4019 } 4020 4021 if (bp.isDevelopment()) { 4022 // Development permissions must be handled specially, since they are not 4023 // normal runtime permissions. For now they apply to all users. 4024 if (permissionsState.grantInstallPermission(bp) != 4025 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4026 scheduleWriteSettingsLocked(); 4027 } 4028 return; 4029 } 4030 4031 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4032 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4033 return; 4034 } 4035 4036 final int result = permissionsState.grantRuntimePermission(bp, userId); 4037 switch (result) { 4038 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4039 return; 4040 } 4041 4042 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4043 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4044 mHandler.post(new Runnable() { 4045 @Override 4046 public void run() { 4047 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4048 } 4049 }); 4050 } 4051 break; 4052 } 4053 4054 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4055 4056 // Not critical if that is lost - app has to request again. 4057 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4058 } 4059 4060 // Only need to do this if user is initialized. Otherwise it's a new user 4061 // and there are no processes running as the user yet and there's no need 4062 // to make an expensive call to remount processes for the changed permissions. 4063 if (READ_EXTERNAL_STORAGE.equals(name) 4064 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4065 final long token = Binder.clearCallingIdentity(); 4066 try { 4067 if (sUserManager.isInitialized(userId)) { 4068 MountServiceInternal mountServiceInternal = LocalServices.getService( 4069 MountServiceInternal.class); 4070 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4071 } 4072 } finally { 4073 Binder.restoreCallingIdentity(token); 4074 } 4075 } 4076 } 4077 4078 @Override 4079 public void revokeRuntimePermission(String packageName, String name, int userId) { 4080 if (!sUserManager.exists(userId)) { 4081 Log.e(TAG, "No such user:" + userId); 4082 return; 4083 } 4084 4085 mContext.enforceCallingOrSelfPermission( 4086 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4087 "revokeRuntimePermission"); 4088 4089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4090 true /* requireFullPermission */, true /* checkShell */, 4091 "revokeRuntimePermission"); 4092 4093 final int appId; 4094 4095 synchronized (mPackages) { 4096 final PackageParser.Package pkg = mPackages.get(packageName); 4097 if (pkg == null) { 4098 throw new IllegalArgumentException("Unknown package: " + packageName); 4099 } 4100 4101 final BasePermission bp = mSettings.mPermissions.get(name); 4102 if (bp == null) { 4103 throw new IllegalArgumentException("Unknown permission: " + name); 4104 } 4105 4106 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4107 4108 // If a permission review is required for legacy apps we represent 4109 // their permissions as always granted runtime ones since we need 4110 // to keep the review required permission flag per user while an 4111 // install permission's state is shared across all users. 4112 if (Build.PERMISSIONS_REVIEW_REQUIRED 4113 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4114 && bp.isRuntime()) { 4115 return; 4116 } 4117 4118 SettingBase sb = (SettingBase) pkg.mExtras; 4119 if (sb == null) { 4120 throw new IllegalArgumentException("Unknown package: " + packageName); 4121 } 4122 4123 final PermissionsState permissionsState = sb.getPermissionsState(); 4124 4125 final int flags = permissionsState.getPermissionFlags(name, userId); 4126 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4127 throw new SecurityException("Cannot revoke system fixed permission " 4128 + name + " for package " + packageName); 4129 } 4130 4131 if (bp.isDevelopment()) { 4132 // Development permissions must be handled specially, since they are not 4133 // normal runtime permissions. For now they apply to all users. 4134 if (permissionsState.revokeInstallPermission(bp) != 4135 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4136 scheduleWriteSettingsLocked(); 4137 } 4138 return; 4139 } 4140 4141 if (permissionsState.revokeRuntimePermission(bp, userId) == 4142 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4143 return; 4144 } 4145 4146 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4147 4148 // Critical, after this call app should never have the permission. 4149 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4150 4151 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4152 } 4153 4154 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4155 } 4156 4157 @Override 4158 public void resetRuntimePermissions() { 4159 mContext.enforceCallingOrSelfPermission( 4160 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4161 "revokeRuntimePermission"); 4162 4163 int callingUid = Binder.getCallingUid(); 4164 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4165 mContext.enforceCallingOrSelfPermission( 4166 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4167 "resetRuntimePermissions"); 4168 } 4169 4170 synchronized (mPackages) { 4171 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4172 for (int userId : UserManagerService.getInstance().getUserIds()) { 4173 final int packageCount = mPackages.size(); 4174 for (int i = 0; i < packageCount; i++) { 4175 PackageParser.Package pkg = mPackages.valueAt(i); 4176 if (!(pkg.mExtras instanceof PackageSetting)) { 4177 continue; 4178 } 4179 PackageSetting ps = (PackageSetting) pkg.mExtras; 4180 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4181 } 4182 } 4183 } 4184 } 4185 4186 @Override 4187 public int getPermissionFlags(String name, String packageName, int userId) { 4188 if (!sUserManager.exists(userId)) { 4189 return 0; 4190 } 4191 4192 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4193 4194 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4195 true /* requireFullPermission */, false /* checkShell */, 4196 "getPermissionFlags"); 4197 4198 synchronized (mPackages) { 4199 final PackageParser.Package pkg = mPackages.get(packageName); 4200 if (pkg == null) { 4201 throw new IllegalArgumentException("Unknown package: " + packageName); 4202 } 4203 4204 final BasePermission bp = mSettings.mPermissions.get(name); 4205 if (bp == null) { 4206 throw new IllegalArgumentException("Unknown permission: " + name); 4207 } 4208 4209 SettingBase sb = (SettingBase) pkg.mExtras; 4210 if (sb == null) { 4211 throw new IllegalArgumentException("Unknown package: " + packageName); 4212 } 4213 4214 PermissionsState permissionsState = sb.getPermissionsState(); 4215 return permissionsState.getPermissionFlags(name, userId); 4216 } 4217 } 4218 4219 @Override 4220 public void updatePermissionFlags(String name, String packageName, int flagMask, 4221 int flagValues, int userId) { 4222 if (!sUserManager.exists(userId)) { 4223 return; 4224 } 4225 4226 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4227 4228 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4229 true /* requireFullPermission */, true /* checkShell */, 4230 "updatePermissionFlags"); 4231 4232 // Only the system can change these flags and nothing else. 4233 if (getCallingUid() != Process.SYSTEM_UID) { 4234 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4235 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4236 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4237 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4238 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4239 } 4240 4241 synchronized (mPackages) { 4242 final PackageParser.Package pkg = mPackages.get(packageName); 4243 if (pkg == null) { 4244 throw new IllegalArgumentException("Unknown package: " + packageName); 4245 } 4246 4247 final BasePermission bp = mSettings.mPermissions.get(name); 4248 if (bp == null) { 4249 throw new IllegalArgumentException("Unknown permission: " + name); 4250 } 4251 4252 SettingBase sb = (SettingBase) pkg.mExtras; 4253 if (sb == null) { 4254 throw new IllegalArgumentException("Unknown package: " + packageName); 4255 } 4256 4257 PermissionsState permissionsState = sb.getPermissionsState(); 4258 4259 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4260 4261 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4262 // Install and runtime permissions are stored in different places, 4263 // so figure out what permission changed and persist the change. 4264 if (permissionsState.getInstallPermissionState(name) != null) { 4265 scheduleWriteSettingsLocked(); 4266 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4267 || hadState) { 4268 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4269 } 4270 } 4271 } 4272 } 4273 4274 /** 4275 * Update the permission flags for all packages and runtime permissions of a user in order 4276 * to allow device or profile owner to remove POLICY_FIXED. 4277 */ 4278 @Override 4279 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4280 if (!sUserManager.exists(userId)) { 4281 return; 4282 } 4283 4284 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4285 4286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4287 true /* requireFullPermission */, true /* checkShell */, 4288 "updatePermissionFlagsForAllApps"); 4289 4290 // Only the system can change system fixed flags. 4291 if (getCallingUid() != Process.SYSTEM_UID) { 4292 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4293 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4294 } 4295 4296 synchronized (mPackages) { 4297 boolean changed = false; 4298 final int packageCount = mPackages.size(); 4299 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4300 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4301 SettingBase sb = (SettingBase) pkg.mExtras; 4302 if (sb == null) { 4303 continue; 4304 } 4305 PermissionsState permissionsState = sb.getPermissionsState(); 4306 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4307 userId, flagMask, flagValues); 4308 } 4309 if (changed) { 4310 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4311 } 4312 } 4313 } 4314 4315 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4316 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4317 != PackageManager.PERMISSION_GRANTED 4318 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4319 != PackageManager.PERMISSION_GRANTED) { 4320 throw new SecurityException(message + " requires " 4321 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4322 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4323 } 4324 } 4325 4326 @Override 4327 public boolean shouldShowRequestPermissionRationale(String permissionName, 4328 String packageName, int userId) { 4329 if (UserHandle.getCallingUserId() != userId) { 4330 mContext.enforceCallingPermission( 4331 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4332 "canShowRequestPermissionRationale for user " + userId); 4333 } 4334 4335 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4336 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4337 return false; 4338 } 4339 4340 if (checkPermission(permissionName, packageName, userId) 4341 == PackageManager.PERMISSION_GRANTED) { 4342 return false; 4343 } 4344 4345 final int flags; 4346 4347 final long identity = Binder.clearCallingIdentity(); 4348 try { 4349 flags = getPermissionFlags(permissionName, 4350 packageName, userId); 4351 } finally { 4352 Binder.restoreCallingIdentity(identity); 4353 } 4354 4355 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4356 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4357 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4358 4359 if ((flags & fixedFlags) != 0) { 4360 return false; 4361 } 4362 4363 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4364 } 4365 4366 @Override 4367 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4368 mContext.enforceCallingOrSelfPermission( 4369 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4370 "addOnPermissionsChangeListener"); 4371 4372 synchronized (mPackages) { 4373 mOnPermissionChangeListeners.addListenerLocked(listener); 4374 } 4375 } 4376 4377 @Override 4378 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4379 synchronized (mPackages) { 4380 mOnPermissionChangeListeners.removeListenerLocked(listener); 4381 } 4382 } 4383 4384 @Override 4385 public boolean isProtectedBroadcast(String actionName) { 4386 synchronized (mPackages) { 4387 if (mProtectedBroadcasts.contains(actionName)) { 4388 return true; 4389 } else if (actionName != null) { 4390 // TODO: remove these terrible hacks 4391 if (actionName.startsWith("android.net.netmon.lingerExpired") 4392 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4393 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4394 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4395 return true; 4396 } 4397 } 4398 } 4399 return false; 4400 } 4401 4402 @Override 4403 public int checkSignatures(String pkg1, String pkg2) { 4404 synchronized (mPackages) { 4405 final PackageParser.Package p1 = mPackages.get(pkg1); 4406 final PackageParser.Package p2 = mPackages.get(pkg2); 4407 if (p1 == null || p1.mExtras == null 4408 || p2 == null || p2.mExtras == null) { 4409 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4410 } 4411 return compareSignatures(p1.mSignatures, p2.mSignatures); 4412 } 4413 } 4414 4415 @Override 4416 public int checkUidSignatures(int uid1, int uid2) { 4417 // Map to base uids. 4418 uid1 = UserHandle.getAppId(uid1); 4419 uid2 = UserHandle.getAppId(uid2); 4420 // reader 4421 synchronized (mPackages) { 4422 Signature[] s1; 4423 Signature[] s2; 4424 Object obj = mSettings.getUserIdLPr(uid1); 4425 if (obj != null) { 4426 if (obj instanceof SharedUserSetting) { 4427 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4428 } else if (obj instanceof PackageSetting) { 4429 s1 = ((PackageSetting)obj).signatures.mSignatures; 4430 } else { 4431 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4432 } 4433 } else { 4434 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4435 } 4436 obj = mSettings.getUserIdLPr(uid2); 4437 if (obj != null) { 4438 if (obj instanceof SharedUserSetting) { 4439 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4440 } else if (obj instanceof PackageSetting) { 4441 s2 = ((PackageSetting)obj).signatures.mSignatures; 4442 } else { 4443 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4444 } 4445 } else { 4446 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4447 } 4448 return compareSignatures(s1, s2); 4449 } 4450 } 4451 4452 /** 4453 * This method should typically only be used when granting or revoking 4454 * permissions, since the app may immediately restart after this call. 4455 * <p> 4456 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4457 * guard your work against the app being relaunched. 4458 */ 4459 private void killUid(int appId, int userId, String reason) { 4460 final long identity = Binder.clearCallingIdentity(); 4461 try { 4462 IActivityManager am = ActivityManagerNative.getDefault(); 4463 if (am != null) { 4464 try { 4465 am.killUid(appId, userId, reason); 4466 } catch (RemoteException e) { 4467 /* ignore - same process */ 4468 } 4469 } 4470 } finally { 4471 Binder.restoreCallingIdentity(identity); 4472 } 4473 } 4474 4475 /** 4476 * Compares two sets of signatures. Returns: 4477 * <br /> 4478 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4479 * <br /> 4480 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4481 * <br /> 4482 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4483 * <br /> 4484 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4485 * <br /> 4486 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4487 */ 4488 static int compareSignatures(Signature[] s1, Signature[] s2) { 4489 if (s1 == null) { 4490 return s2 == null 4491 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4492 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4493 } 4494 4495 if (s2 == null) { 4496 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4497 } 4498 4499 if (s1.length != s2.length) { 4500 return PackageManager.SIGNATURE_NO_MATCH; 4501 } 4502 4503 // Since both signature sets are of size 1, we can compare without HashSets. 4504 if (s1.length == 1) { 4505 return s1[0].equals(s2[0]) ? 4506 PackageManager.SIGNATURE_MATCH : 4507 PackageManager.SIGNATURE_NO_MATCH; 4508 } 4509 4510 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4511 for (Signature sig : s1) { 4512 set1.add(sig); 4513 } 4514 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4515 for (Signature sig : s2) { 4516 set2.add(sig); 4517 } 4518 // Make sure s2 contains all signatures in s1. 4519 if (set1.equals(set2)) { 4520 return PackageManager.SIGNATURE_MATCH; 4521 } 4522 return PackageManager.SIGNATURE_NO_MATCH; 4523 } 4524 4525 /** 4526 * If the database version for this type of package (internal storage or 4527 * external storage) is less than the version where package signatures 4528 * were updated, return true. 4529 */ 4530 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4531 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4532 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4533 } 4534 4535 /** 4536 * Used for backward compatibility to make sure any packages with 4537 * certificate chains get upgraded to the new style. {@code existingSigs} 4538 * will be in the old format (since they were stored on disk from before the 4539 * system upgrade) and {@code scannedSigs} will be in the newer format. 4540 */ 4541 private int compareSignaturesCompat(PackageSignatures existingSigs, 4542 PackageParser.Package scannedPkg) { 4543 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4544 return PackageManager.SIGNATURE_NO_MATCH; 4545 } 4546 4547 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4548 for (Signature sig : existingSigs.mSignatures) { 4549 existingSet.add(sig); 4550 } 4551 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4552 for (Signature sig : scannedPkg.mSignatures) { 4553 try { 4554 Signature[] chainSignatures = sig.getChainSignatures(); 4555 for (Signature chainSig : chainSignatures) { 4556 scannedCompatSet.add(chainSig); 4557 } 4558 } catch (CertificateEncodingException e) { 4559 scannedCompatSet.add(sig); 4560 } 4561 } 4562 /* 4563 * Make sure the expanded scanned set contains all signatures in the 4564 * existing one. 4565 */ 4566 if (scannedCompatSet.equals(existingSet)) { 4567 // Migrate the old signatures to the new scheme. 4568 existingSigs.assignSignatures(scannedPkg.mSignatures); 4569 // The new KeySets will be re-added later in the scanning process. 4570 synchronized (mPackages) { 4571 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4572 } 4573 return PackageManager.SIGNATURE_MATCH; 4574 } 4575 return PackageManager.SIGNATURE_NO_MATCH; 4576 } 4577 4578 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4579 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4580 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4581 } 4582 4583 private int compareSignaturesRecover(PackageSignatures existingSigs, 4584 PackageParser.Package scannedPkg) { 4585 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4586 return PackageManager.SIGNATURE_NO_MATCH; 4587 } 4588 4589 String msg = null; 4590 try { 4591 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4592 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4593 + scannedPkg.packageName); 4594 return PackageManager.SIGNATURE_MATCH; 4595 } 4596 } catch (CertificateException e) { 4597 msg = e.getMessage(); 4598 } 4599 4600 logCriticalInfo(Log.INFO, 4601 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4602 return PackageManager.SIGNATURE_NO_MATCH; 4603 } 4604 4605 @Override 4606 public List<String> getAllPackages() { 4607 synchronized (mPackages) { 4608 return new ArrayList<String>(mPackages.keySet()); 4609 } 4610 } 4611 4612 @Override 4613 public String[] getPackagesForUid(int uid) { 4614 uid = UserHandle.getAppId(uid); 4615 // reader 4616 synchronized (mPackages) { 4617 Object obj = mSettings.getUserIdLPr(uid); 4618 if (obj instanceof SharedUserSetting) { 4619 final SharedUserSetting sus = (SharedUserSetting) obj; 4620 final int N = sus.packages.size(); 4621 final String[] res = new String[N]; 4622 final Iterator<PackageSetting> it = sus.packages.iterator(); 4623 int i = 0; 4624 while (it.hasNext()) { 4625 res[i++] = it.next().name; 4626 } 4627 return res; 4628 } else if (obj instanceof PackageSetting) { 4629 final PackageSetting ps = (PackageSetting) obj; 4630 return new String[] { ps.name }; 4631 } 4632 } 4633 return null; 4634 } 4635 4636 @Override 4637 public String getNameForUid(int uid) { 4638 // reader 4639 synchronized (mPackages) { 4640 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4641 if (obj instanceof SharedUserSetting) { 4642 final SharedUserSetting sus = (SharedUserSetting) obj; 4643 return sus.name + ":" + sus.userId; 4644 } else if (obj instanceof PackageSetting) { 4645 final PackageSetting ps = (PackageSetting) obj; 4646 return ps.name; 4647 } 4648 } 4649 return null; 4650 } 4651 4652 @Override 4653 public int getUidForSharedUser(String sharedUserName) { 4654 if(sharedUserName == null) { 4655 return -1; 4656 } 4657 // reader 4658 synchronized (mPackages) { 4659 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4660 if (suid == null) { 4661 return -1; 4662 } 4663 return suid.userId; 4664 } 4665 } 4666 4667 @Override 4668 public int getFlagsForUid(int uid) { 4669 synchronized (mPackages) { 4670 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4671 if (obj instanceof SharedUserSetting) { 4672 final SharedUserSetting sus = (SharedUserSetting) obj; 4673 return sus.pkgFlags; 4674 } else if (obj instanceof PackageSetting) { 4675 final PackageSetting ps = (PackageSetting) obj; 4676 return ps.pkgFlags; 4677 } 4678 } 4679 return 0; 4680 } 4681 4682 @Override 4683 public int getPrivateFlagsForUid(int uid) { 4684 synchronized (mPackages) { 4685 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4686 if (obj instanceof SharedUserSetting) { 4687 final SharedUserSetting sus = (SharedUserSetting) obj; 4688 return sus.pkgPrivateFlags; 4689 } else if (obj instanceof PackageSetting) { 4690 final PackageSetting ps = (PackageSetting) obj; 4691 return ps.pkgPrivateFlags; 4692 } 4693 } 4694 return 0; 4695 } 4696 4697 @Override 4698 public boolean isUidPrivileged(int uid) { 4699 uid = UserHandle.getAppId(uid); 4700 // reader 4701 synchronized (mPackages) { 4702 Object obj = mSettings.getUserIdLPr(uid); 4703 if (obj instanceof SharedUserSetting) { 4704 final SharedUserSetting sus = (SharedUserSetting) obj; 4705 final Iterator<PackageSetting> it = sus.packages.iterator(); 4706 while (it.hasNext()) { 4707 if (it.next().isPrivileged()) { 4708 return true; 4709 } 4710 } 4711 } else if (obj instanceof PackageSetting) { 4712 final PackageSetting ps = (PackageSetting) obj; 4713 return ps.isPrivileged(); 4714 } 4715 } 4716 return false; 4717 } 4718 4719 @Override 4720 public String[] getAppOpPermissionPackages(String permissionName) { 4721 synchronized (mPackages) { 4722 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4723 if (pkgs == null) { 4724 return null; 4725 } 4726 return pkgs.toArray(new String[pkgs.size()]); 4727 } 4728 } 4729 4730 @Override 4731 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4732 int flags, int userId) { 4733 try { 4734 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4735 4736 if (!sUserManager.exists(userId)) return null; 4737 flags = updateFlagsForResolve(flags, userId, intent); 4738 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4739 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4740 4741 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4742 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4743 flags, userId); 4744 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4745 4746 final ResolveInfo bestChoice = 4747 chooseBestActivity(intent, resolvedType, flags, query, userId); 4748 4749 if (isEphemeralAllowed(intent, query, userId)) { 4750 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4751 final EphemeralResolveInfo ai = 4752 getEphemeralResolveInfo(intent, resolvedType, userId); 4753 if (ai != null) { 4754 if (DEBUG_EPHEMERAL) { 4755 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4756 } 4757 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4758 bestChoice.ephemeralResolveInfo = ai; 4759 } 4760 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4761 } 4762 return bestChoice; 4763 } finally { 4764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4765 } 4766 } 4767 4768 @Override 4769 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4770 IntentFilter filter, int match, ComponentName activity) { 4771 final int userId = UserHandle.getCallingUserId(); 4772 if (DEBUG_PREFERRED) { 4773 Log.v(TAG, "setLastChosenActivity intent=" + intent 4774 + " resolvedType=" + resolvedType 4775 + " flags=" + flags 4776 + " filter=" + filter 4777 + " match=" + match 4778 + " activity=" + activity); 4779 filter.dump(new PrintStreamPrinter(System.out), " "); 4780 } 4781 intent.setComponent(null); 4782 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4783 userId); 4784 // Find any earlier preferred or last chosen entries and nuke them 4785 findPreferredActivity(intent, resolvedType, 4786 flags, query, 0, false, true, false, userId); 4787 // Add the new activity as the last chosen for this filter 4788 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4789 "Setting last chosen"); 4790 } 4791 4792 @Override 4793 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4794 final int userId = UserHandle.getCallingUserId(); 4795 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4796 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4797 userId); 4798 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4799 false, false, false, userId); 4800 } 4801 4802 4803 private boolean isEphemeralAllowed( 4804 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4805 // Short circuit and return early if possible. 4806 if (DISABLE_EPHEMERAL_APPS) { 4807 return false; 4808 } 4809 final int callingUser = UserHandle.getCallingUserId(); 4810 if (callingUser != UserHandle.USER_SYSTEM) { 4811 return false; 4812 } 4813 if (mEphemeralResolverConnection == null) { 4814 return false; 4815 } 4816 if (intent.getComponent() != null) { 4817 return false; 4818 } 4819 if (intent.getPackage() != null) { 4820 return false; 4821 } 4822 final boolean isWebUri = hasWebURI(intent); 4823 if (!isWebUri) { 4824 return false; 4825 } 4826 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4827 synchronized (mPackages) { 4828 final int count = resolvedActivites.size(); 4829 for (int n = 0; n < count; n++) { 4830 ResolveInfo info = resolvedActivites.get(n); 4831 String packageName = info.activityInfo.packageName; 4832 PackageSetting ps = mSettings.mPackages.get(packageName); 4833 if (ps != null) { 4834 // Try to get the status from User settings first 4835 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4836 int status = (int) (packedStatus >> 32); 4837 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4838 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4839 if (DEBUG_EPHEMERAL) { 4840 Slog.v(TAG, "DENY ephemeral apps;" 4841 + " pkg: " + packageName + ", status: " + status); 4842 } 4843 return false; 4844 } 4845 } 4846 } 4847 } 4848 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4849 return true; 4850 } 4851 4852 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4853 int userId) { 4854 MessageDigest digest = null; 4855 try { 4856 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4857 } catch (NoSuchAlgorithmException e) { 4858 // If we can't create a digest, ignore ephemeral apps. 4859 return null; 4860 } 4861 4862 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4863 final byte[] digestBytes = digest.digest(hostBytes); 4864 int shaPrefix = 4865 digestBytes[0] << 24 4866 | digestBytes[1] << 16 4867 | digestBytes[2] << 8 4868 | digestBytes[3] << 0; 4869 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4870 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4871 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4872 // No hash prefix match; there are no ephemeral apps for this domain. 4873 return null; 4874 } 4875 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4876 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4877 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4878 continue; 4879 } 4880 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4881 // No filters; this should never happen. 4882 if (filters.isEmpty()) { 4883 continue; 4884 } 4885 // We have a domain match; resolve the filters to see if anything matches. 4886 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4887 for (int j = filters.size() - 1; j >= 0; --j) { 4888 final EphemeralResolveIntentInfo intentInfo = 4889 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4890 ephemeralResolver.addFilter(intentInfo); 4891 } 4892 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4893 intent, resolvedType, false /*defaultOnly*/, userId); 4894 if (!matchedResolveInfoList.isEmpty()) { 4895 return matchedResolveInfoList.get(0); 4896 } 4897 } 4898 // Hash or filter mis-match; no ephemeral apps for this domain. 4899 return null; 4900 } 4901 4902 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4903 int flags, List<ResolveInfo> query, int userId) { 4904 if (query != null) { 4905 final int N = query.size(); 4906 if (N == 1) { 4907 return query.get(0); 4908 } else if (N > 1) { 4909 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4910 // If there is more than one activity with the same priority, 4911 // then let the user decide between them. 4912 ResolveInfo r0 = query.get(0); 4913 ResolveInfo r1 = query.get(1); 4914 if (DEBUG_INTENT_MATCHING || debug) { 4915 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4916 + r1.activityInfo.name + "=" + r1.priority); 4917 } 4918 // If the first activity has a higher priority, or a different 4919 // default, then it is always desirable to pick it. 4920 if (r0.priority != r1.priority 4921 || r0.preferredOrder != r1.preferredOrder 4922 || r0.isDefault != r1.isDefault) { 4923 return query.get(0); 4924 } 4925 // If we have saved a preference for a preferred activity for 4926 // this Intent, use that. 4927 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4928 flags, query, r0.priority, true, false, debug, userId); 4929 if (ri != null) { 4930 return ri; 4931 } 4932 ri = new ResolveInfo(mResolveInfo); 4933 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4934 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4935 ri.activityInfo.applicationInfo = new ApplicationInfo( 4936 ri.activityInfo.applicationInfo); 4937 if (userId != 0) { 4938 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4939 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4940 } 4941 // Make sure that the resolver is displayable in car mode 4942 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4943 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4944 return ri; 4945 } 4946 } 4947 return null; 4948 } 4949 4950 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4951 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4952 final int N = query.size(); 4953 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4954 .get(userId); 4955 // Get the list of persistent preferred activities that handle the intent 4956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4957 List<PersistentPreferredActivity> pprefs = ppir != null 4958 ? ppir.queryIntent(intent, resolvedType, 4959 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4960 : null; 4961 if (pprefs != null && pprefs.size() > 0) { 4962 final int M = pprefs.size(); 4963 for (int i=0; i<M; i++) { 4964 final PersistentPreferredActivity ppa = pprefs.get(i); 4965 if (DEBUG_PREFERRED || debug) { 4966 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4967 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4968 + "\n component=" + ppa.mComponent); 4969 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4970 } 4971 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4972 flags | MATCH_DISABLED_COMPONENTS, userId); 4973 if (DEBUG_PREFERRED || debug) { 4974 Slog.v(TAG, "Found persistent preferred activity:"); 4975 if (ai != null) { 4976 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4977 } else { 4978 Slog.v(TAG, " null"); 4979 } 4980 } 4981 if (ai == null) { 4982 // This previously registered persistent preferred activity 4983 // component is no longer known. Ignore it and do NOT remove it. 4984 continue; 4985 } 4986 for (int j=0; j<N; j++) { 4987 final ResolveInfo ri = query.get(j); 4988 if (!ri.activityInfo.applicationInfo.packageName 4989 .equals(ai.applicationInfo.packageName)) { 4990 continue; 4991 } 4992 if (!ri.activityInfo.name.equals(ai.name)) { 4993 continue; 4994 } 4995 // Found a persistent preference that can handle the intent. 4996 if (DEBUG_PREFERRED || debug) { 4997 Slog.v(TAG, "Returning persistent preferred activity: " + 4998 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4999 } 5000 return ri; 5001 } 5002 } 5003 } 5004 return null; 5005 } 5006 5007 // TODO: handle preferred activities missing while user has amnesia 5008 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5009 List<ResolveInfo> query, int priority, boolean always, 5010 boolean removeMatches, boolean debug, int userId) { 5011 if (!sUserManager.exists(userId)) return null; 5012 flags = updateFlagsForResolve(flags, userId, intent); 5013 // writer 5014 synchronized (mPackages) { 5015 if (intent.getSelector() != null) { 5016 intent = intent.getSelector(); 5017 } 5018 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5019 5020 // Try to find a matching persistent preferred activity. 5021 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5022 debug, userId); 5023 5024 // If a persistent preferred activity matched, use it. 5025 if (pri != null) { 5026 return pri; 5027 } 5028 5029 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5030 // Get the list of preferred activities that handle the intent 5031 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5032 List<PreferredActivity> prefs = pir != null 5033 ? pir.queryIntent(intent, resolvedType, 5034 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5035 : null; 5036 if (prefs != null && prefs.size() > 0) { 5037 boolean changed = false; 5038 try { 5039 // First figure out how good the original match set is. 5040 // We will only allow preferred activities that came 5041 // from the same match quality. 5042 int match = 0; 5043 5044 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5045 5046 final int N = query.size(); 5047 for (int j=0; j<N; j++) { 5048 final ResolveInfo ri = query.get(j); 5049 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5050 + ": 0x" + Integer.toHexString(match)); 5051 if (ri.match > match) { 5052 match = ri.match; 5053 } 5054 } 5055 5056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5057 + Integer.toHexString(match)); 5058 5059 match &= IntentFilter.MATCH_CATEGORY_MASK; 5060 final int M = prefs.size(); 5061 for (int i=0; i<M; i++) { 5062 final PreferredActivity pa = prefs.get(i); 5063 if (DEBUG_PREFERRED || debug) { 5064 Slog.v(TAG, "Checking PreferredActivity ds=" 5065 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5066 + "\n component=" + pa.mPref.mComponent); 5067 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5068 } 5069 if (pa.mPref.mMatch != match) { 5070 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5071 + Integer.toHexString(pa.mPref.mMatch)); 5072 continue; 5073 } 5074 // If it's not an "always" type preferred activity and that's what we're 5075 // looking for, skip it. 5076 if (always && !pa.mPref.mAlways) { 5077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5078 continue; 5079 } 5080 final ActivityInfo ai = getActivityInfo( 5081 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5082 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5083 userId); 5084 if (DEBUG_PREFERRED || debug) { 5085 Slog.v(TAG, "Found preferred activity:"); 5086 if (ai != null) { 5087 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5088 } else { 5089 Slog.v(TAG, " null"); 5090 } 5091 } 5092 if (ai == null) { 5093 // This previously registered preferred activity 5094 // component is no longer known. Most likely an update 5095 // to the app was installed and in the new version this 5096 // component no longer exists. Clean it up by removing 5097 // it from the preferred activities list, and skip it. 5098 Slog.w(TAG, "Removing dangling preferred activity: " 5099 + pa.mPref.mComponent); 5100 pir.removeFilter(pa); 5101 changed = true; 5102 continue; 5103 } 5104 for (int j=0; j<N; j++) { 5105 final ResolveInfo ri = query.get(j); 5106 if (!ri.activityInfo.applicationInfo.packageName 5107 .equals(ai.applicationInfo.packageName)) { 5108 continue; 5109 } 5110 if (!ri.activityInfo.name.equals(ai.name)) { 5111 continue; 5112 } 5113 5114 if (removeMatches) { 5115 pir.removeFilter(pa); 5116 changed = true; 5117 if (DEBUG_PREFERRED) { 5118 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5119 } 5120 break; 5121 } 5122 5123 // Okay we found a previously set preferred or last chosen app. 5124 // If the result set is different from when this 5125 // was created, we need to clear it and re-ask the 5126 // user their preference, if we're looking for an "always" type entry. 5127 if (always && !pa.mPref.sameSet(query)) { 5128 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5129 + intent + " type " + resolvedType); 5130 if (DEBUG_PREFERRED) { 5131 Slog.v(TAG, "Removing preferred activity since set changed " 5132 + pa.mPref.mComponent); 5133 } 5134 pir.removeFilter(pa); 5135 // Re-add the filter as a "last chosen" entry (!always) 5136 PreferredActivity lastChosen = new PreferredActivity( 5137 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5138 pir.addFilter(lastChosen); 5139 changed = true; 5140 return null; 5141 } 5142 5143 // Yay! Either the set matched or we're looking for the last chosen 5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5145 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5146 return ri; 5147 } 5148 } 5149 } finally { 5150 if (changed) { 5151 if (DEBUG_PREFERRED) { 5152 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5153 } 5154 scheduleWritePackageRestrictionsLocked(userId); 5155 } 5156 } 5157 } 5158 } 5159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5160 return null; 5161 } 5162 5163 /* 5164 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5165 */ 5166 @Override 5167 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5168 int targetUserId) { 5169 mContext.enforceCallingOrSelfPermission( 5170 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5171 List<CrossProfileIntentFilter> matches = 5172 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5173 if (matches != null) { 5174 int size = matches.size(); 5175 for (int i = 0; i < size; i++) { 5176 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5177 } 5178 } 5179 if (hasWebURI(intent)) { 5180 // cross-profile app linking works only towards the parent. 5181 final UserInfo parent = getProfileParent(sourceUserId); 5182 synchronized(mPackages) { 5183 int flags = updateFlagsForResolve(0, parent.id, intent); 5184 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5185 intent, resolvedType, flags, sourceUserId, parent.id); 5186 return xpDomainInfo != null; 5187 } 5188 } 5189 return false; 5190 } 5191 5192 private UserInfo getProfileParent(int userId) { 5193 final long identity = Binder.clearCallingIdentity(); 5194 try { 5195 return sUserManager.getProfileParent(userId); 5196 } finally { 5197 Binder.restoreCallingIdentity(identity); 5198 } 5199 } 5200 5201 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5202 String resolvedType, int userId) { 5203 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5204 if (resolver != null) { 5205 return resolver.queryIntent(intent, resolvedType, false, userId); 5206 } 5207 return null; 5208 } 5209 5210 @Override 5211 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5212 String resolvedType, int flags, int userId) { 5213 try { 5214 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5215 5216 return new ParceledListSlice<>( 5217 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5218 } finally { 5219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5220 } 5221 } 5222 5223 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5224 String resolvedType, int flags, int userId) { 5225 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5226 flags = updateFlagsForResolve(flags, userId, intent); 5227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5228 false /* requireFullPermission */, false /* checkShell */, 5229 "query intent activities"); 5230 ComponentName comp = intent.getComponent(); 5231 if (comp == null) { 5232 if (intent.getSelector() != null) { 5233 intent = intent.getSelector(); 5234 comp = intent.getComponent(); 5235 } 5236 } 5237 5238 if (comp != null) { 5239 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5240 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5241 if (ai != null) { 5242 final ResolveInfo ri = new ResolveInfo(); 5243 ri.activityInfo = ai; 5244 list.add(ri); 5245 } 5246 return list; 5247 } 5248 5249 // reader 5250 synchronized (mPackages) { 5251 final String pkgName = intent.getPackage(); 5252 if (pkgName == null) { 5253 List<CrossProfileIntentFilter> matchingFilters = 5254 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5255 // Check for results that need to skip the current profile. 5256 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5257 resolvedType, flags, userId); 5258 if (xpResolveInfo != null) { 5259 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5260 result.add(xpResolveInfo); 5261 return filterIfNotSystemUser(result, userId); 5262 } 5263 5264 // Check for results in the current profile. 5265 List<ResolveInfo> result = mActivities.queryIntent( 5266 intent, resolvedType, flags, userId); 5267 result = filterIfNotSystemUser(result, userId); 5268 5269 // Check for cross profile results. 5270 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5271 xpResolveInfo = queryCrossProfileIntents( 5272 matchingFilters, intent, resolvedType, flags, userId, 5273 hasNonNegativePriorityResult); 5274 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5275 boolean isVisibleToUser = filterIfNotSystemUser( 5276 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5277 if (isVisibleToUser) { 5278 result.add(xpResolveInfo); 5279 Collections.sort(result, mResolvePrioritySorter); 5280 } 5281 } 5282 if (hasWebURI(intent)) { 5283 CrossProfileDomainInfo xpDomainInfo = null; 5284 final UserInfo parent = getProfileParent(userId); 5285 if (parent != null) { 5286 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5287 flags, userId, parent.id); 5288 } 5289 if (xpDomainInfo != null) { 5290 if (xpResolveInfo != null) { 5291 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5292 // in the result. 5293 result.remove(xpResolveInfo); 5294 } 5295 if (result.size() == 0) { 5296 result.add(xpDomainInfo.resolveInfo); 5297 return result; 5298 } 5299 } else if (result.size() <= 1) { 5300 return result; 5301 } 5302 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5303 xpDomainInfo, userId); 5304 Collections.sort(result, mResolvePrioritySorter); 5305 } 5306 return result; 5307 } 5308 final PackageParser.Package pkg = mPackages.get(pkgName); 5309 if (pkg != null) { 5310 return filterIfNotSystemUser( 5311 mActivities.queryIntentForPackage( 5312 intent, resolvedType, flags, pkg.activities, userId), 5313 userId); 5314 } 5315 return new ArrayList<ResolveInfo>(); 5316 } 5317 } 5318 5319 private static class CrossProfileDomainInfo { 5320 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5321 ResolveInfo resolveInfo; 5322 /* Best domain verification status of the activities found in the other profile */ 5323 int bestDomainVerificationStatus; 5324 } 5325 5326 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5327 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5328 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5329 sourceUserId)) { 5330 return null; 5331 } 5332 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5333 resolvedType, flags, parentUserId); 5334 5335 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5336 return null; 5337 } 5338 CrossProfileDomainInfo result = null; 5339 int size = resultTargetUser.size(); 5340 for (int i = 0; i < size; i++) { 5341 ResolveInfo riTargetUser = resultTargetUser.get(i); 5342 // Intent filter verification is only for filters that specify a host. So don't return 5343 // those that handle all web uris. 5344 if (riTargetUser.handleAllWebDataURI) { 5345 continue; 5346 } 5347 String packageName = riTargetUser.activityInfo.packageName; 5348 PackageSetting ps = mSettings.mPackages.get(packageName); 5349 if (ps == null) { 5350 continue; 5351 } 5352 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5353 int status = (int)(verificationState >> 32); 5354 if (result == null) { 5355 result = new CrossProfileDomainInfo(); 5356 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5357 sourceUserId, parentUserId); 5358 result.bestDomainVerificationStatus = status; 5359 } else { 5360 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5361 result.bestDomainVerificationStatus); 5362 } 5363 } 5364 // Don't consider matches with status NEVER across profiles. 5365 if (result != null && result.bestDomainVerificationStatus 5366 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5367 return null; 5368 } 5369 return result; 5370 } 5371 5372 /** 5373 * Verification statuses are ordered from the worse to the best, except for 5374 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5375 */ 5376 private int bestDomainVerificationStatus(int status1, int status2) { 5377 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5378 return status2; 5379 } 5380 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5381 return status1; 5382 } 5383 return (int) MathUtils.max(status1, status2); 5384 } 5385 5386 private boolean isUserEnabled(int userId) { 5387 long callingId = Binder.clearCallingIdentity(); 5388 try { 5389 UserInfo userInfo = sUserManager.getUserInfo(userId); 5390 return userInfo != null && userInfo.isEnabled(); 5391 } finally { 5392 Binder.restoreCallingIdentity(callingId); 5393 } 5394 } 5395 5396 /** 5397 * Filter out activities with systemUserOnly flag set, when current user is not System. 5398 * 5399 * @return filtered list 5400 */ 5401 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5402 if (userId == UserHandle.USER_SYSTEM) { 5403 return resolveInfos; 5404 } 5405 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5406 ResolveInfo info = resolveInfos.get(i); 5407 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5408 resolveInfos.remove(i); 5409 } 5410 } 5411 return resolveInfos; 5412 } 5413 5414 /** 5415 * @param resolveInfos list of resolve infos in descending priority order 5416 * @return if the list contains a resolve info with non-negative priority 5417 */ 5418 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5419 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5420 } 5421 5422 private static boolean hasWebURI(Intent intent) { 5423 if (intent.getData() == null) { 5424 return false; 5425 } 5426 final String scheme = intent.getScheme(); 5427 if (TextUtils.isEmpty(scheme)) { 5428 return false; 5429 } 5430 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5431 } 5432 5433 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5434 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5435 int userId) { 5436 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5437 5438 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5439 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5440 candidates.size()); 5441 } 5442 5443 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5444 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5445 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5446 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5447 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5448 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5449 5450 synchronized (mPackages) { 5451 final int count = candidates.size(); 5452 // First, try to use linked apps. Partition the candidates into four lists: 5453 // one for the final results, one for the "do not use ever", one for "undefined status" 5454 // and finally one for "browser app type". 5455 for (int n=0; n<count; n++) { 5456 ResolveInfo info = candidates.get(n); 5457 String packageName = info.activityInfo.packageName; 5458 PackageSetting ps = mSettings.mPackages.get(packageName); 5459 if (ps != null) { 5460 // Add to the special match all list (Browser use case) 5461 if (info.handleAllWebDataURI) { 5462 matchAllList.add(info); 5463 continue; 5464 } 5465 // Try to get the status from User settings first 5466 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5467 int status = (int)(packedStatus >> 32); 5468 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5469 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5470 if (DEBUG_DOMAIN_VERIFICATION) { 5471 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5472 + " : linkgen=" + linkGeneration); 5473 } 5474 // Use link-enabled generation as preferredOrder, i.e. 5475 // prefer newly-enabled over earlier-enabled. 5476 info.preferredOrder = linkGeneration; 5477 alwaysList.add(info); 5478 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5479 if (DEBUG_DOMAIN_VERIFICATION) { 5480 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5481 } 5482 neverList.add(info); 5483 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5484 if (DEBUG_DOMAIN_VERIFICATION) { 5485 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5486 } 5487 alwaysAskList.add(info); 5488 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5489 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5490 if (DEBUG_DOMAIN_VERIFICATION) { 5491 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5492 } 5493 undefinedList.add(info); 5494 } 5495 } 5496 } 5497 5498 // We'll want to include browser possibilities in a few cases 5499 boolean includeBrowser = false; 5500 5501 // First try to add the "always" resolution(s) for the current user, if any 5502 if (alwaysList.size() > 0) { 5503 result.addAll(alwaysList); 5504 } else { 5505 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5506 result.addAll(undefinedList); 5507 // Maybe add one for the other profile. 5508 if (xpDomainInfo != null && ( 5509 xpDomainInfo.bestDomainVerificationStatus 5510 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5511 result.add(xpDomainInfo.resolveInfo); 5512 } 5513 includeBrowser = true; 5514 } 5515 5516 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5517 // If there were 'always' entries their preferred order has been set, so we also 5518 // back that off to make the alternatives equivalent 5519 if (alwaysAskList.size() > 0) { 5520 for (ResolveInfo i : result) { 5521 i.preferredOrder = 0; 5522 } 5523 result.addAll(alwaysAskList); 5524 includeBrowser = true; 5525 } 5526 5527 if (includeBrowser) { 5528 // Also add browsers (all of them or only the default one) 5529 if (DEBUG_DOMAIN_VERIFICATION) { 5530 Slog.v(TAG, " ...including browsers in candidate set"); 5531 } 5532 if ((matchFlags & MATCH_ALL) != 0) { 5533 result.addAll(matchAllList); 5534 } else { 5535 // Browser/generic handling case. If there's a default browser, go straight 5536 // to that (but only if there is no other higher-priority match). 5537 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5538 int maxMatchPrio = 0; 5539 ResolveInfo defaultBrowserMatch = null; 5540 final int numCandidates = matchAllList.size(); 5541 for (int n = 0; n < numCandidates; n++) { 5542 ResolveInfo info = matchAllList.get(n); 5543 // track the highest overall match priority... 5544 if (info.priority > maxMatchPrio) { 5545 maxMatchPrio = info.priority; 5546 } 5547 // ...and the highest-priority default browser match 5548 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5549 if (defaultBrowserMatch == null 5550 || (defaultBrowserMatch.priority < info.priority)) { 5551 if (debug) { 5552 Slog.v(TAG, "Considering default browser match " + info); 5553 } 5554 defaultBrowserMatch = info; 5555 } 5556 } 5557 } 5558 if (defaultBrowserMatch != null 5559 && defaultBrowserMatch.priority >= maxMatchPrio 5560 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5561 { 5562 if (debug) { 5563 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5564 } 5565 result.add(defaultBrowserMatch); 5566 } else { 5567 result.addAll(matchAllList); 5568 } 5569 } 5570 5571 // If there is nothing selected, add all candidates and remove the ones that the user 5572 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5573 if (result.size() == 0) { 5574 result.addAll(candidates); 5575 result.removeAll(neverList); 5576 } 5577 } 5578 } 5579 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5580 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5581 result.size()); 5582 for (ResolveInfo info : result) { 5583 Slog.v(TAG, " + " + info.activityInfo); 5584 } 5585 } 5586 return result; 5587 } 5588 5589 // Returns a packed value as a long: 5590 // 5591 // high 'int'-sized word: link status: undefined/ask/never/always. 5592 // low 'int'-sized word: relative priority among 'always' results. 5593 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5594 long result = ps.getDomainVerificationStatusForUser(userId); 5595 // if none available, get the master status 5596 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5597 if (ps.getIntentFilterVerificationInfo() != null) { 5598 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5599 } 5600 } 5601 return result; 5602 } 5603 5604 private ResolveInfo querySkipCurrentProfileIntents( 5605 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5606 int flags, int sourceUserId) { 5607 if (matchingFilters != null) { 5608 int size = matchingFilters.size(); 5609 for (int i = 0; i < size; i ++) { 5610 CrossProfileIntentFilter filter = matchingFilters.get(i); 5611 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5612 // Checking if there are activities in the target user that can handle the 5613 // intent. 5614 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5615 resolvedType, flags, sourceUserId); 5616 if (resolveInfo != null) { 5617 return resolveInfo; 5618 } 5619 } 5620 } 5621 } 5622 return null; 5623 } 5624 5625 // Return matching ResolveInfo in target user if any. 5626 private ResolveInfo queryCrossProfileIntents( 5627 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5628 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5629 if (matchingFilters != null) { 5630 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5631 // match the same intent. For performance reasons, it is better not to 5632 // run queryIntent twice for the same userId 5633 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5634 int size = matchingFilters.size(); 5635 for (int i = 0; i < size; i++) { 5636 CrossProfileIntentFilter filter = matchingFilters.get(i); 5637 int targetUserId = filter.getTargetUserId(); 5638 boolean skipCurrentProfile = 5639 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5640 boolean skipCurrentProfileIfNoMatchFound = 5641 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5642 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5643 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5644 // Checking if there are activities in the target user that can handle the 5645 // intent. 5646 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5647 resolvedType, flags, sourceUserId); 5648 if (resolveInfo != null) return resolveInfo; 5649 alreadyTriedUserIds.put(targetUserId, true); 5650 } 5651 } 5652 } 5653 return null; 5654 } 5655 5656 /** 5657 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5658 * will forward the intent to the filter's target user. 5659 * Otherwise, returns null. 5660 */ 5661 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5662 String resolvedType, int flags, int sourceUserId) { 5663 int targetUserId = filter.getTargetUserId(); 5664 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5665 resolvedType, flags, targetUserId); 5666 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5667 // If all the matches in the target profile are suspended, return null. 5668 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5669 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5670 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5671 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5672 targetUserId); 5673 } 5674 } 5675 } 5676 return null; 5677 } 5678 5679 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5680 int sourceUserId, int targetUserId) { 5681 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5682 long ident = Binder.clearCallingIdentity(); 5683 boolean targetIsProfile; 5684 try { 5685 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5686 } finally { 5687 Binder.restoreCallingIdentity(ident); 5688 } 5689 String className; 5690 if (targetIsProfile) { 5691 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5692 } else { 5693 className = FORWARD_INTENT_TO_PARENT; 5694 } 5695 ComponentName forwardingActivityComponentName = new ComponentName( 5696 mAndroidApplication.packageName, className); 5697 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5698 sourceUserId); 5699 if (!targetIsProfile) { 5700 forwardingActivityInfo.showUserIcon = targetUserId; 5701 forwardingResolveInfo.noResourceId = true; 5702 } 5703 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5704 forwardingResolveInfo.priority = 0; 5705 forwardingResolveInfo.preferredOrder = 0; 5706 forwardingResolveInfo.match = 0; 5707 forwardingResolveInfo.isDefault = true; 5708 forwardingResolveInfo.filter = filter; 5709 forwardingResolveInfo.targetUserId = targetUserId; 5710 return forwardingResolveInfo; 5711 } 5712 5713 @Override 5714 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5715 Intent[] specifics, String[] specificTypes, Intent intent, 5716 String resolvedType, int flags, int userId) { 5717 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5718 specificTypes, intent, resolvedType, flags, userId)); 5719 } 5720 5721 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5722 Intent[] specifics, String[] specificTypes, Intent intent, 5723 String resolvedType, int flags, int userId) { 5724 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5725 flags = updateFlagsForResolve(flags, userId, intent); 5726 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5727 false /* requireFullPermission */, false /* checkShell */, 5728 "query intent activity options"); 5729 final String resultsAction = intent.getAction(); 5730 5731 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5732 | PackageManager.GET_RESOLVED_FILTER, userId); 5733 5734 if (DEBUG_INTENT_MATCHING) { 5735 Log.v(TAG, "Query " + intent + ": " + results); 5736 } 5737 5738 int specificsPos = 0; 5739 int N; 5740 5741 // todo: note that the algorithm used here is O(N^2). This 5742 // isn't a problem in our current environment, but if we start running 5743 // into situations where we have more than 5 or 10 matches then this 5744 // should probably be changed to something smarter... 5745 5746 // First we go through and resolve each of the specific items 5747 // that were supplied, taking care of removing any corresponding 5748 // duplicate items in the generic resolve list. 5749 if (specifics != null) { 5750 for (int i=0; i<specifics.length; i++) { 5751 final Intent sintent = specifics[i]; 5752 if (sintent == null) { 5753 continue; 5754 } 5755 5756 if (DEBUG_INTENT_MATCHING) { 5757 Log.v(TAG, "Specific #" + i + ": " + sintent); 5758 } 5759 5760 String action = sintent.getAction(); 5761 if (resultsAction != null && resultsAction.equals(action)) { 5762 // If this action was explicitly requested, then don't 5763 // remove things that have it. 5764 action = null; 5765 } 5766 5767 ResolveInfo ri = null; 5768 ActivityInfo ai = null; 5769 5770 ComponentName comp = sintent.getComponent(); 5771 if (comp == null) { 5772 ri = resolveIntent( 5773 sintent, 5774 specificTypes != null ? specificTypes[i] : null, 5775 flags, userId); 5776 if (ri == null) { 5777 continue; 5778 } 5779 if (ri == mResolveInfo) { 5780 // ACK! Must do something better with this. 5781 } 5782 ai = ri.activityInfo; 5783 comp = new ComponentName(ai.applicationInfo.packageName, 5784 ai.name); 5785 } else { 5786 ai = getActivityInfo(comp, flags, userId); 5787 if (ai == null) { 5788 continue; 5789 } 5790 } 5791 5792 // Look for any generic query activities that are duplicates 5793 // of this specific one, and remove them from the results. 5794 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5795 N = results.size(); 5796 int j; 5797 for (j=specificsPos; j<N; j++) { 5798 ResolveInfo sri = results.get(j); 5799 if ((sri.activityInfo.name.equals(comp.getClassName()) 5800 && sri.activityInfo.applicationInfo.packageName.equals( 5801 comp.getPackageName())) 5802 || (action != null && sri.filter.matchAction(action))) { 5803 results.remove(j); 5804 if (DEBUG_INTENT_MATCHING) Log.v( 5805 TAG, "Removing duplicate item from " + j 5806 + " due to specific " + specificsPos); 5807 if (ri == null) { 5808 ri = sri; 5809 } 5810 j--; 5811 N--; 5812 } 5813 } 5814 5815 // Add this specific item to its proper place. 5816 if (ri == null) { 5817 ri = new ResolveInfo(); 5818 ri.activityInfo = ai; 5819 } 5820 results.add(specificsPos, ri); 5821 ri.specificIndex = i; 5822 specificsPos++; 5823 } 5824 } 5825 5826 // Now we go through the remaining generic results and remove any 5827 // duplicate actions that are found here. 5828 N = results.size(); 5829 for (int i=specificsPos; i<N-1; i++) { 5830 final ResolveInfo rii = results.get(i); 5831 if (rii.filter == null) { 5832 continue; 5833 } 5834 5835 // Iterate over all of the actions of this result's intent 5836 // filter... typically this should be just one. 5837 final Iterator<String> it = rii.filter.actionsIterator(); 5838 if (it == null) { 5839 continue; 5840 } 5841 while (it.hasNext()) { 5842 final String action = it.next(); 5843 if (resultsAction != null && resultsAction.equals(action)) { 5844 // If this action was explicitly requested, then don't 5845 // remove things that have it. 5846 continue; 5847 } 5848 for (int j=i+1; j<N; j++) { 5849 final ResolveInfo rij = results.get(j); 5850 if (rij.filter != null && rij.filter.hasAction(action)) { 5851 results.remove(j); 5852 if (DEBUG_INTENT_MATCHING) Log.v( 5853 TAG, "Removing duplicate item from " + j 5854 + " due to action " + action + " at " + i); 5855 j--; 5856 N--; 5857 } 5858 } 5859 } 5860 5861 // If the caller didn't request filter information, drop it now 5862 // so we don't have to marshall/unmarshall it. 5863 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5864 rii.filter = null; 5865 } 5866 } 5867 5868 // Filter out the caller activity if so requested. 5869 if (caller != null) { 5870 N = results.size(); 5871 for (int i=0; i<N; i++) { 5872 ActivityInfo ainfo = results.get(i).activityInfo; 5873 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5874 && caller.getClassName().equals(ainfo.name)) { 5875 results.remove(i); 5876 break; 5877 } 5878 } 5879 } 5880 5881 // If the caller didn't request filter information, 5882 // drop them now so we don't have to 5883 // marshall/unmarshall it. 5884 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5885 N = results.size(); 5886 for (int i=0; i<N; i++) { 5887 results.get(i).filter = null; 5888 } 5889 } 5890 5891 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5892 return results; 5893 } 5894 5895 @Override 5896 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5897 String resolvedType, int flags, int userId) { 5898 return new ParceledListSlice<>( 5899 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5900 } 5901 5902 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5903 String resolvedType, int flags, int userId) { 5904 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5905 flags = updateFlagsForResolve(flags, userId, intent); 5906 ComponentName comp = intent.getComponent(); 5907 if (comp == null) { 5908 if (intent.getSelector() != null) { 5909 intent = intent.getSelector(); 5910 comp = intent.getComponent(); 5911 } 5912 } 5913 if (comp != null) { 5914 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5915 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5916 if (ai != null) { 5917 ResolveInfo ri = new ResolveInfo(); 5918 ri.activityInfo = ai; 5919 list.add(ri); 5920 } 5921 return list; 5922 } 5923 5924 // reader 5925 synchronized (mPackages) { 5926 String pkgName = intent.getPackage(); 5927 if (pkgName == null) { 5928 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5929 } 5930 final PackageParser.Package pkg = mPackages.get(pkgName); 5931 if (pkg != null) { 5932 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5933 userId); 5934 } 5935 return Collections.emptyList(); 5936 } 5937 } 5938 5939 @Override 5940 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5941 if (!sUserManager.exists(userId)) return null; 5942 flags = updateFlagsForResolve(flags, userId, intent); 5943 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5944 if (query != null) { 5945 if (query.size() >= 1) { 5946 // If there is more than one service with the same priority, 5947 // just arbitrarily pick the first one. 5948 return query.get(0); 5949 } 5950 } 5951 return null; 5952 } 5953 5954 @Override 5955 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5956 String resolvedType, int flags, int userId) { 5957 return new ParceledListSlice<>( 5958 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5959 } 5960 5961 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5962 String resolvedType, int flags, int userId) { 5963 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5964 flags = updateFlagsForResolve(flags, userId, intent); 5965 ComponentName comp = intent.getComponent(); 5966 if (comp == null) { 5967 if (intent.getSelector() != null) { 5968 intent = intent.getSelector(); 5969 comp = intent.getComponent(); 5970 } 5971 } 5972 if (comp != null) { 5973 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5974 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5975 if (si != null) { 5976 final ResolveInfo ri = new ResolveInfo(); 5977 ri.serviceInfo = si; 5978 list.add(ri); 5979 } 5980 return list; 5981 } 5982 5983 // reader 5984 synchronized (mPackages) { 5985 String pkgName = intent.getPackage(); 5986 if (pkgName == null) { 5987 return mServices.queryIntent(intent, resolvedType, flags, userId); 5988 } 5989 final PackageParser.Package pkg = mPackages.get(pkgName); 5990 if (pkg != null) { 5991 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5992 userId); 5993 } 5994 return Collections.emptyList(); 5995 } 5996 } 5997 5998 @Override 5999 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6000 String resolvedType, int flags, int userId) { 6001 return new ParceledListSlice<>( 6002 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6003 } 6004 6005 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6006 Intent intent, String resolvedType, int flags, int userId) { 6007 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6008 flags = updateFlagsForResolve(flags, userId, intent); 6009 ComponentName comp = intent.getComponent(); 6010 if (comp == null) { 6011 if (intent.getSelector() != null) { 6012 intent = intent.getSelector(); 6013 comp = intent.getComponent(); 6014 } 6015 } 6016 if (comp != null) { 6017 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6018 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6019 if (pi != null) { 6020 final ResolveInfo ri = new ResolveInfo(); 6021 ri.providerInfo = pi; 6022 list.add(ri); 6023 } 6024 return list; 6025 } 6026 6027 // reader 6028 synchronized (mPackages) { 6029 String pkgName = intent.getPackage(); 6030 if (pkgName == null) { 6031 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6032 } 6033 final PackageParser.Package pkg = mPackages.get(pkgName); 6034 if (pkg != null) { 6035 return mProviders.queryIntentForPackage( 6036 intent, resolvedType, flags, pkg.providers, userId); 6037 } 6038 return Collections.emptyList(); 6039 } 6040 } 6041 6042 @Override 6043 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6044 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6045 flags = updateFlagsForPackage(flags, userId, null); 6046 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6047 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6048 true /* requireFullPermission */, false /* checkShell */, 6049 "get installed packages"); 6050 6051 // writer 6052 synchronized (mPackages) { 6053 ArrayList<PackageInfo> list; 6054 if (listUninstalled) { 6055 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6056 for (PackageSetting ps : mSettings.mPackages.values()) { 6057 final PackageInfo pi; 6058 if (ps.pkg != null) { 6059 pi = generatePackageInfo(ps, flags, userId); 6060 } else { 6061 pi = generatePackageInfo(ps, flags, userId); 6062 } 6063 if (pi != null) { 6064 list.add(pi); 6065 } 6066 } 6067 } else { 6068 list = new ArrayList<PackageInfo>(mPackages.size()); 6069 for (PackageParser.Package p : mPackages.values()) { 6070 final PackageInfo pi = 6071 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6072 if (pi != null) { 6073 list.add(pi); 6074 } 6075 } 6076 } 6077 6078 return new ParceledListSlice<PackageInfo>(list); 6079 } 6080 } 6081 6082 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6083 String[] permissions, boolean[] tmp, int flags, int userId) { 6084 int numMatch = 0; 6085 final PermissionsState permissionsState = ps.getPermissionsState(); 6086 for (int i=0; i<permissions.length; i++) { 6087 final String permission = permissions[i]; 6088 if (permissionsState.hasPermission(permission, userId)) { 6089 tmp[i] = true; 6090 numMatch++; 6091 } else { 6092 tmp[i] = false; 6093 } 6094 } 6095 if (numMatch == 0) { 6096 return; 6097 } 6098 final PackageInfo pi; 6099 if (ps.pkg != null) { 6100 pi = generatePackageInfo(ps, flags, userId); 6101 } else { 6102 pi = generatePackageInfo(ps, flags, userId); 6103 } 6104 // The above might return null in cases of uninstalled apps or install-state 6105 // skew across users/profiles. 6106 if (pi != null) { 6107 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6108 if (numMatch == permissions.length) { 6109 pi.requestedPermissions = permissions; 6110 } else { 6111 pi.requestedPermissions = new String[numMatch]; 6112 numMatch = 0; 6113 for (int i=0; i<permissions.length; i++) { 6114 if (tmp[i]) { 6115 pi.requestedPermissions[numMatch] = permissions[i]; 6116 numMatch++; 6117 } 6118 } 6119 } 6120 } 6121 list.add(pi); 6122 } 6123 } 6124 6125 @Override 6126 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6127 String[] permissions, int flags, int userId) { 6128 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6129 flags = updateFlagsForPackage(flags, userId, permissions); 6130 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6131 6132 // writer 6133 synchronized (mPackages) { 6134 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6135 boolean[] tmpBools = new boolean[permissions.length]; 6136 if (listUninstalled) { 6137 for (PackageSetting ps : mSettings.mPackages.values()) { 6138 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6139 } 6140 } else { 6141 for (PackageParser.Package pkg : mPackages.values()) { 6142 PackageSetting ps = (PackageSetting)pkg.mExtras; 6143 if (ps != null) { 6144 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6145 userId); 6146 } 6147 } 6148 } 6149 6150 return new ParceledListSlice<PackageInfo>(list); 6151 } 6152 } 6153 6154 @Override 6155 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6156 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6157 flags = updateFlagsForApplication(flags, userId, null); 6158 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6159 6160 // writer 6161 synchronized (mPackages) { 6162 ArrayList<ApplicationInfo> list; 6163 if (listUninstalled) { 6164 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6165 for (PackageSetting ps : mSettings.mPackages.values()) { 6166 ApplicationInfo ai; 6167 if (ps.pkg != null) { 6168 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6169 ps.readUserState(userId), userId); 6170 } else { 6171 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6172 } 6173 if (ai != null) { 6174 list.add(ai); 6175 } 6176 } 6177 } else { 6178 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6179 for (PackageParser.Package p : mPackages.values()) { 6180 if (p.mExtras != null) { 6181 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6182 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6183 if (ai != null) { 6184 list.add(ai); 6185 } 6186 } 6187 } 6188 } 6189 6190 return new ParceledListSlice<ApplicationInfo>(list); 6191 } 6192 } 6193 6194 @Override 6195 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6196 if (DISABLE_EPHEMERAL_APPS) { 6197 return null; 6198 } 6199 6200 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6201 "getEphemeralApplications"); 6202 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6203 true /* requireFullPermission */, false /* checkShell */, 6204 "getEphemeralApplications"); 6205 synchronized (mPackages) { 6206 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6207 .getEphemeralApplicationsLPw(userId); 6208 if (ephemeralApps != null) { 6209 return new ParceledListSlice<>(ephemeralApps); 6210 } 6211 } 6212 return null; 6213 } 6214 6215 @Override 6216 public boolean isEphemeralApplication(String packageName, int userId) { 6217 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6218 true /* requireFullPermission */, false /* checkShell */, 6219 "isEphemeral"); 6220 if (DISABLE_EPHEMERAL_APPS) { 6221 return false; 6222 } 6223 6224 if (!isCallerSameApp(packageName)) { 6225 return false; 6226 } 6227 synchronized (mPackages) { 6228 PackageParser.Package pkg = mPackages.get(packageName); 6229 if (pkg != null) { 6230 return pkg.applicationInfo.isEphemeralApp(); 6231 } 6232 } 6233 return false; 6234 } 6235 6236 @Override 6237 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6238 if (DISABLE_EPHEMERAL_APPS) { 6239 return null; 6240 } 6241 6242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6243 true /* requireFullPermission */, false /* checkShell */, 6244 "getCookie"); 6245 if (!isCallerSameApp(packageName)) { 6246 return null; 6247 } 6248 synchronized (mPackages) { 6249 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6250 packageName, userId); 6251 } 6252 } 6253 6254 @Override 6255 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6256 if (DISABLE_EPHEMERAL_APPS) { 6257 return true; 6258 } 6259 6260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6261 true /* requireFullPermission */, true /* checkShell */, 6262 "setCookie"); 6263 if (!isCallerSameApp(packageName)) { 6264 return false; 6265 } 6266 synchronized (mPackages) { 6267 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6268 packageName, cookie, userId); 6269 } 6270 } 6271 6272 @Override 6273 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6274 if (DISABLE_EPHEMERAL_APPS) { 6275 return null; 6276 } 6277 6278 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6279 "getEphemeralApplicationIcon"); 6280 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6281 true /* requireFullPermission */, false /* checkShell */, 6282 "getEphemeralApplicationIcon"); 6283 synchronized (mPackages) { 6284 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6285 packageName, userId); 6286 } 6287 } 6288 6289 private boolean isCallerSameApp(String packageName) { 6290 PackageParser.Package pkg = mPackages.get(packageName); 6291 return pkg != null 6292 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6293 } 6294 6295 @Override 6296 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6297 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6298 } 6299 6300 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6301 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6302 6303 // reader 6304 synchronized (mPackages) { 6305 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6306 final int userId = UserHandle.getCallingUserId(); 6307 while (i.hasNext()) { 6308 final PackageParser.Package p = i.next(); 6309 if (p.applicationInfo == null) continue; 6310 6311 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6312 && !p.applicationInfo.isDirectBootAware(); 6313 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6314 && p.applicationInfo.isDirectBootAware(); 6315 6316 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6317 && (!mSafeMode || isSystemApp(p)) 6318 && (matchesUnaware || matchesAware)) { 6319 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6320 if (ps != null) { 6321 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6322 ps.readUserState(userId), userId); 6323 if (ai != null) { 6324 finalList.add(ai); 6325 } 6326 } 6327 } 6328 } 6329 } 6330 6331 return finalList; 6332 } 6333 6334 @Override 6335 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6336 if (!sUserManager.exists(userId)) return null; 6337 flags = updateFlagsForComponent(flags, userId, name); 6338 // reader 6339 synchronized (mPackages) { 6340 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6341 PackageSetting ps = provider != null 6342 ? mSettings.mPackages.get(provider.owner.packageName) 6343 : null; 6344 return ps != null 6345 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6346 ? PackageParser.generateProviderInfo(provider, flags, 6347 ps.readUserState(userId), userId) 6348 : null; 6349 } 6350 } 6351 6352 /** 6353 * @deprecated 6354 */ 6355 @Deprecated 6356 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6357 // reader 6358 synchronized (mPackages) { 6359 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6360 .entrySet().iterator(); 6361 final int userId = UserHandle.getCallingUserId(); 6362 while (i.hasNext()) { 6363 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6364 PackageParser.Provider p = entry.getValue(); 6365 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6366 6367 if (ps != null && p.syncable 6368 && (!mSafeMode || (p.info.applicationInfo.flags 6369 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6370 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6371 ps.readUserState(userId), userId); 6372 if (info != null) { 6373 outNames.add(entry.getKey()); 6374 outInfo.add(info); 6375 } 6376 } 6377 } 6378 } 6379 } 6380 6381 @Override 6382 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6383 int uid, int flags) { 6384 final int userId = processName != null ? UserHandle.getUserId(uid) 6385 : UserHandle.getCallingUserId(); 6386 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6387 flags = updateFlagsForComponent(flags, userId, processName); 6388 6389 ArrayList<ProviderInfo> finalList = null; 6390 // reader 6391 synchronized (mPackages) { 6392 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6393 while (i.hasNext()) { 6394 final PackageParser.Provider p = i.next(); 6395 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6396 if (ps != null && p.info.authority != null 6397 && (processName == null 6398 || (p.info.processName.equals(processName) 6399 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6400 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6401 if (finalList == null) { 6402 finalList = new ArrayList<ProviderInfo>(3); 6403 } 6404 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6405 ps.readUserState(userId), userId); 6406 if (info != null) { 6407 finalList.add(info); 6408 } 6409 } 6410 } 6411 } 6412 6413 if (finalList != null) { 6414 Collections.sort(finalList, mProviderInitOrderSorter); 6415 return new ParceledListSlice<ProviderInfo>(finalList); 6416 } 6417 6418 return ParceledListSlice.emptyList(); 6419 } 6420 6421 @Override 6422 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6423 // reader 6424 synchronized (mPackages) { 6425 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6426 return PackageParser.generateInstrumentationInfo(i, flags); 6427 } 6428 } 6429 6430 @Override 6431 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6432 String targetPackage, int flags) { 6433 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6434 } 6435 6436 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6437 int flags) { 6438 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6439 6440 // reader 6441 synchronized (mPackages) { 6442 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6443 while (i.hasNext()) { 6444 final PackageParser.Instrumentation p = i.next(); 6445 if (targetPackage == null 6446 || targetPackage.equals(p.info.targetPackage)) { 6447 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6448 flags); 6449 if (ii != null) { 6450 finalList.add(ii); 6451 } 6452 } 6453 } 6454 } 6455 6456 return finalList; 6457 } 6458 6459 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6460 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6461 if (overlays == null) { 6462 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6463 return; 6464 } 6465 for (PackageParser.Package opkg : overlays.values()) { 6466 // Not much to do if idmap fails: we already logged the error 6467 // and we certainly don't want to abort installation of pkg simply 6468 // because an overlay didn't fit properly. For these reasons, 6469 // ignore the return value of createIdmapForPackagePairLI. 6470 createIdmapForPackagePairLI(pkg, opkg); 6471 } 6472 } 6473 6474 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6475 PackageParser.Package opkg) { 6476 if (!opkg.mTrustedOverlay) { 6477 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6478 opkg.baseCodePath + ": overlay not trusted"); 6479 return false; 6480 } 6481 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6482 if (overlaySet == null) { 6483 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6484 opkg.baseCodePath + " but target package has no known overlays"); 6485 return false; 6486 } 6487 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6488 // TODO: generate idmap for split APKs 6489 try { 6490 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6491 } catch (InstallerException e) { 6492 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6493 + opkg.baseCodePath); 6494 return false; 6495 } 6496 PackageParser.Package[] overlayArray = 6497 overlaySet.values().toArray(new PackageParser.Package[0]); 6498 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6499 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6500 return p1.mOverlayPriority - p2.mOverlayPriority; 6501 } 6502 }; 6503 Arrays.sort(overlayArray, cmp); 6504 6505 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6506 int i = 0; 6507 for (PackageParser.Package p : overlayArray) { 6508 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6509 } 6510 return true; 6511 } 6512 6513 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6514 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6515 try { 6516 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6517 } finally { 6518 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6519 } 6520 } 6521 6522 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6523 final File[] files = dir.listFiles(); 6524 if (ArrayUtils.isEmpty(files)) { 6525 Log.d(TAG, "No files in app dir " + dir); 6526 return; 6527 } 6528 6529 if (DEBUG_PACKAGE_SCANNING) { 6530 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6531 + " flags=0x" + Integer.toHexString(parseFlags)); 6532 } 6533 6534 for (File file : files) { 6535 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6536 && !PackageInstallerService.isStageName(file.getName()); 6537 if (!isPackage) { 6538 // Ignore entries which are not packages 6539 continue; 6540 } 6541 try { 6542 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6543 scanFlags, currentTime, null); 6544 } catch (PackageManagerException e) { 6545 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6546 6547 // Delete invalid userdata apps 6548 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6549 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6550 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6551 removeCodePathLI(file); 6552 } 6553 } 6554 } 6555 } 6556 6557 private static File getSettingsProblemFile() { 6558 File dataDir = Environment.getDataDirectory(); 6559 File systemDir = new File(dataDir, "system"); 6560 File fname = new File(systemDir, "uiderrors.txt"); 6561 return fname; 6562 } 6563 6564 static void reportSettingsProblem(int priority, String msg) { 6565 logCriticalInfo(priority, msg); 6566 } 6567 6568 static void logCriticalInfo(int priority, String msg) { 6569 Slog.println(priority, TAG, msg); 6570 EventLogTags.writePmCriticalInfo(msg); 6571 try { 6572 File fname = getSettingsProblemFile(); 6573 FileOutputStream out = new FileOutputStream(fname, true); 6574 PrintWriter pw = new FastPrintWriter(out); 6575 SimpleDateFormat formatter = new SimpleDateFormat(); 6576 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6577 pw.println(dateString + ": " + msg); 6578 pw.close(); 6579 FileUtils.setPermissions( 6580 fname.toString(), 6581 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6582 -1, -1); 6583 } catch (java.io.IOException e) { 6584 } 6585 } 6586 6587 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6588 final int policyFlags) throws PackageManagerException { 6589 if (ps != null 6590 && ps.codePath.equals(srcFile) 6591 && ps.timeStamp == srcFile.lastModified() 6592 && !isCompatSignatureUpdateNeeded(pkg) 6593 && !isRecoverSignatureUpdateNeeded(pkg)) { 6594 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6595 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6596 ArraySet<PublicKey> signingKs; 6597 synchronized (mPackages) { 6598 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6599 } 6600 if (ps.signatures.mSignatures != null 6601 && ps.signatures.mSignatures.length != 0 6602 && signingKs != null) { 6603 // Optimization: reuse the existing cached certificates 6604 // if the package appears to be unchanged. 6605 pkg.mSignatures = ps.signatures.mSignatures; 6606 pkg.mSigningKeys = signingKs; 6607 return; 6608 } 6609 6610 Slog.w(TAG, "PackageSetting for " + ps.name 6611 + " is missing signatures. Collecting certs again to recover them."); 6612 } else { 6613 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6614 } 6615 6616 try { 6617 PackageParser.collectCertificates(pkg, policyFlags); 6618 } catch (PackageParserException e) { 6619 throw PackageManagerException.from(e); 6620 } 6621 } 6622 6623 /** 6624 * Traces a package scan. 6625 * @see #scanPackageLI(File, int, int, long, UserHandle) 6626 */ 6627 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6628 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6630 try { 6631 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6632 } finally { 6633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6634 } 6635 } 6636 6637 /** 6638 * Scans a package and returns the newly parsed package. 6639 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6640 */ 6641 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6642 long currentTime, UserHandle user) throws PackageManagerException { 6643 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6644 PackageParser pp = new PackageParser(); 6645 pp.setSeparateProcesses(mSeparateProcesses); 6646 pp.setOnlyCoreApps(mOnlyCore); 6647 pp.setDisplayMetrics(mMetrics); 6648 6649 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6650 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6651 } 6652 6653 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6654 final PackageParser.Package pkg; 6655 try { 6656 pkg = pp.parsePackage(scanFile, parseFlags); 6657 } catch (PackageParserException e) { 6658 throw PackageManagerException.from(e); 6659 } finally { 6660 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6661 } 6662 6663 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6664 } 6665 6666 /** 6667 * Scans a package and returns the newly parsed package. 6668 * @throws PackageManagerException on a parse error. 6669 */ 6670 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6671 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6672 throws PackageManagerException { 6673 // If the package has children and this is the first dive in the function 6674 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6675 // packages (parent and children) would be successfully scanned before the 6676 // actual scan since scanning mutates internal state and we want to atomically 6677 // install the package and its children. 6678 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6679 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6680 scanFlags |= SCAN_CHECK_ONLY; 6681 } 6682 } else { 6683 scanFlags &= ~SCAN_CHECK_ONLY; 6684 } 6685 6686 // Scan the parent 6687 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6688 scanFlags, currentTime, user); 6689 6690 // Scan the children 6691 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6692 for (int i = 0; i < childCount; i++) { 6693 PackageParser.Package childPackage = pkg.childPackages.get(i); 6694 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6695 currentTime, user); 6696 } 6697 6698 6699 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6700 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6701 } 6702 6703 return scannedPkg; 6704 } 6705 6706 /** 6707 * Scans a package and returns the newly parsed package. 6708 * @throws PackageManagerException on a parse error. 6709 */ 6710 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6711 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6712 throws PackageManagerException { 6713 PackageSetting ps = null; 6714 PackageSetting updatedPkg; 6715 // reader 6716 synchronized (mPackages) { 6717 // Look to see if we already know about this package. 6718 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6719 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6720 // This package has been renamed to its original name. Let's 6721 // use that. 6722 ps = mSettings.peekPackageLPr(oldName); 6723 } 6724 // If there was no original package, see one for the real package name. 6725 if (ps == null) { 6726 ps = mSettings.peekPackageLPr(pkg.packageName); 6727 } 6728 // Check to see if this package could be hiding/updating a system 6729 // package. Must look for it either under the original or real 6730 // package name depending on our state. 6731 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6732 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6733 6734 // If this is a package we don't know about on the system partition, we 6735 // may need to remove disabled child packages on the system partition 6736 // or may need to not add child packages if the parent apk is updated 6737 // on the data partition and no longer defines this child package. 6738 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6739 // If this is a parent package for an updated system app and this system 6740 // app got an OTA update which no longer defines some of the child packages 6741 // we have to prune them from the disabled system packages. 6742 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6743 if (disabledPs != null) { 6744 final int scannedChildCount = (pkg.childPackages != null) 6745 ? pkg.childPackages.size() : 0; 6746 final int disabledChildCount = disabledPs.childPackageNames != null 6747 ? disabledPs.childPackageNames.size() : 0; 6748 for (int i = 0; i < disabledChildCount; i++) { 6749 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6750 boolean disabledPackageAvailable = false; 6751 for (int j = 0; j < scannedChildCount; j++) { 6752 PackageParser.Package childPkg = pkg.childPackages.get(j); 6753 if (childPkg.packageName.equals(disabledChildPackageName)) { 6754 disabledPackageAvailable = true; 6755 break; 6756 } 6757 } 6758 if (!disabledPackageAvailable) { 6759 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6760 } 6761 } 6762 } 6763 } 6764 } 6765 6766 boolean updatedPkgBetter = false; 6767 // First check if this is a system package that may involve an update 6768 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6769 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6770 // it needs to drop FLAG_PRIVILEGED. 6771 if (locationIsPrivileged(scanFile)) { 6772 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6773 } else { 6774 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6775 } 6776 6777 if (ps != null && !ps.codePath.equals(scanFile)) { 6778 // The path has changed from what was last scanned... check the 6779 // version of the new path against what we have stored to determine 6780 // what to do. 6781 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6782 if (pkg.mVersionCode <= ps.versionCode) { 6783 // The system package has been updated and the code path does not match 6784 // Ignore entry. Skip it. 6785 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6786 + " ignored: updated version " + ps.versionCode 6787 + " better than this " + pkg.mVersionCode); 6788 if (!updatedPkg.codePath.equals(scanFile)) { 6789 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6790 + ps.name + " changing from " + updatedPkg.codePathString 6791 + " to " + scanFile); 6792 updatedPkg.codePath = scanFile; 6793 updatedPkg.codePathString = scanFile.toString(); 6794 updatedPkg.resourcePath = scanFile; 6795 updatedPkg.resourcePathString = scanFile.toString(); 6796 } 6797 updatedPkg.pkg = pkg; 6798 updatedPkg.versionCode = pkg.mVersionCode; 6799 6800 // Update the disabled system child packages to point to the package too. 6801 final int childCount = updatedPkg.childPackageNames != null 6802 ? updatedPkg.childPackageNames.size() : 0; 6803 for (int i = 0; i < childCount; i++) { 6804 String childPackageName = updatedPkg.childPackageNames.get(i); 6805 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6806 childPackageName); 6807 if (updatedChildPkg != null) { 6808 updatedChildPkg.pkg = pkg; 6809 updatedChildPkg.versionCode = pkg.mVersionCode; 6810 } 6811 } 6812 6813 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6814 + scanFile + " ignored: updated version " + ps.versionCode 6815 + " better than this " + pkg.mVersionCode); 6816 } else { 6817 // The current app on the system partition is better than 6818 // what we have updated to on the data partition; switch 6819 // back to the system partition version. 6820 // At this point, its safely assumed that package installation for 6821 // apps in system partition will go through. If not there won't be a working 6822 // version of the app 6823 // writer 6824 synchronized (mPackages) { 6825 // Just remove the loaded entries from package lists. 6826 mPackages.remove(ps.name); 6827 } 6828 6829 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6830 + " reverting from " + ps.codePathString 6831 + ": new version " + pkg.mVersionCode 6832 + " better than installed " + ps.versionCode); 6833 6834 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6835 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6836 synchronized (mInstallLock) { 6837 args.cleanUpResourcesLI(); 6838 } 6839 synchronized (mPackages) { 6840 mSettings.enableSystemPackageLPw(ps.name); 6841 } 6842 updatedPkgBetter = true; 6843 } 6844 } 6845 } 6846 6847 if (updatedPkg != null) { 6848 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6849 // initially 6850 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6851 6852 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6853 // flag set initially 6854 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6855 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6856 } 6857 } 6858 6859 // Verify certificates against what was last scanned 6860 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6861 6862 /* 6863 * A new system app appeared, but we already had a non-system one of the 6864 * same name installed earlier. 6865 */ 6866 boolean shouldHideSystemApp = false; 6867 if (updatedPkg == null && ps != null 6868 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6869 /* 6870 * Check to make sure the signatures match first. If they don't, 6871 * wipe the installed application and its data. 6872 */ 6873 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6874 != PackageManager.SIGNATURE_MATCH) { 6875 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6876 + " signatures don't match existing userdata copy; removing"); 6877 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6878 "scanPackageInternalLI")) { 6879 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6880 } 6881 ps = null; 6882 } else { 6883 /* 6884 * If the newly-added system app is an older version than the 6885 * already installed version, hide it. It will be scanned later 6886 * and re-added like an update. 6887 */ 6888 if (pkg.mVersionCode <= ps.versionCode) { 6889 shouldHideSystemApp = true; 6890 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6891 + " but new version " + pkg.mVersionCode + " better than installed " 6892 + ps.versionCode + "; hiding system"); 6893 } else { 6894 /* 6895 * The newly found system app is a newer version that the 6896 * one previously installed. Simply remove the 6897 * already-installed application and replace it with our own 6898 * while keeping the application data. 6899 */ 6900 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6901 + " reverting from " + ps.codePathString + ": new version " 6902 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6903 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6904 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6905 synchronized (mInstallLock) { 6906 args.cleanUpResourcesLI(); 6907 } 6908 } 6909 } 6910 } 6911 6912 // The apk is forward locked (not public) if its code and resources 6913 // are kept in different files. (except for app in either system or 6914 // vendor path). 6915 // TODO grab this value from PackageSettings 6916 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6917 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6918 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6919 } 6920 } 6921 6922 // TODO: extend to support forward-locked splits 6923 String resourcePath = null; 6924 String baseResourcePath = null; 6925 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6926 if (ps != null && ps.resourcePathString != null) { 6927 resourcePath = ps.resourcePathString; 6928 baseResourcePath = ps.resourcePathString; 6929 } else { 6930 // Should not happen at all. Just log an error. 6931 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6932 } 6933 } else { 6934 resourcePath = pkg.codePath; 6935 baseResourcePath = pkg.baseCodePath; 6936 } 6937 6938 // Set application objects path explicitly. 6939 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6940 pkg.setApplicationInfoCodePath(pkg.codePath); 6941 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6942 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6943 pkg.setApplicationInfoResourcePath(resourcePath); 6944 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6945 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6946 6947 // Note that we invoke the following method only if we are about to unpack an application 6948 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 6949 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6950 6951 /* 6952 * If the system app should be overridden by a previously installed 6953 * data, hide the system app now and let the /data/app scan pick it up 6954 * again. 6955 */ 6956 if (shouldHideSystemApp) { 6957 synchronized (mPackages) { 6958 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6959 } 6960 } 6961 6962 return scannedPkg; 6963 } 6964 6965 private static String fixProcessName(String defProcessName, 6966 String processName, int uid) { 6967 if (processName == null) { 6968 return defProcessName; 6969 } 6970 return processName; 6971 } 6972 6973 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6974 throws PackageManagerException { 6975 if (pkgSetting.signatures.mSignatures != null) { 6976 // Already existing package. Make sure signatures match 6977 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6978 == PackageManager.SIGNATURE_MATCH; 6979 if (!match) { 6980 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6981 == PackageManager.SIGNATURE_MATCH; 6982 } 6983 if (!match) { 6984 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6985 == PackageManager.SIGNATURE_MATCH; 6986 } 6987 if (!match) { 6988 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6989 + pkg.packageName + " signatures do not match the " 6990 + "previously installed version; ignoring!"); 6991 } 6992 } 6993 6994 // Check for shared user signatures 6995 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6996 // Already existing package. Make sure signatures match 6997 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6998 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6999 if (!match) { 7000 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7001 == PackageManager.SIGNATURE_MATCH; 7002 } 7003 if (!match) { 7004 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7005 == PackageManager.SIGNATURE_MATCH; 7006 } 7007 if (!match) { 7008 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7009 "Package " + pkg.packageName 7010 + " has no signatures that match those in shared user " 7011 + pkgSetting.sharedUser.name + "; ignoring!"); 7012 } 7013 } 7014 } 7015 7016 /** 7017 * Enforces that only the system UID or root's UID can call a method exposed 7018 * via Binder. 7019 * 7020 * @param message used as message if SecurityException is thrown 7021 * @throws SecurityException if the caller is not system or root 7022 */ 7023 private static final void enforceSystemOrRoot(String message) { 7024 final int uid = Binder.getCallingUid(); 7025 if (uid != Process.SYSTEM_UID && uid != 0) { 7026 throw new SecurityException(message); 7027 } 7028 } 7029 7030 @Override 7031 public void performFstrimIfNeeded() { 7032 enforceSystemOrRoot("Only the system can request fstrim"); 7033 7034 // Before everything else, see whether we need to fstrim. 7035 try { 7036 IMountService ms = PackageHelper.getMountService(); 7037 if (ms != null) { 7038 final boolean isUpgrade = isUpgrade(); 7039 boolean doTrim = isUpgrade; 7040 if (doTrim) { 7041 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7042 } else { 7043 final long interval = android.provider.Settings.Global.getLong( 7044 mContext.getContentResolver(), 7045 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7046 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7047 if (interval > 0) { 7048 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7049 if (timeSinceLast > interval) { 7050 doTrim = true; 7051 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7052 + "; running immediately"); 7053 } 7054 } 7055 } 7056 if (doTrim) { 7057 if (!isFirstBoot()) { 7058 try { 7059 ActivityManagerNative.getDefault().showBootMessage( 7060 mContext.getResources().getString( 7061 R.string.android_upgrading_fstrim), true); 7062 } catch (RemoteException e) { 7063 } 7064 } 7065 ms.runMaintenance(); 7066 } 7067 } else { 7068 Slog.e(TAG, "Mount service unavailable!"); 7069 } 7070 } catch (RemoteException e) { 7071 // Can't happen; MountService is local 7072 } 7073 } 7074 7075 @Override 7076 public void updatePackagesIfNeeded() { 7077 enforceSystemOrRoot("Only the system can request package update"); 7078 7079 // We need to re-extract after an OTA. 7080 boolean causeUpgrade = isUpgrade(); 7081 7082 // First boot or factory reset. 7083 // Note: we also handle devices that are upgrading to N right now as if it is their 7084 // first boot, as they do not have profile data. 7085 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7086 7087 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7088 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7089 7090 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7091 return; 7092 } 7093 7094 List<PackageParser.Package> pkgs; 7095 synchronized (mPackages) { 7096 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7097 } 7098 7099 int curr = 0; 7100 int total = pkgs.size(); 7101 for (PackageParser.Package pkg : pkgs) { 7102 curr++; 7103 7104 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7105 if (DEBUG_DEXOPT) { 7106 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7107 } 7108 continue; 7109 } 7110 7111 if (DEBUG_DEXOPT) { 7112 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7113 } 7114 7115 if (!isFirstBoot()) { 7116 try { 7117 ActivityManagerNative.getDefault().showBootMessage( 7118 mContext.getResources().getString(R.string.android_upgrading_apk, 7119 curr, total), true); 7120 } catch (RemoteException e) { 7121 } 7122 } 7123 7124 performDexOpt(pkg.packageName, 7125 null /* instructionSet */, 7126 false /* checkProfiles */, 7127 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7128 false /* force */); 7129 } 7130 } 7131 7132 @Override 7133 public void notifyPackageUse(String packageName) { 7134 synchronized (mPackages) { 7135 PackageParser.Package p = mPackages.get(packageName); 7136 if (p == null) { 7137 return; 7138 } 7139 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7140 } 7141 } 7142 7143 // TODO: this is not used nor needed. Delete it. 7144 @Override 7145 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7146 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7147 getFullCompilerFilter(), false /* force */); 7148 } 7149 7150 @Override 7151 public boolean performDexOpt(String packageName, String instructionSet, 7152 boolean checkProfiles, int compileReason, boolean force) { 7153 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7154 getCompilerFilterForReason(compileReason), force); 7155 } 7156 7157 @Override 7158 public boolean performDexOptMode(String packageName, String instructionSet, 7159 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7160 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7161 targetCompilerFilter, force); 7162 } 7163 7164 private boolean performDexOptTraced(String packageName, String instructionSet, 7165 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7166 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7167 try { 7168 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7169 targetCompilerFilter, force); 7170 } finally { 7171 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7172 } 7173 } 7174 7175 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7176 // if the package can now be considered up to date for the given filter. 7177 private boolean performDexOptInternal(String packageName, String instructionSet, 7178 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7179 PackageParser.Package p; 7180 final String targetInstructionSet; 7181 synchronized (mPackages) { 7182 p = mPackages.get(packageName); 7183 if (p == null) { 7184 return false; 7185 } 7186 mPackageUsage.write(false); 7187 7188 targetInstructionSet = instructionSet != null ? instructionSet : 7189 getPrimaryInstructionSet(p.applicationInfo); 7190 } 7191 long callingId = Binder.clearCallingIdentity(); 7192 try { 7193 synchronized (mInstallLock) { 7194 final String[] instructionSets = new String[] { targetInstructionSet }; 7195 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7196 checkProfiles, targetCompilerFilter, force); 7197 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7198 } 7199 } finally { 7200 Binder.restoreCallingIdentity(callingId); 7201 } 7202 } 7203 7204 public ArraySet<String> getOptimizablePackages() { 7205 ArraySet<String> pkgs = new ArraySet<String>(); 7206 synchronized (mPackages) { 7207 for (PackageParser.Package p : mPackages.values()) { 7208 if (PackageDexOptimizer.canOptimizePackage(p)) { 7209 pkgs.add(p.packageName); 7210 } 7211 } 7212 } 7213 return pkgs; 7214 } 7215 7216 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7217 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7218 boolean force) { 7219 // Select the dex optimizer based on the force parameter. 7220 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7221 // allocate an object here. 7222 PackageDexOptimizer pdo = force 7223 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7224 : mPackageDexOptimizer; 7225 7226 // Optimize all dependencies first. Note: we ignore the return value and march on 7227 // on errors. 7228 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7229 if (!deps.isEmpty()) { 7230 for (PackageParser.Package depPackage : deps) { 7231 // TODO: Analyze and investigate if we (should) profile libraries. 7232 // Currently this will do a full compilation of the library by default. 7233 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7234 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7235 } 7236 } 7237 7238 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7239 } 7240 7241 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7242 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7243 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7244 Set<String> collectedNames = new HashSet<>(); 7245 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7246 7247 retValue.remove(p); 7248 7249 return retValue; 7250 } else { 7251 return Collections.emptyList(); 7252 } 7253 } 7254 7255 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7256 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7257 if (!collectedNames.contains(p.packageName)) { 7258 collectedNames.add(p.packageName); 7259 collected.add(p); 7260 7261 if (p.usesLibraries != null) { 7262 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7263 } 7264 if (p.usesOptionalLibraries != null) { 7265 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7266 collectedNames); 7267 } 7268 } 7269 } 7270 7271 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7272 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7273 for (String libName : libs) { 7274 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7275 if (libPkg != null) { 7276 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7277 } 7278 } 7279 } 7280 7281 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7282 synchronized (mPackages) { 7283 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7284 if (lib != null && lib.apk != null) { 7285 return mPackages.get(lib.apk); 7286 } 7287 } 7288 return null; 7289 } 7290 7291 public void shutdown() { 7292 mPackageUsage.write(true); 7293 } 7294 7295 @Override 7296 public void forceDexOpt(String packageName) { 7297 enforceSystemOrRoot("forceDexOpt"); 7298 7299 PackageParser.Package pkg; 7300 synchronized (mPackages) { 7301 pkg = mPackages.get(packageName); 7302 if (pkg == null) { 7303 throw new IllegalArgumentException("Unknown package: " + packageName); 7304 } 7305 } 7306 7307 synchronized (mInstallLock) { 7308 final String[] instructionSets = new String[] { 7309 getPrimaryInstructionSet(pkg.applicationInfo) }; 7310 7311 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7312 7313 // Whoever is calling forceDexOpt wants a fully compiled package. 7314 // Don't use profiles since that may cause compilation to be skipped. 7315 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7316 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7317 true /* force */); 7318 7319 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7320 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7321 throw new IllegalStateException("Failed to dexopt: " + res); 7322 } 7323 } 7324 } 7325 7326 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7327 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7328 Slog.w(TAG, "Unable to update from " + oldPkg.name 7329 + " to " + newPkg.packageName 7330 + ": old package not in system partition"); 7331 return false; 7332 } else if (mPackages.get(oldPkg.name) != null) { 7333 Slog.w(TAG, "Unable to update from " + oldPkg.name 7334 + " to " + newPkg.packageName 7335 + ": old package still exists"); 7336 return false; 7337 } 7338 return true; 7339 } 7340 7341 void removeCodePathLI(File codePath) { 7342 if (codePath.isDirectory()) { 7343 try { 7344 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7345 } catch (InstallerException e) { 7346 Slog.w(TAG, "Failed to remove code path", e); 7347 } 7348 } else { 7349 codePath.delete(); 7350 } 7351 } 7352 7353 private int[] resolveUserIds(int userId) { 7354 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7355 } 7356 7357 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7358 if (pkg == null) { 7359 Slog.wtf(TAG, "Package was null!", new Throwable()); 7360 return; 7361 } 7362 clearAppDataLeafLIF(pkg, userId, flags); 7363 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7364 for (int i = 0; i < childCount; i++) { 7365 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7366 } 7367 } 7368 7369 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7370 final PackageSetting ps; 7371 synchronized (mPackages) { 7372 ps = mSettings.mPackages.get(pkg.packageName); 7373 } 7374 for (int realUserId : resolveUserIds(userId)) { 7375 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7376 try { 7377 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7378 ceDataInode); 7379 } catch (InstallerException e) { 7380 Slog.w(TAG, String.valueOf(e)); 7381 } 7382 } 7383 } 7384 7385 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7386 if (pkg == null) { 7387 Slog.wtf(TAG, "Package was null!", new Throwable()); 7388 return; 7389 } 7390 destroyAppDataLeafLIF(pkg, userId, flags); 7391 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7392 for (int i = 0; i < childCount; i++) { 7393 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7394 } 7395 } 7396 7397 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7398 final PackageSetting ps; 7399 synchronized (mPackages) { 7400 ps = mSettings.mPackages.get(pkg.packageName); 7401 } 7402 for (int realUserId : resolveUserIds(userId)) { 7403 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7404 try { 7405 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7406 ceDataInode); 7407 } catch (InstallerException e) { 7408 Slog.w(TAG, String.valueOf(e)); 7409 } 7410 } 7411 } 7412 7413 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7414 if (pkg == null) { 7415 Slog.wtf(TAG, "Package was null!", new Throwable()); 7416 return; 7417 } 7418 destroyAppProfilesLeafLIF(pkg); 7419 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7420 for (int i = 0; i < childCount; i++) { 7421 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7422 } 7423 } 7424 7425 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7426 try { 7427 mInstaller.destroyAppProfiles(pkg.packageName); 7428 } catch (InstallerException e) { 7429 Slog.w(TAG, String.valueOf(e)); 7430 } 7431 } 7432 7433 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7434 if (pkg == null) { 7435 Slog.wtf(TAG, "Package was null!", new Throwable()); 7436 return; 7437 } 7438 clearAppProfilesLeafLIF(pkg); 7439 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7440 for (int i = 0; i < childCount; i++) { 7441 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7442 } 7443 } 7444 7445 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7446 try { 7447 mInstaller.clearAppProfiles(pkg.packageName); 7448 } catch (InstallerException e) { 7449 Slog.w(TAG, String.valueOf(e)); 7450 } 7451 } 7452 7453 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7454 long lastUpdateTime) { 7455 // Set parent install/update time 7456 PackageSetting ps = (PackageSetting) pkg.mExtras; 7457 if (ps != null) { 7458 ps.firstInstallTime = firstInstallTime; 7459 ps.lastUpdateTime = lastUpdateTime; 7460 } 7461 // Set children install/update time 7462 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7463 for (int i = 0; i < childCount; i++) { 7464 PackageParser.Package childPkg = pkg.childPackages.get(i); 7465 ps = (PackageSetting) childPkg.mExtras; 7466 if (ps != null) { 7467 ps.firstInstallTime = firstInstallTime; 7468 ps.lastUpdateTime = lastUpdateTime; 7469 } 7470 } 7471 } 7472 7473 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7474 PackageParser.Package changingLib) { 7475 if (file.path != null) { 7476 usesLibraryFiles.add(file.path); 7477 return; 7478 } 7479 PackageParser.Package p = mPackages.get(file.apk); 7480 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7481 // If we are doing this while in the middle of updating a library apk, 7482 // then we need to make sure to use that new apk for determining the 7483 // dependencies here. (We haven't yet finished committing the new apk 7484 // to the package manager state.) 7485 if (p == null || p.packageName.equals(changingLib.packageName)) { 7486 p = changingLib; 7487 } 7488 } 7489 if (p != null) { 7490 usesLibraryFiles.addAll(p.getAllCodePaths()); 7491 } 7492 } 7493 7494 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7495 PackageParser.Package changingLib) throws PackageManagerException { 7496 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7497 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7498 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7499 for (int i=0; i<N; i++) { 7500 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7501 if (file == null) { 7502 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7503 "Package " + pkg.packageName + " requires unavailable shared library " 7504 + pkg.usesLibraries.get(i) + "; failing!"); 7505 } 7506 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7507 } 7508 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7509 for (int i=0; i<N; i++) { 7510 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7511 if (file == null) { 7512 Slog.w(TAG, "Package " + pkg.packageName 7513 + " desires unavailable shared library " 7514 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7515 } else { 7516 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7517 } 7518 } 7519 N = usesLibraryFiles.size(); 7520 if (N > 0) { 7521 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7522 } else { 7523 pkg.usesLibraryFiles = null; 7524 } 7525 } 7526 } 7527 7528 private static boolean hasString(List<String> list, List<String> which) { 7529 if (list == null) { 7530 return false; 7531 } 7532 for (int i=list.size()-1; i>=0; i--) { 7533 for (int j=which.size()-1; j>=0; j--) { 7534 if (which.get(j).equals(list.get(i))) { 7535 return true; 7536 } 7537 } 7538 } 7539 return false; 7540 } 7541 7542 private void updateAllSharedLibrariesLPw() { 7543 for (PackageParser.Package pkg : mPackages.values()) { 7544 try { 7545 updateSharedLibrariesLPw(pkg, null); 7546 } catch (PackageManagerException e) { 7547 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7548 } 7549 } 7550 } 7551 7552 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7553 PackageParser.Package changingPkg) { 7554 ArrayList<PackageParser.Package> res = null; 7555 for (PackageParser.Package pkg : mPackages.values()) { 7556 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7557 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7558 if (res == null) { 7559 res = new ArrayList<PackageParser.Package>(); 7560 } 7561 res.add(pkg); 7562 try { 7563 updateSharedLibrariesLPw(pkg, changingPkg); 7564 } catch (PackageManagerException e) { 7565 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7566 } 7567 } 7568 } 7569 return res; 7570 } 7571 7572 /** 7573 * Derive the value of the {@code cpuAbiOverride} based on the provided 7574 * value and an optional stored value from the package settings. 7575 */ 7576 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7577 String cpuAbiOverride = null; 7578 7579 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7580 cpuAbiOverride = null; 7581 } else if (abiOverride != null) { 7582 cpuAbiOverride = abiOverride; 7583 } else if (settings != null) { 7584 cpuAbiOverride = settings.cpuAbiOverrideString; 7585 } 7586 7587 return cpuAbiOverride; 7588 } 7589 7590 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7591 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7592 throws PackageManagerException { 7593 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7594 // If the package has children and this is the first dive in the function 7595 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7596 // whether all packages (parent and children) would be successfully scanned 7597 // before the actual scan since scanning mutates internal state and we want 7598 // to atomically install the package and its children. 7599 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7600 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7601 scanFlags |= SCAN_CHECK_ONLY; 7602 } 7603 } else { 7604 scanFlags &= ~SCAN_CHECK_ONLY; 7605 } 7606 7607 final PackageParser.Package scannedPkg; 7608 try { 7609 // Scan the parent 7610 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7611 // Scan the children 7612 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7613 for (int i = 0; i < childCount; i++) { 7614 PackageParser.Package childPkg = pkg.childPackages.get(i); 7615 scanPackageLI(childPkg, policyFlags, 7616 scanFlags, currentTime, user); 7617 } 7618 } finally { 7619 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7620 } 7621 7622 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7623 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7624 } 7625 7626 return scannedPkg; 7627 } 7628 7629 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7630 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7631 boolean success = false; 7632 try { 7633 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7634 currentTime, user); 7635 success = true; 7636 return res; 7637 } finally { 7638 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7639 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7640 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7641 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7642 destroyAppProfilesLIF(pkg); 7643 } 7644 } 7645 } 7646 7647 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7648 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7649 throws PackageManagerException { 7650 final File scanFile = new File(pkg.codePath); 7651 if (pkg.applicationInfo.getCodePath() == null || 7652 pkg.applicationInfo.getResourcePath() == null) { 7653 // Bail out. The resource and code paths haven't been set. 7654 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7655 "Code and resource paths haven't been set correctly"); 7656 } 7657 7658 // Apply policy 7659 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7660 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7661 if (pkg.applicationInfo.isDirectBootAware()) { 7662 // we're direct boot aware; set for all components 7663 for (PackageParser.Service s : pkg.services) { 7664 s.info.encryptionAware = s.info.directBootAware = true; 7665 } 7666 for (PackageParser.Provider p : pkg.providers) { 7667 p.info.encryptionAware = p.info.directBootAware = true; 7668 } 7669 for (PackageParser.Activity a : pkg.activities) { 7670 a.info.encryptionAware = a.info.directBootAware = true; 7671 } 7672 for (PackageParser.Activity r : pkg.receivers) { 7673 r.info.encryptionAware = r.info.directBootAware = true; 7674 } 7675 } 7676 } else { 7677 // Only allow system apps to be flagged as core apps. 7678 pkg.coreApp = false; 7679 // clear flags not applicable to regular apps 7680 pkg.applicationInfo.privateFlags &= 7681 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7682 pkg.applicationInfo.privateFlags &= 7683 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7684 } 7685 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7686 7687 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7688 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7689 } 7690 7691 if (mCustomResolverComponentName != null && 7692 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7693 setUpCustomResolverActivity(pkg); 7694 } 7695 7696 if (pkg.packageName.equals("android")) { 7697 synchronized (mPackages) { 7698 if (mAndroidApplication != null) { 7699 Slog.w(TAG, "*************************************************"); 7700 Slog.w(TAG, "Core android package being redefined. Skipping."); 7701 Slog.w(TAG, " file=" + scanFile); 7702 Slog.w(TAG, "*************************************************"); 7703 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7704 "Core android package being redefined. Skipping."); 7705 } 7706 7707 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7708 // Set up information for our fall-back user intent resolution activity. 7709 mPlatformPackage = pkg; 7710 pkg.mVersionCode = mSdkVersion; 7711 mAndroidApplication = pkg.applicationInfo; 7712 7713 if (!mResolverReplaced) { 7714 mResolveActivity.applicationInfo = mAndroidApplication; 7715 mResolveActivity.name = ResolverActivity.class.getName(); 7716 mResolveActivity.packageName = mAndroidApplication.packageName; 7717 mResolveActivity.processName = "system:ui"; 7718 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7719 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7720 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7721 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7722 mResolveActivity.exported = true; 7723 mResolveActivity.enabled = true; 7724 mResolveInfo.activityInfo = mResolveActivity; 7725 mResolveInfo.priority = 0; 7726 mResolveInfo.preferredOrder = 0; 7727 mResolveInfo.match = 0; 7728 mResolveComponentName = new ComponentName( 7729 mAndroidApplication.packageName, mResolveActivity.name); 7730 } 7731 } 7732 } 7733 } 7734 7735 if (DEBUG_PACKAGE_SCANNING) { 7736 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7737 Log.d(TAG, "Scanning package " + pkg.packageName); 7738 } 7739 7740 synchronized (mPackages) { 7741 if (mPackages.containsKey(pkg.packageName) 7742 || mSharedLibraries.containsKey(pkg.packageName)) { 7743 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7744 "Application package " + pkg.packageName 7745 + " already installed. Skipping duplicate."); 7746 } 7747 7748 // If we're only installing presumed-existing packages, require that the 7749 // scanned APK is both already known and at the path previously established 7750 // for it. Previously unknown packages we pick up normally, but if we have an 7751 // a priori expectation about this package's install presence, enforce it. 7752 // With a singular exception for new system packages. When an OTA contains 7753 // a new system package, we allow the codepath to change from a system location 7754 // to the user-installed location. If we don't allow this change, any newer, 7755 // user-installed version of the application will be ignored. 7756 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7757 if (mExpectingBetter.containsKey(pkg.packageName)) { 7758 logCriticalInfo(Log.WARN, 7759 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7760 } else { 7761 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7762 if (known != null) { 7763 if (DEBUG_PACKAGE_SCANNING) { 7764 Log.d(TAG, "Examining " + pkg.codePath 7765 + " and requiring known paths " + known.codePathString 7766 + " & " + known.resourcePathString); 7767 } 7768 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7769 || !pkg.applicationInfo.getResourcePath().equals( 7770 known.resourcePathString)) { 7771 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7772 "Application package " + pkg.packageName 7773 + " found at " + pkg.applicationInfo.getCodePath() 7774 + " but expected at " + known.codePathString 7775 + "; ignoring."); 7776 } 7777 } 7778 } 7779 } 7780 } 7781 7782 // Initialize package source and resource directories 7783 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7784 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7785 7786 SharedUserSetting suid = null; 7787 PackageSetting pkgSetting = null; 7788 7789 if (!isSystemApp(pkg)) { 7790 // Only system apps can use these features. 7791 pkg.mOriginalPackages = null; 7792 pkg.mRealPackage = null; 7793 pkg.mAdoptPermissions = null; 7794 } 7795 7796 // Getting the package setting may have a side-effect, so if we 7797 // are only checking if scan would succeed, stash a copy of the 7798 // old setting to restore at the end. 7799 PackageSetting nonMutatedPs = null; 7800 7801 // writer 7802 synchronized (mPackages) { 7803 if (pkg.mSharedUserId != null) { 7804 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7805 if (suid == null) { 7806 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7807 "Creating application package " + pkg.packageName 7808 + " for shared user failed"); 7809 } 7810 if (DEBUG_PACKAGE_SCANNING) { 7811 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7812 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7813 + "): packages=" + suid.packages); 7814 } 7815 } 7816 7817 // Check if we are renaming from an original package name. 7818 PackageSetting origPackage = null; 7819 String realName = null; 7820 if (pkg.mOriginalPackages != null) { 7821 // This package may need to be renamed to a previously 7822 // installed name. Let's check on that... 7823 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7824 if (pkg.mOriginalPackages.contains(renamed)) { 7825 // This package had originally been installed as the 7826 // original name, and we have already taken care of 7827 // transitioning to the new one. Just update the new 7828 // one to continue using the old name. 7829 realName = pkg.mRealPackage; 7830 if (!pkg.packageName.equals(renamed)) { 7831 // Callers into this function may have already taken 7832 // care of renaming the package; only do it here if 7833 // it is not already done. 7834 pkg.setPackageName(renamed); 7835 } 7836 7837 } else { 7838 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7839 if ((origPackage = mSettings.peekPackageLPr( 7840 pkg.mOriginalPackages.get(i))) != null) { 7841 // We do have the package already installed under its 7842 // original name... should we use it? 7843 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7844 // New package is not compatible with original. 7845 origPackage = null; 7846 continue; 7847 } else if (origPackage.sharedUser != null) { 7848 // Make sure uid is compatible between packages. 7849 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7850 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7851 + " to " + pkg.packageName + ": old uid " 7852 + origPackage.sharedUser.name 7853 + " differs from " + pkg.mSharedUserId); 7854 origPackage = null; 7855 continue; 7856 } 7857 // TODO: Add case when shared user id is added [b/28144775] 7858 } else { 7859 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7860 + pkg.packageName + " to old name " + origPackage.name); 7861 } 7862 break; 7863 } 7864 } 7865 } 7866 } 7867 7868 if (mTransferedPackages.contains(pkg.packageName)) { 7869 Slog.w(TAG, "Package " + pkg.packageName 7870 + " was transferred to another, but its .apk remains"); 7871 } 7872 7873 // See comments in nonMutatedPs declaration 7874 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7875 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7876 if (foundPs != null) { 7877 nonMutatedPs = new PackageSetting(foundPs); 7878 } 7879 } 7880 7881 // Just create the setting, don't add it yet. For already existing packages 7882 // the PkgSetting exists already and doesn't have to be created. 7883 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7884 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7885 pkg.applicationInfo.primaryCpuAbi, 7886 pkg.applicationInfo.secondaryCpuAbi, 7887 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7888 user, false); 7889 if (pkgSetting == null) { 7890 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7891 "Creating application package " + pkg.packageName + " failed"); 7892 } 7893 7894 if (pkgSetting.origPackage != null) { 7895 // If we are first transitioning from an original package, 7896 // fix up the new package's name now. We need to do this after 7897 // looking up the package under its new name, so getPackageLP 7898 // can take care of fiddling things correctly. 7899 pkg.setPackageName(origPackage.name); 7900 7901 // File a report about this. 7902 String msg = "New package " + pkgSetting.realName 7903 + " renamed to replace old package " + pkgSetting.name; 7904 reportSettingsProblem(Log.WARN, msg); 7905 7906 // Make a note of it. 7907 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7908 mTransferedPackages.add(origPackage.name); 7909 } 7910 7911 // No longer need to retain this. 7912 pkgSetting.origPackage = null; 7913 } 7914 7915 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7916 // Make a note of it. 7917 mTransferedPackages.add(pkg.packageName); 7918 } 7919 7920 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7921 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7922 } 7923 7924 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7925 // Check all shared libraries and map to their actual file path. 7926 // We only do this here for apps not on a system dir, because those 7927 // are the only ones that can fail an install due to this. We 7928 // will take care of the system apps by updating all of their 7929 // library paths after the scan is done. 7930 updateSharedLibrariesLPw(pkg, null); 7931 } 7932 7933 if (mFoundPolicyFile) { 7934 SELinuxMMAC.assignSeinfoValue(pkg); 7935 } 7936 7937 pkg.applicationInfo.uid = pkgSetting.appId; 7938 pkg.mExtras = pkgSetting; 7939 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7940 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7941 // We just determined the app is signed correctly, so bring 7942 // over the latest parsed certs. 7943 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7944 } else { 7945 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7946 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7947 "Package " + pkg.packageName + " upgrade keys do not match the " 7948 + "previously installed version"); 7949 } else { 7950 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7951 String msg = "System package " + pkg.packageName 7952 + " signature changed; retaining data."; 7953 reportSettingsProblem(Log.WARN, msg); 7954 } 7955 } 7956 } else { 7957 try { 7958 verifySignaturesLP(pkgSetting, pkg); 7959 // We just determined the app is signed correctly, so bring 7960 // over the latest parsed certs. 7961 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7962 } catch (PackageManagerException e) { 7963 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7964 throw e; 7965 } 7966 // The signature has changed, but this package is in the system 7967 // image... let's recover! 7968 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7969 // However... if this package is part of a shared user, but it 7970 // doesn't match the signature of the shared user, let's fail. 7971 // What this means is that you can't change the signatures 7972 // associated with an overall shared user, which doesn't seem all 7973 // that unreasonable. 7974 if (pkgSetting.sharedUser != null) { 7975 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7976 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7977 throw new PackageManagerException( 7978 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7979 "Signature mismatch for shared user: " 7980 + pkgSetting.sharedUser); 7981 } 7982 } 7983 // File a report about this. 7984 String msg = "System package " + pkg.packageName 7985 + " signature changed; retaining data."; 7986 reportSettingsProblem(Log.WARN, msg); 7987 } 7988 } 7989 // Verify that this new package doesn't have any content providers 7990 // that conflict with existing packages. Only do this if the 7991 // package isn't already installed, since we don't want to break 7992 // things that are installed. 7993 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7994 final int N = pkg.providers.size(); 7995 int i; 7996 for (i=0; i<N; i++) { 7997 PackageParser.Provider p = pkg.providers.get(i); 7998 if (p.info.authority != null) { 7999 String names[] = p.info.authority.split(";"); 8000 for (int j = 0; j < names.length; j++) { 8001 if (mProvidersByAuthority.containsKey(names[j])) { 8002 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8003 final String otherPackageName = 8004 ((other != null && other.getComponentName() != null) ? 8005 other.getComponentName().getPackageName() : "?"); 8006 throw new PackageManagerException( 8007 INSTALL_FAILED_CONFLICTING_PROVIDER, 8008 "Can't install because provider name " + names[j] 8009 + " (in package " + pkg.applicationInfo.packageName 8010 + ") is already used by " + otherPackageName); 8011 } 8012 } 8013 } 8014 } 8015 } 8016 8017 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8018 // This package wants to adopt ownership of permissions from 8019 // another package. 8020 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8021 final String origName = pkg.mAdoptPermissions.get(i); 8022 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8023 if (orig != null) { 8024 if (verifyPackageUpdateLPr(orig, pkg)) { 8025 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8026 + pkg.packageName); 8027 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8028 } 8029 } 8030 } 8031 } 8032 } 8033 8034 final String pkgName = pkg.packageName; 8035 8036 final long scanFileTime = scanFile.lastModified(); 8037 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8038 pkg.applicationInfo.processName = fixProcessName( 8039 pkg.applicationInfo.packageName, 8040 pkg.applicationInfo.processName, 8041 pkg.applicationInfo.uid); 8042 8043 if (pkg != mPlatformPackage) { 8044 // Get all of our default paths setup 8045 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8046 } 8047 8048 final String path = scanFile.getPath(); 8049 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8050 8051 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8052 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8053 8054 // Some system apps still use directory structure for native libraries 8055 // in which case we might end up not detecting abi solely based on apk 8056 // structure. Try to detect abi based on directory structure. 8057 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8058 pkg.applicationInfo.primaryCpuAbi == null) { 8059 setBundledAppAbisAndRoots(pkg, pkgSetting); 8060 setNativeLibraryPaths(pkg); 8061 } 8062 8063 } else { 8064 if ((scanFlags & SCAN_MOVE) != 0) { 8065 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8066 // but we already have this packages package info in the PackageSetting. We just 8067 // use that and derive the native library path based on the new codepath. 8068 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8069 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8070 } 8071 8072 // Set native library paths again. For moves, the path will be updated based on the 8073 // ABIs we've determined above. For non-moves, the path will be updated based on the 8074 // ABIs we determined during compilation, but the path will depend on the final 8075 // package path (after the rename away from the stage path). 8076 setNativeLibraryPaths(pkg); 8077 } 8078 8079 // This is a special case for the "system" package, where the ABI is 8080 // dictated by the zygote configuration (and init.rc). We should keep track 8081 // of this ABI so that we can deal with "normal" applications that run under 8082 // the same UID correctly. 8083 if (mPlatformPackage == pkg) { 8084 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8085 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8086 } 8087 8088 // If there's a mismatch between the abi-override in the package setting 8089 // and the abiOverride specified for the install. Warn about this because we 8090 // would've already compiled the app without taking the package setting into 8091 // account. 8092 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8093 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8094 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8095 " for package " + pkg.packageName); 8096 } 8097 } 8098 8099 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8100 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8101 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8102 8103 // Copy the derived override back to the parsed package, so that we can 8104 // update the package settings accordingly. 8105 pkg.cpuAbiOverride = cpuAbiOverride; 8106 8107 if (DEBUG_ABI_SELECTION) { 8108 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8109 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8110 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8111 } 8112 8113 // Push the derived path down into PackageSettings so we know what to 8114 // clean up at uninstall time. 8115 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8116 8117 if (DEBUG_ABI_SELECTION) { 8118 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8119 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8120 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8121 } 8122 8123 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8124 // We don't do this here during boot because we can do it all 8125 // at once after scanning all existing packages. 8126 // 8127 // We also do this *before* we perform dexopt on this package, so that 8128 // we can avoid redundant dexopts, and also to make sure we've got the 8129 // code and package path correct. 8130 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8131 pkg, true /* boot complete */); 8132 } 8133 8134 if (mFactoryTest && pkg.requestedPermissions.contains( 8135 android.Manifest.permission.FACTORY_TEST)) { 8136 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8137 } 8138 8139 ArrayList<PackageParser.Package> clientLibPkgs = null; 8140 8141 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8142 if (nonMutatedPs != null) { 8143 synchronized (mPackages) { 8144 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8145 } 8146 } 8147 return pkg; 8148 } 8149 8150 // Only privileged apps and updated privileged apps can add child packages. 8151 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8152 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8153 throw new PackageManagerException("Only privileged apps and updated " 8154 + "privileged apps can add child packages. Ignoring package " 8155 + pkg.packageName); 8156 } 8157 final int childCount = pkg.childPackages.size(); 8158 for (int i = 0; i < childCount; i++) { 8159 PackageParser.Package childPkg = pkg.childPackages.get(i); 8160 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8161 childPkg.packageName)) { 8162 throw new PackageManagerException("Cannot override a child package of " 8163 + "another disabled system app. Ignoring package " + pkg.packageName); 8164 } 8165 } 8166 } 8167 8168 // writer 8169 synchronized (mPackages) { 8170 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8171 // Only system apps can add new shared libraries. 8172 if (pkg.libraryNames != null) { 8173 for (int i=0; i<pkg.libraryNames.size(); i++) { 8174 String name = pkg.libraryNames.get(i); 8175 boolean allowed = false; 8176 if (pkg.isUpdatedSystemApp()) { 8177 // New library entries can only be added through the 8178 // system image. This is important to get rid of a lot 8179 // of nasty edge cases: for example if we allowed a non- 8180 // system update of the app to add a library, then uninstalling 8181 // the update would make the library go away, and assumptions 8182 // we made such as through app install filtering would now 8183 // have allowed apps on the device which aren't compatible 8184 // with it. Better to just have the restriction here, be 8185 // conservative, and create many fewer cases that can negatively 8186 // impact the user experience. 8187 final PackageSetting sysPs = mSettings 8188 .getDisabledSystemPkgLPr(pkg.packageName); 8189 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8190 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8191 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8192 allowed = true; 8193 break; 8194 } 8195 } 8196 } 8197 } else { 8198 allowed = true; 8199 } 8200 if (allowed) { 8201 if (!mSharedLibraries.containsKey(name)) { 8202 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8203 } else if (!name.equals(pkg.packageName)) { 8204 Slog.w(TAG, "Package " + pkg.packageName + " library " 8205 + name + " already exists; skipping"); 8206 } 8207 } else { 8208 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8209 + name + " that is not declared on system image; skipping"); 8210 } 8211 } 8212 if ((scanFlags & SCAN_BOOTING) == 0) { 8213 // If we are not booting, we need to update any applications 8214 // that are clients of our shared library. If we are booting, 8215 // this will all be done once the scan is complete. 8216 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8217 } 8218 } 8219 } 8220 } 8221 8222 if ((scanFlags & SCAN_BOOTING) != 0) { 8223 // No apps can run during boot scan, so they don't need to be frozen 8224 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8225 // Caller asked to not kill app, so it's probably not frozen 8226 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8227 // Caller asked us to ignore frozen check for some reason; they 8228 // probably didn't know the package name 8229 } else { 8230 // We're doing major surgery on this package, so it better be frozen 8231 // right now to keep it from launching 8232 checkPackageFrozen(pkgName); 8233 } 8234 8235 // Also need to kill any apps that are dependent on the library. 8236 if (clientLibPkgs != null) { 8237 for (int i=0; i<clientLibPkgs.size(); i++) { 8238 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8239 killApplication(clientPkg.applicationInfo.packageName, 8240 clientPkg.applicationInfo.uid, "update lib"); 8241 } 8242 } 8243 8244 // Make sure we're not adding any bogus keyset info 8245 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8246 ksms.assertScannedPackageValid(pkg); 8247 8248 // writer 8249 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8250 8251 boolean createIdmapFailed = false; 8252 synchronized (mPackages) { 8253 // We don't expect installation to fail beyond this point 8254 8255 // Add the new setting to mSettings 8256 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8257 // Add the new setting to mPackages 8258 mPackages.put(pkg.applicationInfo.packageName, pkg); 8259 // Make sure we don't accidentally delete its data. 8260 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8261 while (iter.hasNext()) { 8262 PackageCleanItem item = iter.next(); 8263 if (pkgName.equals(item.packageName)) { 8264 iter.remove(); 8265 } 8266 } 8267 8268 // Take care of first install / last update times. 8269 if (currentTime != 0) { 8270 if (pkgSetting.firstInstallTime == 0) { 8271 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8272 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8273 pkgSetting.lastUpdateTime = currentTime; 8274 } 8275 } else if (pkgSetting.firstInstallTime == 0) { 8276 // We need *something*. Take time time stamp of the file. 8277 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8278 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8279 if (scanFileTime != pkgSetting.timeStamp) { 8280 // A package on the system image has changed; consider this 8281 // to be an update. 8282 pkgSetting.lastUpdateTime = scanFileTime; 8283 } 8284 } 8285 8286 // Add the package's KeySets to the global KeySetManagerService 8287 ksms.addScannedPackageLPw(pkg); 8288 8289 int N = pkg.providers.size(); 8290 StringBuilder r = null; 8291 int i; 8292 for (i=0; i<N; i++) { 8293 PackageParser.Provider p = pkg.providers.get(i); 8294 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8295 p.info.processName, pkg.applicationInfo.uid); 8296 mProviders.addProvider(p); 8297 p.syncable = p.info.isSyncable; 8298 if (p.info.authority != null) { 8299 String names[] = p.info.authority.split(";"); 8300 p.info.authority = null; 8301 for (int j = 0; j < names.length; j++) { 8302 if (j == 1 && p.syncable) { 8303 // We only want the first authority for a provider to possibly be 8304 // syncable, so if we already added this provider using a different 8305 // authority clear the syncable flag. We copy the provider before 8306 // changing it because the mProviders object contains a reference 8307 // to a provider that we don't want to change. 8308 // Only do this for the second authority since the resulting provider 8309 // object can be the same for all future authorities for this provider. 8310 p = new PackageParser.Provider(p); 8311 p.syncable = false; 8312 } 8313 if (!mProvidersByAuthority.containsKey(names[j])) { 8314 mProvidersByAuthority.put(names[j], p); 8315 if (p.info.authority == null) { 8316 p.info.authority = names[j]; 8317 } else { 8318 p.info.authority = p.info.authority + ";" + names[j]; 8319 } 8320 if (DEBUG_PACKAGE_SCANNING) { 8321 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8322 Log.d(TAG, "Registered content provider: " + names[j] 8323 + ", className = " + p.info.name + ", isSyncable = " 8324 + p.info.isSyncable); 8325 } 8326 } else { 8327 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8328 Slog.w(TAG, "Skipping provider name " + names[j] + 8329 " (in package " + pkg.applicationInfo.packageName + 8330 "): name already used by " 8331 + ((other != null && other.getComponentName() != null) 8332 ? other.getComponentName().getPackageName() : "?")); 8333 } 8334 } 8335 } 8336 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8337 if (r == null) { 8338 r = new StringBuilder(256); 8339 } else { 8340 r.append(' '); 8341 } 8342 r.append(p.info.name); 8343 } 8344 } 8345 if (r != null) { 8346 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8347 } 8348 8349 N = pkg.services.size(); 8350 r = null; 8351 for (i=0; i<N; i++) { 8352 PackageParser.Service s = pkg.services.get(i); 8353 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8354 s.info.processName, pkg.applicationInfo.uid); 8355 mServices.addService(s); 8356 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8357 if (r == null) { 8358 r = new StringBuilder(256); 8359 } else { 8360 r.append(' '); 8361 } 8362 r.append(s.info.name); 8363 } 8364 } 8365 if (r != null) { 8366 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8367 } 8368 8369 N = pkg.receivers.size(); 8370 r = null; 8371 for (i=0; i<N; i++) { 8372 PackageParser.Activity a = pkg.receivers.get(i); 8373 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8374 a.info.processName, pkg.applicationInfo.uid); 8375 mReceivers.addActivity(a, "receiver"); 8376 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8377 if (r == null) { 8378 r = new StringBuilder(256); 8379 } else { 8380 r.append(' '); 8381 } 8382 r.append(a.info.name); 8383 } 8384 } 8385 if (r != null) { 8386 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8387 } 8388 8389 N = pkg.activities.size(); 8390 r = null; 8391 for (i=0; i<N; i++) { 8392 PackageParser.Activity a = pkg.activities.get(i); 8393 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8394 a.info.processName, pkg.applicationInfo.uid); 8395 mActivities.addActivity(a, "activity"); 8396 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8397 if (r == null) { 8398 r = new StringBuilder(256); 8399 } else { 8400 r.append(' '); 8401 } 8402 r.append(a.info.name); 8403 } 8404 } 8405 if (r != null) { 8406 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8407 } 8408 8409 N = pkg.permissionGroups.size(); 8410 r = null; 8411 for (i=0; i<N; i++) { 8412 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8413 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8414 if (cur == null) { 8415 mPermissionGroups.put(pg.info.name, pg); 8416 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8417 if (r == null) { 8418 r = new StringBuilder(256); 8419 } else { 8420 r.append(' '); 8421 } 8422 r.append(pg.info.name); 8423 } 8424 } else { 8425 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8426 + pg.info.packageName + " ignored: original from " 8427 + cur.info.packageName); 8428 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8429 if (r == null) { 8430 r = new StringBuilder(256); 8431 } else { 8432 r.append(' '); 8433 } 8434 r.append("DUP:"); 8435 r.append(pg.info.name); 8436 } 8437 } 8438 } 8439 if (r != null) { 8440 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8441 } 8442 8443 N = pkg.permissions.size(); 8444 r = null; 8445 for (i=0; i<N; i++) { 8446 PackageParser.Permission p = pkg.permissions.get(i); 8447 8448 // Assume by default that we did not install this permission into the system. 8449 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8450 8451 // Now that permission groups have a special meaning, we ignore permission 8452 // groups for legacy apps to prevent unexpected behavior. In particular, 8453 // permissions for one app being granted to someone just becase they happen 8454 // to be in a group defined by another app (before this had no implications). 8455 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8456 p.group = mPermissionGroups.get(p.info.group); 8457 // Warn for a permission in an unknown group. 8458 if (p.info.group != null && p.group == null) { 8459 Slog.w(TAG, "Permission " + p.info.name + " from package " 8460 + p.info.packageName + " in an unknown group " + p.info.group); 8461 } 8462 } 8463 8464 ArrayMap<String, BasePermission> permissionMap = 8465 p.tree ? mSettings.mPermissionTrees 8466 : mSettings.mPermissions; 8467 BasePermission bp = permissionMap.get(p.info.name); 8468 8469 // Allow system apps to redefine non-system permissions 8470 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8471 final boolean currentOwnerIsSystem = (bp.perm != null 8472 && isSystemApp(bp.perm.owner)); 8473 if (isSystemApp(p.owner)) { 8474 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8475 // It's a built-in permission and no owner, take ownership now 8476 bp.packageSetting = pkgSetting; 8477 bp.perm = p; 8478 bp.uid = pkg.applicationInfo.uid; 8479 bp.sourcePackage = p.info.packageName; 8480 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8481 } else if (!currentOwnerIsSystem) { 8482 String msg = "New decl " + p.owner + " of permission " 8483 + p.info.name + " is system; overriding " + bp.sourcePackage; 8484 reportSettingsProblem(Log.WARN, msg); 8485 bp = null; 8486 } 8487 } 8488 } 8489 8490 if (bp == null) { 8491 bp = new BasePermission(p.info.name, p.info.packageName, 8492 BasePermission.TYPE_NORMAL); 8493 permissionMap.put(p.info.name, bp); 8494 } 8495 8496 if (bp.perm == null) { 8497 if (bp.sourcePackage == null 8498 || bp.sourcePackage.equals(p.info.packageName)) { 8499 BasePermission tree = findPermissionTreeLP(p.info.name); 8500 if (tree == null 8501 || tree.sourcePackage.equals(p.info.packageName)) { 8502 bp.packageSetting = pkgSetting; 8503 bp.perm = p; 8504 bp.uid = pkg.applicationInfo.uid; 8505 bp.sourcePackage = p.info.packageName; 8506 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8507 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8508 if (r == null) { 8509 r = new StringBuilder(256); 8510 } else { 8511 r.append(' '); 8512 } 8513 r.append(p.info.name); 8514 } 8515 } else { 8516 Slog.w(TAG, "Permission " + p.info.name + " from package " 8517 + p.info.packageName + " ignored: base tree " 8518 + tree.name + " is from package " 8519 + tree.sourcePackage); 8520 } 8521 } else { 8522 Slog.w(TAG, "Permission " + p.info.name + " from package " 8523 + p.info.packageName + " ignored: original from " 8524 + bp.sourcePackage); 8525 } 8526 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8527 if (r == null) { 8528 r = new StringBuilder(256); 8529 } else { 8530 r.append(' '); 8531 } 8532 r.append("DUP:"); 8533 r.append(p.info.name); 8534 } 8535 if (bp.perm == p) { 8536 bp.protectionLevel = p.info.protectionLevel; 8537 } 8538 } 8539 8540 if (r != null) { 8541 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8542 } 8543 8544 N = pkg.instrumentation.size(); 8545 r = null; 8546 for (i=0; i<N; i++) { 8547 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8548 a.info.packageName = pkg.applicationInfo.packageName; 8549 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8550 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8551 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8552 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8553 a.info.dataDir = pkg.applicationInfo.dataDir; 8554 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8555 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8556 8557 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8558 // need other information about the application, like the ABI and what not ? 8559 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8560 mInstrumentation.put(a.getComponentName(), a); 8561 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8562 if (r == null) { 8563 r = new StringBuilder(256); 8564 } else { 8565 r.append(' '); 8566 } 8567 r.append(a.info.name); 8568 } 8569 } 8570 if (r != null) { 8571 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8572 } 8573 8574 if (pkg.protectedBroadcasts != null) { 8575 N = pkg.protectedBroadcasts.size(); 8576 for (i=0; i<N; i++) { 8577 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8578 } 8579 } 8580 8581 pkgSetting.setTimeStamp(scanFileTime); 8582 8583 // Create idmap files for pairs of (packages, overlay packages). 8584 // Note: "android", ie framework-res.apk, is handled by native layers. 8585 if (pkg.mOverlayTarget != null) { 8586 // This is an overlay package. 8587 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8588 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8589 mOverlays.put(pkg.mOverlayTarget, 8590 new ArrayMap<String, PackageParser.Package>()); 8591 } 8592 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8593 map.put(pkg.packageName, pkg); 8594 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8595 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8596 createIdmapFailed = true; 8597 } 8598 } 8599 } else if (mOverlays.containsKey(pkg.packageName) && 8600 !pkg.packageName.equals("android")) { 8601 // This is a regular package, with one or more known overlay packages. 8602 createIdmapsForPackageLI(pkg); 8603 } 8604 } 8605 8606 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8607 8608 if (createIdmapFailed) { 8609 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8610 "scanPackageLI failed to createIdmap"); 8611 } 8612 return pkg; 8613 } 8614 8615 /** 8616 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8617 * is derived purely on the basis of the contents of {@code scanFile} and 8618 * {@code cpuAbiOverride}. 8619 * 8620 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8621 */ 8622 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8623 String cpuAbiOverride, boolean extractLibs) 8624 throws PackageManagerException { 8625 // TODO: We can probably be smarter about this stuff. For installed apps, 8626 // we can calculate this information at install time once and for all. For 8627 // system apps, we can probably assume that this information doesn't change 8628 // after the first boot scan. As things stand, we do lots of unnecessary work. 8629 8630 // Give ourselves some initial paths; we'll come back for another 8631 // pass once we've determined ABI below. 8632 setNativeLibraryPaths(pkg); 8633 8634 // We would never need to extract libs for forward-locked and external packages, 8635 // since the container service will do it for us. We shouldn't attempt to 8636 // extract libs from system app when it was not updated. 8637 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8638 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8639 extractLibs = false; 8640 } 8641 8642 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8643 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8644 8645 NativeLibraryHelper.Handle handle = null; 8646 try { 8647 handle = NativeLibraryHelper.Handle.create(pkg); 8648 // TODO(multiArch): This can be null for apps that didn't go through the 8649 // usual installation process. We can calculate it again, like we 8650 // do during install time. 8651 // 8652 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8653 // unnecessary. 8654 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8655 8656 // Null out the abis so that they can be recalculated. 8657 pkg.applicationInfo.primaryCpuAbi = null; 8658 pkg.applicationInfo.secondaryCpuAbi = null; 8659 if (isMultiArch(pkg.applicationInfo)) { 8660 // Warn if we've set an abiOverride for multi-lib packages.. 8661 // By definition, we need to copy both 32 and 64 bit libraries for 8662 // such packages. 8663 if (pkg.cpuAbiOverride != null 8664 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8665 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8666 } 8667 8668 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8669 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8670 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8671 if (extractLibs) { 8672 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8673 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8674 useIsaSpecificSubdirs); 8675 } else { 8676 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8677 } 8678 } 8679 8680 maybeThrowExceptionForMultiArchCopy( 8681 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8682 8683 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8684 if (extractLibs) { 8685 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8686 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8687 useIsaSpecificSubdirs); 8688 } else { 8689 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8690 } 8691 } 8692 8693 maybeThrowExceptionForMultiArchCopy( 8694 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8695 8696 if (abi64 >= 0) { 8697 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8698 } 8699 8700 if (abi32 >= 0) { 8701 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8702 if (abi64 >= 0) { 8703 if (pkg.use32bitAbi) { 8704 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8705 pkg.applicationInfo.primaryCpuAbi = abi; 8706 } else { 8707 pkg.applicationInfo.secondaryCpuAbi = abi; 8708 } 8709 } else { 8710 pkg.applicationInfo.primaryCpuAbi = abi; 8711 } 8712 } 8713 8714 } else { 8715 String[] abiList = (cpuAbiOverride != null) ? 8716 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8717 8718 // Enable gross and lame hacks for apps that are built with old 8719 // SDK tools. We must scan their APKs for renderscript bitcode and 8720 // not launch them if it's present. Don't bother checking on devices 8721 // that don't have 64 bit support. 8722 boolean needsRenderScriptOverride = false; 8723 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8724 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8725 abiList = Build.SUPPORTED_32_BIT_ABIS; 8726 needsRenderScriptOverride = true; 8727 } 8728 8729 final int copyRet; 8730 if (extractLibs) { 8731 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8732 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8733 } else { 8734 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8735 } 8736 8737 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8738 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8739 "Error unpackaging native libs for app, errorCode=" + copyRet); 8740 } 8741 8742 if (copyRet >= 0) { 8743 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8744 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8745 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8746 } else if (needsRenderScriptOverride) { 8747 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8748 } 8749 } 8750 } catch (IOException ioe) { 8751 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8752 } finally { 8753 IoUtils.closeQuietly(handle); 8754 } 8755 8756 // Now that we've calculated the ABIs and determined if it's an internal app, 8757 // we will go ahead and populate the nativeLibraryPath. 8758 setNativeLibraryPaths(pkg); 8759 } 8760 8761 /** 8762 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8763 * i.e, so that all packages can be run inside a single process if required. 8764 * 8765 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8766 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8767 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8768 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8769 * updating a package that belongs to a shared user. 8770 * 8771 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8772 * adds unnecessary complexity. 8773 */ 8774 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8775 PackageParser.Package scannedPackage, boolean bootComplete) { 8776 String requiredInstructionSet = null; 8777 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8778 requiredInstructionSet = VMRuntime.getInstructionSet( 8779 scannedPackage.applicationInfo.primaryCpuAbi); 8780 } 8781 8782 PackageSetting requirer = null; 8783 for (PackageSetting ps : packagesForUser) { 8784 // If packagesForUser contains scannedPackage, we skip it. This will happen 8785 // when scannedPackage is an update of an existing package. Without this check, 8786 // we will never be able to change the ABI of any package belonging to a shared 8787 // user, even if it's compatible with other packages. 8788 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8789 if (ps.primaryCpuAbiString == null) { 8790 continue; 8791 } 8792 8793 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8794 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8795 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8796 // this but there's not much we can do. 8797 String errorMessage = "Instruction set mismatch, " 8798 + ((requirer == null) ? "[caller]" : requirer) 8799 + " requires " + requiredInstructionSet + " whereas " + ps 8800 + " requires " + instructionSet; 8801 Slog.w(TAG, errorMessage); 8802 } 8803 8804 if (requiredInstructionSet == null) { 8805 requiredInstructionSet = instructionSet; 8806 requirer = ps; 8807 } 8808 } 8809 } 8810 8811 if (requiredInstructionSet != null) { 8812 String adjustedAbi; 8813 if (requirer != null) { 8814 // requirer != null implies that either scannedPackage was null or that scannedPackage 8815 // did not require an ABI, in which case we have to adjust scannedPackage to match 8816 // the ABI of the set (which is the same as requirer's ABI) 8817 adjustedAbi = requirer.primaryCpuAbiString; 8818 if (scannedPackage != null) { 8819 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8820 } 8821 } else { 8822 // requirer == null implies that we're updating all ABIs in the set to 8823 // match scannedPackage. 8824 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8825 } 8826 8827 for (PackageSetting ps : packagesForUser) { 8828 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8829 if (ps.primaryCpuAbiString != null) { 8830 continue; 8831 } 8832 8833 ps.primaryCpuAbiString = adjustedAbi; 8834 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8835 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8836 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8837 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8838 + " (requirer=" 8839 + (requirer == null ? "null" : requirer.pkg.packageName) 8840 + ", scannedPackage=" 8841 + (scannedPackage != null ? scannedPackage.packageName : "null") 8842 + ")"); 8843 try { 8844 mInstaller.rmdex(ps.codePathString, 8845 getDexCodeInstructionSet(getPreferredInstructionSet())); 8846 } catch (InstallerException ignored) { 8847 } 8848 } 8849 } 8850 } 8851 } 8852 } 8853 8854 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8855 synchronized (mPackages) { 8856 mResolverReplaced = true; 8857 // Set up information for custom user intent resolution activity. 8858 mResolveActivity.applicationInfo = pkg.applicationInfo; 8859 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8860 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8861 mResolveActivity.processName = pkg.applicationInfo.packageName; 8862 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8863 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8864 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8865 mResolveActivity.theme = 0; 8866 mResolveActivity.exported = true; 8867 mResolveActivity.enabled = true; 8868 mResolveInfo.activityInfo = mResolveActivity; 8869 mResolveInfo.priority = 0; 8870 mResolveInfo.preferredOrder = 0; 8871 mResolveInfo.match = 0; 8872 mResolveComponentName = mCustomResolverComponentName; 8873 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8874 mResolveComponentName); 8875 } 8876 } 8877 8878 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8879 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8880 8881 // Set up information for ephemeral installer activity 8882 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8883 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8884 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8885 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8886 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8887 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8888 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8889 mEphemeralInstallerActivity.theme = 0; 8890 mEphemeralInstallerActivity.exported = true; 8891 mEphemeralInstallerActivity.enabled = true; 8892 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8893 mEphemeralInstallerInfo.priority = 0; 8894 mEphemeralInstallerInfo.preferredOrder = 0; 8895 mEphemeralInstallerInfo.match = 0; 8896 8897 if (DEBUG_EPHEMERAL) { 8898 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8899 } 8900 } 8901 8902 private static String calculateBundledApkRoot(final String codePathString) { 8903 final File codePath = new File(codePathString); 8904 final File codeRoot; 8905 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8906 codeRoot = Environment.getRootDirectory(); 8907 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8908 codeRoot = Environment.getOemDirectory(); 8909 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8910 codeRoot = Environment.getVendorDirectory(); 8911 } else { 8912 // Unrecognized code path; take its top real segment as the apk root: 8913 // e.g. /something/app/blah.apk => /something 8914 try { 8915 File f = codePath.getCanonicalFile(); 8916 File parent = f.getParentFile(); // non-null because codePath is a file 8917 File tmp; 8918 while ((tmp = parent.getParentFile()) != null) { 8919 f = parent; 8920 parent = tmp; 8921 } 8922 codeRoot = f; 8923 Slog.w(TAG, "Unrecognized code path " 8924 + codePath + " - using " + codeRoot); 8925 } catch (IOException e) { 8926 // Can't canonicalize the code path -- shenanigans? 8927 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8928 return Environment.getRootDirectory().getPath(); 8929 } 8930 } 8931 return codeRoot.getPath(); 8932 } 8933 8934 /** 8935 * Derive and set the location of native libraries for the given package, 8936 * which varies depending on where and how the package was installed. 8937 */ 8938 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8939 final ApplicationInfo info = pkg.applicationInfo; 8940 final String codePath = pkg.codePath; 8941 final File codeFile = new File(codePath); 8942 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8943 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8944 8945 info.nativeLibraryRootDir = null; 8946 info.nativeLibraryRootRequiresIsa = false; 8947 info.nativeLibraryDir = null; 8948 info.secondaryNativeLibraryDir = null; 8949 8950 if (isApkFile(codeFile)) { 8951 // Monolithic install 8952 if (bundledApp) { 8953 // If "/system/lib64/apkname" exists, assume that is the per-package 8954 // native library directory to use; otherwise use "/system/lib/apkname". 8955 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8956 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8957 getPrimaryInstructionSet(info)); 8958 8959 // This is a bundled system app so choose the path based on the ABI. 8960 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8961 // is just the default path. 8962 final String apkName = deriveCodePathName(codePath); 8963 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8964 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8965 apkName).getAbsolutePath(); 8966 8967 if (info.secondaryCpuAbi != null) { 8968 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8969 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8970 secondaryLibDir, apkName).getAbsolutePath(); 8971 } 8972 } else if (asecApp) { 8973 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8974 .getAbsolutePath(); 8975 } else { 8976 final String apkName = deriveCodePathName(codePath); 8977 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8978 .getAbsolutePath(); 8979 } 8980 8981 info.nativeLibraryRootRequiresIsa = false; 8982 info.nativeLibraryDir = info.nativeLibraryRootDir; 8983 } else { 8984 // Cluster install 8985 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8986 info.nativeLibraryRootRequiresIsa = true; 8987 8988 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8989 getPrimaryInstructionSet(info)).getAbsolutePath(); 8990 8991 if (info.secondaryCpuAbi != null) { 8992 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8993 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8994 } 8995 } 8996 } 8997 8998 /** 8999 * Calculate the abis and roots for a bundled app. These can uniquely 9000 * be determined from the contents of the system partition, i.e whether 9001 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9002 * of this information, and instead assume that the system was built 9003 * sensibly. 9004 */ 9005 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9006 PackageSetting pkgSetting) { 9007 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9008 9009 // If "/system/lib64/apkname" exists, assume that is the per-package 9010 // native library directory to use; otherwise use "/system/lib/apkname". 9011 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9012 setBundledAppAbi(pkg, apkRoot, apkName); 9013 // pkgSetting might be null during rescan following uninstall of updates 9014 // to a bundled app, so accommodate that possibility. The settings in 9015 // that case will be established later from the parsed package. 9016 // 9017 // If the settings aren't null, sync them up with what we've just derived. 9018 // note that apkRoot isn't stored in the package settings. 9019 if (pkgSetting != null) { 9020 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9021 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9022 } 9023 } 9024 9025 /** 9026 * Deduces the ABI of a bundled app and sets the relevant fields on the 9027 * parsed pkg object. 9028 * 9029 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9030 * under which system libraries are installed. 9031 * @param apkName the name of the installed package. 9032 */ 9033 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9034 final File codeFile = new File(pkg.codePath); 9035 9036 final boolean has64BitLibs; 9037 final boolean has32BitLibs; 9038 if (isApkFile(codeFile)) { 9039 // Monolithic install 9040 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9041 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9042 } else { 9043 // Cluster install 9044 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9045 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9046 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9047 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9048 has64BitLibs = (new File(rootDir, isa)).exists(); 9049 } else { 9050 has64BitLibs = false; 9051 } 9052 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9053 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9054 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9055 has32BitLibs = (new File(rootDir, isa)).exists(); 9056 } else { 9057 has32BitLibs = false; 9058 } 9059 } 9060 9061 if (has64BitLibs && !has32BitLibs) { 9062 // The package has 64 bit libs, but not 32 bit libs. Its primary 9063 // ABI should be 64 bit. We can safely assume here that the bundled 9064 // native libraries correspond to the most preferred ABI in the list. 9065 9066 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9067 pkg.applicationInfo.secondaryCpuAbi = null; 9068 } else if (has32BitLibs && !has64BitLibs) { 9069 // The package has 32 bit libs but not 64 bit libs. Its primary 9070 // ABI should be 32 bit. 9071 9072 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9073 pkg.applicationInfo.secondaryCpuAbi = null; 9074 } else if (has32BitLibs && has64BitLibs) { 9075 // The application has both 64 and 32 bit bundled libraries. We check 9076 // here that the app declares multiArch support, and warn if it doesn't. 9077 // 9078 // We will be lenient here and record both ABIs. The primary will be the 9079 // ABI that's higher on the list, i.e, a device that's configured to prefer 9080 // 64 bit apps will see a 64 bit primary ABI, 9081 9082 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9083 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9084 } 9085 9086 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9087 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9088 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9089 } else { 9090 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9091 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9092 } 9093 } else { 9094 pkg.applicationInfo.primaryCpuAbi = null; 9095 pkg.applicationInfo.secondaryCpuAbi = null; 9096 } 9097 } 9098 9099 private void killApplication(String pkgName, int appId, String reason) { 9100 // Request the ActivityManager to kill the process(only for existing packages) 9101 // so that we do not end up in a confused state while the user is still using the older 9102 // version of the application while the new one gets installed. 9103 final long token = Binder.clearCallingIdentity(); 9104 try { 9105 IActivityManager am = ActivityManagerNative.getDefault(); 9106 if (am != null) { 9107 try { 9108 am.killApplicationWithAppId(pkgName, appId, reason); 9109 } catch (RemoteException e) { 9110 } 9111 } 9112 } finally { 9113 Binder.restoreCallingIdentity(token); 9114 } 9115 } 9116 9117 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9118 // Remove the parent package setting 9119 PackageSetting ps = (PackageSetting) pkg.mExtras; 9120 if (ps != null) { 9121 removePackageLI(ps, chatty); 9122 } 9123 // Remove the child package setting 9124 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9125 for (int i = 0; i < childCount; i++) { 9126 PackageParser.Package childPkg = pkg.childPackages.get(i); 9127 ps = (PackageSetting) childPkg.mExtras; 9128 if (ps != null) { 9129 removePackageLI(ps, chatty); 9130 } 9131 } 9132 } 9133 9134 void removePackageLI(PackageSetting ps, boolean chatty) { 9135 if (DEBUG_INSTALL) { 9136 if (chatty) 9137 Log.d(TAG, "Removing package " + ps.name); 9138 } 9139 9140 // writer 9141 synchronized (mPackages) { 9142 mPackages.remove(ps.name); 9143 final PackageParser.Package pkg = ps.pkg; 9144 if (pkg != null) { 9145 cleanPackageDataStructuresLILPw(pkg, chatty); 9146 } 9147 } 9148 } 9149 9150 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9151 if (DEBUG_INSTALL) { 9152 if (chatty) 9153 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9154 } 9155 9156 // writer 9157 synchronized (mPackages) { 9158 // Remove the parent package 9159 mPackages.remove(pkg.applicationInfo.packageName); 9160 cleanPackageDataStructuresLILPw(pkg, chatty); 9161 9162 // Remove the child packages 9163 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9164 for (int i = 0; i < childCount; i++) { 9165 PackageParser.Package childPkg = pkg.childPackages.get(i); 9166 mPackages.remove(childPkg.applicationInfo.packageName); 9167 cleanPackageDataStructuresLILPw(childPkg, chatty); 9168 } 9169 } 9170 } 9171 9172 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9173 int N = pkg.providers.size(); 9174 StringBuilder r = null; 9175 int i; 9176 for (i=0; i<N; i++) { 9177 PackageParser.Provider p = pkg.providers.get(i); 9178 mProviders.removeProvider(p); 9179 if (p.info.authority == null) { 9180 9181 /* There was another ContentProvider with this authority when 9182 * this app was installed so this authority is null, 9183 * Ignore it as we don't have to unregister the provider. 9184 */ 9185 continue; 9186 } 9187 String names[] = p.info.authority.split(";"); 9188 for (int j = 0; j < names.length; j++) { 9189 if (mProvidersByAuthority.get(names[j]) == p) { 9190 mProvidersByAuthority.remove(names[j]); 9191 if (DEBUG_REMOVE) { 9192 if (chatty) 9193 Log.d(TAG, "Unregistered content provider: " + names[j] 9194 + ", className = " + p.info.name + ", isSyncable = " 9195 + p.info.isSyncable); 9196 } 9197 } 9198 } 9199 if (DEBUG_REMOVE && chatty) { 9200 if (r == null) { 9201 r = new StringBuilder(256); 9202 } else { 9203 r.append(' '); 9204 } 9205 r.append(p.info.name); 9206 } 9207 } 9208 if (r != null) { 9209 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9210 } 9211 9212 N = pkg.services.size(); 9213 r = null; 9214 for (i=0; i<N; i++) { 9215 PackageParser.Service s = pkg.services.get(i); 9216 mServices.removeService(s); 9217 if (chatty) { 9218 if (r == null) { 9219 r = new StringBuilder(256); 9220 } else { 9221 r.append(' '); 9222 } 9223 r.append(s.info.name); 9224 } 9225 } 9226 if (r != null) { 9227 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9228 } 9229 9230 N = pkg.receivers.size(); 9231 r = null; 9232 for (i=0; i<N; i++) { 9233 PackageParser.Activity a = pkg.receivers.get(i); 9234 mReceivers.removeActivity(a, "receiver"); 9235 if (DEBUG_REMOVE && chatty) { 9236 if (r == null) { 9237 r = new StringBuilder(256); 9238 } else { 9239 r.append(' '); 9240 } 9241 r.append(a.info.name); 9242 } 9243 } 9244 if (r != null) { 9245 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9246 } 9247 9248 N = pkg.activities.size(); 9249 r = null; 9250 for (i=0; i<N; i++) { 9251 PackageParser.Activity a = pkg.activities.get(i); 9252 mActivities.removeActivity(a, "activity"); 9253 if (DEBUG_REMOVE && chatty) { 9254 if (r == null) { 9255 r = new StringBuilder(256); 9256 } else { 9257 r.append(' '); 9258 } 9259 r.append(a.info.name); 9260 } 9261 } 9262 if (r != null) { 9263 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9264 } 9265 9266 N = pkg.permissions.size(); 9267 r = null; 9268 for (i=0; i<N; i++) { 9269 PackageParser.Permission p = pkg.permissions.get(i); 9270 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9271 if (bp == null) { 9272 bp = mSettings.mPermissionTrees.get(p.info.name); 9273 } 9274 if (bp != null && bp.perm == p) { 9275 bp.perm = null; 9276 if (DEBUG_REMOVE && chatty) { 9277 if (r == null) { 9278 r = new StringBuilder(256); 9279 } else { 9280 r.append(' '); 9281 } 9282 r.append(p.info.name); 9283 } 9284 } 9285 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9286 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9287 if (appOpPkgs != null) { 9288 appOpPkgs.remove(pkg.packageName); 9289 } 9290 } 9291 } 9292 if (r != null) { 9293 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9294 } 9295 9296 N = pkg.requestedPermissions.size(); 9297 r = null; 9298 for (i=0; i<N; i++) { 9299 String perm = pkg.requestedPermissions.get(i); 9300 BasePermission bp = mSettings.mPermissions.get(perm); 9301 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9302 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9303 if (appOpPkgs != null) { 9304 appOpPkgs.remove(pkg.packageName); 9305 if (appOpPkgs.isEmpty()) { 9306 mAppOpPermissionPackages.remove(perm); 9307 } 9308 } 9309 } 9310 } 9311 if (r != null) { 9312 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9313 } 9314 9315 N = pkg.instrumentation.size(); 9316 r = null; 9317 for (i=0; i<N; i++) { 9318 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9319 mInstrumentation.remove(a.getComponentName()); 9320 if (DEBUG_REMOVE && chatty) { 9321 if (r == null) { 9322 r = new StringBuilder(256); 9323 } else { 9324 r.append(' '); 9325 } 9326 r.append(a.info.name); 9327 } 9328 } 9329 if (r != null) { 9330 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9331 } 9332 9333 r = null; 9334 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9335 // Only system apps can hold shared libraries. 9336 if (pkg.libraryNames != null) { 9337 for (i=0; i<pkg.libraryNames.size(); i++) { 9338 String name = pkg.libraryNames.get(i); 9339 SharedLibraryEntry cur = mSharedLibraries.get(name); 9340 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9341 mSharedLibraries.remove(name); 9342 if (DEBUG_REMOVE && chatty) { 9343 if (r == null) { 9344 r = new StringBuilder(256); 9345 } else { 9346 r.append(' '); 9347 } 9348 r.append(name); 9349 } 9350 } 9351 } 9352 } 9353 } 9354 if (r != null) { 9355 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9356 } 9357 } 9358 9359 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9360 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9361 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9362 return true; 9363 } 9364 } 9365 return false; 9366 } 9367 9368 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9369 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9370 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9371 9372 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9373 // Update the parent permissions 9374 updatePermissionsLPw(pkg.packageName, pkg, flags); 9375 // Update the child permissions 9376 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9377 for (int i = 0; i < childCount; i++) { 9378 PackageParser.Package childPkg = pkg.childPackages.get(i); 9379 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9380 } 9381 } 9382 9383 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9384 int flags) { 9385 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9386 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9387 } 9388 9389 private void updatePermissionsLPw(String changingPkg, 9390 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9391 // Make sure there are no dangling permission trees. 9392 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9393 while (it.hasNext()) { 9394 final BasePermission bp = it.next(); 9395 if (bp.packageSetting == null) { 9396 // We may not yet have parsed the package, so just see if 9397 // we still know about its settings. 9398 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9399 } 9400 if (bp.packageSetting == null) { 9401 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9402 + " from package " + bp.sourcePackage); 9403 it.remove(); 9404 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9405 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9406 Slog.i(TAG, "Removing old permission tree: " + bp.name 9407 + " from package " + bp.sourcePackage); 9408 flags |= UPDATE_PERMISSIONS_ALL; 9409 it.remove(); 9410 } 9411 } 9412 } 9413 9414 // Make sure all dynamic permissions have been assigned to a package, 9415 // and make sure there are no dangling permissions. 9416 it = mSettings.mPermissions.values().iterator(); 9417 while (it.hasNext()) { 9418 final BasePermission bp = it.next(); 9419 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9420 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9421 + bp.name + " pkg=" + bp.sourcePackage 9422 + " info=" + bp.pendingInfo); 9423 if (bp.packageSetting == null && bp.pendingInfo != null) { 9424 final BasePermission tree = findPermissionTreeLP(bp.name); 9425 if (tree != null && tree.perm != null) { 9426 bp.packageSetting = tree.packageSetting; 9427 bp.perm = new PackageParser.Permission(tree.perm.owner, 9428 new PermissionInfo(bp.pendingInfo)); 9429 bp.perm.info.packageName = tree.perm.info.packageName; 9430 bp.perm.info.name = bp.name; 9431 bp.uid = tree.uid; 9432 } 9433 } 9434 } 9435 if (bp.packageSetting == null) { 9436 // We may not yet have parsed the package, so just see if 9437 // we still know about its settings. 9438 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9439 } 9440 if (bp.packageSetting == null) { 9441 Slog.w(TAG, "Removing dangling permission: " + bp.name 9442 + " from package " + bp.sourcePackage); 9443 it.remove(); 9444 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9445 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9446 Slog.i(TAG, "Removing old permission: " + bp.name 9447 + " from package " + bp.sourcePackage); 9448 flags |= UPDATE_PERMISSIONS_ALL; 9449 it.remove(); 9450 } 9451 } 9452 } 9453 9454 // Now update the permissions for all packages, in particular 9455 // replace the granted permissions of the system packages. 9456 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9457 for (PackageParser.Package pkg : mPackages.values()) { 9458 if (pkg != pkgInfo) { 9459 // Only replace for packages on requested volume 9460 final String volumeUuid = getVolumeUuidForPackage(pkg); 9461 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9462 && Objects.equals(replaceVolumeUuid, volumeUuid); 9463 grantPermissionsLPw(pkg, replace, changingPkg); 9464 } 9465 } 9466 } 9467 9468 if (pkgInfo != null) { 9469 // Only replace for packages on requested volume 9470 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9471 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9472 && Objects.equals(replaceVolumeUuid, volumeUuid); 9473 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9474 } 9475 } 9476 9477 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9478 String packageOfInterest) { 9479 // IMPORTANT: There are two types of permissions: install and runtime. 9480 // Install time permissions are granted when the app is installed to 9481 // all device users and users added in the future. Runtime permissions 9482 // are granted at runtime explicitly to specific users. Normal and signature 9483 // protected permissions are install time permissions. Dangerous permissions 9484 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9485 // otherwise they are runtime permissions. This function does not manage 9486 // runtime permissions except for the case an app targeting Lollipop MR1 9487 // being upgraded to target a newer SDK, in which case dangerous permissions 9488 // are transformed from install time to runtime ones. 9489 9490 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9491 if (ps == null) { 9492 return; 9493 } 9494 9495 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9496 9497 PermissionsState permissionsState = ps.getPermissionsState(); 9498 PermissionsState origPermissions = permissionsState; 9499 9500 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9501 9502 boolean runtimePermissionsRevoked = false; 9503 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9504 9505 boolean changedInstallPermission = false; 9506 9507 if (replace) { 9508 ps.installPermissionsFixed = false; 9509 if (!ps.isSharedUser()) { 9510 origPermissions = new PermissionsState(permissionsState); 9511 permissionsState.reset(); 9512 } else { 9513 // We need to know only about runtime permission changes since the 9514 // calling code always writes the install permissions state but 9515 // the runtime ones are written only if changed. The only cases of 9516 // changed runtime permissions here are promotion of an install to 9517 // runtime and revocation of a runtime from a shared user. 9518 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9519 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9520 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9521 runtimePermissionsRevoked = true; 9522 } 9523 } 9524 } 9525 9526 permissionsState.setGlobalGids(mGlobalGids); 9527 9528 final int N = pkg.requestedPermissions.size(); 9529 for (int i=0; i<N; i++) { 9530 final String name = pkg.requestedPermissions.get(i); 9531 final BasePermission bp = mSettings.mPermissions.get(name); 9532 9533 if (DEBUG_INSTALL) { 9534 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9535 } 9536 9537 if (bp == null || bp.packageSetting == null) { 9538 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9539 Slog.w(TAG, "Unknown permission " + name 9540 + " in package " + pkg.packageName); 9541 } 9542 continue; 9543 } 9544 9545 final String perm = bp.name; 9546 boolean allowedSig = false; 9547 int grant = GRANT_DENIED; 9548 9549 // Keep track of app op permissions. 9550 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9551 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9552 if (pkgs == null) { 9553 pkgs = new ArraySet<>(); 9554 mAppOpPermissionPackages.put(bp.name, pkgs); 9555 } 9556 pkgs.add(pkg.packageName); 9557 } 9558 9559 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9560 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9561 >= Build.VERSION_CODES.M; 9562 switch (level) { 9563 case PermissionInfo.PROTECTION_NORMAL: { 9564 // For all apps normal permissions are install time ones. 9565 grant = GRANT_INSTALL; 9566 } break; 9567 9568 case PermissionInfo.PROTECTION_DANGEROUS: { 9569 // If a permission review is required for legacy apps we represent 9570 // their permissions as always granted runtime ones since we need 9571 // to keep the review required permission flag per user while an 9572 // install permission's state is shared across all users. 9573 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9574 // For legacy apps dangerous permissions are install time ones. 9575 grant = GRANT_INSTALL; 9576 } else if (origPermissions.hasInstallPermission(bp.name)) { 9577 // For legacy apps that became modern, install becomes runtime. 9578 grant = GRANT_UPGRADE; 9579 } else if (mPromoteSystemApps 9580 && isSystemApp(ps) 9581 && mExistingSystemPackages.contains(ps.name)) { 9582 // For legacy system apps, install becomes runtime. 9583 // We cannot check hasInstallPermission() for system apps since those 9584 // permissions were granted implicitly and not persisted pre-M. 9585 grant = GRANT_UPGRADE; 9586 } else { 9587 // For modern apps keep runtime permissions unchanged. 9588 grant = GRANT_RUNTIME; 9589 } 9590 } break; 9591 9592 case PermissionInfo.PROTECTION_SIGNATURE: { 9593 // For all apps signature permissions are install time ones. 9594 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9595 if (allowedSig) { 9596 grant = GRANT_INSTALL; 9597 } 9598 } break; 9599 } 9600 9601 if (DEBUG_INSTALL) { 9602 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9603 } 9604 9605 if (grant != GRANT_DENIED) { 9606 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9607 // If this is an existing, non-system package, then 9608 // we can't add any new permissions to it. 9609 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9610 // Except... if this is a permission that was added 9611 // to the platform (note: need to only do this when 9612 // updating the platform). 9613 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9614 grant = GRANT_DENIED; 9615 } 9616 } 9617 } 9618 9619 switch (grant) { 9620 case GRANT_INSTALL: { 9621 // Revoke this as runtime permission to handle the case of 9622 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9623 for (int userId : UserManagerService.getInstance().getUserIds()) { 9624 if (origPermissions.getRuntimePermissionState( 9625 bp.name, userId) != null) { 9626 // Revoke the runtime permission and clear the flags. 9627 origPermissions.revokeRuntimePermission(bp, userId); 9628 origPermissions.updatePermissionFlags(bp, userId, 9629 PackageManager.MASK_PERMISSION_FLAGS, 0); 9630 // If we revoked a permission permission, we have to write. 9631 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9632 changedRuntimePermissionUserIds, userId); 9633 } 9634 } 9635 // Grant an install permission. 9636 if (permissionsState.grantInstallPermission(bp) != 9637 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9638 changedInstallPermission = true; 9639 } 9640 } break; 9641 9642 case GRANT_RUNTIME: { 9643 // Grant previously granted runtime permissions. 9644 for (int userId : UserManagerService.getInstance().getUserIds()) { 9645 PermissionState permissionState = origPermissions 9646 .getRuntimePermissionState(bp.name, userId); 9647 int flags = permissionState != null 9648 ? permissionState.getFlags() : 0; 9649 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9650 if (permissionsState.grantRuntimePermission(bp, userId) == 9651 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9652 // If we cannot put the permission as it was, we have to write. 9653 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9654 changedRuntimePermissionUserIds, userId); 9655 } 9656 // If the app supports runtime permissions no need for a review. 9657 if (Build.PERMISSIONS_REVIEW_REQUIRED 9658 && appSupportsRuntimePermissions 9659 && (flags & PackageManager 9660 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9661 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9662 // Since we changed the flags, we have to write. 9663 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9664 changedRuntimePermissionUserIds, userId); 9665 } 9666 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9667 && !appSupportsRuntimePermissions) { 9668 // For legacy apps that need a permission review, every new 9669 // runtime permission is granted but it is pending a review. 9670 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9671 permissionsState.grantRuntimePermission(bp, userId); 9672 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9673 // We changed the permission and flags, hence have to write. 9674 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9675 changedRuntimePermissionUserIds, userId); 9676 } 9677 } 9678 // Propagate the permission flags. 9679 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9680 } 9681 } break; 9682 9683 case GRANT_UPGRADE: { 9684 // Grant runtime permissions for a previously held install permission. 9685 PermissionState permissionState = origPermissions 9686 .getInstallPermissionState(bp.name); 9687 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9688 9689 if (origPermissions.revokeInstallPermission(bp) 9690 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9691 // We will be transferring the permission flags, so clear them. 9692 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9693 PackageManager.MASK_PERMISSION_FLAGS, 0); 9694 changedInstallPermission = true; 9695 } 9696 9697 // If the permission is not to be promoted to runtime we ignore it and 9698 // also its other flags as they are not applicable to install permissions. 9699 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9700 for (int userId : currentUserIds) { 9701 if (permissionsState.grantRuntimePermission(bp, userId) != 9702 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9703 // Transfer the permission flags. 9704 permissionsState.updatePermissionFlags(bp, userId, 9705 flags, flags); 9706 // If we granted the permission, we have to write. 9707 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9708 changedRuntimePermissionUserIds, userId); 9709 } 9710 } 9711 } 9712 } break; 9713 9714 default: { 9715 if (packageOfInterest == null 9716 || packageOfInterest.equals(pkg.packageName)) { 9717 Slog.w(TAG, "Not granting permission " + perm 9718 + " to package " + pkg.packageName 9719 + " because it was previously installed without"); 9720 } 9721 } break; 9722 } 9723 } else { 9724 if (permissionsState.revokeInstallPermission(bp) != 9725 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9726 // Also drop the permission flags. 9727 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9728 PackageManager.MASK_PERMISSION_FLAGS, 0); 9729 changedInstallPermission = true; 9730 Slog.i(TAG, "Un-granting permission " + perm 9731 + " from package " + pkg.packageName 9732 + " (protectionLevel=" + bp.protectionLevel 9733 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9734 + ")"); 9735 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9736 // Don't print warning for app op permissions, since it is fine for them 9737 // not to be granted, there is a UI for the user to decide. 9738 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9739 Slog.w(TAG, "Not granting permission " + perm 9740 + " to package " + pkg.packageName 9741 + " (protectionLevel=" + bp.protectionLevel 9742 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9743 + ")"); 9744 } 9745 } 9746 } 9747 } 9748 9749 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9750 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9751 // This is the first that we have heard about this package, so the 9752 // permissions we have now selected are fixed until explicitly 9753 // changed. 9754 ps.installPermissionsFixed = true; 9755 } 9756 9757 // Persist the runtime permissions state for users with changes. If permissions 9758 // were revoked because no app in the shared user declares them we have to 9759 // write synchronously to avoid losing runtime permissions state. 9760 for (int userId : changedRuntimePermissionUserIds) { 9761 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9762 } 9763 9764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9765 } 9766 9767 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9768 boolean allowed = false; 9769 final int NP = PackageParser.NEW_PERMISSIONS.length; 9770 for (int ip=0; ip<NP; ip++) { 9771 final PackageParser.NewPermissionInfo npi 9772 = PackageParser.NEW_PERMISSIONS[ip]; 9773 if (npi.name.equals(perm) 9774 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9775 allowed = true; 9776 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9777 + pkg.packageName); 9778 break; 9779 } 9780 } 9781 return allowed; 9782 } 9783 9784 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9785 BasePermission bp, PermissionsState origPermissions) { 9786 boolean allowed; 9787 allowed = (compareSignatures( 9788 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9789 == PackageManager.SIGNATURE_MATCH) 9790 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9791 == PackageManager.SIGNATURE_MATCH); 9792 if (!allowed && (bp.protectionLevel 9793 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9794 if (isSystemApp(pkg)) { 9795 // For updated system applications, a system permission 9796 // is granted only if it had been defined by the original application. 9797 if (pkg.isUpdatedSystemApp()) { 9798 final PackageSetting sysPs = mSettings 9799 .getDisabledSystemPkgLPr(pkg.packageName); 9800 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9801 // If the original was granted this permission, we take 9802 // that grant decision as read and propagate it to the 9803 // update. 9804 if (sysPs.isPrivileged()) { 9805 allowed = true; 9806 } 9807 } else { 9808 // The system apk may have been updated with an older 9809 // version of the one on the data partition, but which 9810 // granted a new system permission that it didn't have 9811 // before. In this case we do want to allow the app to 9812 // now get the new permission if the ancestral apk is 9813 // privileged to get it. 9814 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9815 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9816 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9817 allowed = true; 9818 break; 9819 } 9820 } 9821 } 9822 // Also if a privileged parent package on the system image or any of 9823 // its children requested a privileged permission, the updated child 9824 // packages can also get the permission. 9825 if (pkg.parentPackage != null) { 9826 final PackageSetting disabledSysParentPs = mSettings 9827 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9828 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9829 && disabledSysParentPs.isPrivileged()) { 9830 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9831 allowed = true; 9832 } else if (disabledSysParentPs.pkg.childPackages != null) { 9833 final int count = disabledSysParentPs.pkg.childPackages.size(); 9834 for (int i = 0; i < count; i++) { 9835 PackageParser.Package disabledSysChildPkg = 9836 disabledSysParentPs.pkg.childPackages.get(i); 9837 if (isPackageRequestingPermission(disabledSysChildPkg, 9838 perm)) { 9839 allowed = true; 9840 break; 9841 } 9842 } 9843 } 9844 } 9845 } 9846 } 9847 } else { 9848 allowed = isPrivilegedApp(pkg); 9849 } 9850 } 9851 } 9852 if (!allowed) { 9853 if (!allowed && (bp.protectionLevel 9854 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9855 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9856 // If this was a previously normal/dangerous permission that got moved 9857 // to a system permission as part of the runtime permission redesign, then 9858 // we still want to blindly grant it to old apps. 9859 allowed = true; 9860 } 9861 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9862 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9863 // If this permission is to be granted to the system installer and 9864 // this app is an installer, then it gets the permission. 9865 allowed = true; 9866 } 9867 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9868 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9869 // If this permission is to be granted to the system verifier and 9870 // this app is a verifier, then it gets the permission. 9871 allowed = true; 9872 } 9873 if (!allowed && (bp.protectionLevel 9874 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9875 && isSystemApp(pkg)) { 9876 // Any pre-installed system app is allowed to get this permission. 9877 allowed = true; 9878 } 9879 if (!allowed && (bp.protectionLevel 9880 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9881 // For development permissions, a development permission 9882 // is granted only if it was already granted. 9883 allowed = origPermissions.hasInstallPermission(perm); 9884 } 9885 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9886 && pkg.packageName.equals(mSetupWizardPackage)) { 9887 // If this permission is to be granted to the system setup wizard and 9888 // this app is a setup wizard, then it gets the permission. 9889 allowed = true; 9890 } 9891 } 9892 return allowed; 9893 } 9894 9895 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9896 final int permCount = pkg.requestedPermissions.size(); 9897 for (int j = 0; j < permCount; j++) { 9898 String requestedPermission = pkg.requestedPermissions.get(j); 9899 if (permission.equals(requestedPermission)) { 9900 return true; 9901 } 9902 } 9903 return false; 9904 } 9905 9906 final class ActivityIntentResolver 9907 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9908 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9909 boolean defaultOnly, int userId) { 9910 if (!sUserManager.exists(userId)) return null; 9911 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9912 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9913 } 9914 9915 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9916 int userId) { 9917 if (!sUserManager.exists(userId)) return null; 9918 mFlags = flags; 9919 return super.queryIntent(intent, resolvedType, 9920 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9921 } 9922 9923 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9924 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9925 if (!sUserManager.exists(userId)) return null; 9926 if (packageActivities == null) { 9927 return null; 9928 } 9929 mFlags = flags; 9930 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9931 final int N = packageActivities.size(); 9932 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9933 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9934 9935 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9936 for (int i = 0; i < N; ++i) { 9937 intentFilters = packageActivities.get(i).intents; 9938 if (intentFilters != null && intentFilters.size() > 0) { 9939 PackageParser.ActivityIntentInfo[] array = 9940 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9941 intentFilters.toArray(array); 9942 listCut.add(array); 9943 } 9944 } 9945 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9946 } 9947 9948 /** 9949 * Finds a privileged activity that matches the specified activity names. 9950 */ 9951 private PackageParser.Activity findMatchingActivity( 9952 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9953 for (PackageParser.Activity sysActivity : activityList) { 9954 if (sysActivity.info.name.equals(activityInfo.name)) { 9955 return sysActivity; 9956 } 9957 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9958 return sysActivity; 9959 } 9960 if (sysActivity.info.targetActivity != null) { 9961 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9962 return sysActivity; 9963 } 9964 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9965 return sysActivity; 9966 } 9967 } 9968 } 9969 return null; 9970 } 9971 9972 public class IterGenerator<E> { 9973 public Iterator<E> generate(ActivityIntentInfo info) { 9974 return null; 9975 } 9976 } 9977 9978 public class ActionIterGenerator extends IterGenerator<String> { 9979 @Override 9980 public Iterator<String> generate(ActivityIntentInfo info) { 9981 return info.actionsIterator(); 9982 } 9983 } 9984 9985 public class CategoriesIterGenerator extends IterGenerator<String> { 9986 @Override 9987 public Iterator<String> generate(ActivityIntentInfo info) { 9988 return info.categoriesIterator(); 9989 } 9990 } 9991 9992 public class SchemesIterGenerator extends IterGenerator<String> { 9993 @Override 9994 public Iterator<String> generate(ActivityIntentInfo info) { 9995 return info.schemesIterator(); 9996 } 9997 } 9998 9999 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10000 @Override 10001 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10002 return info.authoritiesIterator(); 10003 } 10004 } 10005 10006 /** 10007 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10008 * MODIFIED. Do not pass in a list that should not be changed. 10009 */ 10010 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10011 IterGenerator<T> generator, Iterator<T> searchIterator) { 10012 // loop through the set of actions; every one must be found in the intent filter 10013 while (searchIterator.hasNext()) { 10014 // we must have at least one filter in the list to consider a match 10015 if (intentList.size() == 0) { 10016 break; 10017 } 10018 10019 final T searchAction = searchIterator.next(); 10020 10021 // loop through the set of intent filters 10022 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10023 while (intentIter.hasNext()) { 10024 final ActivityIntentInfo intentInfo = intentIter.next(); 10025 boolean selectionFound = false; 10026 10027 // loop through the intent filter's selection criteria; at least one 10028 // of them must match the searched criteria 10029 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10030 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10031 final T intentSelection = intentSelectionIter.next(); 10032 if (intentSelection != null && intentSelection.equals(searchAction)) { 10033 selectionFound = true; 10034 break; 10035 } 10036 } 10037 10038 // the selection criteria wasn't found in this filter's set; this filter 10039 // is not a potential match 10040 if (!selectionFound) { 10041 intentIter.remove(); 10042 } 10043 } 10044 } 10045 } 10046 10047 private boolean isProtectedAction(ActivityIntentInfo filter) { 10048 final Iterator<String> actionsIter = filter.actionsIterator(); 10049 while (actionsIter != null && actionsIter.hasNext()) { 10050 final String filterAction = actionsIter.next(); 10051 if (PROTECTED_ACTIONS.contains(filterAction)) { 10052 return true; 10053 } 10054 } 10055 return false; 10056 } 10057 10058 /** 10059 * Adjusts the priority of the given intent filter according to policy. 10060 * <p> 10061 * <ul> 10062 * <li>The priority for non privileged applications is capped to '0'</li> 10063 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10064 * <li>The priority for unbundled updates to privileged applications is capped to the 10065 * priority defined on the system partition</li> 10066 * </ul> 10067 * <p> 10068 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10069 * allowed to obtain any priority on any action. 10070 */ 10071 private void adjustPriority( 10072 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10073 // nothing to do; priority is fine as-is 10074 if (intent.getPriority() <= 0) { 10075 return; 10076 } 10077 10078 final ActivityInfo activityInfo = intent.activity.info; 10079 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10080 10081 final boolean privilegedApp = 10082 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10083 if (!privilegedApp) { 10084 // non-privileged applications can never define a priority >0 10085 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10086 + " package: " + applicationInfo.packageName 10087 + " activity: " + intent.activity.className 10088 + " origPrio: " + intent.getPriority()); 10089 intent.setPriority(0); 10090 return; 10091 } 10092 10093 if (systemActivities == null) { 10094 // the system package is not disabled; we're parsing the system partition 10095 if (isProtectedAction(intent)) { 10096 if (mDeferProtectedFilters) { 10097 // We can't deal with these just yet. No component should ever obtain a 10098 // >0 priority for a protected actions, with ONE exception -- the setup 10099 // wizard. The setup wizard, however, cannot be known until we're able to 10100 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10101 // until all intent filters have been processed. Chicken, meet egg. 10102 // Let the filter temporarily have a high priority and rectify the 10103 // priorities after all system packages have been scanned. 10104 mProtectedFilters.add(intent); 10105 if (DEBUG_FILTERS) { 10106 Slog.i(TAG, "Protected action; save for later;" 10107 + " package: " + applicationInfo.packageName 10108 + " activity: " + intent.activity.className 10109 + " origPrio: " + intent.getPriority()); 10110 } 10111 return; 10112 } else { 10113 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10114 Slog.i(TAG, "No setup wizard;" 10115 + " All protected intents capped to priority 0"); 10116 } 10117 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10118 if (DEBUG_FILTERS) { 10119 Slog.i(TAG, "Found setup wizard;" 10120 + " allow priority " + intent.getPriority() + ";" 10121 + " package: " + intent.activity.info.packageName 10122 + " activity: " + intent.activity.className 10123 + " priority: " + intent.getPriority()); 10124 } 10125 // setup wizard gets whatever it wants 10126 return; 10127 } 10128 Slog.w(TAG, "Protected action; cap priority to 0;" 10129 + " package: " + intent.activity.info.packageName 10130 + " activity: " + intent.activity.className 10131 + " origPrio: " + intent.getPriority()); 10132 intent.setPriority(0); 10133 return; 10134 } 10135 } 10136 // privileged apps on the system image get whatever priority they request 10137 return; 10138 } 10139 10140 // privileged app unbundled update ... try to find the same activity 10141 final PackageParser.Activity foundActivity = 10142 findMatchingActivity(systemActivities, activityInfo); 10143 if (foundActivity == null) { 10144 // this is a new activity; it cannot obtain >0 priority 10145 if (DEBUG_FILTERS) { 10146 Slog.i(TAG, "New activity; cap priority to 0;" 10147 + " package: " + applicationInfo.packageName 10148 + " activity: " + intent.activity.className 10149 + " origPrio: " + intent.getPriority()); 10150 } 10151 intent.setPriority(0); 10152 return; 10153 } 10154 10155 // found activity, now check for filter equivalence 10156 10157 // a shallow copy is enough; we modify the list, not its contents 10158 final List<ActivityIntentInfo> intentListCopy = 10159 new ArrayList<>(foundActivity.intents); 10160 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10161 10162 // find matching action subsets 10163 final Iterator<String> actionsIterator = intent.actionsIterator(); 10164 if (actionsIterator != null) { 10165 getIntentListSubset( 10166 intentListCopy, new ActionIterGenerator(), actionsIterator); 10167 if (intentListCopy.size() == 0) { 10168 // no more intents to match; we're not equivalent 10169 if (DEBUG_FILTERS) { 10170 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10171 + " package: " + applicationInfo.packageName 10172 + " activity: " + intent.activity.className 10173 + " origPrio: " + intent.getPriority()); 10174 } 10175 intent.setPriority(0); 10176 return; 10177 } 10178 } 10179 10180 // find matching category subsets 10181 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10182 if (categoriesIterator != null) { 10183 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10184 categoriesIterator); 10185 if (intentListCopy.size() == 0) { 10186 // no more intents to match; we're not equivalent 10187 if (DEBUG_FILTERS) { 10188 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10189 + " package: " + applicationInfo.packageName 10190 + " activity: " + intent.activity.className 10191 + " origPrio: " + intent.getPriority()); 10192 } 10193 intent.setPriority(0); 10194 return; 10195 } 10196 } 10197 10198 // find matching schemes subsets 10199 final Iterator<String> schemesIterator = intent.schemesIterator(); 10200 if (schemesIterator != null) { 10201 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10202 schemesIterator); 10203 if (intentListCopy.size() == 0) { 10204 // no more intents to match; we're not equivalent 10205 if (DEBUG_FILTERS) { 10206 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10207 + " package: " + applicationInfo.packageName 10208 + " activity: " + intent.activity.className 10209 + " origPrio: " + intent.getPriority()); 10210 } 10211 intent.setPriority(0); 10212 return; 10213 } 10214 } 10215 10216 // find matching authorities subsets 10217 final Iterator<IntentFilter.AuthorityEntry> 10218 authoritiesIterator = intent.authoritiesIterator(); 10219 if (authoritiesIterator != null) { 10220 getIntentListSubset(intentListCopy, 10221 new AuthoritiesIterGenerator(), 10222 authoritiesIterator); 10223 if (intentListCopy.size() == 0) { 10224 // no more intents to match; we're not equivalent 10225 if (DEBUG_FILTERS) { 10226 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10227 + " package: " + applicationInfo.packageName 10228 + " activity: " + intent.activity.className 10229 + " origPrio: " + intent.getPriority()); 10230 } 10231 intent.setPriority(0); 10232 return; 10233 } 10234 } 10235 10236 // we found matching filter(s); app gets the max priority of all intents 10237 int cappedPriority = 0; 10238 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10239 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10240 } 10241 if (intent.getPriority() > cappedPriority) { 10242 if (DEBUG_FILTERS) { 10243 Slog.i(TAG, "Found matching filter(s);" 10244 + " cap priority to " + cappedPriority + ";" 10245 + " package: " + applicationInfo.packageName 10246 + " activity: " + intent.activity.className 10247 + " origPrio: " + intent.getPriority()); 10248 } 10249 intent.setPriority(cappedPriority); 10250 return; 10251 } 10252 // all this for nothing; the requested priority was <= what was on the system 10253 } 10254 10255 public final void addActivity(PackageParser.Activity a, String type) { 10256 mActivities.put(a.getComponentName(), a); 10257 if (DEBUG_SHOW_INFO) 10258 Log.v( 10259 TAG, " " + type + " " + 10260 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10261 if (DEBUG_SHOW_INFO) 10262 Log.v(TAG, " Class=" + a.info.name); 10263 final int NI = a.intents.size(); 10264 for (int j=0; j<NI; j++) { 10265 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10266 if ("activity".equals(type)) { 10267 final PackageSetting ps = 10268 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10269 final List<PackageParser.Activity> systemActivities = 10270 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10271 adjustPriority(systemActivities, intent); 10272 } 10273 if (DEBUG_SHOW_INFO) { 10274 Log.v(TAG, " IntentFilter:"); 10275 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10276 } 10277 if (!intent.debugCheck()) { 10278 Log.w(TAG, "==> For Activity " + a.info.name); 10279 } 10280 addFilter(intent); 10281 } 10282 } 10283 10284 public final void removeActivity(PackageParser.Activity a, String type) { 10285 mActivities.remove(a.getComponentName()); 10286 if (DEBUG_SHOW_INFO) { 10287 Log.v(TAG, " " + type + " " 10288 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10289 : a.info.name) + ":"); 10290 Log.v(TAG, " Class=" + a.info.name); 10291 } 10292 final int NI = a.intents.size(); 10293 for (int j=0; j<NI; j++) { 10294 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10295 if (DEBUG_SHOW_INFO) { 10296 Log.v(TAG, " IntentFilter:"); 10297 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10298 } 10299 removeFilter(intent); 10300 } 10301 } 10302 10303 @Override 10304 protected boolean allowFilterResult( 10305 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10306 ActivityInfo filterAi = filter.activity.info; 10307 for (int i=dest.size()-1; i>=0; i--) { 10308 ActivityInfo destAi = dest.get(i).activityInfo; 10309 if (destAi.name == filterAi.name 10310 && destAi.packageName == filterAi.packageName) { 10311 return false; 10312 } 10313 } 10314 return true; 10315 } 10316 10317 @Override 10318 protected ActivityIntentInfo[] newArray(int size) { 10319 return new ActivityIntentInfo[size]; 10320 } 10321 10322 @Override 10323 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10324 if (!sUserManager.exists(userId)) return true; 10325 PackageParser.Package p = filter.activity.owner; 10326 if (p != null) { 10327 PackageSetting ps = (PackageSetting)p.mExtras; 10328 if (ps != null) { 10329 // System apps are never considered stopped for purposes of 10330 // filtering, because there may be no way for the user to 10331 // actually re-launch them. 10332 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10333 && ps.getStopped(userId); 10334 } 10335 } 10336 return false; 10337 } 10338 10339 @Override 10340 protected boolean isPackageForFilter(String packageName, 10341 PackageParser.ActivityIntentInfo info) { 10342 return packageName.equals(info.activity.owner.packageName); 10343 } 10344 10345 @Override 10346 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10347 int match, int userId) { 10348 if (!sUserManager.exists(userId)) return null; 10349 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10350 return null; 10351 } 10352 final PackageParser.Activity activity = info.activity; 10353 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10354 if (ps == null) { 10355 return null; 10356 } 10357 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10358 ps.readUserState(userId), userId); 10359 if (ai == null) { 10360 return null; 10361 } 10362 final ResolveInfo res = new ResolveInfo(); 10363 res.activityInfo = ai; 10364 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10365 res.filter = info; 10366 } 10367 if (info != null) { 10368 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10369 } 10370 res.priority = info.getPriority(); 10371 res.preferredOrder = activity.owner.mPreferredOrder; 10372 //System.out.println("Result: " + res.activityInfo.className + 10373 // " = " + res.priority); 10374 res.match = match; 10375 res.isDefault = info.hasDefault; 10376 res.labelRes = info.labelRes; 10377 res.nonLocalizedLabel = info.nonLocalizedLabel; 10378 if (userNeedsBadging(userId)) { 10379 res.noResourceId = true; 10380 } else { 10381 res.icon = info.icon; 10382 } 10383 res.iconResourceId = info.icon; 10384 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10385 return res; 10386 } 10387 10388 @Override 10389 protected void sortResults(List<ResolveInfo> results) { 10390 Collections.sort(results, mResolvePrioritySorter); 10391 } 10392 10393 @Override 10394 protected void dumpFilter(PrintWriter out, String prefix, 10395 PackageParser.ActivityIntentInfo filter) { 10396 out.print(prefix); out.print( 10397 Integer.toHexString(System.identityHashCode(filter.activity))); 10398 out.print(' '); 10399 filter.activity.printComponentShortName(out); 10400 out.print(" filter "); 10401 out.println(Integer.toHexString(System.identityHashCode(filter))); 10402 } 10403 10404 @Override 10405 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10406 return filter.activity; 10407 } 10408 10409 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10410 PackageParser.Activity activity = (PackageParser.Activity)label; 10411 out.print(prefix); out.print( 10412 Integer.toHexString(System.identityHashCode(activity))); 10413 out.print(' '); 10414 activity.printComponentShortName(out); 10415 if (count > 1) { 10416 out.print(" ("); out.print(count); out.print(" filters)"); 10417 } 10418 out.println(); 10419 } 10420 10421 // Keys are String (activity class name), values are Activity. 10422 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10423 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10424 private int mFlags; 10425 } 10426 10427 private final class ServiceIntentResolver 10428 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10429 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10430 boolean defaultOnly, int userId) { 10431 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10432 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10433 } 10434 10435 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10436 int userId) { 10437 if (!sUserManager.exists(userId)) return null; 10438 mFlags = flags; 10439 return super.queryIntent(intent, resolvedType, 10440 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10441 } 10442 10443 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10444 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10445 if (!sUserManager.exists(userId)) return null; 10446 if (packageServices == null) { 10447 return null; 10448 } 10449 mFlags = flags; 10450 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10451 final int N = packageServices.size(); 10452 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10453 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10454 10455 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10456 for (int i = 0; i < N; ++i) { 10457 intentFilters = packageServices.get(i).intents; 10458 if (intentFilters != null && intentFilters.size() > 0) { 10459 PackageParser.ServiceIntentInfo[] array = 10460 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10461 intentFilters.toArray(array); 10462 listCut.add(array); 10463 } 10464 } 10465 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10466 } 10467 10468 public final void addService(PackageParser.Service s) { 10469 mServices.put(s.getComponentName(), s); 10470 if (DEBUG_SHOW_INFO) { 10471 Log.v(TAG, " " 10472 + (s.info.nonLocalizedLabel != null 10473 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10474 Log.v(TAG, " Class=" + s.info.name); 10475 } 10476 final int NI = s.intents.size(); 10477 int j; 10478 for (j=0; j<NI; j++) { 10479 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10480 if (DEBUG_SHOW_INFO) { 10481 Log.v(TAG, " IntentFilter:"); 10482 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10483 } 10484 if (!intent.debugCheck()) { 10485 Log.w(TAG, "==> For Service " + s.info.name); 10486 } 10487 addFilter(intent); 10488 } 10489 } 10490 10491 public final void removeService(PackageParser.Service s) { 10492 mServices.remove(s.getComponentName()); 10493 if (DEBUG_SHOW_INFO) { 10494 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10495 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10496 Log.v(TAG, " Class=" + s.info.name); 10497 } 10498 final int NI = s.intents.size(); 10499 int j; 10500 for (j=0; j<NI; j++) { 10501 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10502 if (DEBUG_SHOW_INFO) { 10503 Log.v(TAG, " IntentFilter:"); 10504 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10505 } 10506 removeFilter(intent); 10507 } 10508 } 10509 10510 @Override 10511 protected boolean allowFilterResult( 10512 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10513 ServiceInfo filterSi = filter.service.info; 10514 for (int i=dest.size()-1; i>=0; i--) { 10515 ServiceInfo destAi = dest.get(i).serviceInfo; 10516 if (destAi.name == filterSi.name 10517 && destAi.packageName == filterSi.packageName) { 10518 return false; 10519 } 10520 } 10521 return true; 10522 } 10523 10524 @Override 10525 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10526 return new PackageParser.ServiceIntentInfo[size]; 10527 } 10528 10529 @Override 10530 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10531 if (!sUserManager.exists(userId)) return true; 10532 PackageParser.Package p = filter.service.owner; 10533 if (p != null) { 10534 PackageSetting ps = (PackageSetting)p.mExtras; 10535 if (ps != null) { 10536 // System apps are never considered stopped for purposes of 10537 // filtering, because there may be no way for the user to 10538 // actually re-launch them. 10539 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10540 && ps.getStopped(userId); 10541 } 10542 } 10543 return false; 10544 } 10545 10546 @Override 10547 protected boolean isPackageForFilter(String packageName, 10548 PackageParser.ServiceIntentInfo info) { 10549 return packageName.equals(info.service.owner.packageName); 10550 } 10551 10552 @Override 10553 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10554 int match, int userId) { 10555 if (!sUserManager.exists(userId)) return null; 10556 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10557 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10558 return null; 10559 } 10560 final PackageParser.Service service = info.service; 10561 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10562 if (ps == null) { 10563 return null; 10564 } 10565 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10566 ps.readUserState(userId), userId); 10567 if (si == null) { 10568 return null; 10569 } 10570 final ResolveInfo res = new ResolveInfo(); 10571 res.serviceInfo = si; 10572 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10573 res.filter = filter; 10574 } 10575 res.priority = info.getPriority(); 10576 res.preferredOrder = service.owner.mPreferredOrder; 10577 res.match = match; 10578 res.isDefault = info.hasDefault; 10579 res.labelRes = info.labelRes; 10580 res.nonLocalizedLabel = info.nonLocalizedLabel; 10581 res.icon = info.icon; 10582 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10583 return res; 10584 } 10585 10586 @Override 10587 protected void sortResults(List<ResolveInfo> results) { 10588 Collections.sort(results, mResolvePrioritySorter); 10589 } 10590 10591 @Override 10592 protected void dumpFilter(PrintWriter out, String prefix, 10593 PackageParser.ServiceIntentInfo filter) { 10594 out.print(prefix); out.print( 10595 Integer.toHexString(System.identityHashCode(filter.service))); 10596 out.print(' '); 10597 filter.service.printComponentShortName(out); 10598 out.print(" filter "); 10599 out.println(Integer.toHexString(System.identityHashCode(filter))); 10600 } 10601 10602 @Override 10603 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10604 return filter.service; 10605 } 10606 10607 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10608 PackageParser.Service service = (PackageParser.Service)label; 10609 out.print(prefix); out.print( 10610 Integer.toHexString(System.identityHashCode(service))); 10611 out.print(' '); 10612 service.printComponentShortName(out); 10613 if (count > 1) { 10614 out.print(" ("); out.print(count); out.print(" filters)"); 10615 } 10616 out.println(); 10617 } 10618 10619// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10620// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10621// final List<ResolveInfo> retList = Lists.newArrayList(); 10622// while (i.hasNext()) { 10623// final ResolveInfo resolveInfo = (ResolveInfo) i; 10624// if (isEnabledLP(resolveInfo.serviceInfo)) { 10625// retList.add(resolveInfo); 10626// } 10627// } 10628// return retList; 10629// } 10630 10631 // Keys are String (activity class name), values are Activity. 10632 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10633 = new ArrayMap<ComponentName, PackageParser.Service>(); 10634 private int mFlags; 10635 }; 10636 10637 private final class ProviderIntentResolver 10638 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10639 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10640 boolean defaultOnly, int userId) { 10641 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10642 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10643 } 10644 10645 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10646 int userId) { 10647 if (!sUserManager.exists(userId)) 10648 return null; 10649 mFlags = flags; 10650 return super.queryIntent(intent, resolvedType, 10651 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10652 } 10653 10654 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10655 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10656 if (!sUserManager.exists(userId)) 10657 return null; 10658 if (packageProviders == null) { 10659 return null; 10660 } 10661 mFlags = flags; 10662 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10663 final int N = packageProviders.size(); 10664 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10665 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10666 10667 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10668 for (int i = 0; i < N; ++i) { 10669 intentFilters = packageProviders.get(i).intents; 10670 if (intentFilters != null && intentFilters.size() > 0) { 10671 PackageParser.ProviderIntentInfo[] array = 10672 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10673 intentFilters.toArray(array); 10674 listCut.add(array); 10675 } 10676 } 10677 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10678 } 10679 10680 public final void addProvider(PackageParser.Provider p) { 10681 if (mProviders.containsKey(p.getComponentName())) { 10682 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10683 return; 10684 } 10685 10686 mProviders.put(p.getComponentName(), p); 10687 if (DEBUG_SHOW_INFO) { 10688 Log.v(TAG, " " 10689 + (p.info.nonLocalizedLabel != null 10690 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10691 Log.v(TAG, " Class=" + p.info.name); 10692 } 10693 final int NI = p.intents.size(); 10694 int j; 10695 for (j = 0; j < NI; j++) { 10696 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10697 if (DEBUG_SHOW_INFO) { 10698 Log.v(TAG, " IntentFilter:"); 10699 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10700 } 10701 if (!intent.debugCheck()) { 10702 Log.w(TAG, "==> For Provider " + p.info.name); 10703 } 10704 addFilter(intent); 10705 } 10706 } 10707 10708 public final void removeProvider(PackageParser.Provider p) { 10709 mProviders.remove(p.getComponentName()); 10710 if (DEBUG_SHOW_INFO) { 10711 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10712 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10713 Log.v(TAG, " Class=" + p.info.name); 10714 } 10715 final int NI = p.intents.size(); 10716 int j; 10717 for (j = 0; j < NI; j++) { 10718 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10719 if (DEBUG_SHOW_INFO) { 10720 Log.v(TAG, " IntentFilter:"); 10721 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10722 } 10723 removeFilter(intent); 10724 } 10725 } 10726 10727 @Override 10728 protected boolean allowFilterResult( 10729 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10730 ProviderInfo filterPi = filter.provider.info; 10731 for (int i = dest.size() - 1; i >= 0; i--) { 10732 ProviderInfo destPi = dest.get(i).providerInfo; 10733 if (destPi.name == filterPi.name 10734 && destPi.packageName == filterPi.packageName) { 10735 return false; 10736 } 10737 } 10738 return true; 10739 } 10740 10741 @Override 10742 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10743 return new PackageParser.ProviderIntentInfo[size]; 10744 } 10745 10746 @Override 10747 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10748 if (!sUserManager.exists(userId)) 10749 return true; 10750 PackageParser.Package p = filter.provider.owner; 10751 if (p != null) { 10752 PackageSetting ps = (PackageSetting) p.mExtras; 10753 if (ps != null) { 10754 // System apps are never considered stopped for purposes of 10755 // filtering, because there may be no way for the user to 10756 // actually re-launch them. 10757 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10758 && ps.getStopped(userId); 10759 } 10760 } 10761 return false; 10762 } 10763 10764 @Override 10765 protected boolean isPackageForFilter(String packageName, 10766 PackageParser.ProviderIntentInfo info) { 10767 return packageName.equals(info.provider.owner.packageName); 10768 } 10769 10770 @Override 10771 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10772 int match, int userId) { 10773 if (!sUserManager.exists(userId)) 10774 return null; 10775 final PackageParser.ProviderIntentInfo info = filter; 10776 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10777 return null; 10778 } 10779 final PackageParser.Provider provider = info.provider; 10780 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10781 if (ps == null) { 10782 return null; 10783 } 10784 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10785 ps.readUserState(userId), userId); 10786 if (pi == null) { 10787 return null; 10788 } 10789 final ResolveInfo res = new ResolveInfo(); 10790 res.providerInfo = pi; 10791 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10792 res.filter = filter; 10793 } 10794 res.priority = info.getPriority(); 10795 res.preferredOrder = provider.owner.mPreferredOrder; 10796 res.match = match; 10797 res.isDefault = info.hasDefault; 10798 res.labelRes = info.labelRes; 10799 res.nonLocalizedLabel = info.nonLocalizedLabel; 10800 res.icon = info.icon; 10801 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10802 return res; 10803 } 10804 10805 @Override 10806 protected void sortResults(List<ResolveInfo> results) { 10807 Collections.sort(results, mResolvePrioritySorter); 10808 } 10809 10810 @Override 10811 protected void dumpFilter(PrintWriter out, String prefix, 10812 PackageParser.ProviderIntentInfo filter) { 10813 out.print(prefix); 10814 out.print( 10815 Integer.toHexString(System.identityHashCode(filter.provider))); 10816 out.print(' '); 10817 filter.provider.printComponentShortName(out); 10818 out.print(" filter "); 10819 out.println(Integer.toHexString(System.identityHashCode(filter))); 10820 } 10821 10822 @Override 10823 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10824 return filter.provider; 10825 } 10826 10827 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10828 PackageParser.Provider provider = (PackageParser.Provider)label; 10829 out.print(prefix); out.print( 10830 Integer.toHexString(System.identityHashCode(provider))); 10831 out.print(' '); 10832 provider.printComponentShortName(out); 10833 if (count > 1) { 10834 out.print(" ("); out.print(count); out.print(" filters)"); 10835 } 10836 out.println(); 10837 } 10838 10839 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10840 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10841 private int mFlags; 10842 } 10843 10844 private static final class EphemeralIntentResolver 10845 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10846 @Override 10847 protected EphemeralResolveIntentInfo[] newArray(int size) { 10848 return new EphemeralResolveIntentInfo[size]; 10849 } 10850 10851 @Override 10852 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10853 return true; 10854 } 10855 10856 @Override 10857 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10858 int userId) { 10859 if (!sUserManager.exists(userId)) { 10860 return null; 10861 } 10862 return info.getEphemeralResolveInfo(); 10863 } 10864 } 10865 10866 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10867 new Comparator<ResolveInfo>() { 10868 public int compare(ResolveInfo r1, ResolveInfo r2) { 10869 int v1 = r1.priority; 10870 int v2 = r2.priority; 10871 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10872 if (v1 != v2) { 10873 return (v1 > v2) ? -1 : 1; 10874 } 10875 v1 = r1.preferredOrder; 10876 v2 = r2.preferredOrder; 10877 if (v1 != v2) { 10878 return (v1 > v2) ? -1 : 1; 10879 } 10880 if (r1.isDefault != r2.isDefault) { 10881 return r1.isDefault ? -1 : 1; 10882 } 10883 v1 = r1.match; 10884 v2 = r2.match; 10885 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10886 if (v1 != v2) { 10887 return (v1 > v2) ? -1 : 1; 10888 } 10889 if (r1.system != r2.system) { 10890 return r1.system ? -1 : 1; 10891 } 10892 if (r1.activityInfo != null) { 10893 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10894 } 10895 if (r1.serviceInfo != null) { 10896 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10897 } 10898 if (r1.providerInfo != null) { 10899 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10900 } 10901 return 0; 10902 } 10903 }; 10904 10905 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10906 new Comparator<ProviderInfo>() { 10907 public int compare(ProviderInfo p1, ProviderInfo p2) { 10908 final int v1 = p1.initOrder; 10909 final int v2 = p2.initOrder; 10910 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10911 } 10912 }; 10913 10914 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10915 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10916 final int[] userIds) { 10917 mHandler.post(new Runnable() { 10918 @Override 10919 public void run() { 10920 try { 10921 final IActivityManager am = ActivityManagerNative.getDefault(); 10922 if (am == null) return; 10923 final int[] resolvedUserIds; 10924 if (userIds == null) { 10925 resolvedUserIds = am.getRunningUserIds(); 10926 } else { 10927 resolvedUserIds = userIds; 10928 } 10929 for (int id : resolvedUserIds) { 10930 final Intent intent = new Intent(action, 10931 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10932 if (extras != null) { 10933 intent.putExtras(extras); 10934 } 10935 if (targetPkg != null) { 10936 intent.setPackage(targetPkg); 10937 } 10938 // Modify the UID when posting to other users 10939 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10940 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10941 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10942 intent.putExtra(Intent.EXTRA_UID, uid); 10943 } 10944 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10945 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10946 if (DEBUG_BROADCASTS) { 10947 RuntimeException here = new RuntimeException("here"); 10948 here.fillInStackTrace(); 10949 Slog.d(TAG, "Sending to user " + id + ": " 10950 + intent.toShortString(false, true, false, false) 10951 + " " + intent.getExtras(), here); 10952 } 10953 am.broadcastIntent(null, intent, null, finishedReceiver, 10954 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10955 null, finishedReceiver != null, false, id); 10956 } 10957 } catch (RemoteException ex) { 10958 } 10959 } 10960 }); 10961 } 10962 10963 /** 10964 * Check if the external storage media is available. This is true if there 10965 * is a mounted external storage medium or if the external storage is 10966 * emulated. 10967 */ 10968 private boolean isExternalMediaAvailable() { 10969 return mMediaMounted || Environment.isExternalStorageEmulated(); 10970 } 10971 10972 @Override 10973 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10974 // writer 10975 synchronized (mPackages) { 10976 if (!isExternalMediaAvailable()) { 10977 // If the external storage is no longer mounted at this point, 10978 // the caller may not have been able to delete all of this 10979 // packages files and can not delete any more. Bail. 10980 return null; 10981 } 10982 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10983 if (lastPackage != null) { 10984 pkgs.remove(lastPackage); 10985 } 10986 if (pkgs.size() > 0) { 10987 return pkgs.get(0); 10988 } 10989 } 10990 return null; 10991 } 10992 10993 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10994 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10995 userId, andCode ? 1 : 0, packageName); 10996 if (mSystemReady) { 10997 msg.sendToTarget(); 10998 } else { 10999 if (mPostSystemReadyMessages == null) { 11000 mPostSystemReadyMessages = new ArrayList<>(); 11001 } 11002 mPostSystemReadyMessages.add(msg); 11003 } 11004 } 11005 11006 void startCleaningPackages() { 11007 // reader 11008 if (!isExternalMediaAvailable()) { 11009 return; 11010 } 11011 synchronized (mPackages) { 11012 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11013 return; 11014 } 11015 } 11016 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11017 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11018 IActivityManager am = ActivityManagerNative.getDefault(); 11019 if (am != null) { 11020 try { 11021 am.startService(null, intent, null, mContext.getOpPackageName(), 11022 UserHandle.USER_SYSTEM); 11023 } catch (RemoteException e) { 11024 } 11025 } 11026 } 11027 11028 @Override 11029 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11030 int installFlags, String installerPackageName, int userId) { 11031 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11032 11033 final int callingUid = Binder.getCallingUid(); 11034 enforceCrossUserPermission(callingUid, userId, 11035 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11036 11037 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11038 try { 11039 if (observer != null) { 11040 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11041 } 11042 } catch (RemoteException re) { 11043 } 11044 return; 11045 } 11046 11047 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11048 installFlags |= PackageManager.INSTALL_FROM_ADB; 11049 11050 } else { 11051 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11052 // about installerPackageName. 11053 11054 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11055 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11056 } 11057 11058 UserHandle user; 11059 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11060 user = UserHandle.ALL; 11061 } else { 11062 user = new UserHandle(userId); 11063 } 11064 11065 // Only system components can circumvent runtime permissions when installing. 11066 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11067 && mContext.checkCallingOrSelfPermission(Manifest.permission 11068 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11069 throw new SecurityException("You need the " 11070 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11071 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11072 } 11073 11074 final File originFile = new File(originPath); 11075 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11076 11077 final Message msg = mHandler.obtainMessage(INIT_COPY); 11078 final VerificationInfo verificationInfo = new VerificationInfo( 11079 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11080 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11081 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11082 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11083 null /*certificates*/); 11084 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11085 msg.obj = params; 11086 11087 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11088 System.identityHashCode(msg.obj)); 11089 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11090 System.identityHashCode(msg.obj)); 11091 11092 mHandler.sendMessage(msg); 11093 } 11094 11095 void installStage(String packageName, File stagedDir, String stagedCid, 11096 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11097 String installerPackageName, int installerUid, UserHandle user, 11098 Certificate[][] certificates) { 11099 if (DEBUG_EPHEMERAL) { 11100 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11101 Slog.d(TAG, "Ephemeral install of " + packageName); 11102 } 11103 } 11104 final VerificationInfo verificationInfo = new VerificationInfo( 11105 sessionParams.originatingUri, sessionParams.referrerUri, 11106 sessionParams.originatingUid, installerUid); 11107 11108 final OriginInfo origin; 11109 if (stagedDir != null) { 11110 origin = OriginInfo.fromStagedFile(stagedDir); 11111 } else { 11112 origin = OriginInfo.fromStagedContainer(stagedCid); 11113 } 11114 11115 final Message msg = mHandler.obtainMessage(INIT_COPY); 11116 final InstallParams params = new InstallParams(origin, null, observer, 11117 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11118 verificationInfo, user, sessionParams.abiOverride, 11119 sessionParams.grantedRuntimePermissions, certificates); 11120 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11121 msg.obj = params; 11122 11123 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11124 System.identityHashCode(msg.obj)); 11125 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11126 System.identityHashCode(msg.obj)); 11127 11128 mHandler.sendMessage(msg); 11129 } 11130 11131 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11132 int userId) { 11133 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11134 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11135 } 11136 11137 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11138 int appId, int userId) { 11139 Bundle extras = new Bundle(1); 11140 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11141 11142 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11143 packageName, extras, 0, null, null, new int[] {userId}); 11144 try { 11145 IActivityManager am = ActivityManagerNative.getDefault(); 11146 if (isSystem && am.isUserRunning(userId, 0)) { 11147 // The just-installed/enabled app is bundled on the system, so presumed 11148 // to be able to run automatically without needing an explicit launch. 11149 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11150 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11151 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11152 .setPackage(packageName); 11153 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11154 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11155 } 11156 } catch (RemoteException e) { 11157 // shouldn't happen 11158 Slog.w(TAG, "Unable to bootstrap installed package", e); 11159 } 11160 } 11161 11162 @Override 11163 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11164 int userId) { 11165 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11166 PackageSetting pkgSetting; 11167 final int uid = Binder.getCallingUid(); 11168 enforceCrossUserPermission(uid, userId, 11169 true /* requireFullPermission */, true /* checkShell */, 11170 "setApplicationHiddenSetting for user " + userId); 11171 11172 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11173 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11174 return false; 11175 } 11176 11177 long callingId = Binder.clearCallingIdentity(); 11178 try { 11179 boolean sendAdded = false; 11180 boolean sendRemoved = false; 11181 // writer 11182 synchronized (mPackages) { 11183 pkgSetting = mSettings.mPackages.get(packageName); 11184 if (pkgSetting == null) { 11185 return false; 11186 } 11187 if (pkgSetting.getHidden(userId) != hidden) { 11188 pkgSetting.setHidden(hidden, userId); 11189 mSettings.writePackageRestrictionsLPr(userId); 11190 if (hidden) { 11191 sendRemoved = true; 11192 } else { 11193 sendAdded = true; 11194 } 11195 } 11196 } 11197 if (sendAdded) { 11198 sendPackageAddedForUser(packageName, pkgSetting, userId); 11199 return true; 11200 } 11201 if (sendRemoved) { 11202 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11203 "hiding pkg"); 11204 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11205 return true; 11206 } 11207 } finally { 11208 Binder.restoreCallingIdentity(callingId); 11209 } 11210 return false; 11211 } 11212 11213 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11214 int userId) { 11215 final PackageRemovedInfo info = new PackageRemovedInfo(); 11216 info.removedPackage = packageName; 11217 info.removedUsers = new int[] {userId}; 11218 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11219 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11220 } 11221 11222 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11223 if (pkgList.length > 0) { 11224 Bundle extras = new Bundle(1); 11225 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11226 11227 sendPackageBroadcast( 11228 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11229 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11230 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11231 new int[] {userId}); 11232 } 11233 } 11234 11235 /** 11236 * Returns true if application is not found or there was an error. Otherwise it returns 11237 * the hidden state of the package for the given user. 11238 */ 11239 @Override 11240 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11241 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11243 true /* requireFullPermission */, false /* checkShell */, 11244 "getApplicationHidden for user " + userId); 11245 PackageSetting pkgSetting; 11246 long callingId = Binder.clearCallingIdentity(); 11247 try { 11248 // writer 11249 synchronized (mPackages) { 11250 pkgSetting = mSettings.mPackages.get(packageName); 11251 if (pkgSetting == null) { 11252 return true; 11253 } 11254 return pkgSetting.getHidden(userId); 11255 } 11256 } finally { 11257 Binder.restoreCallingIdentity(callingId); 11258 } 11259 } 11260 11261 /** 11262 * @hide 11263 */ 11264 @Override 11265 public int installExistingPackageAsUser(String packageName, int userId) { 11266 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11267 null); 11268 PackageSetting pkgSetting; 11269 final int uid = Binder.getCallingUid(); 11270 enforceCrossUserPermission(uid, userId, 11271 true /* requireFullPermission */, true /* checkShell */, 11272 "installExistingPackage for user " + userId); 11273 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11274 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11275 } 11276 11277 long callingId = Binder.clearCallingIdentity(); 11278 try { 11279 boolean installed = false; 11280 11281 // writer 11282 synchronized (mPackages) { 11283 pkgSetting = mSettings.mPackages.get(packageName); 11284 if (pkgSetting == null) { 11285 return PackageManager.INSTALL_FAILED_INVALID_URI; 11286 } 11287 if (!pkgSetting.getInstalled(userId)) { 11288 pkgSetting.setInstalled(true, userId); 11289 pkgSetting.setHidden(false, userId); 11290 mSettings.writePackageRestrictionsLPr(userId); 11291 installed = true; 11292 } 11293 } 11294 11295 if (installed) { 11296 if (pkgSetting.pkg != null) { 11297 synchronized (mInstallLock) { 11298 // We don't need to freeze for a brand new install 11299 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11300 } 11301 } 11302 sendPackageAddedForUser(packageName, pkgSetting, userId); 11303 } 11304 } finally { 11305 Binder.restoreCallingIdentity(callingId); 11306 } 11307 11308 return PackageManager.INSTALL_SUCCEEDED; 11309 } 11310 11311 boolean isUserRestricted(int userId, String restrictionKey) { 11312 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11313 if (restrictions.getBoolean(restrictionKey, false)) { 11314 Log.w(TAG, "User is restricted: " + restrictionKey); 11315 return true; 11316 } 11317 return false; 11318 } 11319 11320 @Override 11321 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11322 int userId) { 11323 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11324 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11325 true /* requireFullPermission */, true /* checkShell */, 11326 "setPackagesSuspended for user " + userId); 11327 11328 if (ArrayUtils.isEmpty(packageNames)) { 11329 return packageNames; 11330 } 11331 11332 // List of package names for whom the suspended state has changed. 11333 List<String> changedPackages = new ArrayList<>(packageNames.length); 11334 // List of package names for whom the suspended state is not set as requested in this 11335 // method. 11336 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11337 for (int i = 0; i < packageNames.length; i++) { 11338 String packageName = packageNames[i]; 11339 long callingId = Binder.clearCallingIdentity(); 11340 try { 11341 boolean changed = false; 11342 final int appId; 11343 synchronized (mPackages) { 11344 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11345 if (pkgSetting == null) { 11346 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11347 + "\". Skipping suspending/un-suspending."); 11348 unactionedPackages.add(packageName); 11349 continue; 11350 } 11351 appId = pkgSetting.appId; 11352 if (pkgSetting.getSuspended(userId) != suspended) { 11353 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11354 unactionedPackages.add(packageName); 11355 continue; 11356 } 11357 pkgSetting.setSuspended(suspended, userId); 11358 mSettings.writePackageRestrictionsLPr(userId); 11359 changed = true; 11360 changedPackages.add(packageName); 11361 } 11362 } 11363 11364 if (changed && suspended) { 11365 killApplication(packageName, UserHandle.getUid(userId, appId), 11366 "suspending package"); 11367 } 11368 } finally { 11369 Binder.restoreCallingIdentity(callingId); 11370 } 11371 } 11372 11373 if (!changedPackages.isEmpty()) { 11374 sendPackagesSuspendedForUser(changedPackages.toArray( 11375 new String[changedPackages.size()]), userId, suspended); 11376 } 11377 11378 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11379 } 11380 11381 @Override 11382 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11383 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11384 true /* requireFullPermission */, false /* checkShell */, 11385 "isPackageSuspendedForUser for user " + userId); 11386 synchronized (mPackages) { 11387 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11388 if (pkgSetting == null) { 11389 throw new IllegalArgumentException("Unknown target package: " + packageName); 11390 } 11391 return pkgSetting.getSuspended(userId); 11392 } 11393 } 11394 11395 /** 11396 * TODO: cache and disallow blocking the active dialer. 11397 * 11398 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11399 */ 11400 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11401 if (isPackageDeviceAdmin(packageName, userId)) { 11402 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11403 + "\": has an active device admin"); 11404 return false; 11405 } 11406 11407 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11408 if (packageName.equals(activeLauncherPackageName)) { 11409 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11410 + "\": contains the active launcher"); 11411 return false; 11412 } 11413 11414 if (packageName.equals(mRequiredInstallerPackage)) { 11415 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11416 + "\": required for package installation"); 11417 return false; 11418 } 11419 11420 if (packageName.equals(mRequiredVerifierPackage)) { 11421 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11422 + "\": required for package verification"); 11423 return false; 11424 } 11425 11426 final PackageParser.Package pkg = mPackages.get(packageName); 11427 if (pkg != null && isPrivilegedApp(pkg)) { 11428 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11429 + "\": is a privileged app"); 11430 return false; 11431 } 11432 11433 return true; 11434 } 11435 11436 private String getActiveLauncherPackageName(int userId) { 11437 Intent intent = new Intent(Intent.ACTION_MAIN); 11438 intent.addCategory(Intent.CATEGORY_HOME); 11439 ResolveInfo resolveInfo = resolveIntent( 11440 intent, 11441 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11442 PackageManager.MATCH_DEFAULT_ONLY, 11443 userId); 11444 11445 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11446 } 11447 11448 @Override 11449 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11450 mContext.enforceCallingOrSelfPermission( 11451 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11452 "Only package verification agents can verify applications"); 11453 11454 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11455 final PackageVerificationResponse response = new PackageVerificationResponse( 11456 verificationCode, Binder.getCallingUid()); 11457 msg.arg1 = id; 11458 msg.obj = response; 11459 mHandler.sendMessage(msg); 11460 } 11461 11462 @Override 11463 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11464 long millisecondsToDelay) { 11465 mContext.enforceCallingOrSelfPermission( 11466 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11467 "Only package verification agents can extend verification timeouts"); 11468 11469 final PackageVerificationState state = mPendingVerification.get(id); 11470 final PackageVerificationResponse response = new PackageVerificationResponse( 11471 verificationCodeAtTimeout, Binder.getCallingUid()); 11472 11473 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11474 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11475 } 11476 if (millisecondsToDelay < 0) { 11477 millisecondsToDelay = 0; 11478 } 11479 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11480 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11481 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11482 } 11483 11484 if ((state != null) && !state.timeoutExtended()) { 11485 state.extendTimeout(); 11486 11487 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11488 msg.arg1 = id; 11489 msg.obj = response; 11490 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11491 } 11492 } 11493 11494 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11495 int verificationCode, UserHandle user) { 11496 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11497 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11498 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11499 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11500 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11501 11502 mContext.sendBroadcastAsUser(intent, user, 11503 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11504 } 11505 11506 private ComponentName matchComponentForVerifier(String packageName, 11507 List<ResolveInfo> receivers) { 11508 ActivityInfo targetReceiver = null; 11509 11510 final int NR = receivers.size(); 11511 for (int i = 0; i < NR; i++) { 11512 final ResolveInfo info = receivers.get(i); 11513 if (info.activityInfo == null) { 11514 continue; 11515 } 11516 11517 if (packageName.equals(info.activityInfo.packageName)) { 11518 targetReceiver = info.activityInfo; 11519 break; 11520 } 11521 } 11522 11523 if (targetReceiver == null) { 11524 return null; 11525 } 11526 11527 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11528 } 11529 11530 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11531 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11532 if (pkgInfo.verifiers.length == 0) { 11533 return null; 11534 } 11535 11536 final int N = pkgInfo.verifiers.length; 11537 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11538 for (int i = 0; i < N; i++) { 11539 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11540 11541 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11542 receivers); 11543 if (comp == null) { 11544 continue; 11545 } 11546 11547 final int verifierUid = getUidForVerifier(verifierInfo); 11548 if (verifierUid == -1) { 11549 continue; 11550 } 11551 11552 if (DEBUG_VERIFY) { 11553 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11554 + " with the correct signature"); 11555 } 11556 sufficientVerifiers.add(comp); 11557 verificationState.addSufficientVerifier(verifierUid); 11558 } 11559 11560 return sufficientVerifiers; 11561 } 11562 11563 private int getUidForVerifier(VerifierInfo verifierInfo) { 11564 synchronized (mPackages) { 11565 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11566 if (pkg == null) { 11567 return -1; 11568 } else if (pkg.mSignatures.length != 1) { 11569 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11570 + " has more than one signature; ignoring"); 11571 return -1; 11572 } 11573 11574 /* 11575 * If the public key of the package's signature does not match 11576 * our expected public key, then this is a different package and 11577 * we should skip. 11578 */ 11579 11580 final byte[] expectedPublicKey; 11581 try { 11582 final Signature verifierSig = pkg.mSignatures[0]; 11583 final PublicKey publicKey = verifierSig.getPublicKey(); 11584 expectedPublicKey = publicKey.getEncoded(); 11585 } catch (CertificateException e) { 11586 return -1; 11587 } 11588 11589 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11590 11591 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11592 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11593 + " does not have the expected public key; ignoring"); 11594 return -1; 11595 } 11596 11597 return pkg.applicationInfo.uid; 11598 } 11599 } 11600 11601 @Override 11602 public void finishPackageInstall(int token) { 11603 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11604 11605 if (DEBUG_INSTALL) { 11606 Slog.v(TAG, "BM finishing package install for " + token); 11607 } 11608 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11609 11610 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11611 mHandler.sendMessage(msg); 11612 } 11613 11614 /** 11615 * Get the verification agent timeout. 11616 * 11617 * @return verification timeout in milliseconds 11618 */ 11619 private long getVerificationTimeout() { 11620 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11621 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11622 DEFAULT_VERIFICATION_TIMEOUT); 11623 } 11624 11625 /** 11626 * Get the default verification agent response code. 11627 * 11628 * @return default verification response code 11629 */ 11630 private int getDefaultVerificationResponse() { 11631 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11632 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11633 DEFAULT_VERIFICATION_RESPONSE); 11634 } 11635 11636 /** 11637 * Check whether or not package verification has been enabled. 11638 * 11639 * @return true if verification should be performed 11640 */ 11641 private boolean isVerificationEnabled(int userId, int installFlags) { 11642 if (!DEFAULT_VERIFY_ENABLE) { 11643 return false; 11644 } 11645 // Ephemeral apps don't get the full verification treatment 11646 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11647 if (DEBUG_EPHEMERAL) { 11648 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11649 } 11650 return false; 11651 } 11652 11653 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11654 11655 // Check if installing from ADB 11656 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11657 // Do not run verification in a test harness environment 11658 if (ActivityManager.isRunningInTestHarness()) { 11659 return false; 11660 } 11661 if (ensureVerifyAppsEnabled) { 11662 return true; 11663 } 11664 // Check if the developer does not want package verification for ADB installs 11665 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11666 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11667 return false; 11668 } 11669 } 11670 11671 if (ensureVerifyAppsEnabled) { 11672 return true; 11673 } 11674 11675 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11676 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11677 } 11678 11679 @Override 11680 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11681 throws RemoteException { 11682 mContext.enforceCallingOrSelfPermission( 11683 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11684 "Only intentfilter verification agents can verify applications"); 11685 11686 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11687 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11688 Binder.getCallingUid(), verificationCode, failedDomains); 11689 msg.arg1 = id; 11690 msg.obj = response; 11691 mHandler.sendMessage(msg); 11692 } 11693 11694 @Override 11695 public int getIntentVerificationStatus(String packageName, int userId) { 11696 synchronized (mPackages) { 11697 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11698 } 11699 } 11700 11701 @Override 11702 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11703 mContext.enforceCallingOrSelfPermission( 11704 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11705 11706 boolean result = false; 11707 synchronized (mPackages) { 11708 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11709 } 11710 if (result) { 11711 scheduleWritePackageRestrictionsLocked(userId); 11712 } 11713 return result; 11714 } 11715 11716 @Override 11717 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11718 String packageName) { 11719 synchronized (mPackages) { 11720 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11721 } 11722 } 11723 11724 @Override 11725 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11726 if (TextUtils.isEmpty(packageName)) { 11727 return ParceledListSlice.emptyList(); 11728 } 11729 synchronized (mPackages) { 11730 PackageParser.Package pkg = mPackages.get(packageName); 11731 if (pkg == null || pkg.activities == null) { 11732 return ParceledListSlice.emptyList(); 11733 } 11734 final int count = pkg.activities.size(); 11735 ArrayList<IntentFilter> result = new ArrayList<>(); 11736 for (int n=0; n<count; n++) { 11737 PackageParser.Activity activity = pkg.activities.get(n); 11738 if (activity.intents != null && activity.intents.size() > 0) { 11739 result.addAll(activity.intents); 11740 } 11741 } 11742 return new ParceledListSlice<>(result); 11743 } 11744 } 11745 11746 @Override 11747 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11748 mContext.enforceCallingOrSelfPermission( 11749 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11750 11751 synchronized (mPackages) { 11752 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11753 if (packageName != null) { 11754 result |= updateIntentVerificationStatus(packageName, 11755 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11756 userId); 11757 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11758 packageName, userId); 11759 } 11760 return result; 11761 } 11762 } 11763 11764 @Override 11765 public String getDefaultBrowserPackageName(int userId) { 11766 synchronized (mPackages) { 11767 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11768 } 11769 } 11770 11771 /** 11772 * Get the "allow unknown sources" setting. 11773 * 11774 * @return the current "allow unknown sources" setting 11775 */ 11776 private int getUnknownSourcesSettings() { 11777 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11778 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11779 -1); 11780 } 11781 11782 @Override 11783 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11784 final int uid = Binder.getCallingUid(); 11785 // writer 11786 synchronized (mPackages) { 11787 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11788 if (targetPackageSetting == null) { 11789 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11790 } 11791 11792 PackageSetting installerPackageSetting; 11793 if (installerPackageName != null) { 11794 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11795 if (installerPackageSetting == null) { 11796 throw new IllegalArgumentException("Unknown installer package: " 11797 + installerPackageName); 11798 } 11799 } else { 11800 installerPackageSetting = null; 11801 } 11802 11803 Signature[] callerSignature; 11804 Object obj = mSettings.getUserIdLPr(uid); 11805 if (obj != null) { 11806 if (obj instanceof SharedUserSetting) { 11807 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11808 } else if (obj instanceof PackageSetting) { 11809 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11810 } else { 11811 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11812 } 11813 } else { 11814 throw new SecurityException("Unknown calling UID: " + uid); 11815 } 11816 11817 // Verify: can't set installerPackageName to a package that is 11818 // not signed with the same cert as the caller. 11819 if (installerPackageSetting != null) { 11820 if (compareSignatures(callerSignature, 11821 installerPackageSetting.signatures.mSignatures) 11822 != PackageManager.SIGNATURE_MATCH) { 11823 throw new SecurityException( 11824 "Caller does not have same cert as new installer package " 11825 + installerPackageName); 11826 } 11827 } 11828 11829 // Verify: if target already has an installer package, it must 11830 // be signed with the same cert as the caller. 11831 if (targetPackageSetting.installerPackageName != null) { 11832 PackageSetting setting = mSettings.mPackages.get( 11833 targetPackageSetting.installerPackageName); 11834 // If the currently set package isn't valid, then it's always 11835 // okay to change it. 11836 if (setting != null) { 11837 if (compareSignatures(callerSignature, 11838 setting.signatures.mSignatures) 11839 != PackageManager.SIGNATURE_MATCH) { 11840 throw new SecurityException( 11841 "Caller does not have same cert as old installer package " 11842 + targetPackageSetting.installerPackageName); 11843 } 11844 } 11845 } 11846 11847 // Okay! 11848 targetPackageSetting.installerPackageName = installerPackageName; 11849 if (installerPackageName != null) { 11850 mSettings.mInstallerPackages.add(installerPackageName); 11851 } 11852 scheduleWriteSettingsLocked(); 11853 } 11854 } 11855 11856 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11857 // Queue up an async operation since the package installation may take a little while. 11858 mHandler.post(new Runnable() { 11859 public void run() { 11860 mHandler.removeCallbacks(this); 11861 // Result object to be returned 11862 PackageInstalledInfo res = new PackageInstalledInfo(); 11863 res.setReturnCode(currentStatus); 11864 res.uid = -1; 11865 res.pkg = null; 11866 res.removedInfo = null; 11867 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11868 args.doPreInstall(res.returnCode); 11869 synchronized (mInstallLock) { 11870 installPackageTracedLI(args, res); 11871 } 11872 args.doPostInstall(res.returnCode, res.uid); 11873 } 11874 11875 // A restore should be performed at this point if (a) the install 11876 // succeeded, (b) the operation is not an update, and (c) the new 11877 // package has not opted out of backup participation. 11878 final boolean update = res.removedInfo != null 11879 && res.removedInfo.removedPackage != null; 11880 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11881 boolean doRestore = !update 11882 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11883 11884 // Set up the post-install work request bookkeeping. This will be used 11885 // and cleaned up by the post-install event handling regardless of whether 11886 // there's a restore pass performed. Token values are >= 1. 11887 int token; 11888 if (mNextInstallToken < 0) mNextInstallToken = 1; 11889 token = mNextInstallToken++; 11890 11891 PostInstallData data = new PostInstallData(args, res); 11892 mRunningInstalls.put(token, data); 11893 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11894 11895 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11896 // Pass responsibility to the Backup Manager. It will perform a 11897 // restore if appropriate, then pass responsibility back to the 11898 // Package Manager to run the post-install observer callbacks 11899 // and broadcasts. 11900 IBackupManager bm = IBackupManager.Stub.asInterface( 11901 ServiceManager.getService(Context.BACKUP_SERVICE)); 11902 if (bm != null) { 11903 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11904 + " to BM for possible restore"); 11905 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11906 try { 11907 // TODO: http://b/22388012 11908 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11909 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11910 } else { 11911 doRestore = false; 11912 } 11913 } catch (RemoteException e) { 11914 // can't happen; the backup manager is local 11915 } catch (Exception e) { 11916 Slog.e(TAG, "Exception trying to enqueue restore", e); 11917 doRestore = false; 11918 } 11919 } else { 11920 Slog.e(TAG, "Backup Manager not found!"); 11921 doRestore = false; 11922 } 11923 } 11924 11925 if (!doRestore) { 11926 // No restore possible, or the Backup Manager was mysteriously not 11927 // available -- just fire the post-install work request directly. 11928 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11929 11930 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11931 11932 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11933 mHandler.sendMessage(msg); 11934 } 11935 } 11936 }); 11937 } 11938 11939 private abstract class HandlerParams { 11940 private static final int MAX_RETRIES = 4; 11941 11942 /** 11943 * Number of times startCopy() has been attempted and had a non-fatal 11944 * error. 11945 */ 11946 private int mRetries = 0; 11947 11948 /** User handle for the user requesting the information or installation. */ 11949 private final UserHandle mUser; 11950 String traceMethod; 11951 int traceCookie; 11952 11953 HandlerParams(UserHandle user) { 11954 mUser = user; 11955 } 11956 11957 UserHandle getUser() { 11958 return mUser; 11959 } 11960 11961 HandlerParams setTraceMethod(String traceMethod) { 11962 this.traceMethod = traceMethod; 11963 return this; 11964 } 11965 11966 HandlerParams setTraceCookie(int traceCookie) { 11967 this.traceCookie = traceCookie; 11968 return this; 11969 } 11970 11971 final boolean startCopy() { 11972 boolean res; 11973 try { 11974 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11975 11976 if (++mRetries > MAX_RETRIES) { 11977 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11978 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11979 handleServiceError(); 11980 return false; 11981 } else { 11982 handleStartCopy(); 11983 res = true; 11984 } 11985 } catch (RemoteException e) { 11986 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11987 mHandler.sendEmptyMessage(MCS_RECONNECT); 11988 res = false; 11989 } 11990 handleReturnCode(); 11991 return res; 11992 } 11993 11994 final void serviceError() { 11995 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11996 handleServiceError(); 11997 handleReturnCode(); 11998 } 11999 12000 abstract void handleStartCopy() throws RemoteException; 12001 abstract void handleServiceError(); 12002 abstract void handleReturnCode(); 12003 } 12004 12005 class MeasureParams extends HandlerParams { 12006 private final PackageStats mStats; 12007 private boolean mSuccess; 12008 12009 private final IPackageStatsObserver mObserver; 12010 12011 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12012 super(new UserHandle(stats.userHandle)); 12013 mObserver = observer; 12014 mStats = stats; 12015 } 12016 12017 @Override 12018 public String toString() { 12019 return "MeasureParams{" 12020 + Integer.toHexString(System.identityHashCode(this)) 12021 + " " + mStats.packageName + "}"; 12022 } 12023 12024 @Override 12025 void handleStartCopy() throws RemoteException { 12026 synchronized (mInstallLock) { 12027 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12028 } 12029 12030 if (mSuccess) { 12031 final boolean mounted; 12032 if (Environment.isExternalStorageEmulated()) { 12033 mounted = true; 12034 } else { 12035 final String status = Environment.getExternalStorageState(); 12036 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12037 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12038 } 12039 12040 if (mounted) { 12041 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12042 12043 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12044 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12045 12046 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12047 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12048 12049 // Always subtract cache size, since it's a subdirectory 12050 mStats.externalDataSize -= mStats.externalCacheSize; 12051 12052 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12053 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12054 12055 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12056 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12057 } 12058 } 12059 } 12060 12061 @Override 12062 void handleReturnCode() { 12063 if (mObserver != null) { 12064 try { 12065 mObserver.onGetStatsCompleted(mStats, mSuccess); 12066 } catch (RemoteException e) { 12067 Slog.i(TAG, "Observer no longer exists."); 12068 } 12069 } 12070 } 12071 12072 @Override 12073 void handleServiceError() { 12074 Slog.e(TAG, "Could not measure application " + mStats.packageName 12075 + " external storage"); 12076 } 12077 } 12078 12079 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12080 throws RemoteException { 12081 long result = 0; 12082 for (File path : paths) { 12083 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12084 } 12085 return result; 12086 } 12087 12088 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12089 for (File path : paths) { 12090 try { 12091 mcs.clearDirectory(path.getAbsolutePath()); 12092 } catch (RemoteException e) { 12093 } 12094 } 12095 } 12096 12097 static class OriginInfo { 12098 /** 12099 * Location where install is coming from, before it has been 12100 * copied/renamed into place. This could be a single monolithic APK 12101 * file, or a cluster directory. This location may be untrusted. 12102 */ 12103 final File file; 12104 final String cid; 12105 12106 /** 12107 * Flag indicating that {@link #file} or {@link #cid} has already been 12108 * staged, meaning downstream users don't need to defensively copy the 12109 * contents. 12110 */ 12111 final boolean staged; 12112 12113 /** 12114 * Flag indicating that {@link #file} or {@link #cid} is an already 12115 * installed app that is being moved. 12116 */ 12117 final boolean existing; 12118 12119 final String resolvedPath; 12120 final File resolvedFile; 12121 12122 static OriginInfo fromNothing() { 12123 return new OriginInfo(null, null, false, false); 12124 } 12125 12126 static OriginInfo fromUntrustedFile(File file) { 12127 return new OriginInfo(file, null, false, false); 12128 } 12129 12130 static OriginInfo fromExistingFile(File file) { 12131 return new OriginInfo(file, null, false, true); 12132 } 12133 12134 static OriginInfo fromStagedFile(File file) { 12135 return new OriginInfo(file, null, true, false); 12136 } 12137 12138 static OriginInfo fromStagedContainer(String cid) { 12139 return new OriginInfo(null, cid, true, false); 12140 } 12141 12142 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12143 this.file = file; 12144 this.cid = cid; 12145 this.staged = staged; 12146 this.existing = existing; 12147 12148 if (cid != null) { 12149 resolvedPath = PackageHelper.getSdDir(cid); 12150 resolvedFile = new File(resolvedPath); 12151 } else if (file != null) { 12152 resolvedPath = file.getAbsolutePath(); 12153 resolvedFile = file; 12154 } else { 12155 resolvedPath = null; 12156 resolvedFile = null; 12157 } 12158 } 12159 } 12160 12161 static class MoveInfo { 12162 final int moveId; 12163 final String fromUuid; 12164 final String toUuid; 12165 final String packageName; 12166 final String dataAppName; 12167 final int appId; 12168 final String seinfo; 12169 final int targetSdkVersion; 12170 12171 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12172 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12173 this.moveId = moveId; 12174 this.fromUuid = fromUuid; 12175 this.toUuid = toUuid; 12176 this.packageName = packageName; 12177 this.dataAppName = dataAppName; 12178 this.appId = appId; 12179 this.seinfo = seinfo; 12180 this.targetSdkVersion = targetSdkVersion; 12181 } 12182 } 12183 12184 static class VerificationInfo { 12185 /** A constant used to indicate that a uid value is not present. */ 12186 public static final int NO_UID = -1; 12187 12188 /** URI referencing where the package was downloaded from. */ 12189 final Uri originatingUri; 12190 12191 /** HTTP referrer URI associated with the originatingURI. */ 12192 final Uri referrer; 12193 12194 /** UID of the application that the install request originated from. */ 12195 final int originatingUid; 12196 12197 /** UID of application requesting the install */ 12198 final int installerUid; 12199 12200 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12201 this.originatingUri = originatingUri; 12202 this.referrer = referrer; 12203 this.originatingUid = originatingUid; 12204 this.installerUid = installerUid; 12205 } 12206 } 12207 12208 class InstallParams extends HandlerParams { 12209 final OriginInfo origin; 12210 final MoveInfo move; 12211 final IPackageInstallObserver2 observer; 12212 int installFlags; 12213 final String installerPackageName; 12214 final String volumeUuid; 12215 private InstallArgs mArgs; 12216 private int mRet; 12217 final String packageAbiOverride; 12218 final String[] grantedRuntimePermissions; 12219 final VerificationInfo verificationInfo; 12220 final Certificate[][] certificates; 12221 12222 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12223 int installFlags, String installerPackageName, String volumeUuid, 12224 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12225 String[] grantedPermissions, Certificate[][] certificates) { 12226 super(user); 12227 this.origin = origin; 12228 this.move = move; 12229 this.observer = observer; 12230 this.installFlags = installFlags; 12231 this.installerPackageName = installerPackageName; 12232 this.volumeUuid = volumeUuid; 12233 this.verificationInfo = verificationInfo; 12234 this.packageAbiOverride = packageAbiOverride; 12235 this.grantedRuntimePermissions = grantedPermissions; 12236 this.certificates = certificates; 12237 } 12238 12239 @Override 12240 public String toString() { 12241 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12242 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12243 } 12244 12245 private int installLocationPolicy(PackageInfoLite pkgLite) { 12246 String packageName = pkgLite.packageName; 12247 int installLocation = pkgLite.installLocation; 12248 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12249 // reader 12250 synchronized (mPackages) { 12251 // Currently installed package which the new package is attempting to replace or 12252 // null if no such package is installed. 12253 PackageParser.Package installedPkg = mPackages.get(packageName); 12254 // Package which currently owns the data which the new package will own if installed. 12255 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12256 // will be null whereas dataOwnerPkg will contain information about the package 12257 // which was uninstalled while keeping its data. 12258 PackageParser.Package dataOwnerPkg = installedPkg; 12259 if (dataOwnerPkg == null) { 12260 PackageSetting ps = mSettings.mPackages.get(packageName); 12261 if (ps != null) { 12262 dataOwnerPkg = ps.pkg; 12263 } 12264 } 12265 12266 if (dataOwnerPkg != null) { 12267 // If installed, the package will get access to data left on the device by its 12268 // predecessor. As a security measure, this is permited only if this is not a 12269 // version downgrade or if the predecessor package is marked as debuggable and 12270 // a downgrade is explicitly requested. 12271 // 12272 // On debuggable platform builds, downgrades are permitted even for 12273 // non-debuggable packages to make testing easier. Debuggable platform builds do 12274 // not offer security guarantees and thus it's OK to disable some security 12275 // mechanisms to make debugging/testing easier on those builds. However, even on 12276 // debuggable builds downgrades of packages are permitted only if requested via 12277 // installFlags. This is because we aim to keep the behavior of debuggable 12278 // platform builds as close as possible to the behavior of non-debuggable 12279 // platform builds. 12280 final boolean downgradeRequested = 12281 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12282 final boolean packageDebuggable = 12283 (dataOwnerPkg.applicationInfo.flags 12284 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12285 final boolean downgradePermitted = 12286 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12287 if (!downgradePermitted) { 12288 try { 12289 checkDowngrade(dataOwnerPkg, pkgLite); 12290 } catch (PackageManagerException e) { 12291 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12292 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12293 } 12294 } 12295 } 12296 12297 if (installedPkg != null) { 12298 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12299 // Check for updated system application. 12300 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12301 if (onSd) { 12302 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12303 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12304 } 12305 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12306 } else { 12307 if (onSd) { 12308 // Install flag overrides everything. 12309 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12310 } 12311 // If current upgrade specifies particular preference 12312 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12313 // Application explicitly specified internal. 12314 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12315 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12316 // App explictly prefers external. Let policy decide 12317 } else { 12318 // Prefer previous location 12319 if (isExternal(installedPkg)) { 12320 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12321 } 12322 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12323 } 12324 } 12325 } else { 12326 // Invalid install. Return error code 12327 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12328 } 12329 } 12330 } 12331 // All the special cases have been taken care of. 12332 // Return result based on recommended install location. 12333 if (onSd) { 12334 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12335 } 12336 return pkgLite.recommendedInstallLocation; 12337 } 12338 12339 /* 12340 * Invoke remote method to get package information and install 12341 * location values. Override install location based on default 12342 * policy if needed and then create install arguments based 12343 * on the install location. 12344 */ 12345 public void handleStartCopy() throws RemoteException { 12346 int ret = PackageManager.INSTALL_SUCCEEDED; 12347 12348 // If we're already staged, we've firmly committed to an install location 12349 if (origin.staged) { 12350 if (origin.file != null) { 12351 installFlags |= PackageManager.INSTALL_INTERNAL; 12352 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12353 } else if (origin.cid != null) { 12354 installFlags |= PackageManager.INSTALL_EXTERNAL; 12355 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12356 } else { 12357 throw new IllegalStateException("Invalid stage location"); 12358 } 12359 } 12360 12361 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12362 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12363 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12364 PackageInfoLite pkgLite = null; 12365 12366 if (onInt && onSd) { 12367 // Check if both bits are set. 12368 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12369 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12370 } else if (onSd && ephemeral) { 12371 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12372 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12373 } else { 12374 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12375 packageAbiOverride); 12376 12377 if (DEBUG_EPHEMERAL && ephemeral) { 12378 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12379 } 12380 12381 /* 12382 * If we have too little free space, try to free cache 12383 * before giving up. 12384 */ 12385 if (!origin.staged && pkgLite.recommendedInstallLocation 12386 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12387 // TODO: focus freeing disk space on the target device 12388 final StorageManager storage = StorageManager.from(mContext); 12389 final long lowThreshold = storage.getStorageLowBytes( 12390 Environment.getDataDirectory()); 12391 12392 final long sizeBytes = mContainerService.calculateInstalledSize( 12393 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12394 12395 try { 12396 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12397 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12398 installFlags, packageAbiOverride); 12399 } catch (InstallerException e) { 12400 Slog.w(TAG, "Failed to free cache", e); 12401 } 12402 12403 /* 12404 * The cache free must have deleted the file we 12405 * downloaded to install. 12406 * 12407 * TODO: fix the "freeCache" call to not delete 12408 * the file we care about. 12409 */ 12410 if (pkgLite.recommendedInstallLocation 12411 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12412 pkgLite.recommendedInstallLocation 12413 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12414 } 12415 } 12416 } 12417 12418 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12419 int loc = pkgLite.recommendedInstallLocation; 12420 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12421 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12422 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12423 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12424 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12425 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12426 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12427 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12428 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12429 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12430 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12431 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12432 } else { 12433 // Override with defaults if needed. 12434 loc = installLocationPolicy(pkgLite); 12435 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12436 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12437 } else if (!onSd && !onInt) { 12438 // Override install location with flags 12439 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12440 // Set the flag to install on external media. 12441 installFlags |= PackageManager.INSTALL_EXTERNAL; 12442 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12443 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12444 if (DEBUG_EPHEMERAL) { 12445 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12446 } 12447 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12448 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12449 |PackageManager.INSTALL_INTERNAL); 12450 } else { 12451 // Make sure the flag for installing on external 12452 // media is unset 12453 installFlags |= PackageManager.INSTALL_INTERNAL; 12454 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12455 } 12456 } 12457 } 12458 } 12459 12460 final InstallArgs args = createInstallArgs(this); 12461 mArgs = args; 12462 12463 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12464 // TODO: http://b/22976637 12465 // Apps installed for "all" users use the device owner to verify the app 12466 UserHandle verifierUser = getUser(); 12467 if (verifierUser == UserHandle.ALL) { 12468 verifierUser = UserHandle.SYSTEM; 12469 } 12470 12471 /* 12472 * Determine if we have any installed package verifiers. If we 12473 * do, then we'll defer to them to verify the packages. 12474 */ 12475 final int requiredUid = mRequiredVerifierPackage == null ? -1 12476 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12477 verifierUser.getIdentifier()); 12478 if (!origin.existing && requiredUid != -1 12479 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12480 final Intent verification = new Intent( 12481 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12482 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12483 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12484 PACKAGE_MIME_TYPE); 12485 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12486 12487 // Query all live verifiers based on current user state 12488 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12489 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12490 12491 if (DEBUG_VERIFY) { 12492 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12493 + verification.toString() + " with " + pkgLite.verifiers.length 12494 + " optional verifiers"); 12495 } 12496 12497 final int verificationId = mPendingVerificationToken++; 12498 12499 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12500 12501 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12502 installerPackageName); 12503 12504 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12505 installFlags); 12506 12507 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12508 pkgLite.packageName); 12509 12510 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12511 pkgLite.versionCode); 12512 12513 if (verificationInfo != null) { 12514 if (verificationInfo.originatingUri != null) { 12515 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12516 verificationInfo.originatingUri); 12517 } 12518 if (verificationInfo.referrer != null) { 12519 verification.putExtra(Intent.EXTRA_REFERRER, 12520 verificationInfo.referrer); 12521 } 12522 if (verificationInfo.originatingUid >= 0) { 12523 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12524 verificationInfo.originatingUid); 12525 } 12526 if (verificationInfo.installerUid >= 0) { 12527 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12528 verificationInfo.installerUid); 12529 } 12530 } 12531 12532 final PackageVerificationState verificationState = new PackageVerificationState( 12533 requiredUid, args); 12534 12535 mPendingVerification.append(verificationId, verificationState); 12536 12537 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12538 receivers, verificationState); 12539 12540 /* 12541 * If any sufficient verifiers were listed in the package 12542 * manifest, attempt to ask them. 12543 */ 12544 if (sufficientVerifiers != null) { 12545 final int N = sufficientVerifiers.size(); 12546 if (N == 0) { 12547 Slog.i(TAG, "Additional verifiers required, but none installed."); 12548 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12549 } else { 12550 for (int i = 0; i < N; i++) { 12551 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12552 12553 final Intent sufficientIntent = new Intent(verification); 12554 sufficientIntent.setComponent(verifierComponent); 12555 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12556 } 12557 } 12558 } 12559 12560 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12561 mRequiredVerifierPackage, receivers); 12562 if (ret == PackageManager.INSTALL_SUCCEEDED 12563 && mRequiredVerifierPackage != null) { 12564 Trace.asyncTraceBegin( 12565 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12566 /* 12567 * Send the intent to the required verification agent, 12568 * but only start the verification timeout after the 12569 * target BroadcastReceivers have run. 12570 */ 12571 verification.setComponent(requiredVerifierComponent); 12572 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12573 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12574 new BroadcastReceiver() { 12575 @Override 12576 public void onReceive(Context context, Intent intent) { 12577 final Message msg = mHandler 12578 .obtainMessage(CHECK_PENDING_VERIFICATION); 12579 msg.arg1 = verificationId; 12580 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12581 } 12582 }, null, 0, null, null); 12583 12584 /* 12585 * We don't want the copy to proceed until verification 12586 * succeeds, so null out this field. 12587 */ 12588 mArgs = null; 12589 } 12590 } else { 12591 /* 12592 * No package verification is enabled, so immediately start 12593 * the remote call to initiate copy using temporary file. 12594 */ 12595 ret = args.copyApk(mContainerService, true); 12596 } 12597 } 12598 12599 mRet = ret; 12600 } 12601 12602 @Override 12603 void handleReturnCode() { 12604 // If mArgs is null, then MCS couldn't be reached. When it 12605 // reconnects, it will try again to install. At that point, this 12606 // will succeed. 12607 if (mArgs != null) { 12608 processPendingInstall(mArgs, mRet); 12609 } 12610 } 12611 12612 @Override 12613 void handleServiceError() { 12614 mArgs = createInstallArgs(this); 12615 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12616 } 12617 12618 public boolean isForwardLocked() { 12619 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12620 } 12621 } 12622 12623 /** 12624 * Used during creation of InstallArgs 12625 * 12626 * @param installFlags package installation flags 12627 * @return true if should be installed on external storage 12628 */ 12629 private static boolean installOnExternalAsec(int installFlags) { 12630 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12631 return false; 12632 } 12633 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12634 return true; 12635 } 12636 return false; 12637 } 12638 12639 /** 12640 * Used during creation of InstallArgs 12641 * 12642 * @param installFlags package installation flags 12643 * @return true if should be installed as forward locked 12644 */ 12645 private static boolean installForwardLocked(int installFlags) { 12646 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12647 } 12648 12649 private InstallArgs createInstallArgs(InstallParams params) { 12650 if (params.move != null) { 12651 return new MoveInstallArgs(params); 12652 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12653 return new AsecInstallArgs(params); 12654 } else { 12655 return new FileInstallArgs(params); 12656 } 12657 } 12658 12659 /** 12660 * Create args that describe an existing installed package. Typically used 12661 * when cleaning up old installs, or used as a move source. 12662 */ 12663 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12664 String resourcePath, String[] instructionSets) { 12665 final boolean isInAsec; 12666 if (installOnExternalAsec(installFlags)) { 12667 /* Apps on SD card are always in ASEC containers. */ 12668 isInAsec = true; 12669 } else if (installForwardLocked(installFlags) 12670 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12671 /* 12672 * Forward-locked apps are only in ASEC containers if they're the 12673 * new style 12674 */ 12675 isInAsec = true; 12676 } else { 12677 isInAsec = false; 12678 } 12679 12680 if (isInAsec) { 12681 return new AsecInstallArgs(codePath, instructionSets, 12682 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12683 } else { 12684 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12685 } 12686 } 12687 12688 static abstract class InstallArgs { 12689 /** @see InstallParams#origin */ 12690 final OriginInfo origin; 12691 /** @see InstallParams#move */ 12692 final MoveInfo move; 12693 12694 final IPackageInstallObserver2 observer; 12695 // Always refers to PackageManager flags only 12696 final int installFlags; 12697 final String installerPackageName; 12698 final String volumeUuid; 12699 final UserHandle user; 12700 final String abiOverride; 12701 final String[] installGrantPermissions; 12702 /** If non-null, drop an async trace when the install completes */ 12703 final String traceMethod; 12704 final int traceCookie; 12705 final Certificate[][] certificates; 12706 12707 // The list of instruction sets supported by this app. This is currently 12708 // only used during the rmdex() phase to clean up resources. We can get rid of this 12709 // if we move dex files under the common app path. 12710 /* nullable */ String[] instructionSets; 12711 12712 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12713 int installFlags, String installerPackageName, String volumeUuid, 12714 UserHandle user, String[] instructionSets, 12715 String abiOverride, String[] installGrantPermissions, 12716 String traceMethod, int traceCookie, Certificate[][] certificates) { 12717 this.origin = origin; 12718 this.move = move; 12719 this.installFlags = installFlags; 12720 this.observer = observer; 12721 this.installerPackageName = installerPackageName; 12722 this.volumeUuid = volumeUuid; 12723 this.user = user; 12724 this.instructionSets = instructionSets; 12725 this.abiOverride = abiOverride; 12726 this.installGrantPermissions = installGrantPermissions; 12727 this.traceMethod = traceMethod; 12728 this.traceCookie = traceCookie; 12729 this.certificates = certificates; 12730 } 12731 12732 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12733 abstract int doPreInstall(int status); 12734 12735 /** 12736 * Rename package into final resting place. All paths on the given 12737 * scanned package should be updated to reflect the rename. 12738 */ 12739 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12740 abstract int doPostInstall(int status, int uid); 12741 12742 /** @see PackageSettingBase#codePathString */ 12743 abstract String getCodePath(); 12744 /** @see PackageSettingBase#resourcePathString */ 12745 abstract String getResourcePath(); 12746 12747 // Need installer lock especially for dex file removal. 12748 abstract void cleanUpResourcesLI(); 12749 abstract boolean doPostDeleteLI(boolean delete); 12750 12751 /** 12752 * Called before the source arguments are copied. This is used mostly 12753 * for MoveParams when it needs to read the source file to put it in the 12754 * destination. 12755 */ 12756 int doPreCopy() { 12757 return PackageManager.INSTALL_SUCCEEDED; 12758 } 12759 12760 /** 12761 * Called after the source arguments are copied. This is used mostly for 12762 * MoveParams when it needs to read the source file to put it in the 12763 * destination. 12764 */ 12765 int doPostCopy(int uid) { 12766 return PackageManager.INSTALL_SUCCEEDED; 12767 } 12768 12769 protected boolean isFwdLocked() { 12770 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12771 } 12772 12773 protected boolean isExternalAsec() { 12774 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12775 } 12776 12777 protected boolean isEphemeral() { 12778 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12779 } 12780 12781 UserHandle getUser() { 12782 return user; 12783 } 12784 } 12785 12786 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12787 if (!allCodePaths.isEmpty()) { 12788 if (instructionSets == null) { 12789 throw new IllegalStateException("instructionSet == null"); 12790 } 12791 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12792 for (String codePath : allCodePaths) { 12793 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12794 try { 12795 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12796 } catch (InstallerException ignored) { 12797 } 12798 } 12799 } 12800 } 12801 } 12802 12803 /** 12804 * Logic to handle installation of non-ASEC applications, including copying 12805 * and renaming logic. 12806 */ 12807 class FileInstallArgs extends InstallArgs { 12808 private File codeFile; 12809 private File resourceFile; 12810 12811 // Example topology: 12812 // /data/app/com.example/base.apk 12813 // /data/app/com.example/split_foo.apk 12814 // /data/app/com.example/lib/arm/libfoo.so 12815 // /data/app/com.example/lib/arm64/libfoo.so 12816 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12817 12818 /** New install */ 12819 FileInstallArgs(InstallParams params) { 12820 super(params.origin, params.move, params.observer, params.installFlags, 12821 params.installerPackageName, params.volumeUuid, 12822 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12823 params.grantedRuntimePermissions, 12824 params.traceMethod, params.traceCookie, params.certificates); 12825 if (isFwdLocked()) { 12826 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12827 } 12828 } 12829 12830 /** Existing install */ 12831 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12832 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12833 null, null, null, 0, null /*certificates*/); 12834 this.codeFile = (codePath != null) ? new File(codePath) : null; 12835 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12836 } 12837 12838 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12839 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12840 try { 12841 return doCopyApk(imcs, temp); 12842 } finally { 12843 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12844 } 12845 } 12846 12847 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12848 if (origin.staged) { 12849 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12850 codeFile = origin.file; 12851 resourceFile = origin.file; 12852 return PackageManager.INSTALL_SUCCEEDED; 12853 } 12854 12855 try { 12856 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12857 final File tempDir = 12858 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12859 codeFile = tempDir; 12860 resourceFile = tempDir; 12861 } catch (IOException e) { 12862 Slog.w(TAG, "Failed to create copy file: " + e); 12863 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12864 } 12865 12866 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12867 @Override 12868 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12869 if (!FileUtils.isValidExtFilename(name)) { 12870 throw new IllegalArgumentException("Invalid filename: " + name); 12871 } 12872 try { 12873 final File file = new File(codeFile, name); 12874 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12875 O_RDWR | O_CREAT, 0644); 12876 Os.chmod(file.getAbsolutePath(), 0644); 12877 return new ParcelFileDescriptor(fd); 12878 } catch (ErrnoException e) { 12879 throw new RemoteException("Failed to open: " + e.getMessage()); 12880 } 12881 } 12882 }; 12883 12884 int ret = PackageManager.INSTALL_SUCCEEDED; 12885 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12886 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12887 Slog.e(TAG, "Failed to copy package"); 12888 return ret; 12889 } 12890 12891 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12892 NativeLibraryHelper.Handle handle = null; 12893 try { 12894 handle = NativeLibraryHelper.Handle.create(codeFile); 12895 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12896 abiOverride); 12897 } catch (IOException e) { 12898 Slog.e(TAG, "Copying native libraries failed", e); 12899 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12900 } finally { 12901 IoUtils.closeQuietly(handle); 12902 } 12903 12904 return ret; 12905 } 12906 12907 int doPreInstall(int status) { 12908 if (status != PackageManager.INSTALL_SUCCEEDED) { 12909 cleanUp(); 12910 } 12911 return status; 12912 } 12913 12914 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12915 if (status != PackageManager.INSTALL_SUCCEEDED) { 12916 cleanUp(); 12917 return false; 12918 } 12919 12920 final File targetDir = codeFile.getParentFile(); 12921 final File beforeCodeFile = codeFile; 12922 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12923 12924 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12925 try { 12926 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12927 } catch (ErrnoException e) { 12928 Slog.w(TAG, "Failed to rename", e); 12929 return false; 12930 } 12931 12932 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12933 Slog.w(TAG, "Failed to restorecon"); 12934 return false; 12935 } 12936 12937 // Reflect the rename internally 12938 codeFile = afterCodeFile; 12939 resourceFile = afterCodeFile; 12940 12941 // Reflect the rename in scanned details 12942 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12943 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12944 afterCodeFile, pkg.baseCodePath)); 12945 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12946 afterCodeFile, pkg.splitCodePaths)); 12947 12948 // Reflect the rename in app info 12949 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12950 pkg.setApplicationInfoCodePath(pkg.codePath); 12951 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12952 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12953 pkg.setApplicationInfoResourcePath(pkg.codePath); 12954 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12955 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12956 12957 return true; 12958 } 12959 12960 int doPostInstall(int status, int uid) { 12961 if (status != PackageManager.INSTALL_SUCCEEDED) { 12962 cleanUp(); 12963 } 12964 return status; 12965 } 12966 12967 @Override 12968 String getCodePath() { 12969 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12970 } 12971 12972 @Override 12973 String getResourcePath() { 12974 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12975 } 12976 12977 private boolean cleanUp() { 12978 if (codeFile == null || !codeFile.exists()) { 12979 return false; 12980 } 12981 12982 removeCodePathLI(codeFile); 12983 12984 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12985 resourceFile.delete(); 12986 } 12987 12988 return true; 12989 } 12990 12991 void cleanUpResourcesLI() { 12992 // Try enumerating all code paths before deleting 12993 List<String> allCodePaths = Collections.EMPTY_LIST; 12994 if (codeFile != null && codeFile.exists()) { 12995 try { 12996 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12997 allCodePaths = pkg.getAllCodePaths(); 12998 } catch (PackageParserException e) { 12999 // Ignored; we tried our best 13000 } 13001 } 13002 13003 cleanUp(); 13004 removeDexFiles(allCodePaths, instructionSets); 13005 } 13006 13007 boolean doPostDeleteLI(boolean delete) { 13008 // XXX err, shouldn't we respect the delete flag? 13009 cleanUpResourcesLI(); 13010 return true; 13011 } 13012 } 13013 13014 private boolean isAsecExternal(String cid) { 13015 final String asecPath = PackageHelper.getSdFilesystem(cid); 13016 return !asecPath.startsWith(mAsecInternalPath); 13017 } 13018 13019 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13020 PackageManagerException { 13021 if (copyRet < 0) { 13022 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13023 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13024 throw new PackageManagerException(copyRet, message); 13025 } 13026 } 13027 } 13028 13029 /** 13030 * Extract the MountService "container ID" from the full code path of an 13031 * .apk. 13032 */ 13033 static String cidFromCodePath(String fullCodePath) { 13034 int eidx = fullCodePath.lastIndexOf("/"); 13035 String subStr1 = fullCodePath.substring(0, eidx); 13036 int sidx = subStr1.lastIndexOf("/"); 13037 return subStr1.substring(sidx+1, eidx); 13038 } 13039 13040 /** 13041 * Logic to handle installation of ASEC applications, including copying and 13042 * renaming logic. 13043 */ 13044 class AsecInstallArgs extends InstallArgs { 13045 static final String RES_FILE_NAME = "pkg.apk"; 13046 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13047 13048 String cid; 13049 String packagePath; 13050 String resourcePath; 13051 13052 /** New install */ 13053 AsecInstallArgs(InstallParams params) { 13054 super(params.origin, params.move, params.observer, params.installFlags, 13055 params.installerPackageName, params.volumeUuid, 13056 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13057 params.grantedRuntimePermissions, 13058 params.traceMethod, params.traceCookie, params.certificates); 13059 } 13060 13061 /** Existing install */ 13062 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13063 boolean isExternal, boolean isForwardLocked) { 13064 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13065 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13066 instructionSets, null, null, null, 0, null /*certificates*/); 13067 // Hackily pretend we're still looking at a full code path 13068 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13069 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13070 } 13071 13072 // Extract cid from fullCodePath 13073 int eidx = fullCodePath.lastIndexOf("/"); 13074 String subStr1 = fullCodePath.substring(0, eidx); 13075 int sidx = subStr1.lastIndexOf("/"); 13076 cid = subStr1.substring(sidx+1, eidx); 13077 setMountPath(subStr1); 13078 } 13079 13080 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13081 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13082 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13083 instructionSets, null, null, null, 0, null /*certificates*/); 13084 this.cid = cid; 13085 setMountPath(PackageHelper.getSdDir(cid)); 13086 } 13087 13088 void createCopyFile() { 13089 cid = mInstallerService.allocateExternalStageCidLegacy(); 13090 } 13091 13092 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13093 if (origin.staged && origin.cid != null) { 13094 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13095 cid = origin.cid; 13096 setMountPath(PackageHelper.getSdDir(cid)); 13097 return PackageManager.INSTALL_SUCCEEDED; 13098 } 13099 13100 if (temp) { 13101 createCopyFile(); 13102 } else { 13103 /* 13104 * Pre-emptively destroy the container since it's destroyed if 13105 * copying fails due to it existing anyway. 13106 */ 13107 PackageHelper.destroySdDir(cid); 13108 } 13109 13110 final String newMountPath = imcs.copyPackageToContainer( 13111 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13112 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13113 13114 if (newMountPath != null) { 13115 setMountPath(newMountPath); 13116 return PackageManager.INSTALL_SUCCEEDED; 13117 } else { 13118 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13119 } 13120 } 13121 13122 @Override 13123 String getCodePath() { 13124 return packagePath; 13125 } 13126 13127 @Override 13128 String getResourcePath() { 13129 return resourcePath; 13130 } 13131 13132 int doPreInstall(int status) { 13133 if (status != PackageManager.INSTALL_SUCCEEDED) { 13134 // Destroy container 13135 PackageHelper.destroySdDir(cid); 13136 } else { 13137 boolean mounted = PackageHelper.isContainerMounted(cid); 13138 if (!mounted) { 13139 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13140 Process.SYSTEM_UID); 13141 if (newMountPath != null) { 13142 setMountPath(newMountPath); 13143 } else { 13144 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13145 } 13146 } 13147 } 13148 return status; 13149 } 13150 13151 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13152 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13153 String newMountPath = null; 13154 if (PackageHelper.isContainerMounted(cid)) { 13155 // Unmount the container 13156 if (!PackageHelper.unMountSdDir(cid)) { 13157 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13158 return false; 13159 } 13160 } 13161 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13162 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13163 " which might be stale. Will try to clean up."); 13164 // Clean up the stale container and proceed to recreate. 13165 if (!PackageHelper.destroySdDir(newCacheId)) { 13166 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13167 return false; 13168 } 13169 // Successfully cleaned up stale container. Try to rename again. 13170 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13171 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13172 + " inspite of cleaning it up."); 13173 return false; 13174 } 13175 } 13176 if (!PackageHelper.isContainerMounted(newCacheId)) { 13177 Slog.w(TAG, "Mounting container " + newCacheId); 13178 newMountPath = PackageHelper.mountSdDir(newCacheId, 13179 getEncryptKey(), Process.SYSTEM_UID); 13180 } else { 13181 newMountPath = PackageHelper.getSdDir(newCacheId); 13182 } 13183 if (newMountPath == null) { 13184 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13185 return false; 13186 } 13187 Log.i(TAG, "Succesfully renamed " + cid + 13188 " to " + newCacheId + 13189 " at new path: " + newMountPath); 13190 cid = newCacheId; 13191 13192 final File beforeCodeFile = new File(packagePath); 13193 setMountPath(newMountPath); 13194 final File afterCodeFile = new File(packagePath); 13195 13196 // Reflect the rename in scanned details 13197 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13198 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13199 afterCodeFile, pkg.baseCodePath)); 13200 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13201 afterCodeFile, pkg.splitCodePaths)); 13202 13203 // Reflect the rename in app info 13204 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13205 pkg.setApplicationInfoCodePath(pkg.codePath); 13206 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13207 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13208 pkg.setApplicationInfoResourcePath(pkg.codePath); 13209 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13210 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13211 13212 return true; 13213 } 13214 13215 private void setMountPath(String mountPath) { 13216 final File mountFile = new File(mountPath); 13217 13218 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13219 if (monolithicFile.exists()) { 13220 packagePath = monolithicFile.getAbsolutePath(); 13221 if (isFwdLocked()) { 13222 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13223 } else { 13224 resourcePath = packagePath; 13225 } 13226 } else { 13227 packagePath = mountFile.getAbsolutePath(); 13228 resourcePath = packagePath; 13229 } 13230 } 13231 13232 int doPostInstall(int status, int uid) { 13233 if (status != PackageManager.INSTALL_SUCCEEDED) { 13234 cleanUp(); 13235 } else { 13236 final int groupOwner; 13237 final String protectedFile; 13238 if (isFwdLocked()) { 13239 groupOwner = UserHandle.getSharedAppGid(uid); 13240 protectedFile = RES_FILE_NAME; 13241 } else { 13242 groupOwner = -1; 13243 protectedFile = null; 13244 } 13245 13246 if (uid < Process.FIRST_APPLICATION_UID 13247 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13248 Slog.e(TAG, "Failed to finalize " + cid); 13249 PackageHelper.destroySdDir(cid); 13250 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13251 } 13252 13253 boolean mounted = PackageHelper.isContainerMounted(cid); 13254 if (!mounted) { 13255 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13256 } 13257 } 13258 return status; 13259 } 13260 13261 private void cleanUp() { 13262 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13263 13264 // Destroy secure container 13265 PackageHelper.destroySdDir(cid); 13266 } 13267 13268 private List<String> getAllCodePaths() { 13269 final File codeFile = new File(getCodePath()); 13270 if (codeFile != null && codeFile.exists()) { 13271 try { 13272 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13273 return pkg.getAllCodePaths(); 13274 } catch (PackageParserException e) { 13275 // Ignored; we tried our best 13276 } 13277 } 13278 return Collections.EMPTY_LIST; 13279 } 13280 13281 void cleanUpResourcesLI() { 13282 // Enumerate all code paths before deleting 13283 cleanUpResourcesLI(getAllCodePaths()); 13284 } 13285 13286 private void cleanUpResourcesLI(List<String> allCodePaths) { 13287 cleanUp(); 13288 removeDexFiles(allCodePaths, instructionSets); 13289 } 13290 13291 String getPackageName() { 13292 return getAsecPackageName(cid); 13293 } 13294 13295 boolean doPostDeleteLI(boolean delete) { 13296 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13297 final List<String> allCodePaths = getAllCodePaths(); 13298 boolean mounted = PackageHelper.isContainerMounted(cid); 13299 if (mounted) { 13300 // Unmount first 13301 if (PackageHelper.unMountSdDir(cid)) { 13302 mounted = false; 13303 } 13304 } 13305 if (!mounted && delete) { 13306 cleanUpResourcesLI(allCodePaths); 13307 } 13308 return !mounted; 13309 } 13310 13311 @Override 13312 int doPreCopy() { 13313 if (isFwdLocked()) { 13314 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13315 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13316 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13317 } 13318 } 13319 13320 return PackageManager.INSTALL_SUCCEEDED; 13321 } 13322 13323 @Override 13324 int doPostCopy(int uid) { 13325 if (isFwdLocked()) { 13326 if (uid < Process.FIRST_APPLICATION_UID 13327 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13328 RES_FILE_NAME)) { 13329 Slog.e(TAG, "Failed to finalize " + cid); 13330 PackageHelper.destroySdDir(cid); 13331 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13332 } 13333 } 13334 13335 return PackageManager.INSTALL_SUCCEEDED; 13336 } 13337 } 13338 13339 /** 13340 * Logic to handle movement of existing installed applications. 13341 */ 13342 class MoveInstallArgs extends InstallArgs { 13343 private File codeFile; 13344 private File resourceFile; 13345 13346 /** New install */ 13347 MoveInstallArgs(InstallParams params) { 13348 super(params.origin, params.move, params.observer, params.installFlags, 13349 params.installerPackageName, params.volumeUuid, 13350 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13351 params.grantedRuntimePermissions, 13352 params.traceMethod, params.traceCookie, params.certificates); 13353 } 13354 13355 int copyApk(IMediaContainerService imcs, boolean temp) { 13356 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13357 + move.fromUuid + " to " + move.toUuid); 13358 synchronized (mInstaller) { 13359 try { 13360 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13361 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13362 } catch (InstallerException e) { 13363 Slog.w(TAG, "Failed to move app", e); 13364 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13365 } 13366 } 13367 13368 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13369 resourceFile = codeFile; 13370 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13371 13372 return PackageManager.INSTALL_SUCCEEDED; 13373 } 13374 13375 int doPreInstall(int status) { 13376 if (status != PackageManager.INSTALL_SUCCEEDED) { 13377 cleanUp(move.toUuid); 13378 } 13379 return status; 13380 } 13381 13382 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13383 if (status != PackageManager.INSTALL_SUCCEEDED) { 13384 cleanUp(move.toUuid); 13385 return false; 13386 } 13387 13388 // Reflect the move in app info 13389 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13390 pkg.setApplicationInfoCodePath(pkg.codePath); 13391 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13392 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13393 pkg.setApplicationInfoResourcePath(pkg.codePath); 13394 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13395 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13396 13397 return true; 13398 } 13399 13400 int doPostInstall(int status, int uid) { 13401 if (status == PackageManager.INSTALL_SUCCEEDED) { 13402 cleanUp(move.fromUuid); 13403 } else { 13404 cleanUp(move.toUuid); 13405 } 13406 return status; 13407 } 13408 13409 @Override 13410 String getCodePath() { 13411 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13412 } 13413 13414 @Override 13415 String getResourcePath() { 13416 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13417 } 13418 13419 private boolean cleanUp(String volumeUuid) { 13420 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13421 move.dataAppName); 13422 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13423 synchronized (mInstallLock) { 13424 // Clean up both app data and code 13425 // All package moves are frozen until finished 13426 try { 13427 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13428 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13429 } catch (InstallerException e) { 13430 Slog.w(TAG, String.valueOf(e)); 13431 } 13432 removeCodePathLI(codeFile); 13433 } 13434 return true; 13435 } 13436 13437 void cleanUpResourcesLI() { 13438 throw new UnsupportedOperationException(); 13439 } 13440 13441 boolean doPostDeleteLI(boolean delete) { 13442 throw new UnsupportedOperationException(); 13443 } 13444 } 13445 13446 static String getAsecPackageName(String packageCid) { 13447 int idx = packageCid.lastIndexOf("-"); 13448 if (idx == -1) { 13449 return packageCid; 13450 } 13451 return packageCid.substring(0, idx); 13452 } 13453 13454 // Utility method used to create code paths based on package name and available index. 13455 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13456 String idxStr = ""; 13457 int idx = 1; 13458 // Fall back to default value of idx=1 if prefix is not 13459 // part of oldCodePath 13460 if (oldCodePath != null) { 13461 String subStr = oldCodePath; 13462 // Drop the suffix right away 13463 if (suffix != null && subStr.endsWith(suffix)) { 13464 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13465 } 13466 // If oldCodePath already contains prefix find out the 13467 // ending index to either increment or decrement. 13468 int sidx = subStr.lastIndexOf(prefix); 13469 if (sidx != -1) { 13470 subStr = subStr.substring(sidx + prefix.length()); 13471 if (subStr != null) { 13472 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13473 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13474 } 13475 try { 13476 idx = Integer.parseInt(subStr); 13477 if (idx <= 1) { 13478 idx++; 13479 } else { 13480 idx--; 13481 } 13482 } catch(NumberFormatException e) { 13483 } 13484 } 13485 } 13486 } 13487 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13488 return prefix + idxStr; 13489 } 13490 13491 private File getNextCodePath(File targetDir, String packageName) { 13492 int suffix = 1; 13493 File result; 13494 do { 13495 result = new File(targetDir, packageName + "-" + suffix); 13496 suffix++; 13497 } while (result.exists()); 13498 return result; 13499 } 13500 13501 // Utility method that returns the relative package path with respect 13502 // to the installation directory. Like say for /data/data/com.test-1.apk 13503 // string com.test-1 is returned. 13504 static String deriveCodePathName(String codePath) { 13505 if (codePath == null) { 13506 return null; 13507 } 13508 final File codeFile = new File(codePath); 13509 final String name = codeFile.getName(); 13510 if (codeFile.isDirectory()) { 13511 return name; 13512 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13513 final int lastDot = name.lastIndexOf('.'); 13514 return name.substring(0, lastDot); 13515 } else { 13516 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13517 return null; 13518 } 13519 } 13520 13521 static class PackageInstalledInfo { 13522 String name; 13523 int uid; 13524 // The set of users that originally had this package installed. 13525 int[] origUsers; 13526 // The set of users that now have this package installed. 13527 int[] newUsers; 13528 PackageParser.Package pkg; 13529 int returnCode; 13530 String returnMsg; 13531 PackageRemovedInfo removedInfo; 13532 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13533 13534 public void setError(int code, String msg) { 13535 setReturnCode(code); 13536 setReturnMessage(msg); 13537 Slog.w(TAG, msg); 13538 } 13539 13540 public void setError(String msg, PackageParserException e) { 13541 setReturnCode(e.error); 13542 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13543 Slog.w(TAG, msg, e); 13544 } 13545 13546 public void setError(String msg, PackageManagerException e) { 13547 returnCode = e.error; 13548 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13549 Slog.w(TAG, msg, e); 13550 } 13551 13552 public void setReturnCode(int returnCode) { 13553 this.returnCode = returnCode; 13554 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13555 for (int i = 0; i < childCount; i++) { 13556 addedChildPackages.valueAt(i).returnCode = returnCode; 13557 } 13558 } 13559 13560 private void setReturnMessage(String returnMsg) { 13561 this.returnMsg = returnMsg; 13562 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13563 for (int i = 0; i < childCount; i++) { 13564 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13565 } 13566 } 13567 13568 // In some error cases we want to convey more info back to the observer 13569 String origPackage; 13570 String origPermission; 13571 } 13572 13573 /* 13574 * Install a non-existing package. 13575 */ 13576 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13577 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13578 PackageInstalledInfo res) { 13579 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13580 13581 // Remember this for later, in case we need to rollback this install 13582 String pkgName = pkg.packageName; 13583 13584 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13585 13586 synchronized(mPackages) { 13587 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13588 // A package with the same name is already installed, though 13589 // it has been renamed to an older name. The package we 13590 // are trying to install should be installed as an update to 13591 // the existing one, but that has not been requested, so bail. 13592 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13593 + " without first uninstalling package running as " 13594 + mSettings.mRenamedPackages.get(pkgName)); 13595 return; 13596 } 13597 if (mPackages.containsKey(pkgName)) { 13598 // Don't allow installation over an existing package with the same name. 13599 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13600 + " without first uninstalling."); 13601 return; 13602 } 13603 } 13604 13605 try { 13606 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13607 System.currentTimeMillis(), user); 13608 13609 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13610 13611 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13612 prepareAppDataAfterInstallLIF(newPackage); 13613 13614 } else { 13615 // Remove package from internal structures, but keep around any 13616 // data that might have already existed 13617 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13618 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13619 } 13620 } catch (PackageManagerException e) { 13621 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13622 } 13623 13624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13625 } 13626 13627 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13628 // Can't rotate keys during boot or if sharedUser. 13629 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13630 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13631 return false; 13632 } 13633 // app is using upgradeKeySets; make sure all are valid 13634 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13635 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13636 for (int i = 0; i < upgradeKeySets.length; i++) { 13637 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13638 Slog.wtf(TAG, "Package " 13639 + (oldPs.name != null ? oldPs.name : "<null>") 13640 + " contains upgrade-key-set reference to unknown key-set: " 13641 + upgradeKeySets[i] 13642 + " reverting to signatures check."); 13643 return false; 13644 } 13645 } 13646 return true; 13647 } 13648 13649 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13650 // Upgrade keysets are being used. Determine if new package has a superset of the 13651 // required keys. 13652 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13653 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13654 for (int i = 0; i < upgradeKeySets.length; i++) { 13655 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13656 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13657 return true; 13658 } 13659 } 13660 return false; 13661 } 13662 13663 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13664 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13665 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13666 13667 final PackageParser.Package oldPackage; 13668 final String pkgName = pkg.packageName; 13669 final int[] allUsers; 13670 13671 // First find the old package info and check signatures 13672 synchronized(mPackages) { 13673 oldPackage = mPackages.get(pkgName); 13674 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13675 if (isEphemeral && !oldIsEphemeral) { 13676 // can't downgrade from full to ephemeral 13677 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13678 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13679 return; 13680 } 13681 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13682 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13683 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13684 if (!checkUpgradeKeySetLP(ps, pkg)) { 13685 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13686 "New package not signed by keys specified by upgrade-keysets: " 13687 + pkgName); 13688 return; 13689 } 13690 } else { 13691 // default to original signature matching 13692 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13693 != PackageManager.SIGNATURE_MATCH) { 13694 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13695 "New package has a different signature: " + pkgName); 13696 return; 13697 } 13698 } 13699 13700 // Check for shared user id changes 13701 String invalidPackageName = 13702 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13703 if (invalidPackageName != null) { 13704 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13705 "Package " + invalidPackageName + " tried to change user " 13706 + oldPackage.mSharedUserId); 13707 return; 13708 } 13709 13710 // In case of rollback, remember per-user/profile install state 13711 allUsers = sUserManager.getUserIds(); 13712 } 13713 13714 // Update what is removed 13715 res.removedInfo = new PackageRemovedInfo(); 13716 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13717 res.removedInfo.removedPackage = oldPackage.packageName; 13718 res.removedInfo.isUpdate = true; 13719 final int childCount = (oldPackage.childPackages != null) 13720 ? oldPackage.childPackages.size() : 0; 13721 for (int i = 0; i < childCount; i++) { 13722 boolean childPackageUpdated = false; 13723 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13724 if (res.addedChildPackages != null) { 13725 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13726 if (childRes != null) { 13727 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13728 childRes.removedInfo.removedPackage = childPkg.packageName; 13729 childRes.removedInfo.isUpdate = true; 13730 childPackageUpdated = true; 13731 } 13732 } 13733 if (!childPackageUpdated) { 13734 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13735 childRemovedRes.removedPackage = childPkg.packageName; 13736 childRemovedRes.isUpdate = false; 13737 childRemovedRes.dataRemoved = true; 13738 synchronized (mPackages) { 13739 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13740 if (childPs != null) { 13741 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13742 } 13743 } 13744 if (res.removedInfo.removedChildPackages == null) { 13745 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13746 } 13747 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13748 } 13749 } 13750 13751 boolean sysPkg = (isSystemApp(oldPackage)); 13752 if (sysPkg) { 13753 // Set the system/privileged flags as needed 13754 final boolean privileged = 13755 (oldPackage.applicationInfo.privateFlags 13756 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13757 final int systemPolicyFlags = policyFlags 13758 | PackageParser.PARSE_IS_SYSTEM 13759 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13760 13761 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13762 user, allUsers, installerPackageName, res); 13763 } else { 13764 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13765 user, allUsers, installerPackageName, res); 13766 } 13767 } 13768 13769 public List<String> getPreviousCodePaths(String packageName) { 13770 final PackageSetting ps = mSettings.mPackages.get(packageName); 13771 final List<String> result = new ArrayList<String>(); 13772 if (ps != null && ps.oldCodePaths != null) { 13773 result.addAll(ps.oldCodePaths); 13774 } 13775 return result; 13776 } 13777 13778 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13779 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13780 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13781 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13782 + deletedPackage); 13783 13784 String pkgName = deletedPackage.packageName; 13785 boolean deletedPkg = true; 13786 boolean addedPkg = false; 13787 boolean updatedSettings = false; 13788 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13789 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13790 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13791 13792 final long origUpdateTime = (pkg.mExtras != null) 13793 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13794 13795 // First delete the existing package while retaining the data directory 13796 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13797 res.removedInfo, true, pkg)) { 13798 // If the existing package wasn't successfully deleted 13799 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13800 deletedPkg = false; 13801 } else { 13802 // Successfully deleted the old package; proceed with replace. 13803 13804 // If deleted package lived in a container, give users a chance to 13805 // relinquish resources before killing. 13806 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13807 if (DEBUG_INSTALL) { 13808 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13809 } 13810 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13811 final ArrayList<String> pkgList = new ArrayList<String>(1); 13812 pkgList.add(deletedPackage.applicationInfo.packageName); 13813 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13814 } 13815 13816 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13817 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13818 clearAppProfilesLIF(pkg); 13819 13820 try { 13821 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13822 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13823 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13824 13825 // Update the in-memory copy of the previous code paths. 13826 PackageSetting ps = mSettings.mPackages.get(pkgName); 13827 if (!killApp) { 13828 if (ps.oldCodePaths == null) { 13829 ps.oldCodePaths = new ArraySet<>(); 13830 } 13831 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13832 if (deletedPackage.splitCodePaths != null) { 13833 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13834 } 13835 } else { 13836 ps.oldCodePaths = null; 13837 } 13838 if (ps.childPackageNames != null) { 13839 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13840 final String childPkgName = ps.childPackageNames.get(i); 13841 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13842 childPs.oldCodePaths = ps.oldCodePaths; 13843 } 13844 } 13845 prepareAppDataAfterInstallLIF(newPackage); 13846 addedPkg = true; 13847 } catch (PackageManagerException e) { 13848 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13849 } 13850 } 13851 13852 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13853 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13854 13855 // Revert all internal state mutations and added folders for the failed install 13856 if (addedPkg) { 13857 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13858 res.removedInfo, true, null); 13859 } 13860 13861 // Restore the old package 13862 if (deletedPkg) { 13863 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13864 File restoreFile = new File(deletedPackage.codePath); 13865 // Parse old package 13866 boolean oldExternal = isExternal(deletedPackage); 13867 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13868 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13869 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13870 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13871 try { 13872 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13873 null); 13874 } catch (PackageManagerException e) { 13875 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13876 + e.getMessage()); 13877 return; 13878 } 13879 13880 synchronized (mPackages) { 13881 // Ensure the installer package name up to date 13882 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13883 13884 // Update permissions for restored package 13885 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13886 13887 mSettings.writeLPr(); 13888 } 13889 13890 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13891 } 13892 } else { 13893 synchronized (mPackages) { 13894 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13895 if (ps != null) { 13896 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13897 if (res.removedInfo.removedChildPackages != null) { 13898 final int childCount = res.removedInfo.removedChildPackages.size(); 13899 // Iterate in reverse as we may modify the collection 13900 for (int i = childCount - 1; i >= 0; i--) { 13901 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13902 if (res.addedChildPackages.containsKey(childPackageName)) { 13903 res.removedInfo.removedChildPackages.removeAt(i); 13904 } else { 13905 PackageRemovedInfo childInfo = res.removedInfo 13906 .removedChildPackages.valueAt(i); 13907 childInfo.removedForAllUsers = mPackages.get( 13908 childInfo.removedPackage) == null; 13909 } 13910 } 13911 } 13912 } 13913 } 13914 } 13915 } 13916 13917 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13918 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13919 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13920 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13921 + ", old=" + deletedPackage); 13922 13923 final boolean disabledSystem; 13924 13925 // Remove existing system package 13926 removePackageLI(deletedPackage, true); 13927 13928 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13929 if (!disabledSystem) { 13930 // We didn't need to disable the .apk as a current system package, 13931 // which means we are replacing another update that is already 13932 // installed. We need to make sure to delete the older one's .apk. 13933 res.removedInfo.args = createInstallArgsForExisting(0, 13934 deletedPackage.applicationInfo.getCodePath(), 13935 deletedPackage.applicationInfo.getResourcePath(), 13936 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13937 } else { 13938 res.removedInfo.args = null; 13939 } 13940 13941 // Successfully disabled the old package. Now proceed with re-installation 13942 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13943 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13944 clearAppProfilesLIF(pkg); 13945 13946 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13947 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13948 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13949 13950 PackageParser.Package newPackage = null; 13951 try { 13952 // Add the package to the internal data structures 13953 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 13954 13955 // Set the update and install times 13956 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13957 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13958 System.currentTimeMillis()); 13959 13960 // Update the package dynamic state if succeeded 13961 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13962 // Now that the install succeeded make sure we remove data 13963 // directories for any child package the update removed. 13964 final int deletedChildCount = (deletedPackage.childPackages != null) 13965 ? deletedPackage.childPackages.size() : 0; 13966 final int newChildCount = (newPackage.childPackages != null) 13967 ? newPackage.childPackages.size() : 0; 13968 for (int i = 0; i < deletedChildCount; i++) { 13969 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13970 boolean childPackageDeleted = true; 13971 for (int j = 0; j < newChildCount; j++) { 13972 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13973 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13974 childPackageDeleted = false; 13975 break; 13976 } 13977 } 13978 if (childPackageDeleted) { 13979 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13980 deletedChildPkg.packageName); 13981 if (ps != null && res.removedInfo.removedChildPackages != null) { 13982 PackageRemovedInfo removedChildRes = res.removedInfo 13983 .removedChildPackages.get(deletedChildPkg.packageName); 13984 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13985 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13986 } 13987 } 13988 } 13989 13990 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13991 prepareAppDataAfterInstallLIF(newPackage); 13992 } 13993 } catch (PackageManagerException e) { 13994 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13995 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13996 } 13997 13998 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13999 // Re installation failed. Restore old information 14000 // Remove new pkg information 14001 if (newPackage != null) { 14002 removeInstalledPackageLI(newPackage, true); 14003 } 14004 // Add back the old system package 14005 try { 14006 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14007 } catch (PackageManagerException e) { 14008 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14009 } 14010 14011 synchronized (mPackages) { 14012 if (disabledSystem) { 14013 enableSystemPackageLPw(deletedPackage); 14014 } 14015 14016 // Ensure the installer package name up to date 14017 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14018 14019 // Update permissions for restored package 14020 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14021 14022 mSettings.writeLPr(); 14023 } 14024 14025 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14026 + " after failed upgrade"); 14027 } 14028 } 14029 14030 /** 14031 * Checks whether the parent or any of the child packages have a change shared 14032 * user. For a package to be a valid update the shred users of the parent and 14033 * the children should match. We may later support changing child shared users. 14034 * @param oldPkg The updated package. 14035 * @param newPkg The update package. 14036 * @return The shared user that change between the versions. 14037 */ 14038 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14039 PackageParser.Package newPkg) { 14040 // Check parent shared user 14041 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14042 return newPkg.packageName; 14043 } 14044 // Check child shared users 14045 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14046 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14047 for (int i = 0; i < newChildCount; i++) { 14048 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14049 // If this child was present, did it have the same shared user? 14050 for (int j = 0; j < oldChildCount; j++) { 14051 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14052 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14053 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14054 return newChildPkg.packageName; 14055 } 14056 } 14057 } 14058 return null; 14059 } 14060 14061 private void removeNativeBinariesLI(PackageSetting ps) { 14062 // Remove the lib path for the parent package 14063 if (ps != null) { 14064 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14065 // Remove the lib path for the child packages 14066 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14067 for (int i = 0; i < childCount; i++) { 14068 PackageSetting childPs = null; 14069 synchronized (mPackages) { 14070 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14071 } 14072 if (childPs != null) { 14073 NativeLibraryHelper.removeNativeBinariesLI(childPs 14074 .legacyNativeLibraryPathString); 14075 } 14076 } 14077 } 14078 } 14079 14080 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14081 // Enable the parent package 14082 mSettings.enableSystemPackageLPw(pkg.packageName); 14083 // Enable the child packages 14084 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14085 for (int i = 0; i < childCount; i++) { 14086 PackageParser.Package childPkg = pkg.childPackages.get(i); 14087 mSettings.enableSystemPackageLPw(childPkg.packageName); 14088 } 14089 } 14090 14091 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14092 PackageParser.Package newPkg) { 14093 // Disable the parent package (parent always replaced) 14094 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14095 // Disable the child packages 14096 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14097 for (int i = 0; i < childCount; i++) { 14098 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14099 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14100 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14101 } 14102 return disabled; 14103 } 14104 14105 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14106 String installerPackageName) { 14107 // Enable the parent package 14108 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14109 // Enable the child packages 14110 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14111 for (int i = 0; i < childCount; i++) { 14112 PackageParser.Package childPkg = pkg.childPackages.get(i); 14113 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14114 } 14115 } 14116 14117 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14118 // Collect all used permissions in the UID 14119 ArraySet<String> usedPermissions = new ArraySet<>(); 14120 final int packageCount = su.packages.size(); 14121 for (int i = 0; i < packageCount; i++) { 14122 PackageSetting ps = su.packages.valueAt(i); 14123 if (ps.pkg == null) { 14124 continue; 14125 } 14126 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14127 for (int j = 0; j < requestedPermCount; j++) { 14128 String permission = ps.pkg.requestedPermissions.get(j); 14129 BasePermission bp = mSettings.mPermissions.get(permission); 14130 if (bp != null) { 14131 usedPermissions.add(permission); 14132 } 14133 } 14134 } 14135 14136 PermissionsState permissionsState = su.getPermissionsState(); 14137 // Prune install permissions 14138 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14139 final int installPermCount = installPermStates.size(); 14140 for (int i = installPermCount - 1; i >= 0; i--) { 14141 PermissionState permissionState = installPermStates.get(i); 14142 if (!usedPermissions.contains(permissionState.getName())) { 14143 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14144 if (bp != null) { 14145 permissionsState.revokeInstallPermission(bp); 14146 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14147 PackageManager.MASK_PERMISSION_FLAGS, 0); 14148 } 14149 } 14150 } 14151 14152 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14153 14154 // Prune runtime permissions 14155 for (int userId : allUserIds) { 14156 List<PermissionState> runtimePermStates = permissionsState 14157 .getRuntimePermissionStates(userId); 14158 final int runtimePermCount = runtimePermStates.size(); 14159 for (int i = runtimePermCount - 1; i >= 0; i--) { 14160 PermissionState permissionState = runtimePermStates.get(i); 14161 if (!usedPermissions.contains(permissionState.getName())) { 14162 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14163 if (bp != null) { 14164 permissionsState.revokeRuntimePermission(bp, userId); 14165 permissionsState.updatePermissionFlags(bp, userId, 14166 PackageManager.MASK_PERMISSION_FLAGS, 0); 14167 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14168 runtimePermissionChangedUserIds, userId); 14169 } 14170 } 14171 } 14172 } 14173 14174 return runtimePermissionChangedUserIds; 14175 } 14176 14177 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14178 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14179 // Update the parent package setting 14180 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14181 res, user); 14182 // Update the child packages setting 14183 final int childCount = (newPackage.childPackages != null) 14184 ? newPackage.childPackages.size() : 0; 14185 for (int i = 0; i < childCount; i++) { 14186 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14187 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14188 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14189 childRes.origUsers, childRes, user); 14190 } 14191 } 14192 14193 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14194 String installerPackageName, int[] allUsers, int[] installedForUsers, 14195 PackageInstalledInfo res, UserHandle user) { 14196 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14197 14198 String pkgName = newPackage.packageName; 14199 synchronized (mPackages) { 14200 //write settings. the installStatus will be incomplete at this stage. 14201 //note that the new package setting would have already been 14202 //added to mPackages. It hasn't been persisted yet. 14203 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14204 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14205 mSettings.writeLPr(); 14206 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14207 } 14208 14209 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14210 synchronized (mPackages) { 14211 updatePermissionsLPw(newPackage.packageName, newPackage, 14212 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14213 ? UPDATE_PERMISSIONS_ALL : 0)); 14214 // For system-bundled packages, we assume that installing an upgraded version 14215 // of the package implies that the user actually wants to run that new code, 14216 // so we enable the package. 14217 PackageSetting ps = mSettings.mPackages.get(pkgName); 14218 final int userId = user.getIdentifier(); 14219 if (ps != null) { 14220 if (isSystemApp(newPackage)) { 14221 if (DEBUG_INSTALL) { 14222 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14223 } 14224 // Enable system package for requested users 14225 if (res.origUsers != null) { 14226 for (int origUserId : res.origUsers) { 14227 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14228 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14229 origUserId, installerPackageName); 14230 } 14231 } 14232 } 14233 // Also convey the prior install/uninstall state 14234 if (allUsers != null && installedForUsers != null) { 14235 for (int currentUserId : allUsers) { 14236 final boolean installed = ArrayUtils.contains( 14237 installedForUsers, currentUserId); 14238 if (DEBUG_INSTALL) { 14239 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14240 } 14241 ps.setInstalled(installed, currentUserId); 14242 } 14243 // these install state changes will be persisted in the 14244 // upcoming call to mSettings.writeLPr(). 14245 } 14246 } 14247 // It's implied that when a user requests installation, they want the app to be 14248 // installed and enabled. 14249 if (userId != UserHandle.USER_ALL) { 14250 ps.setInstalled(true, userId); 14251 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14252 } 14253 } 14254 res.name = pkgName; 14255 res.uid = newPackage.applicationInfo.uid; 14256 res.pkg = newPackage; 14257 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14258 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14259 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14260 //to update install status 14261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14262 mSettings.writeLPr(); 14263 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14264 } 14265 14266 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14267 } 14268 14269 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14270 try { 14271 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14272 installPackageLI(args, res); 14273 } finally { 14274 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14275 } 14276 } 14277 14278 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14279 final int installFlags = args.installFlags; 14280 final String installerPackageName = args.installerPackageName; 14281 final String volumeUuid = args.volumeUuid; 14282 final File tmpPackageFile = new File(args.getCodePath()); 14283 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14284 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14285 || (args.volumeUuid != null)); 14286 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14287 boolean replace = false; 14288 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14289 if (args.move != null) { 14290 // moving a complete application; perform an initial scan on the new install location 14291 scanFlags |= SCAN_INITIAL; 14292 } 14293 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14294 scanFlags |= SCAN_DONT_KILL_APP; 14295 } 14296 14297 // Result object to be returned 14298 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14299 14300 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14301 14302 // Sanity check 14303 if (ephemeral && (forwardLocked || onExternal)) { 14304 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14305 + " external=" + onExternal); 14306 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14307 return; 14308 } 14309 14310 // Retrieve PackageSettings and parse package 14311 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14312 | PackageParser.PARSE_ENFORCE_CODE 14313 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14314 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14315 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14316 PackageParser pp = new PackageParser(); 14317 pp.setSeparateProcesses(mSeparateProcesses); 14318 pp.setDisplayMetrics(mMetrics); 14319 14320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14321 final PackageParser.Package pkg; 14322 try { 14323 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14324 } catch (PackageParserException e) { 14325 res.setError("Failed parse during installPackageLI", e); 14326 return; 14327 } finally { 14328 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14329 } 14330 14331 // If we are installing a clustered package add results for the children 14332 if (pkg.childPackages != null) { 14333 synchronized (mPackages) { 14334 final int childCount = pkg.childPackages.size(); 14335 for (int i = 0; i < childCount; i++) { 14336 PackageParser.Package childPkg = pkg.childPackages.get(i); 14337 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14338 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14339 childRes.pkg = childPkg; 14340 childRes.name = childPkg.packageName; 14341 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14342 if (childPs != null) { 14343 childRes.origUsers = childPs.queryInstalledUsers( 14344 sUserManager.getUserIds(), true); 14345 } 14346 if ((mPackages.containsKey(childPkg.packageName))) { 14347 childRes.removedInfo = new PackageRemovedInfo(); 14348 childRes.removedInfo.removedPackage = childPkg.packageName; 14349 } 14350 if (res.addedChildPackages == null) { 14351 res.addedChildPackages = new ArrayMap<>(); 14352 } 14353 res.addedChildPackages.put(childPkg.packageName, childRes); 14354 } 14355 } 14356 } 14357 14358 // If package doesn't declare API override, mark that we have an install 14359 // time CPU ABI override. 14360 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14361 pkg.cpuAbiOverride = args.abiOverride; 14362 } 14363 14364 String pkgName = res.name = pkg.packageName; 14365 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14366 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14367 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14368 return; 14369 } 14370 } 14371 14372 try { 14373 // either use what we've been given or parse directly from the APK 14374 if (args.certificates != null) { 14375 try { 14376 PackageParser.populateCertificates(pkg, args.certificates); 14377 } catch (PackageParserException e) { 14378 // there was something wrong with the certificates we were given; 14379 // try to pull them from the APK 14380 PackageParser.collectCertificates(pkg, parseFlags); 14381 } 14382 } else { 14383 PackageParser.collectCertificates(pkg, parseFlags); 14384 } 14385 } catch (PackageParserException e) { 14386 res.setError("Failed collect during installPackageLI", e); 14387 return; 14388 } 14389 14390 // Get rid of all references to package scan path via parser. 14391 pp = null; 14392 String oldCodePath = null; 14393 boolean systemApp = false; 14394 synchronized (mPackages) { 14395 // Check if installing already existing package 14396 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14397 String oldName = mSettings.mRenamedPackages.get(pkgName); 14398 if (pkg.mOriginalPackages != null 14399 && pkg.mOriginalPackages.contains(oldName) 14400 && mPackages.containsKey(oldName)) { 14401 // This package is derived from an original package, 14402 // and this device has been updating from that original 14403 // name. We must continue using the original name, so 14404 // rename the new package here. 14405 pkg.setPackageName(oldName); 14406 pkgName = pkg.packageName; 14407 replace = true; 14408 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14409 + oldName + " pkgName=" + pkgName); 14410 } else if (mPackages.containsKey(pkgName)) { 14411 // This package, under its official name, already exists 14412 // on the device; we should replace it. 14413 replace = true; 14414 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14415 } 14416 14417 // Child packages are installed through the parent package 14418 if (pkg.parentPackage != null) { 14419 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14420 "Package " + pkg.packageName + " is child of package " 14421 + pkg.parentPackage.parentPackage + ". Child packages " 14422 + "can be updated only through the parent package."); 14423 return; 14424 } 14425 14426 if (replace) { 14427 // Prevent apps opting out from runtime permissions 14428 PackageParser.Package oldPackage = mPackages.get(pkgName); 14429 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14430 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14431 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14432 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14433 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14434 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14435 + " doesn't support runtime permissions but the old" 14436 + " target SDK " + oldTargetSdk + " does."); 14437 return; 14438 } 14439 14440 // Prevent installing of child packages 14441 if (oldPackage.parentPackage != null) { 14442 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14443 "Package " + pkg.packageName + " is child of package " 14444 + oldPackage.parentPackage + ". Child packages " 14445 + "can be updated only through the parent package."); 14446 return; 14447 } 14448 } 14449 } 14450 14451 PackageSetting ps = mSettings.mPackages.get(pkgName); 14452 if (ps != null) { 14453 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14454 14455 // Quick sanity check that we're signed correctly if updating; 14456 // we'll check this again later when scanning, but we want to 14457 // bail early here before tripping over redefined permissions. 14458 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14459 if (!checkUpgradeKeySetLP(ps, pkg)) { 14460 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14461 + pkg.packageName + " upgrade keys do not match the " 14462 + "previously installed version"); 14463 return; 14464 } 14465 } else { 14466 try { 14467 verifySignaturesLP(ps, pkg); 14468 } catch (PackageManagerException e) { 14469 res.setError(e.error, e.getMessage()); 14470 return; 14471 } 14472 } 14473 14474 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14475 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14476 systemApp = (ps.pkg.applicationInfo.flags & 14477 ApplicationInfo.FLAG_SYSTEM) != 0; 14478 } 14479 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14480 } 14481 14482 // Check whether the newly-scanned package wants to define an already-defined perm 14483 int N = pkg.permissions.size(); 14484 for (int i = N-1; i >= 0; i--) { 14485 PackageParser.Permission perm = pkg.permissions.get(i); 14486 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14487 if (bp != null) { 14488 // If the defining package is signed with our cert, it's okay. This 14489 // also includes the "updating the same package" case, of course. 14490 // "updating same package" could also involve key-rotation. 14491 final boolean sigsOk; 14492 if (bp.sourcePackage.equals(pkg.packageName) 14493 && (bp.packageSetting instanceof PackageSetting) 14494 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14495 scanFlags))) { 14496 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14497 } else { 14498 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14499 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14500 } 14501 if (!sigsOk) { 14502 // If the owning package is the system itself, we log but allow 14503 // install to proceed; we fail the install on all other permission 14504 // redefinitions. 14505 if (!bp.sourcePackage.equals("android")) { 14506 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14507 + pkg.packageName + " attempting to redeclare permission " 14508 + perm.info.name + " already owned by " + bp.sourcePackage); 14509 res.origPermission = perm.info.name; 14510 res.origPackage = bp.sourcePackage; 14511 return; 14512 } else { 14513 Slog.w(TAG, "Package " + pkg.packageName 14514 + " attempting to redeclare system permission " 14515 + perm.info.name + "; ignoring new declaration"); 14516 pkg.permissions.remove(i); 14517 } 14518 } 14519 } 14520 } 14521 } 14522 14523 if (systemApp) { 14524 if (onExternal) { 14525 // Abort update; system app can't be replaced with app on sdcard 14526 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14527 "Cannot install updates to system apps on sdcard"); 14528 return; 14529 } else if (ephemeral) { 14530 // Abort update; system app can't be replaced with an ephemeral app 14531 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14532 "Cannot update a system app with an ephemeral app"); 14533 return; 14534 } 14535 } 14536 14537 if (args.move != null) { 14538 // We did an in-place move, so dex is ready to roll 14539 scanFlags |= SCAN_NO_DEX; 14540 scanFlags |= SCAN_MOVE; 14541 14542 synchronized (mPackages) { 14543 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14544 if (ps == null) { 14545 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14546 "Missing settings for moved package " + pkgName); 14547 } 14548 14549 // We moved the entire application as-is, so bring over the 14550 // previously derived ABI information. 14551 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14552 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14553 } 14554 14555 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14556 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14557 scanFlags |= SCAN_NO_DEX; 14558 14559 try { 14560 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14561 args.abiOverride : pkg.cpuAbiOverride); 14562 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14563 true /* extract libs */); 14564 } catch (PackageManagerException pme) { 14565 Slog.e(TAG, "Error deriving application ABI", pme); 14566 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14567 return; 14568 } 14569 14570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14571 // Do not run PackageDexOptimizer through the local performDexOpt 14572 // method because `pkg` is not in `mPackages` yet. 14573 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14574 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14576 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14577 String msg = "Extracting package failed for " + pkgName; 14578 res.setError(INSTALL_FAILED_DEXOPT, msg); 14579 return; 14580 } 14581 14582 // Notify BackgroundDexOptService that the package has been changed. 14583 // If this is an update of a package which used to fail to compile, 14584 // BDOS will remove it from its blacklist. 14585 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14586 } 14587 14588 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14589 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14590 return; 14591 } 14592 14593 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14594 14595 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14596 "installPackageLI")) { 14597 if (replace) { 14598 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14599 installerPackageName, res); 14600 } else { 14601 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14602 args.user, installerPackageName, volumeUuid, res); 14603 } 14604 } 14605 synchronized (mPackages) { 14606 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14607 if (ps != null) { 14608 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14609 } 14610 14611 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14612 for (int i = 0; i < childCount; i++) { 14613 PackageParser.Package childPkg = pkg.childPackages.get(i); 14614 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14615 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14616 if (childPs != null) { 14617 childRes.newUsers = childPs.queryInstalledUsers( 14618 sUserManager.getUserIds(), true); 14619 } 14620 } 14621 } 14622 } 14623 14624 private void startIntentFilterVerifications(int userId, boolean replacing, 14625 PackageParser.Package pkg) { 14626 if (mIntentFilterVerifierComponent == null) { 14627 Slog.w(TAG, "No IntentFilter verification will not be done as " 14628 + "there is no IntentFilterVerifier available!"); 14629 return; 14630 } 14631 14632 final int verifierUid = getPackageUid( 14633 mIntentFilterVerifierComponent.getPackageName(), 14634 MATCH_DEBUG_TRIAGED_MISSING, 14635 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14636 14637 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14638 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14639 mHandler.sendMessage(msg); 14640 14641 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14642 for (int i = 0; i < childCount; i++) { 14643 PackageParser.Package childPkg = pkg.childPackages.get(i); 14644 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14645 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14646 mHandler.sendMessage(msg); 14647 } 14648 } 14649 14650 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14651 PackageParser.Package pkg) { 14652 int size = pkg.activities.size(); 14653 if (size == 0) { 14654 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14655 "No activity, so no need to verify any IntentFilter!"); 14656 return; 14657 } 14658 14659 final boolean hasDomainURLs = hasDomainURLs(pkg); 14660 if (!hasDomainURLs) { 14661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14662 "No domain URLs, so no need to verify any IntentFilter!"); 14663 return; 14664 } 14665 14666 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14667 + " if any IntentFilter from the " + size 14668 + " Activities needs verification ..."); 14669 14670 int count = 0; 14671 final String packageName = pkg.packageName; 14672 14673 synchronized (mPackages) { 14674 // If this is a new install and we see that we've already run verification for this 14675 // package, we have nothing to do: it means the state was restored from backup. 14676 if (!replacing) { 14677 IntentFilterVerificationInfo ivi = 14678 mSettings.getIntentFilterVerificationLPr(packageName); 14679 if (ivi != null) { 14680 if (DEBUG_DOMAIN_VERIFICATION) { 14681 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14682 + ivi.getStatusString()); 14683 } 14684 return; 14685 } 14686 } 14687 14688 // If any filters need to be verified, then all need to be. 14689 boolean needToVerify = false; 14690 for (PackageParser.Activity a : pkg.activities) { 14691 for (ActivityIntentInfo filter : a.intents) { 14692 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14693 if (DEBUG_DOMAIN_VERIFICATION) { 14694 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14695 } 14696 needToVerify = true; 14697 break; 14698 } 14699 } 14700 } 14701 14702 if (needToVerify) { 14703 final int verificationId = mIntentFilterVerificationToken++; 14704 for (PackageParser.Activity a : pkg.activities) { 14705 for (ActivityIntentInfo filter : a.intents) { 14706 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14707 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14708 "Verification needed for IntentFilter:" + filter.toString()); 14709 mIntentFilterVerifier.addOneIntentFilterVerification( 14710 verifierUid, userId, verificationId, filter, packageName); 14711 count++; 14712 } 14713 } 14714 } 14715 } 14716 } 14717 14718 if (count > 0) { 14719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14720 + " IntentFilter verification" + (count > 1 ? "s" : "") 14721 + " for userId:" + userId); 14722 mIntentFilterVerifier.startVerifications(userId); 14723 } else { 14724 if (DEBUG_DOMAIN_VERIFICATION) { 14725 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14726 } 14727 } 14728 } 14729 14730 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14731 final ComponentName cn = filter.activity.getComponentName(); 14732 final String packageName = cn.getPackageName(); 14733 14734 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14735 packageName); 14736 if (ivi == null) { 14737 return true; 14738 } 14739 int status = ivi.getStatus(); 14740 switch (status) { 14741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14742 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14743 return true; 14744 14745 default: 14746 // Nothing to do 14747 return false; 14748 } 14749 } 14750 14751 private static boolean isMultiArch(ApplicationInfo info) { 14752 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14753 } 14754 14755 private static boolean isExternal(PackageParser.Package pkg) { 14756 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14757 } 14758 14759 private static boolean isExternal(PackageSetting ps) { 14760 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14761 } 14762 14763 private static boolean isEphemeral(PackageParser.Package pkg) { 14764 return pkg.applicationInfo.isEphemeralApp(); 14765 } 14766 14767 private static boolean isEphemeral(PackageSetting ps) { 14768 return ps.pkg != null && isEphemeral(ps.pkg); 14769 } 14770 14771 private static boolean isSystemApp(PackageParser.Package pkg) { 14772 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14773 } 14774 14775 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14776 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14777 } 14778 14779 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14780 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14781 } 14782 14783 private static boolean isSystemApp(PackageSetting ps) { 14784 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14785 } 14786 14787 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14788 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14789 } 14790 14791 private int packageFlagsToInstallFlags(PackageSetting ps) { 14792 int installFlags = 0; 14793 if (isEphemeral(ps)) { 14794 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14795 } 14796 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14797 // This existing package was an external ASEC install when we have 14798 // the external flag without a UUID 14799 installFlags |= PackageManager.INSTALL_EXTERNAL; 14800 } 14801 if (ps.isForwardLocked()) { 14802 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14803 } 14804 return installFlags; 14805 } 14806 14807 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14808 if (isExternal(pkg)) { 14809 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14810 return StorageManager.UUID_PRIMARY_PHYSICAL; 14811 } else { 14812 return pkg.volumeUuid; 14813 } 14814 } else { 14815 return StorageManager.UUID_PRIVATE_INTERNAL; 14816 } 14817 } 14818 14819 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14820 if (isExternal(pkg)) { 14821 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14822 return mSettings.getExternalVersion(); 14823 } else { 14824 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14825 } 14826 } else { 14827 return mSettings.getInternalVersion(); 14828 } 14829 } 14830 14831 private void deleteTempPackageFiles() { 14832 final FilenameFilter filter = new FilenameFilter() { 14833 public boolean accept(File dir, String name) { 14834 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14835 } 14836 }; 14837 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14838 file.delete(); 14839 } 14840 } 14841 14842 @Override 14843 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14844 int flags) { 14845 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14846 flags); 14847 } 14848 14849 @Override 14850 public void deletePackage(final String packageName, 14851 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14852 mContext.enforceCallingOrSelfPermission( 14853 android.Manifest.permission.DELETE_PACKAGES, null); 14854 Preconditions.checkNotNull(packageName); 14855 Preconditions.checkNotNull(observer); 14856 final int uid = Binder.getCallingUid(); 14857 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14858 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14859 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14860 mContext.enforceCallingOrSelfPermission( 14861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14862 "deletePackage for user " + userId); 14863 } 14864 14865 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14866 try { 14867 observer.onPackageDeleted(packageName, 14868 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14869 } catch (RemoteException re) { 14870 } 14871 return; 14872 } 14873 14874 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14875 try { 14876 observer.onPackageDeleted(packageName, 14877 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14878 } catch (RemoteException re) { 14879 } 14880 return; 14881 } 14882 14883 if (DEBUG_REMOVE) { 14884 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14885 + " deleteAllUsers: " + deleteAllUsers ); 14886 } 14887 // Queue up an async operation since the package deletion may take a little while. 14888 mHandler.post(new Runnable() { 14889 public void run() { 14890 mHandler.removeCallbacks(this); 14891 int returnCode; 14892 if (!deleteAllUsers) { 14893 returnCode = deletePackageX(packageName, userId, deleteFlags); 14894 } else { 14895 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14896 // If nobody is blocking uninstall, proceed with delete for all users 14897 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14898 returnCode = deletePackageX(packageName, userId, deleteFlags); 14899 } else { 14900 // Otherwise uninstall individually for users with blockUninstalls=false 14901 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14902 for (int userId : users) { 14903 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14904 returnCode = deletePackageX(packageName, userId, userFlags); 14905 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14906 Slog.w(TAG, "Package delete failed for user " + userId 14907 + ", returnCode " + returnCode); 14908 } 14909 } 14910 } 14911 // The app has only been marked uninstalled for certain users. 14912 // We still need to report that delete was blocked 14913 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14914 } 14915 } 14916 try { 14917 observer.onPackageDeleted(packageName, returnCode, null); 14918 } catch (RemoteException e) { 14919 Log.i(TAG, "Observer no longer exists."); 14920 } //end catch 14921 } //end run 14922 }); 14923 } 14924 14925 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14926 int[] result = EMPTY_INT_ARRAY; 14927 for (int userId : userIds) { 14928 if (getBlockUninstallForUser(packageName, userId)) { 14929 result = ArrayUtils.appendInt(result, userId); 14930 } 14931 } 14932 return result; 14933 } 14934 14935 @Override 14936 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14937 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14938 } 14939 14940 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14941 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14942 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14943 try { 14944 if (dpm != null) { 14945 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14946 /* callingUserOnly =*/ false); 14947 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14948 : deviceOwnerComponentName.getPackageName(); 14949 // Does the package contains the device owner? 14950 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14951 // this check is probably not needed, since DO should be registered as a device 14952 // admin on some user too. (Original bug for this: b/17657954) 14953 if (packageName.equals(deviceOwnerPackageName)) { 14954 return true; 14955 } 14956 // Does it contain a device admin for any user? 14957 int[] users; 14958 if (userId == UserHandle.USER_ALL) { 14959 users = sUserManager.getUserIds(); 14960 } else { 14961 users = new int[]{userId}; 14962 } 14963 for (int i = 0; i < users.length; ++i) { 14964 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14965 return true; 14966 } 14967 } 14968 } 14969 } catch (RemoteException e) { 14970 } 14971 return false; 14972 } 14973 14974 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14975 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14976 } 14977 14978 /** 14979 * This method is an internal method that could be get invoked either 14980 * to delete an installed package or to clean up a failed installation. 14981 * After deleting an installed package, a broadcast is sent to notify any 14982 * listeners that the package has been removed. For cleaning up a failed 14983 * installation, the broadcast is not necessary since the package's 14984 * installation wouldn't have sent the initial broadcast either 14985 * The key steps in deleting a package are 14986 * deleting the package information in internal structures like mPackages, 14987 * deleting the packages base directories through installd 14988 * updating mSettings to reflect current status 14989 * persisting settings for later use 14990 * sending a broadcast if necessary 14991 */ 14992 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14993 final PackageRemovedInfo info = new PackageRemovedInfo(); 14994 final boolean res; 14995 14996 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14997 ? UserHandle.ALL : new UserHandle(userId); 14998 14999 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15000 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15001 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15002 } 15003 15004 PackageSetting uninstalledPs = null; 15005 15006 // for the uninstall-updates case and restricted profiles, remember the per- 15007 // user handle installed state 15008 int[] allUsers; 15009 synchronized (mPackages) { 15010 uninstalledPs = mSettings.mPackages.get(packageName); 15011 if (uninstalledPs == null) { 15012 Slog.w(TAG, "Not removing non-existent package " + packageName); 15013 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15014 } 15015 allUsers = sUserManager.getUserIds(); 15016 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15017 } 15018 15019 synchronized (mInstallLock) { 15020 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15021 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15022 "deletePackageX")) { 15023 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15024 deleteFlags | REMOVE_CHATTY, info, true, null); 15025 } 15026 synchronized (mPackages) { 15027 if (res) { 15028 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15029 } 15030 } 15031 } 15032 15033 if (res) { 15034 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15035 info.sendPackageRemovedBroadcasts(killApp); 15036 info.sendSystemPackageUpdatedBroadcasts(); 15037 info.sendSystemPackageAppearedBroadcasts(); 15038 } 15039 // Force a gc here. 15040 Runtime.getRuntime().gc(); 15041 // Delete the resources here after sending the broadcast to let 15042 // other processes clean up before deleting resources. 15043 if (info.args != null) { 15044 synchronized (mInstallLock) { 15045 info.args.doPostDeleteLI(true); 15046 } 15047 } 15048 15049 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15050 } 15051 15052 class PackageRemovedInfo { 15053 String removedPackage; 15054 int uid = -1; 15055 int removedAppId = -1; 15056 int[] origUsers; 15057 int[] removedUsers = null; 15058 boolean isRemovedPackageSystemUpdate = false; 15059 boolean isUpdate; 15060 boolean dataRemoved; 15061 boolean removedForAllUsers; 15062 // Clean up resources deleted packages. 15063 InstallArgs args = null; 15064 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15065 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15066 15067 void sendPackageRemovedBroadcasts(boolean killApp) { 15068 sendPackageRemovedBroadcastInternal(killApp); 15069 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15070 for (int i = 0; i < childCount; i++) { 15071 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15072 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15073 } 15074 } 15075 15076 void sendSystemPackageUpdatedBroadcasts() { 15077 if (isRemovedPackageSystemUpdate) { 15078 sendSystemPackageUpdatedBroadcastsInternal(); 15079 final int childCount = (removedChildPackages != null) 15080 ? removedChildPackages.size() : 0; 15081 for (int i = 0; i < childCount; i++) { 15082 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15083 if (childInfo.isRemovedPackageSystemUpdate) { 15084 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15085 } 15086 } 15087 } 15088 } 15089 15090 void sendSystemPackageAppearedBroadcasts() { 15091 final int packageCount = (appearedChildPackages != null) 15092 ? appearedChildPackages.size() : 0; 15093 for (int i = 0; i < packageCount; i++) { 15094 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15095 for (int userId : installedInfo.newUsers) { 15096 sendPackageAddedForUser(installedInfo.name, true, 15097 UserHandle.getAppId(installedInfo.uid), userId); 15098 } 15099 } 15100 } 15101 15102 private void sendSystemPackageUpdatedBroadcastsInternal() { 15103 Bundle extras = new Bundle(2); 15104 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15105 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15106 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15107 extras, 0, null, null, null); 15108 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15109 extras, 0, null, null, null); 15110 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15111 null, 0, removedPackage, null, null); 15112 } 15113 15114 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15115 Bundle extras = new Bundle(2); 15116 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15117 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15118 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15119 if (isUpdate || isRemovedPackageSystemUpdate) { 15120 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15121 } 15122 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15123 if (removedPackage != null) { 15124 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15125 extras, 0, null, null, removedUsers); 15126 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15127 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15128 removedPackage, extras, 0, null, null, removedUsers); 15129 } 15130 } 15131 if (removedAppId >= 0) { 15132 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15133 removedUsers); 15134 } 15135 } 15136 } 15137 15138 /* 15139 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15140 * flag is not set, the data directory is removed as well. 15141 * make sure this flag is set for partially installed apps. If not its meaningless to 15142 * delete a partially installed application. 15143 */ 15144 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15145 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15146 String packageName = ps.name; 15147 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15148 // Retrieve object to delete permissions for shared user later on 15149 final PackageParser.Package deletedPkg; 15150 final PackageSetting deletedPs; 15151 // reader 15152 synchronized (mPackages) { 15153 deletedPkg = mPackages.get(packageName); 15154 deletedPs = mSettings.mPackages.get(packageName); 15155 if (outInfo != null) { 15156 outInfo.removedPackage = packageName; 15157 outInfo.removedUsers = deletedPs != null 15158 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15159 : null; 15160 } 15161 } 15162 15163 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15164 15165 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15166 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15167 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15168 destroyAppProfilesLIF(deletedPkg); 15169 if (outInfo != null) { 15170 outInfo.dataRemoved = true; 15171 } 15172 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15173 } 15174 15175 // writer 15176 synchronized (mPackages) { 15177 if (deletedPs != null) { 15178 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15179 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15180 clearDefaultBrowserIfNeeded(packageName); 15181 if (outInfo != null) { 15182 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15183 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15184 } 15185 updatePermissionsLPw(deletedPs.name, null, 0); 15186 if (deletedPs.sharedUser != null) { 15187 // Remove permissions associated with package. Since runtime 15188 // permissions are per user we have to kill the removed package 15189 // or packages running under the shared user of the removed 15190 // package if revoking the permissions requested only by the removed 15191 // package is successful and this causes a change in gids. 15192 for (int userId : UserManagerService.getInstance().getUserIds()) { 15193 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15194 userId); 15195 if (userIdToKill == UserHandle.USER_ALL 15196 || userIdToKill >= UserHandle.USER_SYSTEM) { 15197 // If gids changed for this user, kill all affected packages. 15198 mHandler.post(new Runnable() { 15199 @Override 15200 public void run() { 15201 // This has to happen with no lock held. 15202 killApplication(deletedPs.name, deletedPs.appId, 15203 KILL_APP_REASON_GIDS_CHANGED); 15204 } 15205 }); 15206 break; 15207 } 15208 } 15209 } 15210 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15211 } 15212 // make sure to preserve per-user disabled state if this removal was just 15213 // a downgrade of a system app to the factory package 15214 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15215 if (DEBUG_REMOVE) { 15216 Slog.d(TAG, "Propagating install state across downgrade"); 15217 } 15218 for (int userId : allUserHandles) { 15219 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15220 if (DEBUG_REMOVE) { 15221 Slog.d(TAG, " user " + userId + " => " + installed); 15222 } 15223 ps.setInstalled(installed, userId); 15224 } 15225 } 15226 } 15227 // can downgrade to reader 15228 if (writeSettings) { 15229 // Save settings now 15230 mSettings.writeLPr(); 15231 } 15232 } 15233 if (outInfo != null) { 15234 // A user ID was deleted here. Go through all users and remove it 15235 // from KeyStore. 15236 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15237 } 15238 } 15239 15240 static boolean locationIsPrivileged(File path) { 15241 try { 15242 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15243 .getCanonicalPath(); 15244 return path.getCanonicalPath().startsWith(privilegedAppDir); 15245 } catch (IOException e) { 15246 Slog.e(TAG, "Unable to access code path " + path); 15247 } 15248 return false; 15249 } 15250 15251 /* 15252 * Tries to delete system package. 15253 */ 15254 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15255 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15256 boolean writeSettings) { 15257 if (deletedPs.parentPackageName != null) { 15258 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15259 return false; 15260 } 15261 15262 final boolean applyUserRestrictions 15263 = (allUserHandles != null) && (outInfo.origUsers != null); 15264 final PackageSetting disabledPs; 15265 // Confirm if the system package has been updated 15266 // An updated system app can be deleted. This will also have to restore 15267 // the system pkg from system partition 15268 // reader 15269 synchronized (mPackages) { 15270 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15271 } 15272 15273 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15274 + " disabledPs=" + disabledPs); 15275 15276 if (disabledPs == null) { 15277 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15278 return false; 15279 } else if (DEBUG_REMOVE) { 15280 Slog.d(TAG, "Deleting system pkg from data partition"); 15281 } 15282 15283 if (DEBUG_REMOVE) { 15284 if (applyUserRestrictions) { 15285 Slog.d(TAG, "Remembering install states:"); 15286 for (int userId : allUserHandles) { 15287 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15288 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15289 } 15290 } 15291 } 15292 15293 // Delete the updated package 15294 outInfo.isRemovedPackageSystemUpdate = true; 15295 if (outInfo.removedChildPackages != null) { 15296 final int childCount = (deletedPs.childPackageNames != null) 15297 ? deletedPs.childPackageNames.size() : 0; 15298 for (int i = 0; i < childCount; i++) { 15299 String childPackageName = deletedPs.childPackageNames.get(i); 15300 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15301 .contains(childPackageName)) { 15302 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15303 childPackageName); 15304 if (childInfo != null) { 15305 childInfo.isRemovedPackageSystemUpdate = true; 15306 } 15307 } 15308 } 15309 } 15310 15311 if (disabledPs.versionCode < deletedPs.versionCode) { 15312 // Delete data for downgrades 15313 flags &= ~PackageManager.DELETE_KEEP_DATA; 15314 } else { 15315 // Preserve data by setting flag 15316 flags |= PackageManager.DELETE_KEEP_DATA; 15317 } 15318 15319 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15320 outInfo, writeSettings, disabledPs.pkg); 15321 if (!ret) { 15322 return false; 15323 } 15324 15325 // writer 15326 synchronized (mPackages) { 15327 // Reinstate the old system package 15328 enableSystemPackageLPw(disabledPs.pkg); 15329 // Remove any native libraries from the upgraded package. 15330 removeNativeBinariesLI(deletedPs); 15331 } 15332 15333 // Install the system package 15334 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15335 int parseFlags = mDefParseFlags 15336 | PackageParser.PARSE_MUST_BE_APK 15337 | PackageParser.PARSE_IS_SYSTEM 15338 | PackageParser.PARSE_IS_SYSTEM_DIR; 15339 if (locationIsPrivileged(disabledPs.codePath)) { 15340 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15341 } 15342 15343 final PackageParser.Package newPkg; 15344 try { 15345 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15346 } catch (PackageManagerException e) { 15347 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15348 + e.getMessage()); 15349 return false; 15350 } 15351 15352 prepareAppDataAfterInstallLIF(newPkg); 15353 15354 // writer 15355 synchronized (mPackages) { 15356 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15357 15358 // Propagate the permissions state as we do not want to drop on the floor 15359 // runtime permissions. The update permissions method below will take 15360 // care of removing obsolete permissions and grant install permissions. 15361 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15362 updatePermissionsLPw(newPkg.packageName, newPkg, 15363 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15364 15365 if (applyUserRestrictions) { 15366 if (DEBUG_REMOVE) { 15367 Slog.d(TAG, "Propagating install state across reinstall"); 15368 } 15369 for (int userId : allUserHandles) { 15370 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15371 if (DEBUG_REMOVE) { 15372 Slog.d(TAG, " user " + userId + " => " + installed); 15373 } 15374 ps.setInstalled(installed, userId); 15375 15376 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15377 } 15378 // Regardless of writeSettings we need to ensure that this restriction 15379 // state propagation is persisted 15380 mSettings.writeAllUsersPackageRestrictionsLPr(); 15381 } 15382 // can downgrade to reader here 15383 if (writeSettings) { 15384 mSettings.writeLPr(); 15385 } 15386 } 15387 return true; 15388 } 15389 15390 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15391 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15392 PackageRemovedInfo outInfo, boolean writeSettings, 15393 PackageParser.Package replacingPackage) { 15394 synchronized (mPackages) { 15395 if (outInfo != null) { 15396 outInfo.uid = ps.appId; 15397 } 15398 15399 if (outInfo != null && outInfo.removedChildPackages != null) { 15400 final int childCount = (ps.childPackageNames != null) 15401 ? ps.childPackageNames.size() : 0; 15402 for (int i = 0; i < childCount; i++) { 15403 String childPackageName = ps.childPackageNames.get(i); 15404 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15405 if (childPs == null) { 15406 return false; 15407 } 15408 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15409 childPackageName); 15410 if (childInfo != null) { 15411 childInfo.uid = childPs.appId; 15412 } 15413 } 15414 } 15415 } 15416 15417 // Delete package data from internal structures and also remove data if flag is set 15418 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15419 15420 // Delete the child packages data 15421 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15422 for (int i = 0; i < childCount; i++) { 15423 PackageSetting childPs; 15424 synchronized (mPackages) { 15425 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15426 } 15427 if (childPs != null) { 15428 PackageRemovedInfo childOutInfo = (outInfo != null 15429 && outInfo.removedChildPackages != null) 15430 ? outInfo.removedChildPackages.get(childPs.name) : null; 15431 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15432 && (replacingPackage != null 15433 && !replacingPackage.hasChildPackage(childPs.name)) 15434 ? flags & ~DELETE_KEEP_DATA : flags; 15435 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15436 deleteFlags, writeSettings); 15437 } 15438 } 15439 15440 // Delete application code and resources only for parent packages 15441 if (ps.parentPackageName == null) { 15442 if (deleteCodeAndResources && (outInfo != null)) { 15443 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15444 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15445 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15446 } 15447 } 15448 15449 return true; 15450 } 15451 15452 @Override 15453 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15454 int userId) { 15455 mContext.enforceCallingOrSelfPermission( 15456 android.Manifest.permission.DELETE_PACKAGES, null); 15457 synchronized (mPackages) { 15458 PackageSetting ps = mSettings.mPackages.get(packageName); 15459 if (ps == null) { 15460 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15461 return false; 15462 } 15463 if (!ps.getInstalled(userId)) { 15464 // Can't block uninstall for an app that is not installed or enabled. 15465 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15466 return false; 15467 } 15468 ps.setBlockUninstall(blockUninstall, userId); 15469 mSettings.writePackageRestrictionsLPr(userId); 15470 } 15471 return true; 15472 } 15473 15474 @Override 15475 public boolean getBlockUninstallForUser(String packageName, int userId) { 15476 synchronized (mPackages) { 15477 PackageSetting ps = mSettings.mPackages.get(packageName); 15478 if (ps == null) { 15479 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15480 return false; 15481 } 15482 return ps.getBlockUninstall(userId); 15483 } 15484 } 15485 15486 @Override 15487 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15488 int callingUid = Binder.getCallingUid(); 15489 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15490 throw new SecurityException( 15491 "setRequiredForSystemUser can only be run by the system or root"); 15492 } 15493 synchronized (mPackages) { 15494 PackageSetting ps = mSettings.mPackages.get(packageName); 15495 if (ps == null) { 15496 Log.w(TAG, "Package doesn't exist: " + packageName); 15497 return false; 15498 } 15499 if (systemUserApp) { 15500 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15501 } else { 15502 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15503 } 15504 mSettings.writeLPr(); 15505 } 15506 return true; 15507 } 15508 15509 /* 15510 * This method handles package deletion in general 15511 */ 15512 private boolean deletePackageLIF(String packageName, UserHandle user, 15513 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15514 PackageRemovedInfo outInfo, boolean writeSettings, 15515 PackageParser.Package replacingPackage) { 15516 if (packageName == null) { 15517 Slog.w(TAG, "Attempt to delete null packageName."); 15518 return false; 15519 } 15520 15521 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15522 15523 PackageSetting ps; 15524 15525 synchronized (mPackages) { 15526 ps = mSettings.mPackages.get(packageName); 15527 if (ps == null) { 15528 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15529 return false; 15530 } 15531 15532 if (ps.parentPackageName != null && (!isSystemApp(ps) 15533 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15534 if (DEBUG_REMOVE) { 15535 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15536 + ((user == null) ? UserHandle.USER_ALL : user)); 15537 } 15538 final int removedUserId = (user != null) ? user.getIdentifier() 15539 : UserHandle.USER_ALL; 15540 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15541 return false; 15542 } 15543 markPackageUninstalledForUserLPw(ps, user); 15544 scheduleWritePackageRestrictionsLocked(user); 15545 return true; 15546 } 15547 } 15548 15549 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15550 && user.getIdentifier() != UserHandle.USER_ALL)) { 15551 // The caller is asking that the package only be deleted for a single 15552 // user. To do this, we just mark its uninstalled state and delete 15553 // its data. If this is a system app, we only allow this to happen if 15554 // they have set the special DELETE_SYSTEM_APP which requests different 15555 // semantics than normal for uninstalling system apps. 15556 markPackageUninstalledForUserLPw(ps, user); 15557 15558 if (!isSystemApp(ps)) { 15559 // Do not uninstall the APK if an app should be cached 15560 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15561 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15562 // Other user still have this package installed, so all 15563 // we need to do is clear this user's data and save that 15564 // it is uninstalled. 15565 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15566 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15567 return false; 15568 } 15569 scheduleWritePackageRestrictionsLocked(user); 15570 return true; 15571 } else { 15572 // We need to set it back to 'installed' so the uninstall 15573 // broadcasts will be sent correctly. 15574 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15575 ps.setInstalled(true, user.getIdentifier()); 15576 } 15577 } else { 15578 // This is a system app, so we assume that the 15579 // other users still have this package installed, so all 15580 // we need to do is clear this user's data and save that 15581 // it is uninstalled. 15582 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15583 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15584 return false; 15585 } 15586 scheduleWritePackageRestrictionsLocked(user); 15587 return true; 15588 } 15589 } 15590 15591 // If we are deleting a composite package for all users, keep track 15592 // of result for each child. 15593 if (ps.childPackageNames != null && outInfo != null) { 15594 synchronized (mPackages) { 15595 final int childCount = ps.childPackageNames.size(); 15596 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15597 for (int i = 0; i < childCount; i++) { 15598 String childPackageName = ps.childPackageNames.get(i); 15599 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15600 childInfo.removedPackage = childPackageName; 15601 outInfo.removedChildPackages.put(childPackageName, childInfo); 15602 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15603 if (childPs != null) { 15604 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15605 } 15606 } 15607 } 15608 } 15609 15610 boolean ret = false; 15611 if (isSystemApp(ps)) { 15612 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15613 // When an updated system application is deleted we delete the existing resources 15614 // as well and fall back to existing code in system partition 15615 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15616 } else { 15617 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15618 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15619 outInfo, writeSettings, replacingPackage); 15620 } 15621 15622 // Take a note whether we deleted the package for all users 15623 if (outInfo != null) { 15624 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15625 if (outInfo.removedChildPackages != null) { 15626 synchronized (mPackages) { 15627 final int childCount = outInfo.removedChildPackages.size(); 15628 for (int i = 0; i < childCount; i++) { 15629 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15630 if (childInfo != null) { 15631 childInfo.removedForAllUsers = mPackages.get( 15632 childInfo.removedPackage) == null; 15633 } 15634 } 15635 } 15636 } 15637 // If we uninstalled an update to a system app there may be some 15638 // child packages that appeared as they are declared in the system 15639 // app but were not declared in the update. 15640 if (isSystemApp(ps)) { 15641 synchronized (mPackages) { 15642 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15643 final int childCount = (updatedPs.childPackageNames != null) 15644 ? updatedPs.childPackageNames.size() : 0; 15645 for (int i = 0; i < childCount; i++) { 15646 String childPackageName = updatedPs.childPackageNames.get(i); 15647 if (outInfo.removedChildPackages == null 15648 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15649 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15650 if (childPs == null) { 15651 continue; 15652 } 15653 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15654 installRes.name = childPackageName; 15655 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15656 installRes.pkg = mPackages.get(childPackageName); 15657 installRes.uid = childPs.pkg.applicationInfo.uid; 15658 if (outInfo.appearedChildPackages == null) { 15659 outInfo.appearedChildPackages = new ArrayMap<>(); 15660 } 15661 outInfo.appearedChildPackages.put(childPackageName, installRes); 15662 } 15663 } 15664 } 15665 } 15666 } 15667 15668 return ret; 15669 } 15670 15671 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15672 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15673 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15674 for (int nextUserId : userIds) { 15675 if (DEBUG_REMOVE) { 15676 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15677 } 15678 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15679 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15680 false /*hidden*/, false /*suspended*/, null, null, null, 15681 false /*blockUninstall*/, 15682 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15683 } 15684 } 15685 15686 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15687 PackageRemovedInfo outInfo) { 15688 final PackageParser.Package pkg; 15689 synchronized (mPackages) { 15690 pkg = mPackages.get(ps.name); 15691 } 15692 15693 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15694 : new int[] {userId}; 15695 for (int nextUserId : userIds) { 15696 if (DEBUG_REMOVE) { 15697 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15698 + nextUserId); 15699 } 15700 15701 destroyAppDataLIF(pkg, userId, 15702 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15703 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15704 schedulePackageCleaning(ps.name, nextUserId, false); 15705 synchronized (mPackages) { 15706 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15707 scheduleWritePackageRestrictionsLocked(nextUserId); 15708 } 15709 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15710 } 15711 } 15712 15713 if (outInfo != null) { 15714 outInfo.removedPackage = ps.name; 15715 outInfo.removedAppId = ps.appId; 15716 outInfo.removedUsers = userIds; 15717 } 15718 15719 return true; 15720 } 15721 15722 private final class ClearStorageConnection implements ServiceConnection { 15723 IMediaContainerService mContainerService; 15724 15725 @Override 15726 public void onServiceConnected(ComponentName name, IBinder service) { 15727 synchronized (this) { 15728 mContainerService = IMediaContainerService.Stub.asInterface(service); 15729 notifyAll(); 15730 } 15731 } 15732 15733 @Override 15734 public void onServiceDisconnected(ComponentName name) { 15735 } 15736 } 15737 15738 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15739 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15740 15741 final boolean mounted; 15742 if (Environment.isExternalStorageEmulated()) { 15743 mounted = true; 15744 } else { 15745 final String status = Environment.getExternalStorageState(); 15746 15747 mounted = status.equals(Environment.MEDIA_MOUNTED) 15748 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15749 } 15750 15751 if (!mounted) { 15752 return; 15753 } 15754 15755 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15756 int[] users; 15757 if (userId == UserHandle.USER_ALL) { 15758 users = sUserManager.getUserIds(); 15759 } else { 15760 users = new int[] { userId }; 15761 } 15762 final ClearStorageConnection conn = new ClearStorageConnection(); 15763 if (mContext.bindServiceAsUser( 15764 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15765 try { 15766 for (int curUser : users) { 15767 long timeout = SystemClock.uptimeMillis() + 5000; 15768 synchronized (conn) { 15769 long now = SystemClock.uptimeMillis(); 15770 while (conn.mContainerService == null && now < timeout) { 15771 try { 15772 conn.wait(timeout - now); 15773 } catch (InterruptedException e) { 15774 } 15775 } 15776 } 15777 if (conn.mContainerService == null) { 15778 return; 15779 } 15780 15781 final UserEnvironment userEnv = new UserEnvironment(curUser); 15782 clearDirectory(conn.mContainerService, 15783 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15784 if (allData) { 15785 clearDirectory(conn.mContainerService, 15786 userEnv.buildExternalStorageAppDataDirs(packageName)); 15787 clearDirectory(conn.mContainerService, 15788 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15789 } 15790 } 15791 } finally { 15792 mContext.unbindService(conn); 15793 } 15794 } 15795 } 15796 15797 @Override 15798 public void clearApplicationProfileData(String packageName) { 15799 enforceSystemOrRoot("Only the system can clear all profile data"); 15800 15801 final PackageParser.Package pkg; 15802 synchronized (mPackages) { 15803 pkg = mPackages.get(packageName); 15804 } 15805 15806 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15807 synchronized (mInstallLock) { 15808 clearAppProfilesLIF(pkg); 15809 } 15810 } 15811 } 15812 15813 @Override 15814 public void clearApplicationUserData(final String packageName, 15815 final IPackageDataObserver observer, final int userId) { 15816 mContext.enforceCallingOrSelfPermission( 15817 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15818 15819 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15820 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15821 15822 final DevicePolicyManagerInternal dpmi = LocalServices 15823 .getService(DevicePolicyManagerInternal.class); 15824 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15825 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15826 } 15827 // Queue up an async operation since the package deletion may take a little while. 15828 mHandler.post(new Runnable() { 15829 public void run() { 15830 mHandler.removeCallbacks(this); 15831 final boolean succeeded; 15832 try (PackageFreezer freezer = freezePackage(packageName, 15833 "clearApplicationUserData")) { 15834 synchronized (mInstallLock) { 15835 succeeded = clearApplicationUserDataLIF(packageName, userId); 15836 } 15837 clearExternalStorageDataSync(packageName, userId, true); 15838 } 15839 if (succeeded) { 15840 // invoke DeviceStorageMonitor's update method to clear any notifications 15841 DeviceStorageMonitorInternal dsm = LocalServices 15842 .getService(DeviceStorageMonitorInternal.class); 15843 if (dsm != null) { 15844 dsm.checkMemory(); 15845 } 15846 } 15847 if(observer != null) { 15848 try { 15849 observer.onRemoveCompleted(packageName, succeeded); 15850 } catch (RemoteException e) { 15851 Log.i(TAG, "Observer no longer exists."); 15852 } 15853 } //end if observer 15854 } //end run 15855 }); 15856 } 15857 15858 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15859 if (packageName == null) { 15860 Slog.w(TAG, "Attempt to delete null packageName."); 15861 return false; 15862 } 15863 15864 // Try finding details about the requested package 15865 PackageParser.Package pkg; 15866 synchronized (mPackages) { 15867 pkg = mPackages.get(packageName); 15868 if (pkg == null) { 15869 final PackageSetting ps = mSettings.mPackages.get(packageName); 15870 if (ps != null) { 15871 pkg = ps.pkg; 15872 } 15873 } 15874 15875 if (pkg == null) { 15876 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15877 return false; 15878 } 15879 15880 PackageSetting ps = (PackageSetting) pkg.mExtras; 15881 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15882 } 15883 15884 clearAppDataLIF(pkg, userId, 15885 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15886 15887 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15888 removeKeystoreDataIfNeeded(userId, appId); 15889 15890 final UserManager um = mContext.getSystemService(UserManager.class); 15891 final int flags; 15892 if (um.isUserUnlocked(userId)) { 15893 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15894 } else if (um.isUserRunning(userId)) { 15895 flags = StorageManager.FLAG_STORAGE_DE; 15896 } else { 15897 flags = 0; 15898 } 15899 prepareAppDataContentsLIF(pkg, userId, flags); 15900 15901 return true; 15902 } 15903 15904 /** 15905 * Reverts user permission state changes (permissions and flags) in 15906 * all packages for a given user. 15907 * 15908 * @param userId The device user for which to do a reset. 15909 */ 15910 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15911 final int packageCount = mPackages.size(); 15912 for (int i = 0; i < packageCount; i++) { 15913 PackageParser.Package pkg = mPackages.valueAt(i); 15914 PackageSetting ps = (PackageSetting) pkg.mExtras; 15915 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15916 } 15917 } 15918 15919 /** 15920 * Reverts user permission state changes (permissions and flags). 15921 * 15922 * @param ps The package for which to reset. 15923 * @param userId The device user for which to do a reset. 15924 */ 15925 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15926 final PackageSetting ps, final int userId) { 15927 if (ps.pkg == null) { 15928 return; 15929 } 15930 15931 // These are flags that can change base on user actions. 15932 final int userSettableMask = FLAG_PERMISSION_USER_SET 15933 | FLAG_PERMISSION_USER_FIXED 15934 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15935 | FLAG_PERMISSION_REVIEW_REQUIRED; 15936 15937 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15938 | FLAG_PERMISSION_POLICY_FIXED; 15939 15940 boolean writeInstallPermissions = false; 15941 boolean writeRuntimePermissions = false; 15942 15943 final int permissionCount = ps.pkg.requestedPermissions.size(); 15944 for (int i = 0; i < permissionCount; i++) { 15945 String permission = ps.pkg.requestedPermissions.get(i); 15946 15947 BasePermission bp = mSettings.mPermissions.get(permission); 15948 if (bp == null) { 15949 continue; 15950 } 15951 15952 // If shared user we just reset the state to which only this app contributed. 15953 if (ps.sharedUser != null) { 15954 boolean used = false; 15955 final int packageCount = ps.sharedUser.packages.size(); 15956 for (int j = 0; j < packageCount; j++) { 15957 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15958 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15959 && pkg.pkg.requestedPermissions.contains(permission)) { 15960 used = true; 15961 break; 15962 } 15963 } 15964 if (used) { 15965 continue; 15966 } 15967 } 15968 15969 PermissionsState permissionsState = ps.getPermissionsState(); 15970 15971 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15972 15973 // Always clear the user settable flags. 15974 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15975 bp.name) != null; 15976 // If permission review is enabled and this is a legacy app, mark the 15977 // permission as requiring a review as this is the initial state. 15978 int flags = 0; 15979 if (Build.PERMISSIONS_REVIEW_REQUIRED 15980 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15981 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15982 } 15983 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15984 if (hasInstallState) { 15985 writeInstallPermissions = true; 15986 } else { 15987 writeRuntimePermissions = true; 15988 } 15989 } 15990 15991 // Below is only runtime permission handling. 15992 if (!bp.isRuntime()) { 15993 continue; 15994 } 15995 15996 // Never clobber system or policy. 15997 if ((oldFlags & policyOrSystemFlags) != 0) { 15998 continue; 15999 } 16000 16001 // If this permission was granted by default, make sure it is. 16002 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16003 if (permissionsState.grantRuntimePermission(bp, userId) 16004 != PERMISSION_OPERATION_FAILURE) { 16005 writeRuntimePermissions = true; 16006 } 16007 // If permission review is enabled the permissions for a legacy apps 16008 // are represented as constantly granted runtime ones, so don't revoke. 16009 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16010 // Otherwise, reset the permission. 16011 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16012 switch (revokeResult) { 16013 case PERMISSION_OPERATION_SUCCESS: 16014 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16015 writeRuntimePermissions = true; 16016 final int appId = ps.appId; 16017 mHandler.post(new Runnable() { 16018 @Override 16019 public void run() { 16020 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16021 } 16022 }); 16023 } break; 16024 } 16025 } 16026 } 16027 16028 // Synchronously write as we are taking permissions away. 16029 if (writeRuntimePermissions) { 16030 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16031 } 16032 16033 // Synchronously write as we are taking permissions away. 16034 if (writeInstallPermissions) { 16035 mSettings.writeLPr(); 16036 } 16037 } 16038 16039 /** 16040 * Remove entries from the keystore daemon. Will only remove it if the 16041 * {@code appId} is valid. 16042 */ 16043 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16044 if (appId < 0) { 16045 return; 16046 } 16047 16048 final KeyStore keyStore = KeyStore.getInstance(); 16049 if (keyStore != null) { 16050 if (userId == UserHandle.USER_ALL) { 16051 for (final int individual : sUserManager.getUserIds()) { 16052 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16053 } 16054 } else { 16055 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16056 } 16057 } else { 16058 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16059 } 16060 } 16061 16062 @Override 16063 public void deleteApplicationCacheFiles(final String packageName, 16064 final IPackageDataObserver observer) { 16065 final int userId = UserHandle.getCallingUserId(); 16066 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16067 } 16068 16069 @Override 16070 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16071 final IPackageDataObserver observer) { 16072 mContext.enforceCallingOrSelfPermission( 16073 android.Manifest.permission.DELETE_CACHE_FILES, null); 16074 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16075 /* requireFullPermission= */ true, /* checkShell= */ false, 16076 "delete application cache files"); 16077 16078 final PackageParser.Package pkg; 16079 synchronized (mPackages) { 16080 pkg = mPackages.get(packageName); 16081 } 16082 16083 // Queue up an async operation since the package deletion may take a little while. 16084 mHandler.post(new Runnable() { 16085 public void run() { 16086 synchronized (mInstallLock) { 16087 final int flags = StorageManager.FLAG_STORAGE_DE 16088 | StorageManager.FLAG_STORAGE_CE; 16089 // We're only clearing cache files, so we don't care if the 16090 // app is unfrozen and still able to run 16091 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16092 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16093 } 16094 clearExternalStorageDataSync(packageName, userId, false); 16095 if (observer != null) { 16096 try { 16097 observer.onRemoveCompleted(packageName, true); 16098 } catch (RemoteException e) { 16099 Log.i(TAG, "Observer no longer exists."); 16100 } 16101 } 16102 } 16103 }); 16104 } 16105 16106 @Override 16107 public void getPackageSizeInfo(final String packageName, int userHandle, 16108 final IPackageStatsObserver observer) { 16109 mContext.enforceCallingOrSelfPermission( 16110 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16111 if (packageName == null) { 16112 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16113 } 16114 16115 PackageStats stats = new PackageStats(packageName, userHandle); 16116 16117 /* 16118 * Queue up an async operation since the package measurement may take a 16119 * little while. 16120 */ 16121 Message msg = mHandler.obtainMessage(INIT_COPY); 16122 msg.obj = new MeasureParams(stats, observer); 16123 mHandler.sendMessage(msg); 16124 } 16125 16126 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16127 final PackageSetting ps; 16128 synchronized (mPackages) { 16129 ps = mSettings.mPackages.get(packageName); 16130 if (ps == null) { 16131 Slog.w(TAG, "Failed to find settings for " + packageName); 16132 return false; 16133 } 16134 } 16135 try { 16136 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16137 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16138 ps.getCeDataInode(userId), ps.codePathString, stats); 16139 } catch (InstallerException e) { 16140 Slog.w(TAG, String.valueOf(e)); 16141 return false; 16142 } 16143 16144 // For now, ignore code size of packages on system partition 16145 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16146 stats.codeSize = 0; 16147 } 16148 16149 return true; 16150 } 16151 16152 private int getUidTargetSdkVersionLockedLPr(int uid) { 16153 Object obj = mSettings.getUserIdLPr(uid); 16154 if (obj instanceof SharedUserSetting) { 16155 final SharedUserSetting sus = (SharedUserSetting) obj; 16156 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16157 final Iterator<PackageSetting> it = sus.packages.iterator(); 16158 while (it.hasNext()) { 16159 final PackageSetting ps = it.next(); 16160 if (ps.pkg != null) { 16161 int v = ps.pkg.applicationInfo.targetSdkVersion; 16162 if (v < vers) vers = v; 16163 } 16164 } 16165 return vers; 16166 } else if (obj instanceof PackageSetting) { 16167 final PackageSetting ps = (PackageSetting) obj; 16168 if (ps.pkg != null) { 16169 return ps.pkg.applicationInfo.targetSdkVersion; 16170 } 16171 } 16172 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16173 } 16174 16175 @Override 16176 public void addPreferredActivity(IntentFilter filter, int match, 16177 ComponentName[] set, ComponentName activity, int userId) { 16178 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16179 "Adding preferred"); 16180 } 16181 16182 private void addPreferredActivityInternal(IntentFilter filter, int match, 16183 ComponentName[] set, ComponentName activity, boolean always, int userId, 16184 String opname) { 16185 // writer 16186 int callingUid = Binder.getCallingUid(); 16187 enforceCrossUserPermission(callingUid, userId, 16188 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16189 if (filter.countActions() == 0) { 16190 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16191 return; 16192 } 16193 synchronized (mPackages) { 16194 if (mContext.checkCallingOrSelfPermission( 16195 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16196 != PackageManager.PERMISSION_GRANTED) { 16197 if (getUidTargetSdkVersionLockedLPr(callingUid) 16198 < Build.VERSION_CODES.FROYO) { 16199 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16200 + callingUid); 16201 return; 16202 } 16203 mContext.enforceCallingOrSelfPermission( 16204 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16205 } 16206 16207 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16208 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16209 + userId + ":"); 16210 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16211 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16212 scheduleWritePackageRestrictionsLocked(userId); 16213 } 16214 } 16215 16216 @Override 16217 public void replacePreferredActivity(IntentFilter filter, int match, 16218 ComponentName[] set, ComponentName activity, int userId) { 16219 if (filter.countActions() != 1) { 16220 throw new IllegalArgumentException( 16221 "replacePreferredActivity expects filter to have only 1 action."); 16222 } 16223 if (filter.countDataAuthorities() != 0 16224 || filter.countDataPaths() != 0 16225 || filter.countDataSchemes() > 1 16226 || filter.countDataTypes() != 0) { 16227 throw new IllegalArgumentException( 16228 "replacePreferredActivity expects filter to have no data authorities, " + 16229 "paths, or types; and at most one scheme."); 16230 } 16231 16232 final int callingUid = Binder.getCallingUid(); 16233 enforceCrossUserPermission(callingUid, userId, 16234 true /* requireFullPermission */, false /* checkShell */, 16235 "replace preferred activity"); 16236 synchronized (mPackages) { 16237 if (mContext.checkCallingOrSelfPermission( 16238 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16239 != PackageManager.PERMISSION_GRANTED) { 16240 if (getUidTargetSdkVersionLockedLPr(callingUid) 16241 < Build.VERSION_CODES.FROYO) { 16242 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16243 + Binder.getCallingUid()); 16244 return; 16245 } 16246 mContext.enforceCallingOrSelfPermission( 16247 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16248 } 16249 16250 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16251 if (pir != null) { 16252 // Get all of the existing entries that exactly match this filter. 16253 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16254 if (existing != null && existing.size() == 1) { 16255 PreferredActivity cur = existing.get(0); 16256 if (DEBUG_PREFERRED) { 16257 Slog.i(TAG, "Checking replace of preferred:"); 16258 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16259 if (!cur.mPref.mAlways) { 16260 Slog.i(TAG, " -- CUR; not mAlways!"); 16261 } else { 16262 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16263 Slog.i(TAG, " -- CUR: mSet=" 16264 + Arrays.toString(cur.mPref.mSetComponents)); 16265 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16266 Slog.i(TAG, " -- NEW: mMatch=" 16267 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16268 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16269 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16270 } 16271 } 16272 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16273 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16274 && cur.mPref.sameSet(set)) { 16275 // Setting the preferred activity to what it happens to be already 16276 if (DEBUG_PREFERRED) { 16277 Slog.i(TAG, "Replacing with same preferred activity " 16278 + cur.mPref.mShortComponent + " for user " 16279 + userId + ":"); 16280 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16281 } 16282 return; 16283 } 16284 } 16285 16286 if (existing != null) { 16287 if (DEBUG_PREFERRED) { 16288 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16289 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16290 } 16291 for (int i = 0; i < existing.size(); i++) { 16292 PreferredActivity pa = existing.get(i); 16293 if (DEBUG_PREFERRED) { 16294 Slog.i(TAG, "Removing existing preferred activity " 16295 + pa.mPref.mComponent + ":"); 16296 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16297 } 16298 pir.removeFilter(pa); 16299 } 16300 } 16301 } 16302 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16303 "Replacing preferred"); 16304 } 16305 } 16306 16307 @Override 16308 public void clearPackagePreferredActivities(String packageName) { 16309 final int uid = Binder.getCallingUid(); 16310 // writer 16311 synchronized (mPackages) { 16312 PackageParser.Package pkg = mPackages.get(packageName); 16313 if (pkg == null || pkg.applicationInfo.uid != uid) { 16314 if (mContext.checkCallingOrSelfPermission( 16315 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16316 != PackageManager.PERMISSION_GRANTED) { 16317 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16318 < Build.VERSION_CODES.FROYO) { 16319 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16320 + Binder.getCallingUid()); 16321 return; 16322 } 16323 mContext.enforceCallingOrSelfPermission( 16324 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16325 } 16326 } 16327 16328 int user = UserHandle.getCallingUserId(); 16329 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16330 scheduleWritePackageRestrictionsLocked(user); 16331 } 16332 } 16333 } 16334 16335 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16336 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16337 ArrayList<PreferredActivity> removed = null; 16338 boolean changed = false; 16339 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16340 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16341 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16342 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16343 continue; 16344 } 16345 Iterator<PreferredActivity> it = pir.filterIterator(); 16346 while (it.hasNext()) { 16347 PreferredActivity pa = it.next(); 16348 // Mark entry for removal only if it matches the package name 16349 // and the entry is of type "always". 16350 if (packageName == null || 16351 (pa.mPref.mComponent.getPackageName().equals(packageName) 16352 && pa.mPref.mAlways)) { 16353 if (removed == null) { 16354 removed = new ArrayList<PreferredActivity>(); 16355 } 16356 removed.add(pa); 16357 } 16358 } 16359 if (removed != null) { 16360 for (int j=0; j<removed.size(); j++) { 16361 PreferredActivity pa = removed.get(j); 16362 pir.removeFilter(pa); 16363 } 16364 changed = true; 16365 } 16366 } 16367 return changed; 16368 } 16369 16370 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16371 private void clearIntentFilterVerificationsLPw(int userId) { 16372 final int packageCount = mPackages.size(); 16373 for (int i = 0; i < packageCount; i++) { 16374 PackageParser.Package pkg = mPackages.valueAt(i); 16375 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16376 } 16377 } 16378 16379 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16380 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16381 if (userId == UserHandle.USER_ALL) { 16382 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16383 sUserManager.getUserIds())) { 16384 for (int oneUserId : sUserManager.getUserIds()) { 16385 scheduleWritePackageRestrictionsLocked(oneUserId); 16386 } 16387 } 16388 } else { 16389 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16390 scheduleWritePackageRestrictionsLocked(userId); 16391 } 16392 } 16393 } 16394 16395 void clearDefaultBrowserIfNeeded(String packageName) { 16396 for (int oneUserId : sUserManager.getUserIds()) { 16397 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16398 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16399 if (packageName.equals(defaultBrowserPackageName)) { 16400 setDefaultBrowserPackageName(null, oneUserId); 16401 } 16402 } 16403 } 16404 16405 @Override 16406 public void resetApplicationPreferences(int userId) { 16407 mContext.enforceCallingOrSelfPermission( 16408 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16409 // writer 16410 synchronized (mPackages) { 16411 final long identity = Binder.clearCallingIdentity(); 16412 try { 16413 clearPackagePreferredActivitiesLPw(null, userId); 16414 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16415 // TODO: We have to reset the default SMS and Phone. This requires 16416 // significant refactoring to keep all default apps in the package 16417 // manager (cleaner but more work) or have the services provide 16418 // callbacks to the package manager to request a default app reset. 16419 applyFactoryDefaultBrowserLPw(userId); 16420 clearIntentFilterVerificationsLPw(userId); 16421 primeDomainVerificationsLPw(userId); 16422 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16423 scheduleWritePackageRestrictionsLocked(userId); 16424 } finally { 16425 Binder.restoreCallingIdentity(identity); 16426 } 16427 } 16428 } 16429 16430 @Override 16431 public int getPreferredActivities(List<IntentFilter> outFilters, 16432 List<ComponentName> outActivities, String packageName) { 16433 16434 int num = 0; 16435 final int userId = UserHandle.getCallingUserId(); 16436 // reader 16437 synchronized (mPackages) { 16438 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16439 if (pir != null) { 16440 final Iterator<PreferredActivity> it = pir.filterIterator(); 16441 while (it.hasNext()) { 16442 final PreferredActivity pa = it.next(); 16443 if (packageName == null 16444 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16445 && pa.mPref.mAlways)) { 16446 if (outFilters != null) { 16447 outFilters.add(new IntentFilter(pa)); 16448 } 16449 if (outActivities != null) { 16450 outActivities.add(pa.mPref.mComponent); 16451 } 16452 } 16453 } 16454 } 16455 } 16456 16457 return num; 16458 } 16459 16460 @Override 16461 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16462 int userId) { 16463 int callingUid = Binder.getCallingUid(); 16464 if (callingUid != Process.SYSTEM_UID) { 16465 throw new SecurityException( 16466 "addPersistentPreferredActivity can only be run by the system"); 16467 } 16468 if (filter.countActions() == 0) { 16469 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16470 return; 16471 } 16472 synchronized (mPackages) { 16473 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16474 ":"); 16475 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16476 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16477 new PersistentPreferredActivity(filter, activity)); 16478 scheduleWritePackageRestrictionsLocked(userId); 16479 } 16480 } 16481 16482 @Override 16483 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16484 int callingUid = Binder.getCallingUid(); 16485 if (callingUid != Process.SYSTEM_UID) { 16486 throw new SecurityException( 16487 "clearPackagePersistentPreferredActivities can only be run by the system"); 16488 } 16489 ArrayList<PersistentPreferredActivity> removed = null; 16490 boolean changed = false; 16491 synchronized (mPackages) { 16492 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16493 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16494 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16495 .valueAt(i); 16496 if (userId != thisUserId) { 16497 continue; 16498 } 16499 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16500 while (it.hasNext()) { 16501 PersistentPreferredActivity ppa = it.next(); 16502 // Mark entry for removal only if it matches the package name. 16503 if (ppa.mComponent.getPackageName().equals(packageName)) { 16504 if (removed == null) { 16505 removed = new ArrayList<PersistentPreferredActivity>(); 16506 } 16507 removed.add(ppa); 16508 } 16509 } 16510 if (removed != null) { 16511 for (int j=0; j<removed.size(); j++) { 16512 PersistentPreferredActivity ppa = removed.get(j); 16513 ppir.removeFilter(ppa); 16514 } 16515 changed = true; 16516 } 16517 } 16518 16519 if (changed) { 16520 scheduleWritePackageRestrictionsLocked(userId); 16521 } 16522 } 16523 } 16524 16525 /** 16526 * Common machinery for picking apart a restored XML blob and passing 16527 * it to a caller-supplied functor to be applied to the running system. 16528 */ 16529 private void restoreFromXml(XmlPullParser parser, int userId, 16530 String expectedStartTag, BlobXmlRestorer functor) 16531 throws IOException, XmlPullParserException { 16532 int type; 16533 while ((type = parser.next()) != XmlPullParser.START_TAG 16534 && type != XmlPullParser.END_DOCUMENT) { 16535 } 16536 if (type != XmlPullParser.START_TAG) { 16537 // oops didn't find a start tag?! 16538 if (DEBUG_BACKUP) { 16539 Slog.e(TAG, "Didn't find start tag during restore"); 16540 } 16541 return; 16542 } 16543Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16544 // this is supposed to be TAG_PREFERRED_BACKUP 16545 if (!expectedStartTag.equals(parser.getName())) { 16546 if (DEBUG_BACKUP) { 16547 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16548 } 16549 return; 16550 } 16551 16552 // skip interfering stuff, then we're aligned with the backing implementation 16553 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16554Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16555 functor.apply(parser, userId); 16556 } 16557 16558 private interface BlobXmlRestorer { 16559 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16560 } 16561 16562 /** 16563 * Non-Binder method, support for the backup/restore mechanism: write the 16564 * full set of preferred activities in its canonical XML format. Returns the 16565 * XML output as a byte array, or null if there is none. 16566 */ 16567 @Override 16568 public byte[] getPreferredActivityBackup(int userId) { 16569 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16570 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16571 } 16572 16573 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16574 try { 16575 final XmlSerializer serializer = new FastXmlSerializer(); 16576 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16577 serializer.startDocument(null, true); 16578 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16579 16580 synchronized (mPackages) { 16581 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16582 } 16583 16584 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16585 serializer.endDocument(); 16586 serializer.flush(); 16587 } catch (Exception e) { 16588 if (DEBUG_BACKUP) { 16589 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16590 } 16591 return null; 16592 } 16593 16594 return dataStream.toByteArray(); 16595 } 16596 16597 @Override 16598 public void restorePreferredActivities(byte[] backup, int userId) { 16599 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16600 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16601 } 16602 16603 try { 16604 final XmlPullParser parser = Xml.newPullParser(); 16605 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16606 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16607 new BlobXmlRestorer() { 16608 @Override 16609 public void apply(XmlPullParser parser, int userId) 16610 throws XmlPullParserException, IOException { 16611 synchronized (mPackages) { 16612 mSettings.readPreferredActivitiesLPw(parser, userId); 16613 } 16614 } 16615 } ); 16616 } catch (Exception e) { 16617 if (DEBUG_BACKUP) { 16618 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16619 } 16620 } 16621 } 16622 16623 /** 16624 * Non-Binder method, support for the backup/restore mechanism: write the 16625 * default browser (etc) settings in its canonical XML format. Returns the default 16626 * browser XML representation as a byte array, or null if there is none. 16627 */ 16628 @Override 16629 public byte[] getDefaultAppsBackup(int userId) { 16630 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16631 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16632 } 16633 16634 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16635 try { 16636 final XmlSerializer serializer = new FastXmlSerializer(); 16637 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16638 serializer.startDocument(null, true); 16639 serializer.startTag(null, TAG_DEFAULT_APPS); 16640 16641 synchronized (mPackages) { 16642 mSettings.writeDefaultAppsLPr(serializer, userId); 16643 } 16644 16645 serializer.endTag(null, TAG_DEFAULT_APPS); 16646 serializer.endDocument(); 16647 serializer.flush(); 16648 } catch (Exception e) { 16649 if (DEBUG_BACKUP) { 16650 Slog.e(TAG, "Unable to write default apps for backup", e); 16651 } 16652 return null; 16653 } 16654 16655 return dataStream.toByteArray(); 16656 } 16657 16658 @Override 16659 public void restoreDefaultApps(byte[] backup, int userId) { 16660 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16661 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16662 } 16663 16664 try { 16665 final XmlPullParser parser = Xml.newPullParser(); 16666 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16667 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16668 new BlobXmlRestorer() { 16669 @Override 16670 public void apply(XmlPullParser parser, int userId) 16671 throws XmlPullParserException, IOException { 16672 synchronized (mPackages) { 16673 mSettings.readDefaultAppsLPw(parser, userId); 16674 } 16675 } 16676 } ); 16677 } catch (Exception e) { 16678 if (DEBUG_BACKUP) { 16679 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16680 } 16681 } 16682 } 16683 16684 @Override 16685 public byte[] getIntentFilterVerificationBackup(int userId) { 16686 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16687 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16688 } 16689 16690 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16691 try { 16692 final XmlSerializer serializer = new FastXmlSerializer(); 16693 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16694 serializer.startDocument(null, true); 16695 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16696 16697 synchronized (mPackages) { 16698 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16699 } 16700 16701 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16702 serializer.endDocument(); 16703 serializer.flush(); 16704 } catch (Exception e) { 16705 if (DEBUG_BACKUP) { 16706 Slog.e(TAG, "Unable to write default apps for backup", e); 16707 } 16708 return null; 16709 } 16710 16711 return dataStream.toByteArray(); 16712 } 16713 16714 @Override 16715 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16716 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16717 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16718 } 16719 16720 try { 16721 final XmlPullParser parser = Xml.newPullParser(); 16722 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16723 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16724 new BlobXmlRestorer() { 16725 @Override 16726 public void apply(XmlPullParser parser, int userId) 16727 throws XmlPullParserException, IOException { 16728 synchronized (mPackages) { 16729 mSettings.readAllDomainVerificationsLPr(parser, userId); 16730 mSettings.writeLPr(); 16731 } 16732 } 16733 } ); 16734 } catch (Exception e) { 16735 if (DEBUG_BACKUP) { 16736 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16737 } 16738 } 16739 } 16740 16741 @Override 16742 public byte[] getPermissionGrantBackup(int userId) { 16743 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16744 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16745 } 16746 16747 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16748 try { 16749 final XmlSerializer serializer = new FastXmlSerializer(); 16750 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16751 serializer.startDocument(null, true); 16752 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16753 16754 synchronized (mPackages) { 16755 serializeRuntimePermissionGrantsLPr(serializer, userId); 16756 } 16757 16758 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16759 serializer.endDocument(); 16760 serializer.flush(); 16761 } catch (Exception e) { 16762 if (DEBUG_BACKUP) { 16763 Slog.e(TAG, "Unable to write default apps for backup", e); 16764 } 16765 return null; 16766 } 16767 16768 return dataStream.toByteArray(); 16769 } 16770 16771 @Override 16772 public void restorePermissionGrants(byte[] backup, int userId) { 16773 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16774 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16775 } 16776 16777 try { 16778 final XmlPullParser parser = Xml.newPullParser(); 16779 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16780 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16781 new BlobXmlRestorer() { 16782 @Override 16783 public void apply(XmlPullParser parser, int userId) 16784 throws XmlPullParserException, IOException { 16785 synchronized (mPackages) { 16786 processRestoredPermissionGrantsLPr(parser, userId); 16787 } 16788 } 16789 } ); 16790 } catch (Exception e) { 16791 if (DEBUG_BACKUP) { 16792 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16793 } 16794 } 16795 } 16796 16797 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16798 throws IOException { 16799 serializer.startTag(null, TAG_ALL_GRANTS); 16800 16801 final int N = mSettings.mPackages.size(); 16802 for (int i = 0; i < N; i++) { 16803 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16804 boolean pkgGrantsKnown = false; 16805 16806 PermissionsState packagePerms = ps.getPermissionsState(); 16807 16808 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16809 final int grantFlags = state.getFlags(); 16810 // only look at grants that are not system/policy fixed 16811 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16812 final boolean isGranted = state.isGranted(); 16813 // And only back up the user-twiddled state bits 16814 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16815 final String packageName = mSettings.mPackages.keyAt(i); 16816 if (!pkgGrantsKnown) { 16817 serializer.startTag(null, TAG_GRANT); 16818 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16819 pkgGrantsKnown = true; 16820 } 16821 16822 final boolean userSet = 16823 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16824 final boolean userFixed = 16825 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16826 final boolean revoke = 16827 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16828 16829 serializer.startTag(null, TAG_PERMISSION); 16830 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16831 if (isGranted) { 16832 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16833 } 16834 if (userSet) { 16835 serializer.attribute(null, ATTR_USER_SET, "true"); 16836 } 16837 if (userFixed) { 16838 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16839 } 16840 if (revoke) { 16841 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16842 } 16843 serializer.endTag(null, TAG_PERMISSION); 16844 } 16845 } 16846 } 16847 16848 if (pkgGrantsKnown) { 16849 serializer.endTag(null, TAG_GRANT); 16850 } 16851 } 16852 16853 serializer.endTag(null, TAG_ALL_GRANTS); 16854 } 16855 16856 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16857 throws XmlPullParserException, IOException { 16858 String pkgName = null; 16859 int outerDepth = parser.getDepth(); 16860 int type; 16861 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16862 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16863 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16864 continue; 16865 } 16866 16867 final String tagName = parser.getName(); 16868 if (tagName.equals(TAG_GRANT)) { 16869 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16870 if (DEBUG_BACKUP) { 16871 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16872 } 16873 } else if (tagName.equals(TAG_PERMISSION)) { 16874 16875 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16876 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16877 16878 int newFlagSet = 0; 16879 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16880 newFlagSet |= FLAG_PERMISSION_USER_SET; 16881 } 16882 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16883 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16884 } 16885 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16886 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16887 } 16888 if (DEBUG_BACKUP) { 16889 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16890 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16891 } 16892 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16893 if (ps != null) { 16894 // Already installed so we apply the grant immediately 16895 if (DEBUG_BACKUP) { 16896 Slog.v(TAG, " + already installed; applying"); 16897 } 16898 PermissionsState perms = ps.getPermissionsState(); 16899 BasePermission bp = mSettings.mPermissions.get(permName); 16900 if (bp != null) { 16901 if (isGranted) { 16902 perms.grantRuntimePermission(bp, userId); 16903 } 16904 if (newFlagSet != 0) { 16905 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16906 } 16907 } 16908 } else { 16909 // Need to wait for post-restore install to apply the grant 16910 if (DEBUG_BACKUP) { 16911 Slog.v(TAG, " - not yet installed; saving for later"); 16912 } 16913 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16914 isGranted, newFlagSet, userId); 16915 } 16916 } else { 16917 PackageManagerService.reportSettingsProblem(Log.WARN, 16918 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16919 XmlUtils.skipCurrentTag(parser); 16920 } 16921 } 16922 16923 scheduleWriteSettingsLocked(); 16924 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16925 } 16926 16927 @Override 16928 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16929 int sourceUserId, int targetUserId, int flags) { 16930 mContext.enforceCallingOrSelfPermission( 16931 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16932 int callingUid = Binder.getCallingUid(); 16933 enforceOwnerRights(ownerPackage, callingUid); 16934 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16935 if (intentFilter.countActions() == 0) { 16936 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16937 return; 16938 } 16939 synchronized (mPackages) { 16940 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16941 ownerPackage, targetUserId, flags); 16942 CrossProfileIntentResolver resolver = 16943 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16944 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16945 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16946 if (existing != null) { 16947 int size = existing.size(); 16948 for (int i = 0; i < size; i++) { 16949 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16950 return; 16951 } 16952 } 16953 } 16954 resolver.addFilter(newFilter); 16955 scheduleWritePackageRestrictionsLocked(sourceUserId); 16956 } 16957 } 16958 16959 @Override 16960 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16961 mContext.enforceCallingOrSelfPermission( 16962 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16963 int callingUid = Binder.getCallingUid(); 16964 enforceOwnerRights(ownerPackage, callingUid); 16965 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16966 synchronized (mPackages) { 16967 CrossProfileIntentResolver resolver = 16968 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16969 ArraySet<CrossProfileIntentFilter> set = 16970 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16971 for (CrossProfileIntentFilter filter : set) { 16972 if (filter.getOwnerPackage().equals(ownerPackage)) { 16973 resolver.removeFilter(filter); 16974 } 16975 } 16976 scheduleWritePackageRestrictionsLocked(sourceUserId); 16977 } 16978 } 16979 16980 // Enforcing that callingUid is owning pkg on userId 16981 private void enforceOwnerRights(String pkg, int callingUid) { 16982 // The system owns everything. 16983 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16984 return; 16985 } 16986 int callingUserId = UserHandle.getUserId(callingUid); 16987 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16988 if (pi == null) { 16989 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16990 + callingUserId); 16991 } 16992 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16993 throw new SecurityException("Calling uid " + callingUid 16994 + " does not own package " + pkg); 16995 } 16996 } 16997 16998 @Override 16999 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17000 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17001 } 17002 17003 private Intent getHomeIntent() { 17004 Intent intent = new Intent(Intent.ACTION_MAIN); 17005 intent.addCategory(Intent.CATEGORY_HOME); 17006 return intent; 17007 } 17008 17009 private IntentFilter getHomeFilter() { 17010 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17011 filter.addCategory(Intent.CATEGORY_HOME); 17012 filter.addCategory(Intent.CATEGORY_DEFAULT); 17013 return filter; 17014 } 17015 17016 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17017 int userId) { 17018 Intent intent = getHomeIntent(); 17019 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17020 PackageManager.GET_META_DATA, userId); 17021 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17022 true, false, false, userId); 17023 17024 allHomeCandidates.clear(); 17025 if (list != null) { 17026 for (ResolveInfo ri : list) { 17027 allHomeCandidates.add(ri); 17028 } 17029 } 17030 return (preferred == null || preferred.activityInfo == null) 17031 ? null 17032 : new ComponentName(preferred.activityInfo.packageName, 17033 preferred.activityInfo.name); 17034 } 17035 17036 @Override 17037 public void setHomeActivity(ComponentName comp, int userId) { 17038 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17039 getHomeActivitiesAsUser(homeActivities, userId); 17040 17041 boolean found = false; 17042 17043 final int size = homeActivities.size(); 17044 final ComponentName[] set = new ComponentName[size]; 17045 for (int i = 0; i < size; i++) { 17046 final ResolveInfo candidate = homeActivities.get(i); 17047 final ActivityInfo info = candidate.activityInfo; 17048 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17049 set[i] = activityName; 17050 if (!found && activityName.equals(comp)) { 17051 found = true; 17052 } 17053 } 17054 if (!found) { 17055 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17056 + userId); 17057 } 17058 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17059 set, comp, userId); 17060 } 17061 17062 private @Nullable String getSetupWizardPackageName() { 17063 final Intent intent = new Intent(Intent.ACTION_MAIN); 17064 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17065 17066 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17067 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17068 | MATCH_DISABLED_COMPONENTS, 17069 UserHandle.myUserId()); 17070 if (matches.size() == 1) { 17071 return matches.get(0).getComponentInfo().packageName; 17072 } else { 17073 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17074 + ": matches=" + matches); 17075 return null; 17076 } 17077 } 17078 17079 @Override 17080 public void setApplicationEnabledSetting(String appPackageName, 17081 int newState, int flags, int userId, String callingPackage) { 17082 if (!sUserManager.exists(userId)) return; 17083 if (callingPackage == null) { 17084 callingPackage = Integer.toString(Binder.getCallingUid()); 17085 } 17086 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17087 } 17088 17089 @Override 17090 public void setComponentEnabledSetting(ComponentName componentName, 17091 int newState, int flags, int userId) { 17092 if (!sUserManager.exists(userId)) return; 17093 setEnabledSetting(componentName.getPackageName(), 17094 componentName.getClassName(), newState, flags, userId, null); 17095 } 17096 17097 private void setEnabledSetting(final String packageName, String className, int newState, 17098 final int flags, int userId, String callingPackage) { 17099 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17100 || newState == COMPONENT_ENABLED_STATE_ENABLED 17101 || newState == COMPONENT_ENABLED_STATE_DISABLED 17102 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17103 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17104 throw new IllegalArgumentException("Invalid new component state: " 17105 + newState); 17106 } 17107 PackageSetting pkgSetting; 17108 final int uid = Binder.getCallingUid(); 17109 final int permission; 17110 if (uid == Process.SYSTEM_UID) { 17111 permission = PackageManager.PERMISSION_GRANTED; 17112 } else { 17113 permission = mContext.checkCallingOrSelfPermission( 17114 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17115 } 17116 enforceCrossUserPermission(uid, userId, 17117 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17118 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17119 boolean sendNow = false; 17120 boolean isApp = (className == null); 17121 String componentName = isApp ? packageName : className; 17122 int packageUid = -1; 17123 ArrayList<String> components; 17124 17125 // writer 17126 synchronized (mPackages) { 17127 pkgSetting = mSettings.mPackages.get(packageName); 17128 if (pkgSetting == null) { 17129 if (className == null) { 17130 throw new IllegalArgumentException("Unknown package: " + packageName); 17131 } 17132 throw new IllegalArgumentException( 17133 "Unknown component: " + packageName + "/" + className); 17134 } 17135 // Allow root and verify that userId is not being specified by a different user 17136 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17137 throw new SecurityException( 17138 "Permission Denial: attempt to change component state from pid=" 17139 + Binder.getCallingPid() 17140 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17141 } 17142 if (className == null) { 17143 // We're dealing with an application/package level state change 17144 if (pkgSetting.getEnabled(userId) == newState) { 17145 // Nothing to do 17146 return; 17147 } 17148 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17149 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17150 // Don't care about who enables an app. 17151 callingPackage = null; 17152 } 17153 pkgSetting.setEnabled(newState, userId, callingPackage); 17154 // pkgSetting.pkg.mSetEnabled = newState; 17155 } else { 17156 // We're dealing with a component level state change 17157 // First, verify that this is a valid class name. 17158 PackageParser.Package pkg = pkgSetting.pkg; 17159 if (pkg == null || !pkg.hasComponentClassName(className)) { 17160 if (pkg != null && 17161 pkg.applicationInfo.targetSdkVersion >= 17162 Build.VERSION_CODES.JELLY_BEAN) { 17163 throw new IllegalArgumentException("Component class " + className 17164 + " does not exist in " + packageName); 17165 } else { 17166 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17167 + className + " does not exist in " + packageName); 17168 } 17169 } 17170 switch (newState) { 17171 case COMPONENT_ENABLED_STATE_ENABLED: 17172 if (!pkgSetting.enableComponentLPw(className, userId)) { 17173 return; 17174 } 17175 break; 17176 case COMPONENT_ENABLED_STATE_DISABLED: 17177 if (!pkgSetting.disableComponentLPw(className, userId)) { 17178 return; 17179 } 17180 break; 17181 case COMPONENT_ENABLED_STATE_DEFAULT: 17182 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17183 return; 17184 } 17185 break; 17186 default: 17187 Slog.e(TAG, "Invalid new component state: " + newState); 17188 return; 17189 } 17190 } 17191 scheduleWritePackageRestrictionsLocked(userId); 17192 components = mPendingBroadcasts.get(userId, packageName); 17193 final boolean newPackage = components == null; 17194 if (newPackage) { 17195 components = new ArrayList<String>(); 17196 } 17197 if (!components.contains(componentName)) { 17198 components.add(componentName); 17199 } 17200 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17201 sendNow = true; 17202 // Purge entry from pending broadcast list if another one exists already 17203 // since we are sending one right away. 17204 mPendingBroadcasts.remove(userId, packageName); 17205 } else { 17206 if (newPackage) { 17207 mPendingBroadcasts.put(userId, packageName, components); 17208 } 17209 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17210 // Schedule a message 17211 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17212 } 17213 } 17214 } 17215 17216 long callingId = Binder.clearCallingIdentity(); 17217 try { 17218 if (sendNow) { 17219 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17220 sendPackageChangedBroadcast(packageName, 17221 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17222 } 17223 } finally { 17224 Binder.restoreCallingIdentity(callingId); 17225 } 17226 } 17227 17228 @Override 17229 public void flushPackageRestrictionsAsUser(int userId) { 17230 if (!sUserManager.exists(userId)) { 17231 return; 17232 } 17233 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17234 false /* checkShell */, "flushPackageRestrictions"); 17235 synchronized (mPackages) { 17236 mSettings.writePackageRestrictionsLPr(userId); 17237 mDirtyUsers.remove(userId); 17238 if (mDirtyUsers.isEmpty()) { 17239 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17240 } 17241 } 17242 } 17243 17244 private void sendPackageChangedBroadcast(String packageName, 17245 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17246 if (DEBUG_INSTALL) 17247 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17248 + componentNames); 17249 Bundle extras = new Bundle(4); 17250 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17251 String nameList[] = new String[componentNames.size()]; 17252 componentNames.toArray(nameList); 17253 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17254 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17255 extras.putInt(Intent.EXTRA_UID, packageUid); 17256 // If this is not reporting a change of the overall package, then only send it 17257 // to registered receivers. We don't want to launch a swath of apps for every 17258 // little component state change. 17259 final int flags = !componentNames.contains(packageName) 17260 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17261 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17262 new int[] {UserHandle.getUserId(packageUid)}); 17263 } 17264 17265 @Override 17266 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17267 if (!sUserManager.exists(userId)) return; 17268 final int uid = Binder.getCallingUid(); 17269 final int permission = mContext.checkCallingOrSelfPermission( 17270 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17271 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17272 enforceCrossUserPermission(uid, userId, 17273 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17274 // writer 17275 synchronized (mPackages) { 17276 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17277 allowedByPermission, uid, userId)) { 17278 scheduleWritePackageRestrictionsLocked(userId); 17279 } 17280 } 17281 } 17282 17283 @Override 17284 public String getInstallerPackageName(String packageName) { 17285 // reader 17286 synchronized (mPackages) { 17287 return mSettings.getInstallerPackageNameLPr(packageName); 17288 } 17289 } 17290 17291 @Override 17292 public int getApplicationEnabledSetting(String packageName, int userId) { 17293 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17294 int uid = Binder.getCallingUid(); 17295 enforceCrossUserPermission(uid, userId, 17296 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17297 // reader 17298 synchronized (mPackages) { 17299 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17300 } 17301 } 17302 17303 @Override 17304 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17305 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17306 int uid = Binder.getCallingUid(); 17307 enforceCrossUserPermission(uid, userId, 17308 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17309 // reader 17310 synchronized (mPackages) { 17311 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17312 } 17313 } 17314 17315 @Override 17316 public void enterSafeMode() { 17317 enforceSystemOrRoot("Only the system can request entering safe mode"); 17318 17319 if (!mSystemReady) { 17320 mSafeMode = true; 17321 } 17322 } 17323 17324 @Override 17325 public void systemReady() { 17326 mSystemReady = true; 17327 17328 // Read the compatibilty setting when the system is ready. 17329 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17330 mContext.getContentResolver(), 17331 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17332 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17333 if (DEBUG_SETTINGS) { 17334 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17335 } 17336 17337 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17338 17339 synchronized (mPackages) { 17340 // Verify that all of the preferred activity components actually 17341 // exist. It is possible for applications to be updated and at 17342 // that point remove a previously declared activity component that 17343 // had been set as a preferred activity. We try to clean this up 17344 // the next time we encounter that preferred activity, but it is 17345 // possible for the user flow to never be able to return to that 17346 // situation so here we do a sanity check to make sure we haven't 17347 // left any junk around. 17348 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17349 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17350 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17351 removed.clear(); 17352 for (PreferredActivity pa : pir.filterSet()) { 17353 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17354 removed.add(pa); 17355 } 17356 } 17357 if (removed.size() > 0) { 17358 for (int r=0; r<removed.size(); r++) { 17359 PreferredActivity pa = removed.get(r); 17360 Slog.w(TAG, "Removing dangling preferred activity: " 17361 + pa.mPref.mComponent); 17362 pir.removeFilter(pa); 17363 } 17364 mSettings.writePackageRestrictionsLPr( 17365 mSettings.mPreferredActivities.keyAt(i)); 17366 } 17367 } 17368 17369 for (int userId : UserManagerService.getInstance().getUserIds()) { 17370 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17371 grantPermissionsUserIds = ArrayUtils.appendInt( 17372 grantPermissionsUserIds, userId); 17373 } 17374 } 17375 } 17376 sUserManager.systemReady(); 17377 17378 // If we upgraded grant all default permissions before kicking off. 17379 for (int userId : grantPermissionsUserIds) { 17380 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17381 } 17382 17383 // Kick off any messages waiting for system ready 17384 if (mPostSystemReadyMessages != null) { 17385 for (Message msg : mPostSystemReadyMessages) { 17386 msg.sendToTarget(); 17387 } 17388 mPostSystemReadyMessages = null; 17389 } 17390 17391 // Watch for external volumes that come and go over time 17392 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17393 storage.registerListener(mStorageListener); 17394 17395 mInstallerService.systemReady(); 17396 mPackageDexOptimizer.systemReady(); 17397 17398 MountServiceInternal mountServiceInternal = LocalServices.getService( 17399 MountServiceInternal.class); 17400 mountServiceInternal.addExternalStoragePolicy( 17401 new MountServiceInternal.ExternalStorageMountPolicy() { 17402 @Override 17403 public int getMountMode(int uid, String packageName) { 17404 if (Process.isIsolated(uid)) { 17405 return Zygote.MOUNT_EXTERNAL_NONE; 17406 } 17407 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17408 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17409 } 17410 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17411 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17412 } 17413 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17414 return Zygote.MOUNT_EXTERNAL_READ; 17415 } 17416 return Zygote.MOUNT_EXTERNAL_WRITE; 17417 } 17418 17419 @Override 17420 public boolean hasExternalStorage(int uid, String packageName) { 17421 return true; 17422 } 17423 }); 17424 } 17425 17426 @Override 17427 public boolean isSafeMode() { 17428 return mSafeMode; 17429 } 17430 17431 @Override 17432 public boolean hasSystemUidErrors() { 17433 return mHasSystemUidErrors; 17434 } 17435 17436 static String arrayToString(int[] array) { 17437 StringBuffer buf = new StringBuffer(128); 17438 buf.append('['); 17439 if (array != null) { 17440 for (int i=0; i<array.length; i++) { 17441 if (i > 0) buf.append(", "); 17442 buf.append(array[i]); 17443 } 17444 } 17445 buf.append(']'); 17446 return buf.toString(); 17447 } 17448 17449 static class DumpState { 17450 public static final int DUMP_LIBS = 1 << 0; 17451 public static final int DUMP_FEATURES = 1 << 1; 17452 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17453 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17454 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17455 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17456 public static final int DUMP_PERMISSIONS = 1 << 6; 17457 public static final int DUMP_PACKAGES = 1 << 7; 17458 public static final int DUMP_SHARED_USERS = 1 << 8; 17459 public static final int DUMP_MESSAGES = 1 << 9; 17460 public static final int DUMP_PROVIDERS = 1 << 10; 17461 public static final int DUMP_VERIFIERS = 1 << 11; 17462 public static final int DUMP_PREFERRED = 1 << 12; 17463 public static final int DUMP_PREFERRED_XML = 1 << 13; 17464 public static final int DUMP_KEYSETS = 1 << 14; 17465 public static final int DUMP_VERSION = 1 << 15; 17466 public static final int DUMP_INSTALLS = 1 << 16; 17467 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17468 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17469 public static final int DUMP_FROZEN = 1 << 19; 17470 17471 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17472 17473 private int mTypes; 17474 17475 private int mOptions; 17476 17477 private boolean mTitlePrinted; 17478 17479 private SharedUserSetting mSharedUser; 17480 17481 public boolean isDumping(int type) { 17482 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17483 return true; 17484 } 17485 17486 return (mTypes & type) != 0; 17487 } 17488 17489 public void setDump(int type) { 17490 mTypes |= type; 17491 } 17492 17493 public boolean isOptionEnabled(int option) { 17494 return (mOptions & option) != 0; 17495 } 17496 17497 public void setOptionEnabled(int option) { 17498 mOptions |= option; 17499 } 17500 17501 public boolean onTitlePrinted() { 17502 final boolean printed = mTitlePrinted; 17503 mTitlePrinted = true; 17504 return printed; 17505 } 17506 17507 public boolean getTitlePrinted() { 17508 return mTitlePrinted; 17509 } 17510 17511 public void setTitlePrinted(boolean enabled) { 17512 mTitlePrinted = enabled; 17513 } 17514 17515 public SharedUserSetting getSharedUser() { 17516 return mSharedUser; 17517 } 17518 17519 public void setSharedUser(SharedUserSetting user) { 17520 mSharedUser = user; 17521 } 17522 } 17523 17524 @Override 17525 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17526 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17527 (new PackageManagerShellCommand(this)).exec( 17528 this, in, out, err, args, resultReceiver); 17529 } 17530 17531 @Override 17532 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17533 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17534 != PackageManager.PERMISSION_GRANTED) { 17535 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17536 + Binder.getCallingPid() 17537 + ", uid=" + Binder.getCallingUid() 17538 + " without permission " 17539 + android.Manifest.permission.DUMP); 17540 return; 17541 } 17542 17543 DumpState dumpState = new DumpState(); 17544 boolean fullPreferred = false; 17545 boolean checkin = false; 17546 17547 String packageName = null; 17548 ArraySet<String> permissionNames = null; 17549 17550 int opti = 0; 17551 while (opti < args.length) { 17552 String opt = args[opti]; 17553 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17554 break; 17555 } 17556 opti++; 17557 17558 if ("-a".equals(opt)) { 17559 // Right now we only know how to print all. 17560 } else if ("-h".equals(opt)) { 17561 pw.println("Package manager dump options:"); 17562 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17563 pw.println(" --checkin: dump for a checkin"); 17564 pw.println(" -f: print details of intent filters"); 17565 pw.println(" -h: print this help"); 17566 pw.println(" cmd may be one of:"); 17567 pw.println(" l[ibraries]: list known shared libraries"); 17568 pw.println(" f[eatures]: list device features"); 17569 pw.println(" k[eysets]: print known keysets"); 17570 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17571 pw.println(" perm[issions]: dump permissions"); 17572 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17573 pw.println(" pref[erred]: print preferred package settings"); 17574 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17575 pw.println(" prov[iders]: dump content providers"); 17576 pw.println(" p[ackages]: dump installed packages"); 17577 pw.println(" s[hared-users]: dump shared user IDs"); 17578 pw.println(" m[essages]: print collected runtime messages"); 17579 pw.println(" v[erifiers]: print package verifier info"); 17580 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17581 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17582 pw.println(" version: print database version info"); 17583 pw.println(" write: write current settings now"); 17584 pw.println(" installs: details about install sessions"); 17585 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17586 pw.println(" <package.name>: info about given package"); 17587 return; 17588 } else if ("--checkin".equals(opt)) { 17589 checkin = true; 17590 } else if ("-f".equals(opt)) { 17591 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17592 } else { 17593 pw.println("Unknown argument: " + opt + "; use -h for help"); 17594 } 17595 } 17596 17597 // Is the caller requesting to dump a particular piece of data? 17598 if (opti < args.length) { 17599 String cmd = args[opti]; 17600 opti++; 17601 // Is this a package name? 17602 if ("android".equals(cmd) || cmd.contains(".")) { 17603 packageName = cmd; 17604 // When dumping a single package, we always dump all of its 17605 // filter information since the amount of data will be reasonable. 17606 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17607 } else if ("check-permission".equals(cmd)) { 17608 if (opti >= args.length) { 17609 pw.println("Error: check-permission missing permission argument"); 17610 return; 17611 } 17612 String perm = args[opti]; 17613 opti++; 17614 if (opti >= args.length) { 17615 pw.println("Error: check-permission missing package argument"); 17616 return; 17617 } 17618 String pkg = args[opti]; 17619 opti++; 17620 int user = UserHandle.getUserId(Binder.getCallingUid()); 17621 if (opti < args.length) { 17622 try { 17623 user = Integer.parseInt(args[opti]); 17624 } catch (NumberFormatException e) { 17625 pw.println("Error: check-permission user argument is not a number: " 17626 + args[opti]); 17627 return; 17628 } 17629 } 17630 pw.println(checkPermission(perm, pkg, user)); 17631 return; 17632 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17633 dumpState.setDump(DumpState.DUMP_LIBS); 17634 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17635 dumpState.setDump(DumpState.DUMP_FEATURES); 17636 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17637 if (opti >= args.length) { 17638 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17639 | DumpState.DUMP_SERVICE_RESOLVERS 17640 | DumpState.DUMP_RECEIVER_RESOLVERS 17641 | DumpState.DUMP_CONTENT_RESOLVERS); 17642 } else { 17643 while (opti < args.length) { 17644 String name = args[opti]; 17645 if ("a".equals(name) || "activity".equals(name)) { 17646 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17647 } else if ("s".equals(name) || "service".equals(name)) { 17648 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17649 } else if ("r".equals(name) || "receiver".equals(name)) { 17650 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17651 } else if ("c".equals(name) || "content".equals(name)) { 17652 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17653 } else { 17654 pw.println("Error: unknown resolver table type: " + name); 17655 return; 17656 } 17657 opti++; 17658 } 17659 } 17660 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17661 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17662 } else if ("permission".equals(cmd)) { 17663 if (opti >= args.length) { 17664 pw.println("Error: permission requires permission name"); 17665 return; 17666 } 17667 permissionNames = new ArraySet<>(); 17668 while (opti < args.length) { 17669 permissionNames.add(args[opti]); 17670 opti++; 17671 } 17672 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17673 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17674 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17675 dumpState.setDump(DumpState.DUMP_PREFERRED); 17676 } else if ("preferred-xml".equals(cmd)) { 17677 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17678 if (opti < args.length && "--full".equals(args[opti])) { 17679 fullPreferred = true; 17680 opti++; 17681 } 17682 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17683 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17684 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17685 dumpState.setDump(DumpState.DUMP_PACKAGES); 17686 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17687 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17688 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17689 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17690 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17691 dumpState.setDump(DumpState.DUMP_MESSAGES); 17692 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17693 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17694 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17695 || "intent-filter-verifiers".equals(cmd)) { 17696 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17697 } else if ("version".equals(cmd)) { 17698 dumpState.setDump(DumpState.DUMP_VERSION); 17699 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17700 dumpState.setDump(DumpState.DUMP_KEYSETS); 17701 } else if ("installs".equals(cmd)) { 17702 dumpState.setDump(DumpState.DUMP_INSTALLS); 17703 } else if ("frozen".equals(cmd)) { 17704 dumpState.setDump(DumpState.DUMP_FROZEN); 17705 } else if ("write".equals(cmd)) { 17706 synchronized (mPackages) { 17707 mSettings.writeLPr(); 17708 pw.println("Settings written."); 17709 return; 17710 } 17711 } 17712 } 17713 17714 if (checkin) { 17715 pw.println("vers,1"); 17716 } 17717 17718 // reader 17719 synchronized (mPackages) { 17720 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17721 if (!checkin) { 17722 if (dumpState.onTitlePrinted()) 17723 pw.println(); 17724 pw.println("Database versions:"); 17725 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17726 } 17727 } 17728 17729 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17730 if (!checkin) { 17731 if (dumpState.onTitlePrinted()) 17732 pw.println(); 17733 pw.println("Verifiers:"); 17734 pw.print(" Required: "); 17735 pw.print(mRequiredVerifierPackage); 17736 pw.print(" (uid="); 17737 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17738 UserHandle.USER_SYSTEM)); 17739 pw.println(")"); 17740 } else if (mRequiredVerifierPackage != null) { 17741 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17742 pw.print(","); 17743 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17744 UserHandle.USER_SYSTEM)); 17745 } 17746 } 17747 17748 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17749 packageName == null) { 17750 if (mIntentFilterVerifierComponent != null) { 17751 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17752 if (!checkin) { 17753 if (dumpState.onTitlePrinted()) 17754 pw.println(); 17755 pw.println("Intent Filter Verifier:"); 17756 pw.print(" Using: "); 17757 pw.print(verifierPackageName); 17758 pw.print(" (uid="); 17759 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17760 UserHandle.USER_SYSTEM)); 17761 pw.println(")"); 17762 } else if (verifierPackageName != null) { 17763 pw.print("ifv,"); pw.print(verifierPackageName); 17764 pw.print(","); 17765 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17766 UserHandle.USER_SYSTEM)); 17767 } 17768 } else { 17769 pw.println(); 17770 pw.println("No Intent Filter Verifier available!"); 17771 } 17772 } 17773 17774 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17775 boolean printedHeader = false; 17776 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17777 while (it.hasNext()) { 17778 String name = it.next(); 17779 SharedLibraryEntry ent = mSharedLibraries.get(name); 17780 if (!checkin) { 17781 if (!printedHeader) { 17782 if (dumpState.onTitlePrinted()) 17783 pw.println(); 17784 pw.println("Libraries:"); 17785 printedHeader = true; 17786 } 17787 pw.print(" "); 17788 } else { 17789 pw.print("lib,"); 17790 } 17791 pw.print(name); 17792 if (!checkin) { 17793 pw.print(" -> "); 17794 } 17795 if (ent.path != null) { 17796 if (!checkin) { 17797 pw.print("(jar) "); 17798 pw.print(ent.path); 17799 } else { 17800 pw.print(",jar,"); 17801 pw.print(ent.path); 17802 } 17803 } else { 17804 if (!checkin) { 17805 pw.print("(apk) "); 17806 pw.print(ent.apk); 17807 } else { 17808 pw.print(",apk,"); 17809 pw.print(ent.apk); 17810 } 17811 } 17812 pw.println(); 17813 } 17814 } 17815 17816 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17817 if (dumpState.onTitlePrinted()) 17818 pw.println(); 17819 if (!checkin) { 17820 pw.println("Features:"); 17821 } 17822 17823 for (FeatureInfo feat : mAvailableFeatures.values()) { 17824 if (checkin) { 17825 pw.print("feat,"); 17826 pw.print(feat.name); 17827 pw.print(","); 17828 pw.println(feat.version); 17829 } else { 17830 pw.print(" "); 17831 pw.print(feat.name); 17832 if (feat.version > 0) { 17833 pw.print(" version="); 17834 pw.print(feat.version); 17835 } 17836 pw.println(); 17837 } 17838 } 17839 } 17840 17841 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17842 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17843 : "Activity Resolver Table:", " ", packageName, 17844 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17845 dumpState.setTitlePrinted(true); 17846 } 17847 } 17848 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17849 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17850 : "Receiver Resolver Table:", " ", packageName, 17851 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17852 dumpState.setTitlePrinted(true); 17853 } 17854 } 17855 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17856 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17857 : "Service Resolver Table:", " ", packageName, 17858 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17859 dumpState.setTitlePrinted(true); 17860 } 17861 } 17862 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17863 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17864 : "Provider Resolver Table:", " ", packageName, 17865 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17866 dumpState.setTitlePrinted(true); 17867 } 17868 } 17869 17870 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17871 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17872 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17873 int user = mSettings.mPreferredActivities.keyAt(i); 17874 if (pir.dump(pw, 17875 dumpState.getTitlePrinted() 17876 ? "\nPreferred Activities User " + user + ":" 17877 : "Preferred Activities User " + user + ":", " ", 17878 packageName, true, false)) { 17879 dumpState.setTitlePrinted(true); 17880 } 17881 } 17882 } 17883 17884 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17885 pw.flush(); 17886 FileOutputStream fout = new FileOutputStream(fd); 17887 BufferedOutputStream str = new BufferedOutputStream(fout); 17888 XmlSerializer serializer = new FastXmlSerializer(); 17889 try { 17890 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17891 serializer.startDocument(null, true); 17892 serializer.setFeature( 17893 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17894 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17895 serializer.endDocument(); 17896 serializer.flush(); 17897 } catch (IllegalArgumentException e) { 17898 pw.println("Failed writing: " + e); 17899 } catch (IllegalStateException e) { 17900 pw.println("Failed writing: " + e); 17901 } catch (IOException e) { 17902 pw.println("Failed writing: " + e); 17903 } 17904 } 17905 17906 if (!checkin 17907 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17908 && packageName == null) { 17909 pw.println(); 17910 int count = mSettings.mPackages.size(); 17911 if (count == 0) { 17912 pw.println("No applications!"); 17913 pw.println(); 17914 } else { 17915 final String prefix = " "; 17916 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17917 if (allPackageSettings.size() == 0) { 17918 pw.println("No domain preferred apps!"); 17919 pw.println(); 17920 } else { 17921 pw.println("App verification status:"); 17922 pw.println(); 17923 count = 0; 17924 for (PackageSetting ps : allPackageSettings) { 17925 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17926 if (ivi == null || ivi.getPackageName() == null) continue; 17927 pw.println(prefix + "Package: " + ivi.getPackageName()); 17928 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17929 pw.println(prefix + "Status: " + ivi.getStatusString()); 17930 pw.println(); 17931 count++; 17932 } 17933 if (count == 0) { 17934 pw.println(prefix + "No app verification established."); 17935 pw.println(); 17936 } 17937 for (int userId : sUserManager.getUserIds()) { 17938 pw.println("App linkages for user " + userId + ":"); 17939 pw.println(); 17940 count = 0; 17941 for (PackageSetting ps : allPackageSettings) { 17942 final long status = ps.getDomainVerificationStatusForUser(userId); 17943 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17944 continue; 17945 } 17946 pw.println(prefix + "Package: " + ps.name); 17947 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17948 String statusStr = IntentFilterVerificationInfo. 17949 getStatusStringFromValue(status); 17950 pw.println(prefix + "Status: " + statusStr); 17951 pw.println(); 17952 count++; 17953 } 17954 if (count == 0) { 17955 pw.println(prefix + "No configured app linkages."); 17956 pw.println(); 17957 } 17958 } 17959 } 17960 } 17961 } 17962 17963 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17964 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17965 if (packageName == null && permissionNames == null) { 17966 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17967 if (iperm == 0) { 17968 if (dumpState.onTitlePrinted()) 17969 pw.println(); 17970 pw.println("AppOp Permissions:"); 17971 } 17972 pw.print(" AppOp Permission "); 17973 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17974 pw.println(":"); 17975 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17976 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17977 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17978 } 17979 } 17980 } 17981 } 17982 17983 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17984 boolean printedSomething = false; 17985 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17986 if (packageName != null && !packageName.equals(p.info.packageName)) { 17987 continue; 17988 } 17989 if (!printedSomething) { 17990 if (dumpState.onTitlePrinted()) 17991 pw.println(); 17992 pw.println("Registered ContentProviders:"); 17993 printedSomething = true; 17994 } 17995 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17996 pw.print(" "); pw.println(p.toString()); 17997 } 17998 printedSomething = false; 17999 for (Map.Entry<String, PackageParser.Provider> entry : 18000 mProvidersByAuthority.entrySet()) { 18001 PackageParser.Provider p = entry.getValue(); 18002 if (packageName != null && !packageName.equals(p.info.packageName)) { 18003 continue; 18004 } 18005 if (!printedSomething) { 18006 if (dumpState.onTitlePrinted()) 18007 pw.println(); 18008 pw.println("ContentProvider Authorities:"); 18009 printedSomething = true; 18010 } 18011 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18012 pw.print(" "); pw.println(p.toString()); 18013 if (p.info != null && p.info.applicationInfo != null) { 18014 final String appInfo = p.info.applicationInfo.toString(); 18015 pw.print(" applicationInfo="); pw.println(appInfo); 18016 } 18017 } 18018 } 18019 18020 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18021 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18022 } 18023 18024 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18025 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18026 } 18027 18028 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18029 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18030 } 18031 18032 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18033 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18034 } 18035 18036 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18037 // XXX should handle packageName != null by dumping only install data that 18038 // the given package is involved with. 18039 if (dumpState.onTitlePrinted()) pw.println(); 18040 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18041 } 18042 18043 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18044 // XXX should handle packageName != null by dumping only install data that 18045 // the given package is involved with. 18046 if (dumpState.onTitlePrinted()) pw.println(); 18047 18048 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18049 ipw.println(); 18050 ipw.println("Frozen packages:"); 18051 ipw.increaseIndent(); 18052 if (mFrozenPackages.size() == 0) { 18053 ipw.println("(none)"); 18054 } else { 18055 for (int i = 0; i < mFrozenPackages.size(); i++) { 18056 ipw.println(mFrozenPackages.valueAt(i)); 18057 } 18058 } 18059 ipw.decreaseIndent(); 18060 } 18061 18062 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18063 if (dumpState.onTitlePrinted()) pw.println(); 18064 mSettings.dumpReadMessagesLPr(pw, dumpState); 18065 18066 pw.println(); 18067 pw.println("Package warning messages:"); 18068 BufferedReader in = null; 18069 String line = null; 18070 try { 18071 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18072 while ((line = in.readLine()) != null) { 18073 if (line.contains("ignored: updated version")) continue; 18074 pw.println(line); 18075 } 18076 } catch (IOException ignored) { 18077 } finally { 18078 IoUtils.closeQuietly(in); 18079 } 18080 } 18081 18082 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18083 BufferedReader in = null; 18084 String line = null; 18085 try { 18086 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18087 while ((line = in.readLine()) != null) { 18088 if (line.contains("ignored: updated version")) continue; 18089 pw.print("msg,"); 18090 pw.println(line); 18091 } 18092 } catch (IOException ignored) { 18093 } finally { 18094 IoUtils.closeQuietly(in); 18095 } 18096 } 18097 } 18098 } 18099 18100 private String dumpDomainString(String packageName) { 18101 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18102 .getList(); 18103 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18104 18105 ArraySet<String> result = new ArraySet<>(); 18106 if (iviList.size() > 0) { 18107 for (IntentFilterVerificationInfo ivi : iviList) { 18108 for (String host : ivi.getDomains()) { 18109 result.add(host); 18110 } 18111 } 18112 } 18113 if (filters != null && filters.size() > 0) { 18114 for (IntentFilter filter : filters) { 18115 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18116 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18117 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18118 result.addAll(filter.getHostsList()); 18119 } 18120 } 18121 } 18122 18123 StringBuilder sb = new StringBuilder(result.size() * 16); 18124 for (String domain : result) { 18125 if (sb.length() > 0) sb.append(" "); 18126 sb.append(domain); 18127 } 18128 return sb.toString(); 18129 } 18130 18131 // ------- apps on sdcard specific code ------- 18132 static final boolean DEBUG_SD_INSTALL = false; 18133 18134 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18135 18136 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18137 18138 private boolean mMediaMounted = false; 18139 18140 static String getEncryptKey() { 18141 try { 18142 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18143 SD_ENCRYPTION_KEYSTORE_NAME); 18144 if (sdEncKey == null) { 18145 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18146 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18147 if (sdEncKey == null) { 18148 Slog.e(TAG, "Failed to create encryption keys"); 18149 return null; 18150 } 18151 } 18152 return sdEncKey; 18153 } catch (NoSuchAlgorithmException nsae) { 18154 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18155 return null; 18156 } catch (IOException ioe) { 18157 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18158 return null; 18159 } 18160 } 18161 18162 /* 18163 * Update media status on PackageManager. 18164 */ 18165 @Override 18166 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18167 int callingUid = Binder.getCallingUid(); 18168 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18169 throw new SecurityException("Media status can only be updated by the system"); 18170 } 18171 // reader; this apparently protects mMediaMounted, but should probably 18172 // be a different lock in that case. 18173 synchronized (mPackages) { 18174 Log.i(TAG, "Updating external media status from " 18175 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18176 + (mediaStatus ? "mounted" : "unmounted")); 18177 if (DEBUG_SD_INSTALL) 18178 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18179 + ", mMediaMounted=" + mMediaMounted); 18180 if (mediaStatus == mMediaMounted) { 18181 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18182 : 0, -1); 18183 mHandler.sendMessage(msg); 18184 return; 18185 } 18186 mMediaMounted = mediaStatus; 18187 } 18188 // Queue up an async operation since the package installation may take a 18189 // little while. 18190 mHandler.post(new Runnable() { 18191 public void run() { 18192 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18193 } 18194 }); 18195 } 18196 18197 /** 18198 * Called by MountService when the initial ASECs to scan are available. 18199 * Should block until all the ASEC containers are finished being scanned. 18200 */ 18201 public void scanAvailableAsecs() { 18202 updateExternalMediaStatusInner(true, false, false); 18203 } 18204 18205 /* 18206 * Collect information of applications on external media, map them against 18207 * existing containers and update information based on current mount status. 18208 * Please note that we always have to report status if reportStatus has been 18209 * set to true especially when unloading packages. 18210 */ 18211 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18212 boolean externalStorage) { 18213 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18214 int[] uidArr = EmptyArray.INT; 18215 18216 final String[] list = PackageHelper.getSecureContainerList(); 18217 if (ArrayUtils.isEmpty(list)) { 18218 Log.i(TAG, "No secure containers found"); 18219 } else { 18220 // Process list of secure containers and categorize them 18221 // as active or stale based on their package internal state. 18222 18223 // reader 18224 synchronized (mPackages) { 18225 for (String cid : list) { 18226 // Leave stages untouched for now; installer service owns them 18227 if (PackageInstallerService.isStageName(cid)) continue; 18228 18229 if (DEBUG_SD_INSTALL) 18230 Log.i(TAG, "Processing container " + cid); 18231 String pkgName = getAsecPackageName(cid); 18232 if (pkgName == null) { 18233 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18234 continue; 18235 } 18236 if (DEBUG_SD_INSTALL) 18237 Log.i(TAG, "Looking for pkg : " + pkgName); 18238 18239 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18240 if (ps == null) { 18241 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18242 continue; 18243 } 18244 18245 /* 18246 * Skip packages that are not external if we're unmounting 18247 * external storage. 18248 */ 18249 if (externalStorage && !isMounted && !isExternal(ps)) { 18250 continue; 18251 } 18252 18253 final AsecInstallArgs args = new AsecInstallArgs(cid, 18254 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18255 // The package status is changed only if the code path 18256 // matches between settings and the container id. 18257 if (ps.codePathString != null 18258 && ps.codePathString.startsWith(args.getCodePath())) { 18259 if (DEBUG_SD_INSTALL) { 18260 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18261 + " at code path: " + ps.codePathString); 18262 } 18263 18264 // We do have a valid package installed on sdcard 18265 processCids.put(args, ps.codePathString); 18266 final int uid = ps.appId; 18267 if (uid != -1) { 18268 uidArr = ArrayUtils.appendInt(uidArr, uid); 18269 } 18270 } else { 18271 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18272 + ps.codePathString); 18273 } 18274 } 18275 } 18276 18277 Arrays.sort(uidArr); 18278 } 18279 18280 // Process packages with valid entries. 18281 if (isMounted) { 18282 if (DEBUG_SD_INSTALL) 18283 Log.i(TAG, "Loading packages"); 18284 loadMediaPackages(processCids, uidArr, externalStorage); 18285 startCleaningPackages(); 18286 mInstallerService.onSecureContainersAvailable(); 18287 } else { 18288 if (DEBUG_SD_INSTALL) 18289 Log.i(TAG, "Unloading packages"); 18290 unloadMediaPackages(processCids, uidArr, reportStatus); 18291 } 18292 } 18293 18294 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18295 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18296 final int size = infos.size(); 18297 final String[] packageNames = new String[size]; 18298 final int[] packageUids = new int[size]; 18299 for (int i = 0; i < size; i++) { 18300 final ApplicationInfo info = infos.get(i); 18301 packageNames[i] = info.packageName; 18302 packageUids[i] = info.uid; 18303 } 18304 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18305 finishedReceiver); 18306 } 18307 18308 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18309 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18310 sendResourcesChangedBroadcast(mediaStatus, replacing, 18311 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18312 } 18313 18314 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18315 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18316 int size = pkgList.length; 18317 if (size > 0) { 18318 // Send broadcasts here 18319 Bundle extras = new Bundle(); 18320 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18321 if (uidArr != null) { 18322 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18323 } 18324 if (replacing) { 18325 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18326 } 18327 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18328 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18329 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18330 } 18331 } 18332 18333 /* 18334 * Look at potentially valid container ids from processCids If package 18335 * information doesn't match the one on record or package scanning fails, 18336 * the cid is added to list of removeCids. We currently don't delete stale 18337 * containers. 18338 */ 18339 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18340 boolean externalStorage) { 18341 ArrayList<String> pkgList = new ArrayList<String>(); 18342 Set<AsecInstallArgs> keys = processCids.keySet(); 18343 18344 for (AsecInstallArgs args : keys) { 18345 String codePath = processCids.get(args); 18346 if (DEBUG_SD_INSTALL) 18347 Log.i(TAG, "Loading container : " + args.cid); 18348 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18349 try { 18350 // Make sure there are no container errors first. 18351 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18352 Slog.e(TAG, "Failed to mount cid : " + args.cid 18353 + " when installing from sdcard"); 18354 continue; 18355 } 18356 // Check code path here. 18357 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18358 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18359 + " does not match one in settings " + codePath); 18360 continue; 18361 } 18362 // Parse package 18363 int parseFlags = mDefParseFlags; 18364 if (args.isExternalAsec()) { 18365 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18366 } 18367 if (args.isFwdLocked()) { 18368 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18369 } 18370 18371 synchronized (mInstallLock) { 18372 PackageParser.Package pkg = null; 18373 try { 18374 // Sadly we don't know the package name yet to freeze it 18375 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18376 SCAN_IGNORE_FROZEN, 0, null); 18377 } catch (PackageManagerException e) { 18378 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18379 } 18380 // Scan the package 18381 if (pkg != null) { 18382 /* 18383 * TODO why is the lock being held? doPostInstall is 18384 * called in other places without the lock. This needs 18385 * to be straightened out. 18386 */ 18387 // writer 18388 synchronized (mPackages) { 18389 retCode = PackageManager.INSTALL_SUCCEEDED; 18390 pkgList.add(pkg.packageName); 18391 // Post process args 18392 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18393 pkg.applicationInfo.uid); 18394 } 18395 } else { 18396 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18397 } 18398 } 18399 18400 } finally { 18401 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18402 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18403 } 18404 } 18405 } 18406 // writer 18407 synchronized (mPackages) { 18408 // If the platform SDK has changed since the last time we booted, 18409 // we need to re-grant app permission to catch any new ones that 18410 // appear. This is really a hack, and means that apps can in some 18411 // cases get permissions that the user didn't initially explicitly 18412 // allow... it would be nice to have some better way to handle 18413 // this situation. 18414 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18415 : mSettings.getInternalVersion(); 18416 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18417 : StorageManager.UUID_PRIVATE_INTERNAL; 18418 18419 int updateFlags = UPDATE_PERMISSIONS_ALL; 18420 if (ver.sdkVersion != mSdkVersion) { 18421 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18422 + mSdkVersion + "; regranting permissions for external"); 18423 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18424 } 18425 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18426 18427 // Yay, everything is now upgraded 18428 ver.forceCurrent(); 18429 18430 // can downgrade to reader 18431 // Persist settings 18432 mSettings.writeLPr(); 18433 } 18434 // Send a broadcast to let everyone know we are done processing 18435 if (pkgList.size() > 0) { 18436 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18437 } 18438 } 18439 18440 /* 18441 * Utility method to unload a list of specified containers 18442 */ 18443 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18444 // Just unmount all valid containers. 18445 for (AsecInstallArgs arg : cidArgs) { 18446 synchronized (mInstallLock) { 18447 arg.doPostDeleteLI(false); 18448 } 18449 } 18450 } 18451 18452 /* 18453 * Unload packages mounted on external media. This involves deleting package 18454 * data from internal structures, sending broadcasts about disabled packages, 18455 * gc'ing to free up references, unmounting all secure containers 18456 * corresponding to packages on external media, and posting a 18457 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18458 * that we always have to post this message if status has been requested no 18459 * matter what. 18460 */ 18461 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18462 final boolean reportStatus) { 18463 if (DEBUG_SD_INSTALL) 18464 Log.i(TAG, "unloading media packages"); 18465 ArrayList<String> pkgList = new ArrayList<String>(); 18466 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18467 final Set<AsecInstallArgs> keys = processCids.keySet(); 18468 for (AsecInstallArgs args : keys) { 18469 String pkgName = args.getPackageName(); 18470 if (DEBUG_SD_INSTALL) 18471 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18472 // Delete package internally 18473 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18474 synchronized (mInstallLock) { 18475 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18476 final boolean res; 18477 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18478 "unloadMediaPackages")) { 18479 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18480 null); 18481 } 18482 if (res) { 18483 pkgList.add(pkgName); 18484 } else { 18485 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18486 failedList.add(args); 18487 } 18488 } 18489 } 18490 18491 // reader 18492 synchronized (mPackages) { 18493 // We didn't update the settings after removing each package; 18494 // write them now for all packages. 18495 mSettings.writeLPr(); 18496 } 18497 18498 // We have to absolutely send UPDATED_MEDIA_STATUS only 18499 // after confirming that all the receivers processed the ordered 18500 // broadcast when packages get disabled, force a gc to clean things up. 18501 // and unload all the containers. 18502 if (pkgList.size() > 0) { 18503 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18504 new IIntentReceiver.Stub() { 18505 public void performReceive(Intent intent, int resultCode, String data, 18506 Bundle extras, boolean ordered, boolean sticky, 18507 int sendingUser) throws RemoteException { 18508 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18509 reportStatus ? 1 : 0, 1, keys); 18510 mHandler.sendMessage(msg); 18511 } 18512 }); 18513 } else { 18514 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18515 keys); 18516 mHandler.sendMessage(msg); 18517 } 18518 } 18519 18520 private void loadPrivatePackages(final VolumeInfo vol) { 18521 mHandler.post(new Runnable() { 18522 @Override 18523 public void run() { 18524 loadPrivatePackagesInner(vol); 18525 } 18526 }); 18527 } 18528 18529 private void loadPrivatePackagesInner(VolumeInfo vol) { 18530 final String volumeUuid = vol.fsUuid; 18531 if (TextUtils.isEmpty(volumeUuid)) { 18532 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18533 return; 18534 } 18535 18536 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18537 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18538 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18539 18540 final VersionInfo ver; 18541 final List<PackageSetting> packages; 18542 synchronized (mPackages) { 18543 ver = mSettings.findOrCreateVersion(volumeUuid); 18544 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18545 } 18546 18547 for (PackageSetting ps : packages) { 18548 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18549 synchronized (mInstallLock) { 18550 final PackageParser.Package pkg; 18551 try { 18552 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18553 loaded.add(pkg.applicationInfo); 18554 18555 } catch (PackageManagerException e) { 18556 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18557 } 18558 18559 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18560 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18561 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18562 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18563 } 18564 } 18565 } 18566 18567 // Reconcile app data for all started/unlocked users 18568 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18569 final UserManager um = mContext.getSystemService(UserManager.class); 18570 for (UserInfo user : um.getUsers()) { 18571 final int flags; 18572 if (um.isUserUnlocked(user.id)) { 18573 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18574 } else if (um.isUserRunning(user.id)) { 18575 flags = StorageManager.FLAG_STORAGE_DE; 18576 } else { 18577 continue; 18578 } 18579 18580 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18581 synchronized (mInstallLock) { 18582 reconcileAppsDataLI(volumeUuid, user.id, flags); 18583 } 18584 } 18585 18586 synchronized (mPackages) { 18587 int updateFlags = UPDATE_PERMISSIONS_ALL; 18588 if (ver.sdkVersion != mSdkVersion) { 18589 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18590 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18591 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18592 } 18593 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18594 18595 // Yay, everything is now upgraded 18596 ver.forceCurrent(); 18597 18598 mSettings.writeLPr(); 18599 } 18600 18601 for (PackageFreezer freezer : freezers) { 18602 freezer.close(); 18603 } 18604 18605 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18606 sendResourcesChangedBroadcast(true, false, loaded, null); 18607 } 18608 18609 private void unloadPrivatePackages(final VolumeInfo vol) { 18610 mHandler.post(new Runnable() { 18611 @Override 18612 public void run() { 18613 unloadPrivatePackagesInner(vol); 18614 } 18615 }); 18616 } 18617 18618 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18619 final String volumeUuid = vol.fsUuid; 18620 if (TextUtils.isEmpty(volumeUuid)) { 18621 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18622 return; 18623 } 18624 18625 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18626 synchronized (mInstallLock) { 18627 synchronized (mPackages) { 18628 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18629 for (PackageSetting ps : packages) { 18630 if (ps.pkg == null) continue; 18631 18632 final ApplicationInfo info = ps.pkg.applicationInfo; 18633 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18634 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18635 18636 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18637 "unloadPrivatePackagesInner")) { 18638 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18639 false, null)) { 18640 unloaded.add(info); 18641 } else { 18642 Slog.w(TAG, "Failed to unload " + ps.codePath); 18643 } 18644 } 18645 } 18646 18647 mSettings.writeLPr(); 18648 } 18649 } 18650 18651 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18652 sendResourcesChangedBroadcast(false, false, unloaded, null); 18653 } 18654 18655 /** 18656 * Examine all users present on given mounted volume, and destroy data 18657 * belonging to users that are no longer valid, or whose user ID has been 18658 * recycled. 18659 */ 18660 private void reconcileUsers(String volumeUuid) { 18661 // TODO: also reconcile DE directories 18662 final File[] files = FileUtils 18663 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18664 for (File file : files) { 18665 if (!file.isDirectory()) continue; 18666 18667 final int userId; 18668 final UserInfo info; 18669 try { 18670 userId = Integer.parseInt(file.getName()); 18671 info = sUserManager.getUserInfo(userId); 18672 } catch (NumberFormatException e) { 18673 Slog.w(TAG, "Invalid user directory " + file); 18674 continue; 18675 } 18676 18677 boolean destroyUser = false; 18678 if (info == null) { 18679 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18680 + " because no matching user was found"); 18681 destroyUser = true; 18682 } else { 18683 try { 18684 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18685 } catch (IOException e) { 18686 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18687 + " because we failed to enforce serial number: " + e); 18688 destroyUser = true; 18689 } 18690 } 18691 18692 if (destroyUser) { 18693 synchronized (mInstallLock) { 18694 try { 18695 mInstaller.removeUserDataDirs(volumeUuid, userId); 18696 } catch (InstallerException e) { 18697 Slog.w(TAG, "Failed to clean up user dirs", e); 18698 } 18699 } 18700 } 18701 } 18702 } 18703 18704 private void assertPackageKnown(String volumeUuid, String packageName) 18705 throws PackageManagerException { 18706 synchronized (mPackages) { 18707 final PackageSetting ps = mSettings.mPackages.get(packageName); 18708 if (ps == null) { 18709 throw new PackageManagerException("Package " + packageName + " is unknown"); 18710 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18711 throw new PackageManagerException( 18712 "Package " + packageName + " found on unknown volume " + volumeUuid 18713 + "; expected volume " + ps.volumeUuid); 18714 } 18715 } 18716 } 18717 18718 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18719 throws PackageManagerException { 18720 synchronized (mPackages) { 18721 final PackageSetting ps = mSettings.mPackages.get(packageName); 18722 if (ps == null) { 18723 throw new PackageManagerException("Package " + packageName + " is unknown"); 18724 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18725 throw new PackageManagerException( 18726 "Package " + packageName + " found on unknown volume " + volumeUuid 18727 + "; expected volume " + ps.volumeUuid); 18728 } else if (!ps.getInstalled(userId)) { 18729 throw new PackageManagerException( 18730 "Package " + packageName + " not installed for user " + userId); 18731 } 18732 } 18733 } 18734 18735 /** 18736 * Examine all apps present on given mounted volume, and destroy apps that 18737 * aren't expected, either due to uninstallation or reinstallation on 18738 * another volume. 18739 */ 18740 private void reconcileApps(String volumeUuid) { 18741 final File[] files = FileUtils 18742 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18743 for (File file : files) { 18744 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18745 && !PackageInstallerService.isStageName(file.getName()); 18746 if (!isPackage) { 18747 // Ignore entries which are not packages 18748 continue; 18749 } 18750 18751 try { 18752 final PackageLite pkg = PackageParser.parsePackageLite(file, 18753 PackageParser.PARSE_MUST_BE_APK); 18754 assertPackageKnown(volumeUuid, pkg.packageName); 18755 18756 } catch (PackageParserException | PackageManagerException e) { 18757 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18758 synchronized (mInstallLock) { 18759 removeCodePathLI(file); 18760 } 18761 } 18762 } 18763 } 18764 18765 /** 18766 * Reconcile all app data for the given user. 18767 * <p> 18768 * Verifies that directories exist and that ownership and labeling is 18769 * correct for all installed apps on all mounted volumes. 18770 */ 18771 void reconcileAppsData(int userId, int flags) { 18772 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18773 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18774 final String volumeUuid = vol.getFsUuid(); 18775 synchronized (mInstallLock) { 18776 reconcileAppsDataLI(volumeUuid, userId, flags); 18777 } 18778 } 18779 } 18780 18781 /** 18782 * Reconcile all app data on given mounted volume. 18783 * <p> 18784 * Destroys app data that isn't expected, either due to uninstallation or 18785 * reinstallation on another volume. 18786 * <p> 18787 * Verifies that directories exist and that ownership and labeling is 18788 * correct for all installed apps. 18789 */ 18790 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18791 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18792 + Integer.toHexString(flags)); 18793 18794 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18795 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18796 18797 boolean restoreconNeeded = false; 18798 18799 // First look for stale data that doesn't belong, and check if things 18800 // have changed since we did our last restorecon 18801 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18802 if (!isUserKeyUnlocked(userId)) { 18803 throw new RuntimeException( 18804 "Yikes, someone asked us to reconcile CE storage while " + userId 18805 + " was still locked; this would have caused massive data loss!"); 18806 } 18807 18808 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18809 18810 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18811 for (File file : files) { 18812 final String packageName = file.getName(); 18813 try { 18814 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18815 } catch (PackageManagerException e) { 18816 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18817 try { 18818 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18819 StorageManager.FLAG_STORAGE_CE, 0); 18820 } catch (InstallerException e2) { 18821 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18822 } 18823 } 18824 } 18825 } 18826 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18827 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18828 18829 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18830 for (File file : files) { 18831 final String packageName = file.getName(); 18832 try { 18833 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18834 } catch (PackageManagerException e) { 18835 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18836 try { 18837 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18838 StorageManager.FLAG_STORAGE_DE, 0); 18839 } catch (InstallerException e2) { 18840 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18841 } 18842 } 18843 } 18844 } 18845 18846 // Ensure that data directories are ready to roll for all packages 18847 // installed for this volume and user 18848 final List<PackageSetting> packages; 18849 synchronized (mPackages) { 18850 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18851 } 18852 int preparedCount = 0; 18853 for (PackageSetting ps : packages) { 18854 final String packageName = ps.name; 18855 if (ps.pkg == null) { 18856 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18857 // TODO: might be due to legacy ASEC apps; we should circle back 18858 // and reconcile again once they're scanned 18859 continue; 18860 } 18861 18862 if (ps.getInstalled(userId)) { 18863 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18864 18865 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18866 // We may have just shuffled around app data directories, so 18867 // prepare them one more time 18868 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18869 } 18870 18871 preparedCount++; 18872 } 18873 } 18874 18875 if (restoreconNeeded) { 18876 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18877 SELinuxMMAC.setRestoreconDone(ceDir); 18878 } 18879 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18880 SELinuxMMAC.setRestoreconDone(deDir); 18881 } 18882 } 18883 18884 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18885 + " packages; restoreconNeeded was " + restoreconNeeded); 18886 } 18887 18888 /** 18889 * Prepare app data for the given app just after it was installed or 18890 * upgraded. This method carefully only touches users that it's installed 18891 * for, and it forces a restorecon to handle any seinfo changes. 18892 * <p> 18893 * Verifies that directories exist and that ownership and labeling is 18894 * correct for all installed apps. If there is an ownership mismatch, it 18895 * will try recovering system apps by wiping data; third-party app data is 18896 * left intact. 18897 * <p> 18898 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18899 */ 18900 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18901 final PackageSetting ps; 18902 synchronized (mPackages) { 18903 ps = mSettings.mPackages.get(pkg.packageName); 18904 mSettings.writeKernelMappingLPr(ps); 18905 } 18906 18907 final UserManager um = mContext.getSystemService(UserManager.class); 18908 for (UserInfo user : um.getUsers()) { 18909 final int flags; 18910 if (um.isUserUnlocked(user.id)) { 18911 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18912 } else if (um.isUserRunning(user.id)) { 18913 flags = StorageManager.FLAG_STORAGE_DE; 18914 } else { 18915 continue; 18916 } 18917 18918 if (ps.getInstalled(user.id)) { 18919 // Whenever an app changes, force a restorecon of its data 18920 // TODO: when user data is locked, mark that we're still dirty 18921 prepareAppDataLIF(pkg, user.id, flags, true); 18922 } 18923 } 18924 } 18925 18926 /** 18927 * Prepare app data for the given app. 18928 * <p> 18929 * Verifies that directories exist and that ownership and labeling is 18930 * correct for all installed apps. If there is an ownership mismatch, this 18931 * will try recovering system apps by wiping data; third-party app data is 18932 * left intact. 18933 */ 18934 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 18935 boolean restoreconNeeded) { 18936 if (pkg == null) { 18937 Slog.wtf(TAG, "Package was null!", new Throwable()); 18938 return; 18939 } 18940 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 18941 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18942 for (int i = 0; i < childCount; i++) { 18943 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 18944 } 18945 } 18946 18947 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 18948 boolean restoreconNeeded) { 18949 if (DEBUG_APP_DATA) { 18950 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18951 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18952 } 18953 18954 final String volumeUuid = pkg.volumeUuid; 18955 final String packageName = pkg.packageName; 18956 final ApplicationInfo app = pkg.applicationInfo; 18957 final int appId = UserHandle.getAppId(app.uid); 18958 18959 Preconditions.checkNotNull(app.seinfo); 18960 18961 try { 18962 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18963 appId, app.seinfo, app.targetSdkVersion); 18964 } catch (InstallerException e) { 18965 if (app.isSystemApp()) { 18966 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18967 + ", but trying to recover: " + e); 18968 destroyAppDataLeafLIF(pkg, userId, flags); 18969 try { 18970 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18971 appId, app.seinfo, app.targetSdkVersion); 18972 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18973 } catch (InstallerException e2) { 18974 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18975 } 18976 } else { 18977 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18978 } 18979 } 18980 18981 if (restoreconNeeded) { 18982 try { 18983 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 18984 app.seinfo); 18985 } catch (InstallerException e) { 18986 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 18987 } 18988 } 18989 18990 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18991 try { 18992 // CE storage is unlocked right now, so read out the inode and 18993 // remember for use later when it's locked 18994 // TODO: mark this structure as dirty so we persist it! 18995 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 18996 StorageManager.FLAG_STORAGE_CE); 18997 synchronized (mPackages) { 18998 final PackageSetting ps = mSettings.mPackages.get(packageName); 18999 if (ps != null) { 19000 ps.setCeDataInode(ceDataInode, userId); 19001 } 19002 } 19003 } catch (InstallerException e) { 19004 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19005 } 19006 } 19007 19008 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19009 } 19010 19011 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19012 if (pkg == null) { 19013 Slog.wtf(TAG, "Package was null!", new Throwable()); 19014 return; 19015 } 19016 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19017 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19018 for (int i = 0; i < childCount; i++) { 19019 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19020 } 19021 } 19022 19023 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19024 final String volumeUuid = pkg.volumeUuid; 19025 final String packageName = pkg.packageName; 19026 final ApplicationInfo app = pkg.applicationInfo; 19027 19028 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19029 // Create a native library symlink only if we have native libraries 19030 // and if the native libraries are 32 bit libraries. We do not provide 19031 // this symlink for 64 bit libraries. 19032 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19033 final String nativeLibPath = app.nativeLibraryDir; 19034 try { 19035 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19036 nativeLibPath, userId); 19037 } catch (InstallerException e) { 19038 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19039 } 19040 } 19041 } 19042 } 19043 19044 /** 19045 * For system apps on non-FBE devices, this method migrates any existing 19046 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19047 * requested by the app. 19048 */ 19049 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19050 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19051 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19052 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19053 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19054 try { 19055 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19056 storageTarget); 19057 } catch (InstallerException e) { 19058 logCriticalInfo(Log.WARN, 19059 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19060 } 19061 return true; 19062 } else { 19063 return false; 19064 } 19065 } 19066 19067 public PackageFreezer freezePackage(String packageName, String killReason) { 19068 return new PackageFreezer(packageName, killReason); 19069 } 19070 19071 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19072 String killReason) { 19073 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19074 return new PackageFreezer(); 19075 } else { 19076 return freezePackage(packageName, killReason); 19077 } 19078 } 19079 19080 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19081 String killReason) { 19082 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19083 return new PackageFreezer(); 19084 } else { 19085 return freezePackage(packageName, killReason); 19086 } 19087 } 19088 19089 /** 19090 * Class that freezes and kills the given package upon creation, and 19091 * unfreezes it upon closing. This is typically used when doing surgery on 19092 * app code/data to prevent the app from running while you're working. 19093 */ 19094 private class PackageFreezer implements AutoCloseable { 19095 private final String mPackageName; 19096 private final PackageFreezer[] mChildren; 19097 19098 private final boolean mWeFroze; 19099 19100 private final AtomicBoolean mClosed = new AtomicBoolean(); 19101 private final CloseGuard mCloseGuard = CloseGuard.get(); 19102 19103 /** 19104 * Create and return a stub freezer that doesn't actually do anything, 19105 * typically used when someone requested 19106 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19107 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19108 */ 19109 public PackageFreezer() { 19110 mPackageName = null; 19111 mChildren = null; 19112 mWeFroze = false; 19113 mCloseGuard.open("close"); 19114 } 19115 19116 public PackageFreezer(String packageName, String killReason) { 19117 synchronized (mPackages) { 19118 mPackageName = packageName; 19119 mWeFroze = mFrozenPackages.add(mPackageName); 19120 19121 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19122 if (ps != null) { 19123 killApplication(ps.name, ps.appId, killReason); 19124 } 19125 19126 final PackageParser.Package p = mPackages.get(packageName); 19127 if (p != null && p.childPackages != null) { 19128 final int N = p.childPackages.size(); 19129 mChildren = new PackageFreezer[N]; 19130 for (int i = 0; i < N; i++) { 19131 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19132 killReason); 19133 } 19134 } else { 19135 mChildren = null; 19136 } 19137 } 19138 mCloseGuard.open("close"); 19139 } 19140 19141 @Override 19142 protected void finalize() throws Throwable { 19143 try { 19144 mCloseGuard.warnIfOpen(); 19145 close(); 19146 } finally { 19147 super.finalize(); 19148 } 19149 } 19150 19151 @Override 19152 public void close() { 19153 mCloseGuard.close(); 19154 if (mClosed.compareAndSet(false, true)) { 19155 synchronized (mPackages) { 19156 if (mWeFroze) { 19157 mFrozenPackages.remove(mPackageName); 19158 } 19159 19160 if (mChildren != null) { 19161 for (PackageFreezer freezer : mChildren) { 19162 freezer.close(); 19163 } 19164 } 19165 } 19166 } 19167 } 19168 } 19169 19170 /** 19171 * Verify that given package is currently frozen. 19172 */ 19173 private void checkPackageFrozen(String packageName) { 19174 synchronized (mPackages) { 19175 if (!mFrozenPackages.contains(packageName)) { 19176 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19177 } 19178 } 19179 } 19180 19181 @Override 19182 public int movePackage(final String packageName, final String volumeUuid) { 19183 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19184 19185 final int moveId = mNextMoveId.getAndIncrement(); 19186 mHandler.post(new Runnable() { 19187 @Override 19188 public void run() { 19189 try { 19190 movePackageInternal(packageName, volumeUuid, moveId); 19191 } catch (PackageManagerException e) { 19192 Slog.w(TAG, "Failed to move " + packageName, e); 19193 mMoveCallbacks.notifyStatusChanged(moveId, 19194 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19195 } 19196 } 19197 }); 19198 return moveId; 19199 } 19200 19201 private void movePackageInternal(final String packageName, final String volumeUuid, 19202 final int moveId) throws PackageManagerException { 19203 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19204 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19205 final PackageManager pm = mContext.getPackageManager(); 19206 19207 final boolean currentAsec; 19208 final String currentVolumeUuid; 19209 final File codeFile; 19210 final String installerPackageName; 19211 final String packageAbiOverride; 19212 final int appId; 19213 final String seinfo; 19214 final String label; 19215 final int targetSdkVersion; 19216 final PackageFreezer freezer; 19217 19218 // reader 19219 synchronized (mPackages) { 19220 final PackageParser.Package pkg = mPackages.get(packageName); 19221 final PackageSetting ps = mSettings.mPackages.get(packageName); 19222 if (pkg == null || ps == null) { 19223 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19224 } 19225 19226 if (pkg.applicationInfo.isSystemApp()) { 19227 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19228 "Cannot move system application"); 19229 } 19230 19231 if (pkg.applicationInfo.isExternalAsec()) { 19232 currentAsec = true; 19233 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19234 } else if (pkg.applicationInfo.isForwardLocked()) { 19235 currentAsec = true; 19236 currentVolumeUuid = "forward_locked"; 19237 } else { 19238 currentAsec = false; 19239 currentVolumeUuid = ps.volumeUuid; 19240 19241 final File probe = new File(pkg.codePath); 19242 final File probeOat = new File(probe, "oat"); 19243 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19244 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19245 "Move only supported for modern cluster style installs"); 19246 } 19247 } 19248 19249 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19250 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19251 "Package already moved to " + volumeUuid); 19252 } 19253 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19254 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19255 "Device admin cannot be moved"); 19256 } 19257 19258 if (mFrozenPackages.contains(packageName)) { 19259 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19260 "Failed to move already frozen package"); 19261 } 19262 19263 codeFile = new File(pkg.codePath); 19264 installerPackageName = ps.installerPackageName; 19265 packageAbiOverride = ps.cpuAbiOverrideString; 19266 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19267 seinfo = pkg.applicationInfo.seinfo; 19268 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19269 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19270 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19271 } 19272 19273 final Bundle extras = new Bundle(); 19274 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19275 extras.putString(Intent.EXTRA_TITLE, label); 19276 mMoveCallbacks.notifyCreated(moveId, extras); 19277 19278 int installFlags; 19279 final boolean moveCompleteApp; 19280 final File measurePath; 19281 19282 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19283 installFlags = INSTALL_INTERNAL; 19284 moveCompleteApp = !currentAsec; 19285 measurePath = Environment.getDataAppDirectory(volumeUuid); 19286 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19287 installFlags = INSTALL_EXTERNAL; 19288 moveCompleteApp = false; 19289 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19290 } else { 19291 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19292 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19293 || !volume.isMountedWritable()) { 19294 freezer.close(); 19295 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19296 "Move location not mounted private volume"); 19297 } 19298 19299 Preconditions.checkState(!currentAsec); 19300 19301 installFlags = INSTALL_INTERNAL; 19302 moveCompleteApp = true; 19303 measurePath = Environment.getDataAppDirectory(volumeUuid); 19304 } 19305 19306 final PackageStats stats = new PackageStats(null, -1); 19307 synchronized (mInstaller) { 19308 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19309 freezer.close(); 19310 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19311 "Failed to measure package size"); 19312 } 19313 } 19314 19315 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19316 + stats.dataSize); 19317 19318 final long startFreeBytes = measurePath.getFreeSpace(); 19319 final long sizeBytes; 19320 if (moveCompleteApp) { 19321 sizeBytes = stats.codeSize + stats.dataSize; 19322 } else { 19323 sizeBytes = stats.codeSize; 19324 } 19325 19326 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19327 freezer.close(); 19328 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19329 "Not enough free space to move"); 19330 } 19331 19332 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19333 19334 final CountDownLatch installedLatch = new CountDownLatch(1); 19335 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19336 @Override 19337 public void onUserActionRequired(Intent intent) throws RemoteException { 19338 throw new IllegalStateException(); 19339 } 19340 19341 @Override 19342 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19343 Bundle extras) throws RemoteException { 19344 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19345 + PackageManager.installStatusToString(returnCode, msg)); 19346 19347 installedLatch.countDown(); 19348 freezer.close(); 19349 19350 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19351 switch (status) { 19352 case PackageInstaller.STATUS_SUCCESS: 19353 mMoveCallbacks.notifyStatusChanged(moveId, 19354 PackageManager.MOVE_SUCCEEDED); 19355 break; 19356 case PackageInstaller.STATUS_FAILURE_STORAGE: 19357 mMoveCallbacks.notifyStatusChanged(moveId, 19358 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19359 break; 19360 default: 19361 mMoveCallbacks.notifyStatusChanged(moveId, 19362 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19363 break; 19364 } 19365 } 19366 }; 19367 19368 final MoveInfo move; 19369 if (moveCompleteApp) { 19370 // Kick off a thread to report progress estimates 19371 new Thread() { 19372 @Override 19373 public void run() { 19374 while (true) { 19375 try { 19376 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19377 break; 19378 } 19379 } catch (InterruptedException ignored) { 19380 } 19381 19382 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19383 final int progress = 10 + (int) MathUtils.constrain( 19384 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19385 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19386 } 19387 } 19388 }.start(); 19389 19390 final String dataAppName = codeFile.getName(); 19391 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19392 dataAppName, appId, seinfo, targetSdkVersion); 19393 } else { 19394 move = null; 19395 } 19396 19397 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19398 19399 final Message msg = mHandler.obtainMessage(INIT_COPY); 19400 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19401 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19402 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19403 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19404 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19405 msg.obj = params; 19406 19407 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19408 System.identityHashCode(msg.obj)); 19409 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19410 System.identityHashCode(msg.obj)); 19411 19412 mHandler.sendMessage(msg); 19413 } 19414 19415 @Override 19416 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19417 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19418 19419 final int realMoveId = mNextMoveId.getAndIncrement(); 19420 final Bundle extras = new Bundle(); 19421 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19422 mMoveCallbacks.notifyCreated(realMoveId, extras); 19423 19424 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19425 @Override 19426 public void onCreated(int moveId, Bundle extras) { 19427 // Ignored 19428 } 19429 19430 @Override 19431 public void onStatusChanged(int moveId, int status, long estMillis) { 19432 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19433 } 19434 }; 19435 19436 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19437 storage.setPrimaryStorageUuid(volumeUuid, callback); 19438 return realMoveId; 19439 } 19440 19441 @Override 19442 public int getMoveStatus(int moveId) { 19443 mContext.enforceCallingOrSelfPermission( 19444 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19445 return mMoveCallbacks.mLastStatus.get(moveId); 19446 } 19447 19448 @Override 19449 public void registerMoveCallback(IPackageMoveObserver callback) { 19450 mContext.enforceCallingOrSelfPermission( 19451 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19452 mMoveCallbacks.register(callback); 19453 } 19454 19455 @Override 19456 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19457 mContext.enforceCallingOrSelfPermission( 19458 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19459 mMoveCallbacks.unregister(callback); 19460 } 19461 19462 @Override 19463 public boolean setInstallLocation(int loc) { 19464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19465 null); 19466 if (getInstallLocation() == loc) { 19467 return true; 19468 } 19469 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19470 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19471 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19472 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19473 return true; 19474 } 19475 return false; 19476 } 19477 19478 @Override 19479 public int getInstallLocation() { 19480 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19481 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19482 PackageHelper.APP_INSTALL_AUTO); 19483 } 19484 19485 /** Called by UserManagerService */ 19486 void cleanUpUser(UserManagerService userManager, int userHandle) { 19487 synchronized (mPackages) { 19488 mDirtyUsers.remove(userHandle); 19489 mUserNeedsBadging.delete(userHandle); 19490 mSettings.removeUserLPw(userHandle); 19491 mPendingBroadcasts.remove(userHandle); 19492 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19493 } 19494 synchronized (mInstallLock) { 19495 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19496 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19497 final String volumeUuid = vol.getFsUuid(); 19498 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19499 try { 19500 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19501 } catch (InstallerException e) { 19502 Slog.w(TAG, "Failed to remove user data", e); 19503 } 19504 } 19505 synchronized (mPackages) { 19506 removeUnusedPackagesLILPw(userManager, userHandle); 19507 } 19508 } 19509 } 19510 19511 /** 19512 * We're removing userHandle and would like to remove any downloaded packages 19513 * that are no longer in use by any other user. 19514 * @param userHandle the user being removed 19515 */ 19516 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19517 final boolean DEBUG_CLEAN_APKS = false; 19518 int [] users = userManager.getUserIds(); 19519 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19520 while (psit.hasNext()) { 19521 PackageSetting ps = psit.next(); 19522 if (ps.pkg == null) { 19523 continue; 19524 } 19525 final String packageName = ps.pkg.packageName; 19526 // Skip over if system app 19527 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19528 continue; 19529 } 19530 if (DEBUG_CLEAN_APKS) { 19531 Slog.i(TAG, "Checking package " + packageName); 19532 } 19533 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19534 if (keep) { 19535 if (DEBUG_CLEAN_APKS) { 19536 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19537 } 19538 } else { 19539 for (int i = 0; i < users.length; i++) { 19540 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19541 keep = true; 19542 if (DEBUG_CLEAN_APKS) { 19543 Slog.i(TAG, " Keeping package " + packageName + " for user " 19544 + users[i]); 19545 } 19546 break; 19547 } 19548 } 19549 } 19550 if (!keep) { 19551 if (DEBUG_CLEAN_APKS) { 19552 Slog.i(TAG, " Removing package " + packageName); 19553 } 19554 mHandler.post(new Runnable() { 19555 public void run() { 19556 deletePackageX(packageName, userHandle, 0); 19557 } //end run 19558 }); 19559 } 19560 } 19561 } 19562 19563 /** Called by UserManagerService */ 19564 void createNewUser(int userHandle) { 19565 synchronized (mInstallLock) { 19566 try { 19567 mInstaller.createUserConfig(userHandle); 19568 } catch (InstallerException e) { 19569 Slog.w(TAG, "Failed to create user config", e); 19570 } 19571 mSettings.createNewUserLI(this, mInstaller, userHandle); 19572 } 19573 synchronized (mPackages) { 19574 applyFactoryDefaultBrowserLPw(userHandle); 19575 primeDomainVerificationsLPw(userHandle); 19576 } 19577 } 19578 19579 void newUserCreated(final int userHandle) { 19580 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19581 // If permission review for legacy apps is required, we represent 19582 // dagerous permissions for such apps as always granted runtime 19583 // permissions to keep per user flag state whether review is needed. 19584 // Hence, if a new user is added we have to propagate dangerous 19585 // permission grants for these legacy apps. 19586 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19587 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19588 | UPDATE_PERMISSIONS_REPLACE_ALL); 19589 } 19590 } 19591 19592 @Override 19593 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19594 mContext.enforceCallingOrSelfPermission( 19595 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19596 "Only package verification agents can read the verifier device identity"); 19597 19598 synchronized (mPackages) { 19599 return mSettings.getVerifierDeviceIdentityLPw(); 19600 } 19601 } 19602 19603 @Override 19604 public void setPermissionEnforced(String permission, boolean enforced) { 19605 // TODO: Now that we no longer change GID for storage, this should to away. 19606 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19607 "setPermissionEnforced"); 19608 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19609 synchronized (mPackages) { 19610 if (mSettings.mReadExternalStorageEnforced == null 19611 || mSettings.mReadExternalStorageEnforced != enforced) { 19612 mSettings.mReadExternalStorageEnforced = enforced; 19613 mSettings.writeLPr(); 19614 } 19615 } 19616 // kill any non-foreground processes so we restart them and 19617 // grant/revoke the GID. 19618 final IActivityManager am = ActivityManagerNative.getDefault(); 19619 if (am != null) { 19620 final long token = Binder.clearCallingIdentity(); 19621 try { 19622 am.killProcessesBelowForeground("setPermissionEnforcement"); 19623 } catch (RemoteException e) { 19624 } finally { 19625 Binder.restoreCallingIdentity(token); 19626 } 19627 } 19628 } else { 19629 throw new IllegalArgumentException("No selective enforcement for " + permission); 19630 } 19631 } 19632 19633 @Override 19634 @Deprecated 19635 public boolean isPermissionEnforced(String permission) { 19636 return true; 19637 } 19638 19639 @Override 19640 public boolean isStorageLow() { 19641 final long token = Binder.clearCallingIdentity(); 19642 try { 19643 final DeviceStorageMonitorInternal 19644 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19645 if (dsm != null) { 19646 return dsm.isMemoryLow(); 19647 } else { 19648 return false; 19649 } 19650 } finally { 19651 Binder.restoreCallingIdentity(token); 19652 } 19653 } 19654 19655 @Override 19656 public IPackageInstaller getPackageInstaller() { 19657 return mInstallerService; 19658 } 19659 19660 private boolean userNeedsBadging(int userId) { 19661 int index = mUserNeedsBadging.indexOfKey(userId); 19662 if (index < 0) { 19663 final UserInfo userInfo; 19664 final long token = Binder.clearCallingIdentity(); 19665 try { 19666 userInfo = sUserManager.getUserInfo(userId); 19667 } finally { 19668 Binder.restoreCallingIdentity(token); 19669 } 19670 final boolean b; 19671 if (userInfo != null && userInfo.isManagedProfile()) { 19672 b = true; 19673 } else { 19674 b = false; 19675 } 19676 mUserNeedsBadging.put(userId, b); 19677 return b; 19678 } 19679 return mUserNeedsBadging.valueAt(index); 19680 } 19681 19682 @Override 19683 public KeySet getKeySetByAlias(String packageName, String alias) { 19684 if (packageName == null || alias == null) { 19685 return null; 19686 } 19687 synchronized(mPackages) { 19688 final PackageParser.Package pkg = mPackages.get(packageName); 19689 if (pkg == null) { 19690 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19691 throw new IllegalArgumentException("Unknown package: " + packageName); 19692 } 19693 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19694 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19695 } 19696 } 19697 19698 @Override 19699 public KeySet getSigningKeySet(String packageName) { 19700 if (packageName == null) { 19701 return null; 19702 } 19703 synchronized(mPackages) { 19704 final PackageParser.Package pkg = mPackages.get(packageName); 19705 if (pkg == null) { 19706 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19707 throw new IllegalArgumentException("Unknown package: " + packageName); 19708 } 19709 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19710 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19711 throw new SecurityException("May not access signing KeySet of other apps."); 19712 } 19713 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19714 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19715 } 19716 } 19717 19718 @Override 19719 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19720 if (packageName == null || ks == null) { 19721 return false; 19722 } 19723 synchronized(mPackages) { 19724 final PackageParser.Package pkg = mPackages.get(packageName); 19725 if (pkg == null) { 19726 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19727 throw new IllegalArgumentException("Unknown package: " + packageName); 19728 } 19729 IBinder ksh = ks.getToken(); 19730 if (ksh instanceof KeySetHandle) { 19731 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19732 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19733 } 19734 return false; 19735 } 19736 } 19737 19738 @Override 19739 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19740 if (packageName == null || ks == null) { 19741 return false; 19742 } 19743 synchronized(mPackages) { 19744 final PackageParser.Package pkg = mPackages.get(packageName); 19745 if (pkg == null) { 19746 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19747 throw new IllegalArgumentException("Unknown package: " + packageName); 19748 } 19749 IBinder ksh = ks.getToken(); 19750 if (ksh instanceof KeySetHandle) { 19751 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19752 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19753 } 19754 return false; 19755 } 19756 } 19757 19758 private void deletePackageIfUnusedLPr(final String packageName) { 19759 PackageSetting ps = mSettings.mPackages.get(packageName); 19760 if (ps == null) { 19761 return; 19762 } 19763 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19764 // TODO Implement atomic delete if package is unused 19765 // It is currently possible that the package will be deleted even if it is installed 19766 // after this method returns. 19767 mHandler.post(new Runnable() { 19768 public void run() { 19769 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19770 } 19771 }); 19772 } 19773 } 19774 19775 /** 19776 * Check and throw if the given before/after packages would be considered a 19777 * downgrade. 19778 */ 19779 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19780 throws PackageManagerException { 19781 if (after.versionCode < before.mVersionCode) { 19782 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19783 "Update version code " + after.versionCode + " is older than current " 19784 + before.mVersionCode); 19785 } else if (after.versionCode == before.mVersionCode) { 19786 if (after.baseRevisionCode < before.baseRevisionCode) { 19787 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19788 "Update base revision code " + after.baseRevisionCode 19789 + " is older than current " + before.baseRevisionCode); 19790 } 19791 19792 if (!ArrayUtils.isEmpty(after.splitNames)) { 19793 for (int i = 0; i < after.splitNames.length; i++) { 19794 final String splitName = after.splitNames[i]; 19795 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19796 if (j != -1) { 19797 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19798 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19799 "Update split " + splitName + " revision code " 19800 + after.splitRevisionCodes[i] + " is older than current " 19801 + before.splitRevisionCodes[j]); 19802 } 19803 } 19804 } 19805 } 19806 } 19807 } 19808 19809 private static class MoveCallbacks extends Handler { 19810 private static final int MSG_CREATED = 1; 19811 private static final int MSG_STATUS_CHANGED = 2; 19812 19813 private final RemoteCallbackList<IPackageMoveObserver> 19814 mCallbacks = new RemoteCallbackList<>(); 19815 19816 private final SparseIntArray mLastStatus = new SparseIntArray(); 19817 19818 public MoveCallbacks(Looper looper) { 19819 super(looper); 19820 } 19821 19822 public void register(IPackageMoveObserver callback) { 19823 mCallbacks.register(callback); 19824 } 19825 19826 public void unregister(IPackageMoveObserver callback) { 19827 mCallbacks.unregister(callback); 19828 } 19829 19830 @Override 19831 public void handleMessage(Message msg) { 19832 final SomeArgs args = (SomeArgs) msg.obj; 19833 final int n = mCallbacks.beginBroadcast(); 19834 for (int i = 0; i < n; i++) { 19835 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19836 try { 19837 invokeCallback(callback, msg.what, args); 19838 } catch (RemoteException ignored) { 19839 } 19840 } 19841 mCallbacks.finishBroadcast(); 19842 args.recycle(); 19843 } 19844 19845 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19846 throws RemoteException { 19847 switch (what) { 19848 case MSG_CREATED: { 19849 callback.onCreated(args.argi1, (Bundle) args.arg2); 19850 break; 19851 } 19852 case MSG_STATUS_CHANGED: { 19853 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19854 break; 19855 } 19856 } 19857 } 19858 19859 private void notifyCreated(int moveId, Bundle extras) { 19860 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19861 19862 final SomeArgs args = SomeArgs.obtain(); 19863 args.argi1 = moveId; 19864 args.arg2 = extras; 19865 obtainMessage(MSG_CREATED, args).sendToTarget(); 19866 } 19867 19868 private void notifyStatusChanged(int moveId, int status) { 19869 notifyStatusChanged(moveId, status, -1); 19870 } 19871 19872 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19873 Slog.v(TAG, "Move " + moveId + " status " + status); 19874 19875 final SomeArgs args = SomeArgs.obtain(); 19876 args.argi1 = moveId; 19877 args.argi2 = status; 19878 args.arg3 = estMillis; 19879 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19880 19881 synchronized (mLastStatus) { 19882 mLastStatus.put(moveId, status); 19883 } 19884 } 19885 } 19886 19887 private final static class OnPermissionChangeListeners extends Handler { 19888 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19889 19890 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19891 new RemoteCallbackList<>(); 19892 19893 public OnPermissionChangeListeners(Looper looper) { 19894 super(looper); 19895 } 19896 19897 @Override 19898 public void handleMessage(Message msg) { 19899 switch (msg.what) { 19900 case MSG_ON_PERMISSIONS_CHANGED: { 19901 final int uid = msg.arg1; 19902 handleOnPermissionsChanged(uid); 19903 } break; 19904 } 19905 } 19906 19907 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19908 mPermissionListeners.register(listener); 19909 19910 } 19911 19912 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19913 mPermissionListeners.unregister(listener); 19914 } 19915 19916 public void onPermissionsChanged(int uid) { 19917 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19918 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19919 } 19920 } 19921 19922 private void handleOnPermissionsChanged(int uid) { 19923 final int count = mPermissionListeners.beginBroadcast(); 19924 try { 19925 for (int i = 0; i < count; i++) { 19926 IOnPermissionsChangeListener callback = mPermissionListeners 19927 .getBroadcastItem(i); 19928 try { 19929 callback.onPermissionsChanged(uid); 19930 } catch (RemoteException e) { 19931 Log.e(TAG, "Permission listener is dead", e); 19932 } 19933 } 19934 } finally { 19935 mPermissionListeners.finishBroadcast(); 19936 } 19937 } 19938 } 19939 19940 private class PackageManagerInternalImpl extends PackageManagerInternal { 19941 @Override 19942 public void setLocationPackagesProvider(PackagesProvider provider) { 19943 synchronized (mPackages) { 19944 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19945 } 19946 } 19947 19948 @Override 19949 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19950 synchronized (mPackages) { 19951 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19952 } 19953 } 19954 19955 @Override 19956 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19957 synchronized (mPackages) { 19958 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19959 } 19960 } 19961 19962 @Override 19963 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19964 synchronized (mPackages) { 19965 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19966 } 19967 } 19968 19969 @Override 19970 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19971 synchronized (mPackages) { 19972 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19973 } 19974 } 19975 19976 @Override 19977 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19978 synchronized (mPackages) { 19979 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19980 } 19981 } 19982 19983 @Override 19984 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19985 synchronized (mPackages) { 19986 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19987 packageName, userId); 19988 } 19989 } 19990 19991 @Override 19992 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19993 synchronized (mPackages) { 19994 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19995 packageName, userId); 19996 } 19997 } 19998 19999 @Override 20000 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20001 synchronized (mPackages) { 20002 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20003 packageName, userId); 20004 } 20005 } 20006 20007 @Override 20008 public void setKeepUninstalledPackages(final List<String> packageList) { 20009 Preconditions.checkNotNull(packageList); 20010 List<String> removedFromList = null; 20011 synchronized (mPackages) { 20012 if (mKeepUninstalledPackages != null) { 20013 final int packagesCount = mKeepUninstalledPackages.size(); 20014 for (int i = 0; i < packagesCount; i++) { 20015 String oldPackage = mKeepUninstalledPackages.get(i); 20016 if (packageList != null && packageList.contains(oldPackage)) { 20017 continue; 20018 } 20019 if (removedFromList == null) { 20020 removedFromList = new ArrayList<>(); 20021 } 20022 removedFromList.add(oldPackage); 20023 } 20024 } 20025 mKeepUninstalledPackages = new ArrayList<>(packageList); 20026 if (removedFromList != null) { 20027 final int removedCount = removedFromList.size(); 20028 for (int i = 0; i < removedCount; i++) { 20029 deletePackageIfUnusedLPr(removedFromList.get(i)); 20030 } 20031 } 20032 } 20033 } 20034 20035 @Override 20036 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20037 synchronized (mPackages) { 20038 // If we do not support permission review, done. 20039 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20040 return false; 20041 } 20042 20043 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20044 if (packageSetting == null) { 20045 return false; 20046 } 20047 20048 // Permission review applies only to apps not supporting the new permission model. 20049 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20050 return false; 20051 } 20052 20053 // Legacy apps have the permission and get user consent on launch. 20054 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20055 return permissionsState.isPermissionReviewRequired(userId); 20056 } 20057 } 20058 20059 @Override 20060 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20061 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20062 } 20063 20064 @Override 20065 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20066 int userId) { 20067 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20068 } 20069 } 20070 20071 @Override 20072 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20073 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20074 synchronized (mPackages) { 20075 final long identity = Binder.clearCallingIdentity(); 20076 try { 20077 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20078 packageNames, userId); 20079 } finally { 20080 Binder.restoreCallingIdentity(identity); 20081 } 20082 } 20083 } 20084 20085 private static void enforceSystemOrPhoneCaller(String tag) { 20086 int callingUid = Binder.getCallingUid(); 20087 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20088 throw new SecurityException( 20089 "Cannot call " + tag + " from UID " + callingUid); 20090 } 20091 } 20092 20093 boolean isHistoricalPackageUsageAvailable() { 20094 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20095 } 20096 20097 /** 20098 * Return a <b>copy</b> of the collection of packages known to the package manager. 20099 * @return A copy of the values of mPackages. 20100 */ 20101 Collection<PackageParser.Package> getPackages() { 20102 synchronized (mPackages) { 20103 return new ArrayList<>(mPackages.values()); 20104 } 20105 } 20106 20107 /** 20108 * Logs process start information (including base APK hash) to the security log. 20109 * @hide 20110 */ 20111 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20112 String apkFile, int pid) { 20113 if (!SecurityLog.isLoggingEnabled()) { 20114 return; 20115 } 20116 Bundle data = new Bundle(); 20117 data.putLong("startTimestamp", System.currentTimeMillis()); 20118 data.putString("processName", processName); 20119 data.putInt("uid", uid); 20120 data.putString("seinfo", seinfo); 20121 data.putString("apkFile", apkFile); 20122 data.putInt("pid", pid); 20123 Message msg = mProcessLoggingHandler.obtainMessage( 20124 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20125 msg.setData(data); 20126 mProcessLoggingHandler.sendMessage(msg); 20127 } 20128} 20129