PackageManagerService.java revision a7b826b08aa1b185b0e46b648e5c2ed7f818ae09
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.UserManagerInternal; 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.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.logging.MetricsLogger; 230import com.android.internal.os.IParcelFileDescriptorFactory; 231import com.android.internal.os.InstallerConnection.InstallerException; 232import com.android.internal.os.SomeArgs; 233import com.android.internal.os.Zygote; 234import com.android.internal.telephony.CarrierAppUtils; 235import com.android.internal.util.ArrayUtils; 236import com.android.internal.util.FastPrintWriter; 237import com.android.internal.util.FastXmlSerializer; 238import com.android.internal.util.IndentingPrintWriter; 239import com.android.internal.util.Preconditions; 240import com.android.internal.util.XmlUtils; 241import com.android.server.EventLogTags; 242import com.android.server.FgThread; 243import com.android.server.IntentResolver; 244import com.android.server.LocalServices; 245import com.android.server.ServiceThread; 246import com.android.server.SystemConfig; 247import com.android.server.Watchdog; 248import com.android.server.net.NetworkPolicyManagerInternal; 249import com.android.server.pm.PermissionsState.PermissionState; 250import com.android.server.pm.Settings.DatabaseVersion; 251import com.android.server.pm.Settings.VersionInfo; 252import com.android.server.storage.DeviceStorageMonitorInternal; 253 254import dalvik.system.CloseGuard; 255import dalvik.system.DexFile; 256import dalvik.system.VMRuntime; 257 258import libcore.io.IoUtils; 259import libcore.util.EmptyArray; 260 261import org.xmlpull.v1.XmlPullParser; 262import org.xmlpull.v1.XmlPullParserException; 263import org.xmlpull.v1.XmlSerializer; 264 265import java.io.BufferedInputStream; 266import java.io.BufferedOutputStream; 267import java.io.BufferedReader; 268import java.io.ByteArrayInputStream; 269import java.io.ByteArrayOutputStream; 270import java.io.File; 271import java.io.FileDescriptor; 272import java.io.FileInputStream; 273import java.io.FileNotFoundException; 274import java.io.FileOutputStream; 275import java.io.FileReader; 276import java.io.FilenameFilter; 277import java.io.IOException; 278import java.io.InputStream; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305import java.util.concurrent.atomic.AtomicLong; 306 307/** 308 * Keep track of all those APKs everywhere. 309 * <p> 310 * Internally there are two important locks: 311 * <ul> 312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 313 * and other related state. It is a fine-grained lock that should only be held 314 * momentarily, as it's one of the most contended locks in the system. 315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 316 * operations typically involve heavy lifting of application data on disk. Since 317 * {@code installd} is single-threaded, and it's operations can often be slow, 318 * this lock should never be acquired while already holding {@link #mPackages}. 319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 320 * holding {@link #mInstallLock}. 321 * </ul> 322 * Many internal methods rely on the caller to hold the appropriate locks, and 323 * this contract is expressed through method name suffixes: 324 * <ul> 325 * <li>fooLI(): the caller must hold {@link #mInstallLock} 326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 327 * being modified must be frozen 328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 330 * </ul> 331 * <p> 332 * Because this class is very central to the platform's security; please run all 333 * CTS and unit tests whenever making modifications: 334 * 335 * <pre> 336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 338 * </pre> 339 */ 340public class PackageManagerService extends IPackageManager.Stub { 341 static final String TAG = "PackageManager"; 342 static final boolean DEBUG_SETTINGS = false; 343 static final boolean DEBUG_PREFERRED = false; 344 static final boolean DEBUG_UPGRADE = false; 345 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 346 private static final boolean DEBUG_BACKUP = false; 347 private static final boolean DEBUG_INSTALL = false; 348 private static final boolean DEBUG_REMOVE = false; 349 private static final boolean DEBUG_BROADCASTS = false; 350 private static final boolean DEBUG_SHOW_INFO = false; 351 private static final boolean DEBUG_PACKAGE_INFO = false; 352 private static final boolean DEBUG_INTENT_MATCHING = false; 353 private static final boolean DEBUG_PACKAGE_SCANNING = false; 354 private static final boolean DEBUG_VERIFY = false; 355 private static final boolean DEBUG_FILTERS = false; 356 357 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 358 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 359 // user, but by default initialize to this. 360 static final boolean DEBUG_DEXOPT = false; 361 362 private static final boolean DEBUG_ABI_SELECTION = false; 363 private static final boolean DEBUG_EPHEMERAL = false; 364 private static final boolean DEBUG_TRIAGED_MISSING = false; 365 private static final boolean DEBUG_APP_DATA = false; 366 367 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 368 369 private static final boolean DISABLE_EPHEMERAL_APPS = true; 370 371 private static final int RADIO_UID = Process.PHONE_UID; 372 private static final int LOG_UID = Process.LOG_UID; 373 private static final int NFC_UID = Process.NFC_UID; 374 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 375 private static final int SHELL_UID = Process.SHELL_UID; 376 377 // Cap the size of permission trees that 3rd party apps can define 378 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 379 380 // Suffix used during package installation when copying/moving 381 // package apks to install directory. 382 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 383 384 static final int SCAN_NO_DEX = 1<<1; 385 static final int SCAN_FORCE_DEX = 1<<2; 386 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 387 static final int SCAN_NEW_INSTALL = 1<<4; 388 static final int SCAN_NO_PATHS = 1<<5; 389 static final int SCAN_UPDATE_TIME = 1<<6; 390 static final int SCAN_DEFER_DEX = 1<<7; 391 static final int SCAN_BOOTING = 1<<8; 392 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 393 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 394 static final int SCAN_REPLACING = 1<<11; 395 static final int SCAN_REQUIRE_KNOWN = 1<<12; 396 static final int SCAN_MOVE = 1<<13; 397 static final int SCAN_INITIAL = 1<<14; 398 static final int SCAN_CHECK_ONLY = 1<<15; 399 static final int SCAN_DONT_KILL_APP = 1<<17; 400 static final int SCAN_IGNORE_FROZEN = 1<<18; 401 402 static final int REMOVE_CHATTY = 1<<16; 403 404 private static final int[] EMPTY_INT_ARRAY = new int[0]; 405 406 /** 407 * Timeout (in milliseconds) after which the watchdog should declare that 408 * our handler thread is wedged. The usual default for such things is one 409 * minute but we sometimes do very lengthy I/O operations on this thread, 410 * such as installing multi-gigabyte applications, so ours needs to be longer. 411 */ 412 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 413 414 /** 415 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 416 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 417 * settings entry if available, otherwise we use the hardcoded default. If it's been 418 * more than this long since the last fstrim, we force one during the boot sequence. 419 * 420 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 421 * one gets run at the next available charging+idle time. This final mandatory 422 * no-fstrim check kicks in only of the other scheduling criteria is never met. 423 */ 424 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 425 426 /** 427 * Whether verification is enabled by default. 428 */ 429 private static final boolean DEFAULT_VERIFY_ENABLE = true; 430 431 /** 432 * The default maximum time to wait for the verification agent to return in 433 * milliseconds. 434 */ 435 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 436 437 /** 438 * The default response for package verification timeout. 439 * 440 * This can be either PackageManager.VERIFICATION_ALLOW or 441 * PackageManager.VERIFICATION_REJECT. 442 */ 443 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 444 445 static final String PLATFORM_PACKAGE_NAME = "android"; 446 447 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 448 449 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 450 DEFAULT_CONTAINER_PACKAGE, 451 "com.android.defcontainer.DefaultContainerService"); 452 453 private static final String KILL_APP_REASON_GIDS_CHANGED = 454 "permission grant or revoke changed gids"; 455 456 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 457 "permissions revoked"; 458 459 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 460 461 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 462 463 /** Permission grant: not grant the permission. */ 464 private static final int GRANT_DENIED = 1; 465 466 /** Permission grant: grant the permission as an install permission. */ 467 private static final int GRANT_INSTALL = 2; 468 469 /** Permission grant: grant the permission as a runtime one. */ 470 private static final int GRANT_RUNTIME = 3; 471 472 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 473 private static final int GRANT_UPGRADE = 4; 474 475 /** Canonical intent used to identify what counts as a "web browser" app */ 476 private static final Intent sBrowserIntent; 477 static { 478 sBrowserIntent = new Intent(); 479 sBrowserIntent.setAction(Intent.ACTION_VIEW); 480 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 481 sBrowserIntent.setData(Uri.parse("http:")); 482 } 483 484 /** 485 * The set of all protected actions [i.e. those actions for which a high priority 486 * intent filter is disallowed]. 487 */ 488 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 489 static { 490 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 493 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 494 } 495 496 // Compilation reasons. 497 public static final int REASON_FIRST_BOOT = 0; 498 public static final int REASON_BOOT = 1; 499 public static final int REASON_INSTALL = 2; 500 public static final int REASON_BACKGROUND_DEXOPT = 3; 501 public static final int REASON_AB_OTA = 4; 502 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 503 public static final int REASON_SHARED_APK = 6; 504 public static final int REASON_FORCED_DEXOPT = 7; 505 506 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 507 508 /** Special library name that skips shared libraries check during compilation. */ 509 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 510 511 final ServiceThread mHandlerThread; 512 513 final PackageHandler mHandler; 514 515 private final ProcessLoggingHandler mProcessLoggingHandler; 516 517 /** 518 * Messages for {@link #mHandler} that need to wait for system ready before 519 * being dispatched. 520 */ 521 private ArrayList<Message> mPostSystemReadyMessages; 522 523 final int mSdkVersion = Build.VERSION.SDK_INT; 524 525 final Context mContext; 526 final boolean mFactoryTest; 527 final boolean mOnlyCore; 528 final DisplayMetrics mMetrics; 529 final int mDefParseFlags; 530 final String[] mSeparateProcesses; 531 final boolean mIsUpgrade; 532 final boolean mIsPreNUpgrade; 533 534 /** The location for ASEC container files on internal storage. */ 535 final String mAsecInternalPath; 536 537 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 538 // LOCK HELD. Can be called with mInstallLock held. 539 @GuardedBy("mInstallLock") 540 final Installer mInstaller; 541 542 /** Directory where installed third-party apps stored */ 543 final File mAppInstallDir; 544 final File mEphemeralInstallDir; 545 546 /** 547 * Directory to which applications installed internally have their 548 * 32 bit native libraries copied. 549 */ 550 private File mAppLib32InstallDir; 551 552 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 553 // apps. 554 final File mDrmAppPrivateInstallDir; 555 556 // ---------------------------------------------------------------- 557 558 // Lock for state used when installing and doing other long running 559 // operations. Methods that must be called with this lock held have 560 // the suffix "LI". 561 final Object mInstallLock = new Object(); 562 563 // ---------------------------------------------------------------- 564 565 // Keys are String (package name), values are Package. This also serves 566 // as the lock for the global state. Methods that must be called with 567 // this lock held have the prefix "LP". 568 @GuardedBy("mPackages") 569 final ArrayMap<String, PackageParser.Package> mPackages = 570 new ArrayMap<String, PackageParser.Package>(); 571 572 final ArrayMap<String, Set<String>> mKnownCodebase = 573 new ArrayMap<String, Set<String>>(); 574 575 // Tracks available target package names -> overlay package paths. 576 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 577 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 578 579 /** 580 * Tracks new system packages [received in an OTA] that we expect to 581 * find updated user-installed versions. Keys are package name, values 582 * are package location. 583 */ 584 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 585 /** 586 * Tracks high priority intent filters for protected actions. During boot, certain 587 * filter actions are protected and should never be allowed to have a high priority 588 * intent filter for them. However, there is one, and only one exception -- the 589 * setup wizard. It must be able to define a high priority intent filter for these 590 * actions to ensure there are no escapes from the wizard. We need to delay processing 591 * of these during boot as we need to look at all of the system packages in order 592 * to know which component is the setup wizard. 593 */ 594 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 595 /** 596 * Whether or not processing protected filters should be deferred. 597 */ 598 private boolean mDeferProtectedFilters = true; 599 600 /** 601 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 602 */ 603 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 604 /** 605 * Whether or not system app permissions should be promoted from install to runtime. 606 */ 607 boolean mPromoteSystemApps; 608 609 @GuardedBy("mPackages") 610 final Settings mSettings; 611 612 /** 613 * Set of package names that are currently "frozen", which means active 614 * surgery is being done on the code/data for that package. The platform 615 * will refuse to launch frozen packages to avoid race conditions. 616 * 617 * @see PackageFreezer 618 */ 619 @GuardedBy("mPackages") 620 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 621 622 boolean mRestoredSettings; 623 624 // System configuration read by SystemConfig. 625 final int[] mGlobalGids; 626 final SparseArray<ArraySet<String>> mSystemPermissions; 627 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 628 629 // If mac_permissions.xml was found for seinfo labeling. 630 boolean mFoundPolicyFile; 631 632 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 633 634 public static final class SharedLibraryEntry { 635 public final String path; 636 public final String apk; 637 638 SharedLibraryEntry(String _path, String _apk) { 639 path = _path; 640 apk = _apk; 641 } 642 } 643 644 // Currently known shared libraries. 645 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 646 new ArrayMap<String, SharedLibraryEntry>(); 647 648 // All available activities, for your resolving pleasure. 649 final ActivityIntentResolver mActivities = 650 new ActivityIntentResolver(); 651 652 // All available receivers, for your resolving pleasure. 653 final ActivityIntentResolver mReceivers = 654 new ActivityIntentResolver(); 655 656 // All available services, for your resolving pleasure. 657 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 658 659 // All available providers, for your resolving pleasure. 660 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 661 662 // Mapping from provider base names (first directory in content URI codePath) 663 // to the provider information. 664 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 665 new ArrayMap<String, PackageParser.Provider>(); 666 667 // Mapping from instrumentation class names to info about them. 668 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 669 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 670 671 // Mapping from permission names to info about them. 672 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 673 new ArrayMap<String, PackageParser.PermissionGroup>(); 674 675 // Packages whose data we have transfered into another package, thus 676 // should no longer exist. 677 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 678 679 // Broadcast actions that are only available to the system. 680 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 681 682 /** List of packages waiting for verification. */ 683 final SparseArray<PackageVerificationState> mPendingVerification 684 = new SparseArray<PackageVerificationState>(); 685 686 /** Set of packages associated with each app op permission. */ 687 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 688 689 final PackageInstallerService mInstallerService; 690 691 private final PackageDexOptimizer mPackageDexOptimizer; 692 693 private AtomicInteger mNextMoveId = new AtomicInteger(); 694 private final MoveCallbacks mMoveCallbacks; 695 696 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 697 698 // Cache of users who need badging. 699 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 700 701 /** Token for keys in mPendingVerification. */ 702 private int mPendingVerificationToken = 0; 703 704 volatile boolean mSystemReady; 705 volatile boolean mSafeMode; 706 volatile boolean mHasSystemUidErrors; 707 708 ApplicationInfo mAndroidApplication; 709 final ActivityInfo mResolveActivity = new ActivityInfo(); 710 final ResolveInfo mResolveInfo = new ResolveInfo(); 711 ComponentName mResolveComponentName; 712 PackageParser.Package mPlatformPackage; 713 ComponentName mCustomResolverComponentName; 714 715 boolean mResolverReplaced = false; 716 717 private final @Nullable ComponentName mIntentFilterVerifierComponent; 718 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 719 720 private int mIntentFilterVerificationToken = 0; 721 722 /** Component that knows whether or not an ephemeral application exists */ 723 final ComponentName mEphemeralResolverComponent; 724 /** The service connection to the ephemeral resolver */ 725 final EphemeralResolverConnection mEphemeralResolverConnection; 726 727 /** Component used to install ephemeral applications */ 728 final ComponentName mEphemeralInstallerComponent; 729 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 730 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 731 732 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 733 = new SparseArray<IntentFilterVerificationState>(); 734 735 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 736 new DefaultPermissionGrantPolicy(this); 737 738 // List of packages names to keep cached, even if they are uninstalled for all users 739 private List<String> mKeepUninstalledPackages; 740 741 private UserManagerInternal mUserManagerInternal; 742 743 private static class IFVerificationParams { 744 PackageParser.Package pkg; 745 boolean replacing; 746 int userId; 747 int verifierUid; 748 749 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 750 int _userId, int _verifierUid) { 751 pkg = _pkg; 752 replacing = _replacing; 753 userId = _userId; 754 replacing = _replacing; 755 verifierUid = _verifierUid; 756 } 757 } 758 759 private interface IntentFilterVerifier<T extends IntentFilter> { 760 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 761 T filter, String packageName); 762 void startVerifications(int userId); 763 void receiveVerificationResponse(int verificationId); 764 } 765 766 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 767 private Context mContext; 768 private ComponentName mIntentFilterVerifierComponent; 769 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 770 771 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 772 mContext = context; 773 mIntentFilterVerifierComponent = verifierComponent; 774 } 775 776 private String getDefaultScheme() { 777 return IntentFilter.SCHEME_HTTPS; 778 } 779 780 @Override 781 public void startVerifications(int userId) { 782 // Launch verifications requests 783 int count = mCurrentIntentFilterVerifications.size(); 784 for (int n=0; n<count; n++) { 785 int verificationId = mCurrentIntentFilterVerifications.get(n); 786 final IntentFilterVerificationState ivs = 787 mIntentFilterVerificationStates.get(verificationId); 788 789 String packageName = ivs.getPackageName(); 790 791 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 792 final int filterCount = filters.size(); 793 ArraySet<String> domainsSet = new ArraySet<>(); 794 for (int m=0; m<filterCount; m++) { 795 PackageParser.ActivityIntentInfo filter = filters.get(m); 796 domainsSet.addAll(filter.getHostsList()); 797 } 798 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 799 synchronized (mPackages) { 800 if (mSettings.createIntentFilterVerificationIfNeededLPw( 801 packageName, domainsList) != null) { 802 scheduleWriteSettingsLocked(); 803 } 804 } 805 sendVerificationRequest(userId, verificationId, ivs); 806 } 807 mCurrentIntentFilterVerifications.clear(); 808 } 809 810 private void sendVerificationRequest(int userId, int verificationId, 811 IntentFilterVerificationState ivs) { 812 813 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 814 verificationIntent.putExtra( 815 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 816 verificationId); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 819 getDefaultScheme()); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 822 ivs.getHostsString()); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 825 ivs.getPackageName()); 826 verificationIntent.setComponent(mIntentFilterVerifierComponent); 827 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 828 829 UserHandle user = new UserHandle(userId); 830 mContext.sendBroadcastAsUser(verificationIntent, user); 831 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 832 "Sending IntentFilter verification broadcast"); 833 } 834 835 public void receiveVerificationResponse(int verificationId) { 836 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 837 838 final boolean verified = ivs.isVerified(); 839 840 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 841 final int count = filters.size(); 842 if (DEBUG_DOMAIN_VERIFICATION) { 843 Slog.i(TAG, "Received verification response " + verificationId 844 + " for " + count + " filters, verified=" + verified); 845 } 846 for (int n=0; n<count; n++) { 847 PackageParser.ActivityIntentInfo filter = filters.get(n); 848 filter.setVerified(verified); 849 850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 851 + " verified with result:" + verified + " and hosts:" 852 + ivs.getHostsString()); 853 } 854 855 mIntentFilterVerificationStates.remove(verificationId); 856 857 final String packageName = ivs.getPackageName(); 858 IntentFilterVerificationInfo ivi = null; 859 860 synchronized (mPackages) { 861 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 862 } 863 if (ivi == null) { 864 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 865 + verificationId + " packageName:" + packageName); 866 return; 867 } 868 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 869 "Updating IntentFilterVerificationInfo for package " + packageName 870 +" verificationId:" + verificationId); 871 872 synchronized (mPackages) { 873 if (verified) { 874 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 875 } else { 876 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 877 } 878 scheduleWriteSettingsLocked(); 879 880 final int userId = ivs.getUserId(); 881 if (userId != UserHandle.USER_ALL) { 882 final int userStatus = 883 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 884 885 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 886 boolean needUpdate = false; 887 888 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 889 // already been set by the User thru the Disambiguation dialog 890 switch (userStatus) { 891 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 892 if (verified) { 893 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 894 } else { 895 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 896 } 897 needUpdate = true; 898 break; 899 900 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 901 if (verified) { 902 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 903 needUpdate = true; 904 } 905 break; 906 907 default: 908 // Nothing to do 909 } 910 911 if (needUpdate) { 912 mSettings.updateIntentFilterVerificationStatusLPw( 913 packageName, updatedStatus, userId); 914 scheduleWritePackageRestrictionsLocked(userId); 915 } 916 } 917 } 918 } 919 920 @Override 921 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 922 ActivityIntentInfo filter, String packageName) { 923 if (!hasValidDomains(filter)) { 924 return false; 925 } 926 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 927 if (ivs == null) { 928 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 929 packageName); 930 } 931 if (DEBUG_DOMAIN_VERIFICATION) { 932 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 933 } 934 ivs.addFilter(filter); 935 return true; 936 } 937 938 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 939 int userId, int verificationId, String packageName) { 940 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 941 verifierUid, userId, packageName); 942 ivs.setPendingState(); 943 synchronized (mPackages) { 944 mIntentFilterVerificationStates.append(verificationId, ivs); 945 mCurrentIntentFilterVerifications.add(verificationId); 946 } 947 return ivs; 948 } 949 } 950 951 private static boolean hasValidDomains(ActivityIntentInfo filter) { 952 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 953 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 954 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 955 } 956 957 // Set of pending broadcasts for aggregating enable/disable of components. 958 static class PendingPackageBroadcasts { 959 // for each user id, a map of <package name -> components within that package> 960 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 961 962 public PendingPackageBroadcasts() { 963 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 964 } 965 966 public ArrayList<String> get(int userId, String packageName) { 967 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 968 return packages.get(packageName); 969 } 970 971 public void put(int userId, String packageName, ArrayList<String> components) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 packages.put(packageName, components); 974 } 975 976 public void remove(int userId, String packageName) { 977 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 978 if (packages != null) { 979 packages.remove(packageName); 980 } 981 } 982 983 public void remove(int userId) { 984 mUidMap.remove(userId); 985 } 986 987 public int userIdCount() { 988 return mUidMap.size(); 989 } 990 991 public int userIdAt(int n) { 992 return mUidMap.keyAt(n); 993 } 994 995 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 996 return mUidMap.get(userId); 997 } 998 999 public int size() { 1000 // total number of pending broadcast entries across all userIds 1001 int num = 0; 1002 for (int i = 0; i< mUidMap.size(); i++) { 1003 num += mUidMap.valueAt(i).size(); 1004 } 1005 return num; 1006 } 1007 1008 public void clear() { 1009 mUidMap.clear(); 1010 } 1011 1012 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1013 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1014 if (map == null) { 1015 map = new ArrayMap<String, ArrayList<String>>(); 1016 mUidMap.put(userId, map); 1017 } 1018 return map; 1019 } 1020 } 1021 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1022 1023 // Service Connection to remote media container service to copy 1024 // package uri's from external media onto secure containers 1025 // or internal storage. 1026 private IMediaContainerService mContainerService = null; 1027 1028 static final int SEND_PENDING_BROADCAST = 1; 1029 static final int MCS_BOUND = 3; 1030 static final int END_COPY = 4; 1031 static final int INIT_COPY = 5; 1032 static final int MCS_UNBIND = 6; 1033 static final int START_CLEANING_PACKAGE = 7; 1034 static final int FIND_INSTALL_LOC = 8; 1035 static final int POST_INSTALL = 9; 1036 static final int MCS_RECONNECT = 10; 1037 static final int MCS_GIVE_UP = 11; 1038 static final int UPDATED_MEDIA_STATUS = 12; 1039 static final int WRITE_SETTINGS = 13; 1040 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1041 static final int PACKAGE_VERIFIED = 15; 1042 static final int CHECK_PENDING_VERIFICATION = 16; 1043 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1044 static final int INTENT_FILTER_VERIFIED = 18; 1045 static final int WRITE_PACKAGE_LIST = 19; 1046 1047 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1048 1049 // Delay time in millisecs 1050 static final int BROADCAST_DELAY = 10 * 1000; 1051 1052 static UserManagerService sUserManager; 1053 1054 // Stores a list of users whose package restrictions file needs to be updated 1055 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1056 1057 final private DefaultContainerConnection mDefContainerConn = 1058 new DefaultContainerConnection(); 1059 class DefaultContainerConnection implements ServiceConnection { 1060 public void onServiceConnected(ComponentName name, IBinder service) { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1062 IMediaContainerService imcs = 1063 IMediaContainerService.Stub.asInterface(service); 1064 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1065 } 1066 1067 public void onServiceDisconnected(ComponentName name) { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1069 } 1070 } 1071 1072 // Recordkeeping of restore-after-install operations that are currently in flight 1073 // between the Package Manager and the Backup Manager 1074 static class PostInstallData { 1075 public InstallArgs args; 1076 public PackageInstalledInfo res; 1077 1078 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1079 args = _a; 1080 res = _r; 1081 } 1082 } 1083 1084 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1085 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1086 1087 // XML tags for backup/restore of various bits of state 1088 private static final String TAG_PREFERRED_BACKUP = "pa"; 1089 private static final String TAG_DEFAULT_APPS = "da"; 1090 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1091 1092 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1093 private static final String TAG_ALL_GRANTS = "rt-grants"; 1094 private static final String TAG_GRANT = "grant"; 1095 private static final String ATTR_PACKAGE_NAME = "pkg"; 1096 1097 private static final String TAG_PERMISSION = "perm"; 1098 private static final String ATTR_PERMISSION_NAME = "name"; 1099 private static final String ATTR_IS_GRANTED = "g"; 1100 private static final String ATTR_USER_SET = "set"; 1101 private static final String ATTR_USER_FIXED = "fixed"; 1102 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1103 1104 // System/policy permission grants are not backed up 1105 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_POLICY_FIXED 1107 | FLAG_PERMISSION_SYSTEM_FIXED 1108 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1109 1110 // And we back up these user-adjusted states 1111 private static final int USER_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_USER_SET 1113 | FLAG_PERMISSION_USER_FIXED 1114 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1115 1116 final @Nullable String mRequiredVerifierPackage; 1117 final @NonNull String mRequiredInstallerPackage; 1118 final @Nullable String mSetupWizardPackage; 1119 final @NonNull String mServicesSystemSharedLibraryPackageName; 1120 final @NonNull String mSharedSystemSharedLibraryPackageName; 1121 1122 private final PackageUsage mPackageUsage = new PackageUsage(); 1123 1124 private class PackageUsage { 1125 private static final int WRITE_INTERVAL 1126 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1127 1128 private final Object mFileLock = new Object(); 1129 private final AtomicLong mLastWritten = new AtomicLong(0); 1130 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1131 1132 private boolean mIsHistoricalPackageUsageAvailable = true; 1133 1134 boolean isHistoricalPackageUsageAvailable() { 1135 return mIsHistoricalPackageUsageAvailable; 1136 } 1137 1138 void write(boolean force) { 1139 if (force) { 1140 writeInternal(); 1141 return; 1142 } 1143 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1144 && !DEBUG_DEXOPT) { 1145 return; 1146 } 1147 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1148 new Thread("PackageUsage_DiskWriter") { 1149 @Override 1150 public void run() { 1151 try { 1152 writeInternal(); 1153 } finally { 1154 mBackgroundWriteRunning.set(false); 1155 } 1156 } 1157 }.start(); 1158 } 1159 } 1160 1161 private void writeInternal() { 1162 synchronized (mPackages) { 1163 synchronized (mFileLock) { 1164 AtomicFile file = getFile(); 1165 FileOutputStream f = null; 1166 try { 1167 f = file.startWrite(); 1168 BufferedOutputStream out = new BufferedOutputStream(f); 1169 FileUtils.setPermissions(file.getBaseFile().getPath(), 1170 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1171 StringBuilder sb = new StringBuilder(); 1172 1173 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 1177 for (PackageParser.Package pkg : mPackages.values()) { 1178 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1179 continue; 1180 } 1181 sb.setLength(0); 1182 sb.append(pkg.packageName); 1183 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1184 sb.append(' '); 1185 sb.append(usageTimeInMillis); 1186 } 1187 sb.append('\n'); 1188 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1189 } 1190 out.flush(); 1191 file.finishWrite(f); 1192 } catch (IOException e) { 1193 if (f != null) { 1194 file.failWrite(f); 1195 } 1196 Log.e(TAG, "Failed to write package usage times", e); 1197 } 1198 } 1199 } 1200 mLastWritten.set(SystemClock.elapsedRealtime()); 1201 } 1202 1203 void readLP() { 1204 synchronized (mFileLock) { 1205 AtomicFile file = getFile(); 1206 BufferedInputStream in = null; 1207 try { 1208 in = new BufferedInputStream(file.openRead()); 1209 StringBuffer sb = new StringBuffer(); 1210 1211 String firstLine = readLine(in, sb); 1212 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1213 readVersion1LP(in, sb); 1214 } else { 1215 readVersion0LP(in, sb, firstLine); 1216 } 1217 } catch (FileNotFoundException expected) { 1218 mIsHistoricalPackageUsageAvailable = false; 1219 } catch (IOException e) { 1220 Log.w(TAG, "Failed to read package usage times", e); 1221 } finally { 1222 IoUtils.closeQuietly(in); 1223 } 1224 } 1225 mLastWritten.set(SystemClock.elapsedRealtime()); 1226 } 1227 1228 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1229 throws IOException { 1230 // Initial version of the file had no version number and stored one 1231 // package-timestamp pair per line. 1232 // Note that the first line has already been read from the InputStream. 1233 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1234 String[] tokens = line.split(" "); 1235 if (tokens.length != 2) { 1236 throw new IOException("Failed to parse " + line + 1237 " as package-timestamp pair."); 1238 } 1239 1240 String packageName = tokens[0]; 1241 PackageParser.Package pkg = mPackages.get(packageName); 1242 if (pkg == null) { 1243 continue; 1244 } 1245 1246 long timestamp = parseAsLong(tokens[1]); 1247 for (int reason = 0; 1248 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1249 reason++) { 1250 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1251 } 1252 } 1253 } 1254 1255 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1256 // Version 1 of the file started with the corresponding version 1257 // number and then stored a package name and eight timestamps per line. 1258 String line; 1259 while ((line = readLine(in, sb)) != null) { 1260 String[] tokens = line.split(" "); 1261 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1262 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1263 } 1264 1265 String packageName = tokens[0]; 1266 PackageParser.Package pkg = mPackages.get(packageName); 1267 if (pkg == null) { 1268 continue; 1269 } 1270 1271 for (int reason = 0; 1272 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1273 reason++) { 1274 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1275 } 1276 } 1277 } 1278 1279 private long parseAsLong(String token) throws IOException { 1280 try { 1281 return Long.parseLong(token); 1282 } catch (NumberFormatException e) { 1283 throw new IOException("Failed to parse " + token + " as a long.", e); 1284 } 1285 } 1286 1287 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1288 return readToken(in, sb, '\n'); 1289 } 1290 1291 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1292 throws IOException { 1293 sb.setLength(0); 1294 while (true) { 1295 int ch = in.read(); 1296 if (ch == -1) { 1297 if (sb.length() == 0) { 1298 return null; 1299 } 1300 throw new IOException("Unexpected EOF"); 1301 } 1302 if (ch == endOfToken) { 1303 return sb.toString(); 1304 } 1305 sb.append((char)ch); 1306 } 1307 } 1308 1309 private AtomicFile getFile() { 1310 File dataDir = Environment.getDataDirectory(); 1311 File systemDir = new File(dataDir, "system"); 1312 File fname = new File(systemDir, "package-usage.list"); 1313 return new AtomicFile(fname); 1314 } 1315 1316 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1317 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1318 } 1319 1320 class PackageHandler extends Handler { 1321 private boolean mBound = false; 1322 final ArrayList<HandlerParams> mPendingInstalls = 1323 new ArrayList<HandlerParams>(); 1324 1325 private boolean connectToService() { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1327 " DefaultContainerService"); 1328 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1331 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 mBound = true; 1334 return true; 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 return false; 1338 } 1339 1340 private void disconnectService() { 1341 mContainerService = null; 1342 mBound = false; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 mContext.unbindService(mDefContainerConn); 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 1348 PackageHandler(Looper looper) { 1349 super(looper); 1350 } 1351 1352 public void handleMessage(Message msg) { 1353 try { 1354 doHandleMessage(msg); 1355 } finally { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 } 1358 } 1359 1360 void doHandleMessage(Message msg) { 1361 switch (msg.what) { 1362 case INIT_COPY: { 1363 HandlerParams params = (HandlerParams) msg.obj; 1364 int idx = mPendingInstalls.size(); 1365 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1366 // If a bind was already initiated we dont really 1367 // need to do anything. The pending install 1368 // will be processed later on. 1369 if (!mBound) { 1370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 // If this is the only one pending we might 1373 // have to bind to the service again. 1374 if (!connectToService()) { 1375 Slog.e(TAG, "Failed to bind to media container service"); 1376 params.serviceError(); 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 if (params.traceMethod != null) { 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1381 params.traceCookie); 1382 } 1383 return; 1384 } else { 1385 // Once we bind to the service, the first 1386 // pending request will be processed. 1387 mPendingInstalls.add(idx, params); 1388 } 1389 } else { 1390 mPendingInstalls.add(idx, params); 1391 // Already bound to the service. Just make 1392 // sure we trigger off processing the first request. 1393 if (idx == 0) { 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 break; 1398 } 1399 case MCS_BOUND: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1401 if (msg.obj != null) { 1402 mContainerService = (IMediaContainerService) msg.obj; 1403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1404 System.identityHashCode(mHandler)); 1405 } 1406 if (mContainerService == null) { 1407 if (!mBound) { 1408 // Something seriously wrong since we are not bound and we are not 1409 // waiting for connection. Bail out. 1410 Slog.e(TAG, "Cannot bind to media container service"); 1411 for (HandlerParams params : mPendingInstalls) { 1412 // Indicate service bind error 1413 params.serviceError(); 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1415 System.identityHashCode(params)); 1416 if (params.traceMethod != null) { 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1418 params.traceMethod, params.traceCookie); 1419 } 1420 return; 1421 } 1422 mPendingInstalls.clear(); 1423 } else { 1424 Slog.w(TAG, "Waiting to connect to media container service"); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 HandlerParams params = mPendingInstalls.get(0); 1428 if (params != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1430 System.identityHashCode(params)); 1431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1432 if (params.startCopy()) { 1433 // We are done... look for more work or to 1434 // go idle. 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Checking for more work or unbind..."); 1437 // Delete pending install 1438 if (mPendingInstalls.size() > 0) { 1439 mPendingInstalls.remove(0); 1440 } 1441 if (mPendingInstalls.size() == 0) { 1442 if (mBound) { 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, 1444 "Posting delayed MCS_UNBIND"); 1445 removeMessages(MCS_UNBIND); 1446 Message ubmsg = obtainMessage(MCS_UNBIND); 1447 // Unbind after a little delay, to avoid 1448 // continual thrashing. 1449 sendMessageDelayed(ubmsg, 10000); 1450 } 1451 } else { 1452 // There are more pending requests in queue. 1453 // Just post MCS_BOUND message to trigger processing 1454 // of next pending install. 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting MCS_BOUND for next work"); 1457 mHandler.sendEmptyMessage(MCS_BOUND); 1458 } 1459 } 1460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1461 } 1462 } else { 1463 // Should never happen ideally. 1464 Slog.w(TAG, "Empty queue"); 1465 } 1466 break; 1467 } 1468 case MCS_RECONNECT: { 1469 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1470 if (mPendingInstalls.size() > 0) { 1471 if (mBound) { 1472 disconnectService(); 1473 } 1474 if (!connectToService()) { 1475 Slog.e(TAG, "Failed to bind to media container service"); 1476 for (HandlerParams params : mPendingInstalls) { 1477 // Indicate service bind error 1478 params.serviceError(); 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1480 System.identityHashCode(params)); 1481 } 1482 mPendingInstalls.clear(); 1483 } 1484 } 1485 break; 1486 } 1487 case MCS_UNBIND: { 1488 // If there is no actual work left, then time to unbind. 1489 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1490 1491 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1492 if (mBound) { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1494 1495 disconnectService(); 1496 } 1497 } else if (mPendingInstalls.size() > 0) { 1498 // There are more pending requests in queue. 1499 // Just post MCS_BOUND message to trigger processing 1500 // of next pending install. 1501 mHandler.sendEmptyMessage(MCS_BOUND); 1502 } 1503 1504 break; 1505 } 1506 case MCS_GIVE_UP: { 1507 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1508 HandlerParams params = mPendingInstalls.remove(0); 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1510 System.identityHashCode(params)); 1511 break; 1512 } 1513 case SEND_PENDING_BROADCAST: { 1514 String packages[]; 1515 ArrayList<String> components[]; 1516 int size = 0; 1517 int uids[]; 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 if (mPendingBroadcasts == null) { 1521 return; 1522 } 1523 size = mPendingBroadcasts.size(); 1524 if (size <= 0) { 1525 // Nothing to be done. Just return 1526 return; 1527 } 1528 packages = new String[size]; 1529 components = new ArrayList[size]; 1530 uids = new int[size]; 1531 int i = 0; // filling out the above arrays 1532 1533 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1534 int packageUserId = mPendingBroadcasts.userIdAt(n); 1535 Iterator<Map.Entry<String, ArrayList<String>>> it 1536 = mPendingBroadcasts.packagesForUserId(packageUserId) 1537 .entrySet().iterator(); 1538 while (it.hasNext() && i < size) { 1539 Map.Entry<String, ArrayList<String>> ent = it.next(); 1540 packages[i] = ent.getKey(); 1541 components[i] = ent.getValue(); 1542 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1543 uids[i] = (ps != null) 1544 ? UserHandle.getUid(packageUserId, ps.appId) 1545 : -1; 1546 i++; 1547 } 1548 } 1549 size = i; 1550 mPendingBroadcasts.clear(); 1551 } 1552 // Send broadcasts 1553 for (int i = 0; i < size; i++) { 1554 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 break; 1558 } 1559 case START_CLEANING_PACKAGE: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 final String packageName = (String)msg.obj; 1562 final int userId = msg.arg1; 1563 final boolean andCode = msg.arg2 != 0; 1564 synchronized (mPackages) { 1565 if (userId == UserHandle.USER_ALL) { 1566 int[] users = sUserManager.getUserIds(); 1567 for (int user : users) { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(user, packageName, andCode)); 1570 } 1571 } else { 1572 mSettings.addPackageToCleanLPw( 1573 new PackageCleanItem(userId, packageName, andCode)); 1574 } 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 startCleaningPackages(); 1578 } break; 1579 case POST_INSTALL: { 1580 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1581 1582 PostInstallData data = mRunningInstalls.get(msg.arg1); 1583 final boolean didRestore = (msg.arg2 != 0); 1584 mRunningInstalls.delete(msg.arg1); 1585 1586 if (data != null) { 1587 InstallArgs args = data.args; 1588 PackageInstalledInfo parentRes = data.res; 1589 1590 final boolean grantPermissions = (args.installFlags 1591 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1592 final boolean killApp = (args.installFlags 1593 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1594 final String[] grantedPermissions = args.installGrantPermissions; 1595 1596 // Handle the parent package 1597 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1598 grantedPermissions, didRestore, args.installerPackageName, 1599 args.observer); 1600 1601 // Handle the child packages 1602 final int childCount = (parentRes.addedChildPackages != null) 1603 ? parentRes.addedChildPackages.size() : 0; 1604 for (int i = 0; i < childCount; i++) { 1605 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1606 handlePackagePostInstall(childRes, grantPermissions, killApp, 1607 grantedPermissions, false, args.installerPackageName, 1608 args.observer); 1609 } 1610 1611 // Log tracing if needed 1612 if (args.traceMethod != null) { 1613 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1614 args.traceCookie); 1615 } 1616 } else { 1617 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1618 } 1619 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1621 } break; 1622 case UPDATED_MEDIA_STATUS: { 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1624 boolean reportStatus = msg.arg1 == 1; 1625 boolean doGc = msg.arg2 == 1; 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1627 if (doGc) { 1628 // Force a gc to clear up stale containers. 1629 Runtime.getRuntime().gc(); 1630 } 1631 if (msg.obj != null) { 1632 @SuppressWarnings("unchecked") 1633 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1635 // Unload containers 1636 unloadAllContainers(args); 1637 } 1638 if (reportStatus) { 1639 try { 1640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1641 PackageHelper.getMountService().finishMediaUpdate(); 1642 } catch (RemoteException e) { 1643 Log.e(TAG, "MountService not running?"); 1644 } 1645 } 1646 } break; 1647 case WRITE_SETTINGS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_SETTINGS); 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 mSettings.writeLPr(); 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case WRITE_PACKAGE_RESTRICTIONS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1661 for (int userId : mDirtyUsers) { 1662 mSettings.writePackageRestrictionsLPr(userId); 1663 } 1664 mDirtyUsers.clear(); 1665 } 1666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1667 } break; 1668 case WRITE_PACKAGE_LIST: { 1669 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1670 synchronized (mPackages) { 1671 removeMessages(WRITE_PACKAGE_LIST); 1672 mSettings.writePackageListLPr(msg.arg1); 1673 } 1674 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1675 } break; 1676 case CHECK_PENDING_VERIFICATION: { 1677 final int verificationId = msg.arg1; 1678 final PackageVerificationState state = mPendingVerification.get(verificationId); 1679 1680 if ((state != null) && !state.timeoutExtended()) { 1681 final InstallArgs args = state.getInstallArgs(); 1682 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1683 1684 Slog.i(TAG, "Verification timed out for " + originUri); 1685 mPendingVerification.remove(verificationId); 1686 1687 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1688 1689 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1690 Slog.i(TAG, "Continuing with installation of " + originUri); 1691 state.setVerifierResponse(Binder.getCallingUid(), 1692 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1693 broadcastPackageVerified(verificationId, originUri, 1694 PackageManager.VERIFICATION_ALLOW, 1695 state.getInstallArgs().getUser()); 1696 try { 1697 ret = args.copyApk(mContainerService, true); 1698 } catch (RemoteException e) { 1699 Slog.e(TAG, "Could not contact the ContainerService"); 1700 } 1701 } else { 1702 broadcastPackageVerified(verificationId, originUri, 1703 PackageManager.VERIFICATION_REJECT, 1704 state.getInstallArgs().getUser()); 1705 } 1706 1707 Trace.asyncTraceEnd( 1708 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1709 1710 processPendingInstall(args, ret); 1711 mHandler.sendEmptyMessage(MCS_UNBIND); 1712 } 1713 break; 1714 } 1715 case PACKAGE_VERIFIED: { 1716 final int verificationId = msg.arg1; 1717 1718 final PackageVerificationState state = mPendingVerification.get(verificationId); 1719 if (state == null) { 1720 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1721 break; 1722 } 1723 1724 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1725 1726 state.setVerifierResponse(response.callerUid, response.code); 1727 1728 if (state.isVerificationComplete()) { 1729 mPendingVerification.remove(verificationId); 1730 1731 final InstallArgs args = state.getInstallArgs(); 1732 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1733 1734 int ret; 1735 if (state.isInstallAllowed()) { 1736 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1737 broadcastPackageVerified(verificationId, originUri, 1738 response.code, state.getInstallArgs().getUser()); 1739 try { 1740 ret = args.copyApk(mContainerService, true); 1741 } catch (RemoteException e) { 1742 Slog.e(TAG, "Could not contact the ContainerService"); 1743 } 1744 } else { 1745 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1746 } 1747 1748 Trace.asyncTraceEnd( 1749 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1750 1751 processPendingInstall(args, ret); 1752 mHandler.sendEmptyMessage(MCS_UNBIND); 1753 } 1754 1755 break; 1756 } 1757 case START_INTENT_FILTER_VERIFICATIONS: { 1758 IFVerificationParams params = (IFVerificationParams) msg.obj; 1759 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1760 params.replacing, params.pkg); 1761 break; 1762 } 1763 case INTENT_FILTER_VERIFIED: { 1764 final int verificationId = msg.arg1; 1765 1766 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1767 verificationId); 1768 if (state == null) { 1769 Slog.w(TAG, "Invalid IntentFilter verification token " 1770 + verificationId + " received"); 1771 break; 1772 } 1773 1774 final int userId = state.getUserId(); 1775 1776 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1777 "Processing IntentFilter verification with token:" 1778 + verificationId + " and userId:" + userId); 1779 1780 final IntentFilterVerificationResponse response = 1781 (IntentFilterVerificationResponse) msg.obj; 1782 1783 state.setVerifierResponse(response.callerUid, response.code); 1784 1785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1786 "IntentFilter verification with token:" + verificationId 1787 + " and userId:" + userId 1788 + " is settings verifier response with response code:" 1789 + response.code); 1790 1791 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1792 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1793 + response.getFailedDomainsString()); 1794 } 1795 1796 if (state.isVerificationComplete()) { 1797 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1798 } else { 1799 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1800 "IntentFilter verification with token:" + verificationId 1801 + " was not said to be complete"); 1802 } 1803 1804 break; 1805 } 1806 } 1807 } 1808 } 1809 1810 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1811 boolean killApp, String[] grantedPermissions, 1812 boolean launchedForRestore, String installerPackage, 1813 IPackageInstallObserver2 installObserver) { 1814 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1815 // Send the removed broadcasts 1816 if (res.removedInfo != null) { 1817 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1818 } 1819 1820 // Now that we successfully installed the package, grant runtime 1821 // permissions if requested before broadcasting the install. 1822 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1823 >= Build.VERSION_CODES.M) { 1824 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1825 } 1826 1827 final boolean update = res.removedInfo != null 1828 && res.removedInfo.removedPackage != null; 1829 1830 // If this is the first time we have child packages for a disabled privileged 1831 // app that had no children, we grant requested runtime permissions to the new 1832 // children if the parent on the system image had them already granted. 1833 if (res.pkg.parentPackage != null) { 1834 synchronized (mPackages) { 1835 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1836 } 1837 } 1838 1839 synchronized (mPackages) { 1840 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1841 } 1842 1843 final String packageName = res.pkg.applicationInfo.packageName; 1844 Bundle extras = new Bundle(1); 1845 extras.putInt(Intent.EXTRA_UID, res.uid); 1846 1847 // Determine the set of users who are adding this package for 1848 // the first time vs. those who are seeing an update. 1849 int[] firstUsers = EMPTY_INT_ARRAY; 1850 int[] updateUsers = EMPTY_INT_ARRAY; 1851 if (res.origUsers == null || res.origUsers.length == 0) { 1852 firstUsers = res.newUsers; 1853 } else { 1854 for (int newUser : res.newUsers) { 1855 boolean isNew = true; 1856 for (int origUser : res.origUsers) { 1857 if (origUser == newUser) { 1858 isNew = false; 1859 break; 1860 } 1861 } 1862 if (isNew) { 1863 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1864 } else { 1865 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1866 } 1867 } 1868 } 1869 1870 // Send installed broadcasts if the install/update is not ephemeral 1871 if (!isEphemeral(res.pkg)) { 1872 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1873 1874 // Send added for users that see the package for the first time 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1876 extras, 0 /*flags*/, null /*targetPackage*/, 1877 null /*finishedReceiver*/, firstUsers); 1878 1879 // Send added for users that don't see the package for the first time 1880 if (update) { 1881 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1882 } 1883 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1884 extras, 0 /*flags*/, null /*targetPackage*/, 1885 null /*finishedReceiver*/, updateUsers); 1886 1887 // Send replaced for users that don't see the package for the first time 1888 if (update) { 1889 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1890 packageName, extras, 0 /*flags*/, 1891 null /*targetPackage*/, null /*finishedReceiver*/, 1892 updateUsers); 1893 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1894 null /*package*/, null /*extras*/, 0 /*flags*/, 1895 packageName /*targetPackage*/, 1896 null /*finishedReceiver*/, updateUsers); 1897 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1898 // First-install and we did a restore, so we're responsible for the 1899 // first-launch broadcast. 1900 if (DEBUG_BACKUP) { 1901 Slog.i(TAG, "Post-restore of " + packageName 1902 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1903 } 1904 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1905 } 1906 1907 // Send broadcast package appeared if forward locked/external for all users 1908 // treat asec-hosted packages like removable media on upgrade 1909 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1910 if (DEBUG_INSTALL) { 1911 Slog.i(TAG, "upgrading pkg " + res.pkg 1912 + " is ASEC-hosted -> AVAILABLE"); 1913 } 1914 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1915 ArrayList<String> pkgList = new ArrayList<>(1); 1916 pkgList.add(packageName); 1917 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1918 } 1919 } 1920 1921 // Work that needs to happen on first install within each user 1922 if (firstUsers != null && firstUsers.length > 0) { 1923 synchronized (mPackages) { 1924 for (int userId : firstUsers) { 1925 // If this app is a browser and it's newly-installed for some 1926 // users, clear any default-browser state in those users. The 1927 // app's nature doesn't depend on the user, so we can just check 1928 // its browser nature in any user and generalize. 1929 if (packageIsBrowser(packageName, userId)) { 1930 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1931 } 1932 1933 // We may also need to apply pending (restored) runtime 1934 // permission grants within these users. 1935 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1936 } 1937 } 1938 } 1939 1940 // Log current value of "unknown sources" setting 1941 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1942 getUnknownSourcesSettings()); 1943 1944 // Force a gc to clear up things 1945 Runtime.getRuntime().gc(); 1946 1947 // Remove the replaced package's older resources safely now 1948 // We delete after a gc for applications on sdcard. 1949 if (res.removedInfo != null && res.removedInfo.args != null) { 1950 synchronized (mInstallLock) { 1951 res.removedInfo.args.doPostDeleteLI(true); 1952 } 1953 } 1954 } 1955 1956 // If someone is watching installs - notify them 1957 if (installObserver != null) { 1958 try { 1959 Bundle extras = extrasForInstallResult(res); 1960 installObserver.onPackageInstalled(res.name, res.returnCode, 1961 res.returnMsg, extras); 1962 } catch (RemoteException e) { 1963 Slog.i(TAG, "Observer no longer exists."); 1964 } 1965 } 1966 } 1967 1968 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1969 PackageParser.Package pkg) { 1970 if (pkg.parentPackage == null) { 1971 return; 1972 } 1973 if (pkg.requestedPermissions == null) { 1974 return; 1975 } 1976 final PackageSetting disabledSysParentPs = mSettings 1977 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1978 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1979 || !disabledSysParentPs.isPrivileged() 1980 || (disabledSysParentPs.childPackageNames != null 1981 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1982 return; 1983 } 1984 final int[] allUserIds = sUserManager.getUserIds(); 1985 final int permCount = pkg.requestedPermissions.size(); 1986 for (int i = 0; i < permCount; i++) { 1987 String permission = pkg.requestedPermissions.get(i); 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1990 continue; 1991 } 1992 for (int userId : allUserIds) { 1993 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1994 permission, userId)) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 2001 private StorageEventListener mStorageListener = new StorageEventListener() { 2002 @Override 2003 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2004 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2005 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2006 final String volumeUuid = vol.getFsUuid(); 2007 2008 // Clean up any users or apps that were removed or recreated 2009 // while this volume was missing 2010 reconcileUsers(volumeUuid); 2011 reconcileApps(volumeUuid); 2012 2013 // Clean up any install sessions that expired or were 2014 // cancelled while this volume was missing 2015 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2016 2017 loadPrivatePackages(vol); 2018 2019 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2020 unloadPrivatePackages(vol); 2021 } 2022 } 2023 2024 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2025 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2026 updateExternalMediaStatus(true, false); 2027 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2028 updateExternalMediaStatus(false, false); 2029 } 2030 } 2031 } 2032 2033 @Override 2034 public void onVolumeForgotten(String fsUuid) { 2035 if (TextUtils.isEmpty(fsUuid)) { 2036 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2037 return; 2038 } 2039 2040 // Remove any apps installed on the forgotten volume 2041 synchronized (mPackages) { 2042 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2043 for (PackageSetting ps : packages) { 2044 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2045 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2046 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2047 } 2048 2049 mSettings.onVolumeForgotten(fsUuid); 2050 mSettings.writeLPr(); 2051 } 2052 } 2053 }; 2054 2055 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2056 String[] grantedPermissions) { 2057 for (int userId : userIds) { 2058 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2059 } 2060 2061 // We could have touched GID membership, so flush out packages.list 2062 synchronized (mPackages) { 2063 mSettings.writePackageListLPr(); 2064 } 2065 } 2066 2067 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2068 String[] grantedPermissions) { 2069 SettingBase sb = (SettingBase) pkg.mExtras; 2070 if (sb == null) { 2071 return; 2072 } 2073 2074 PermissionsState permissionsState = sb.getPermissionsState(); 2075 2076 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2077 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2078 2079 for (String permission : pkg.requestedPermissions) { 2080 final BasePermission bp; 2081 synchronized (mPackages) { 2082 bp = mSettings.mPermissions.get(permission); 2083 } 2084 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2085 && (grantedPermissions == null 2086 || ArrayUtils.contains(grantedPermissions, permission))) { 2087 final int flags = permissionsState.getPermissionFlags(permission, userId); 2088 // Installer cannot change immutable permissions. 2089 if ((flags & immutableFlags) == 0) { 2090 grantRuntimePermission(pkg.packageName, permission, userId); 2091 } 2092 } 2093 } 2094 } 2095 2096 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2097 Bundle extras = null; 2098 switch (res.returnCode) { 2099 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2100 extras = new Bundle(); 2101 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2102 res.origPermission); 2103 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2104 res.origPackage); 2105 break; 2106 } 2107 case PackageManager.INSTALL_SUCCEEDED: { 2108 extras = new Bundle(); 2109 extras.putBoolean(Intent.EXTRA_REPLACING, 2110 res.removedInfo != null && res.removedInfo.removedPackage != null); 2111 break; 2112 } 2113 } 2114 return extras; 2115 } 2116 2117 void scheduleWriteSettingsLocked() { 2118 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2119 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2120 } 2121 } 2122 2123 void scheduleWritePackageListLocked(int userId) { 2124 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2125 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2126 msg.arg1 = userId; 2127 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 2131 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2132 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2133 scheduleWritePackageRestrictionsLocked(userId); 2134 } 2135 2136 void scheduleWritePackageRestrictionsLocked(int userId) { 2137 final int[] userIds = (userId == UserHandle.USER_ALL) 2138 ? sUserManager.getUserIds() : new int[]{userId}; 2139 for (int nextUserId : userIds) { 2140 if (!sUserManager.exists(nextUserId)) return; 2141 mDirtyUsers.add(nextUserId); 2142 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2143 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2144 } 2145 } 2146 } 2147 2148 public static PackageManagerService main(Context context, Installer installer, 2149 boolean factoryTest, boolean onlyCore) { 2150 // Self-check for initial settings. 2151 PackageManagerServiceCompilerMapping.checkProperties(); 2152 2153 PackageManagerService m = new PackageManagerService(context, installer, 2154 factoryTest, onlyCore); 2155 m.enableSystemUserPackages(); 2156 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2157 // disabled after already being started. 2158 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2159 UserHandle.USER_SYSTEM); 2160 ServiceManager.addService("package", m); 2161 return m; 2162 } 2163 2164 private void enableSystemUserPackages() { 2165 if (!UserManager.isSplitSystemUser()) { 2166 return; 2167 } 2168 // For system user, enable apps based on the following conditions: 2169 // - app is whitelisted or belong to one of these groups: 2170 // -- system app which has no launcher icons 2171 // -- system app which has INTERACT_ACROSS_USERS permission 2172 // -- system IME app 2173 // - app is not in the blacklist 2174 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2175 Set<String> enableApps = new ArraySet<>(); 2176 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2177 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2178 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2179 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2180 enableApps.addAll(wlApps); 2181 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2182 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2183 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2184 enableApps.removeAll(blApps); 2185 Log.i(TAG, "Applications installed for system user: " + enableApps); 2186 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2187 UserHandle.SYSTEM); 2188 final int allAppsSize = allAps.size(); 2189 synchronized (mPackages) { 2190 for (int i = 0; i < allAppsSize; i++) { 2191 String pName = allAps.get(i); 2192 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2193 // Should not happen, but we shouldn't be failing if it does 2194 if (pkgSetting == null) { 2195 continue; 2196 } 2197 boolean install = enableApps.contains(pName); 2198 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2199 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2200 + " for system user"); 2201 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2202 } 2203 } 2204 } 2205 } 2206 2207 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2208 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2209 Context.DISPLAY_SERVICE); 2210 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2211 } 2212 2213 public PackageManagerService(Context context, Installer installer, 2214 boolean factoryTest, boolean onlyCore) { 2215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2216 SystemClock.uptimeMillis()); 2217 2218 if (mSdkVersion <= 0) { 2219 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2220 } 2221 2222 mContext = context; 2223 mFactoryTest = factoryTest; 2224 mOnlyCore = onlyCore; 2225 mMetrics = new DisplayMetrics(); 2226 mSettings = new Settings(mPackages); 2227 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2228 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2229 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2230 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2231 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2232 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2233 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2234 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2235 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 2240 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2241 if (separateProcesses != null && separateProcesses.length() > 0) { 2242 if ("*".equals(separateProcesses)) { 2243 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2244 mSeparateProcesses = null; 2245 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2246 } else { 2247 mDefParseFlags = 0; 2248 mSeparateProcesses = separateProcesses.split(","); 2249 Slog.w(TAG, "Running with debug.separate_processes: " 2250 + separateProcesses); 2251 } 2252 } else { 2253 mDefParseFlags = 0; 2254 mSeparateProcesses = null; 2255 } 2256 2257 mInstaller = installer; 2258 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2259 "*dexopt*"); 2260 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2261 2262 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2263 FgThread.get().getLooper()); 2264 2265 getDefaultDisplayMetrics(context, mMetrics); 2266 2267 SystemConfig systemConfig = SystemConfig.getInstance(); 2268 mGlobalGids = systemConfig.getGlobalGids(); 2269 mSystemPermissions = systemConfig.getSystemPermissions(); 2270 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2271 2272 synchronized (mInstallLock) { 2273 // writer 2274 synchronized (mPackages) { 2275 mHandlerThread = new ServiceThread(TAG, 2276 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2277 mHandlerThread.start(); 2278 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2279 mProcessLoggingHandler = new ProcessLoggingHandler(); 2280 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2281 2282 File dataDir = Environment.getDataDirectory(); 2283 mAppInstallDir = new File(dataDir, "app"); 2284 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2285 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2286 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2287 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2288 2289 sUserManager = new UserManagerService(context, this, mPackages); 2290 2291 // Propagate permission configuration in to package manager. 2292 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2293 = systemConfig.getPermissions(); 2294 for (int i=0; i<permConfig.size(); i++) { 2295 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2296 BasePermission bp = mSettings.mPermissions.get(perm.name); 2297 if (bp == null) { 2298 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2299 mSettings.mPermissions.put(perm.name, bp); 2300 } 2301 if (perm.gids != null) { 2302 bp.setGids(perm.gids, perm.perUser); 2303 } 2304 } 2305 2306 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2307 for (int i=0; i<libConfig.size(); i++) { 2308 mSharedLibraries.put(libConfig.keyAt(i), 2309 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2310 } 2311 2312 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2313 2314 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2315 2316 String customResolverActivity = Resources.getSystem().getString( 2317 R.string.config_customResolverActivity); 2318 if (TextUtils.isEmpty(customResolverActivity)) { 2319 customResolverActivity = null; 2320 } else { 2321 mCustomResolverComponentName = ComponentName.unflattenFromString( 2322 customResolverActivity); 2323 } 2324 2325 long startTime = SystemClock.uptimeMillis(); 2326 2327 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2328 startTime); 2329 2330 // Set flag to monitor and not change apk file paths when 2331 // scanning install directories. 2332 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2333 2334 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2335 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2336 2337 if (bootClassPath == null) { 2338 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2339 } 2340 2341 if (systemServerClassPath == null) { 2342 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2343 } 2344 2345 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2346 final String[] dexCodeInstructionSets = 2347 getDexCodeInstructionSets( 2348 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2349 2350 /** 2351 * Ensure all external libraries have had dexopt run on them. 2352 */ 2353 if (mSharedLibraries.size() > 0) { 2354 // NOTE: For now, we're compiling these system "shared libraries" 2355 // (and framework jars) into all available architectures. It's possible 2356 // to compile them only when we come across an app that uses them (there's 2357 // already logic for that in scanPackageLI) but that adds some complexity. 2358 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2359 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2360 final String lib = libEntry.path; 2361 if (lib == null) { 2362 continue; 2363 } 2364 2365 try { 2366 // Shared libraries do not have profiles so we perform a full 2367 // AOT compilation (if needed). 2368 int dexoptNeeded = DexFile.getDexOptNeeded( 2369 lib, dexCodeInstructionSet, 2370 getCompilerFilterForReason(REASON_SHARED_APK), 2371 false /* newProfile */); 2372 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2373 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2374 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2375 getCompilerFilterForReason(REASON_SHARED_APK), 2376 StorageManager.UUID_PRIVATE_INTERNAL, 2377 SKIP_SHARED_LIBRARY_CHECK); 2378 } 2379 } catch (FileNotFoundException e) { 2380 Slog.w(TAG, "Library not found: " + lib); 2381 } catch (IOException | InstallerException e) { 2382 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2383 + e.getMessage()); 2384 } 2385 } 2386 } 2387 } 2388 2389 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2390 2391 final VersionInfo ver = mSettings.getInternalVersion(); 2392 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2393 2394 // when upgrading from pre-M, promote system app permissions from install to runtime 2395 mPromoteSystemApps = 2396 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2397 2398 // save off the names of pre-existing system packages prior to scanning; we don't 2399 // want to automatically grant runtime permissions for new system apps 2400 if (mPromoteSystemApps) { 2401 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2402 while (pkgSettingIter.hasNext()) { 2403 PackageSetting ps = pkgSettingIter.next(); 2404 if (isSystemApp(ps)) { 2405 mExistingSystemPackages.add(ps.name); 2406 } 2407 } 2408 } 2409 2410 // When upgrading from pre-N, we need to handle package extraction like first boot, 2411 // as there is no profiling data available. 2412 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2413 mSettings.setNWorkDone(); 2414 2415 // Collect vendor overlay packages. 2416 // (Do this before scanning any apps.) 2417 // For security and version matching reason, only consider 2418 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2419 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2420 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2421 | PackageParser.PARSE_IS_SYSTEM 2422 | PackageParser.PARSE_IS_SYSTEM_DIR 2423 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2424 2425 // Find base frameworks (resource packages without code). 2426 scanDirTracedLI(frameworkDir, mDefParseFlags 2427 | PackageParser.PARSE_IS_SYSTEM 2428 | PackageParser.PARSE_IS_SYSTEM_DIR 2429 | PackageParser.PARSE_IS_PRIVILEGED, 2430 scanFlags | SCAN_NO_DEX, 0); 2431 2432 // Collected privileged system packages. 2433 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2434 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR 2437 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2438 2439 // Collect ordinary system packages. 2440 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2441 scanDirTracedLI(systemAppDir, mDefParseFlags 2442 | PackageParser.PARSE_IS_SYSTEM 2443 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2444 2445 // Collect all vendor packages. 2446 File vendorAppDir = new File("/vendor/app"); 2447 try { 2448 vendorAppDir = vendorAppDir.getCanonicalFile(); 2449 } catch (IOException e) { 2450 // failed to look up canonical path, continue with original one 2451 } 2452 scanDirTracedLI(vendorAppDir, mDefParseFlags 2453 | PackageParser.PARSE_IS_SYSTEM 2454 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2455 2456 // Collect all OEM packages. 2457 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2458 scanDirTracedLI(oemAppDir, mDefParseFlags 2459 | PackageParser.PARSE_IS_SYSTEM 2460 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2461 2462 // Prune any system packages that no longer exist. 2463 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2464 if (!mOnlyCore) { 2465 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2466 while (psit.hasNext()) { 2467 PackageSetting ps = psit.next(); 2468 2469 /* 2470 * If this is not a system app, it can't be a 2471 * disable system app. 2472 */ 2473 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2474 continue; 2475 } 2476 2477 /* 2478 * If the package is scanned, it's not erased. 2479 */ 2480 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2481 if (scannedPkg != null) { 2482 /* 2483 * If the system app is both scanned and in the 2484 * disabled packages list, then it must have been 2485 * added via OTA. Remove it from the currently 2486 * scanned package so the previously user-installed 2487 * application can be scanned. 2488 */ 2489 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2490 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2491 + ps.name + "; removing system app. Last known codePath=" 2492 + ps.codePathString + ", installStatus=" + ps.installStatus 2493 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2494 + scannedPkg.mVersionCode); 2495 removePackageLI(scannedPkg, true); 2496 mExpectingBetter.put(ps.name, ps.codePath); 2497 } 2498 2499 continue; 2500 } 2501 2502 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2503 psit.remove(); 2504 logCriticalInfo(Log.WARN, "System package " + ps.name 2505 + " no longer exists; it's data will be wiped"); 2506 // Actual deletion of code and data will be handled by later 2507 // reconciliation step 2508 } else { 2509 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2510 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2511 possiblyDeletedUpdatedSystemApps.add(ps.name); 2512 } 2513 } 2514 } 2515 } 2516 2517 //look for any incomplete package installations 2518 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2519 for (int i = 0; i < deletePkgsList.size(); i++) { 2520 // Actual deletion of code and data will be handled by later 2521 // reconciliation step 2522 final String packageName = deletePkgsList.get(i).name; 2523 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2524 synchronized (mPackages) { 2525 mSettings.removePackageLPw(packageName); 2526 } 2527 } 2528 2529 //delete tmp files 2530 deleteTempPackageFiles(); 2531 2532 // Remove any shared userIDs that have no associated packages 2533 mSettings.pruneSharedUsersLPw(); 2534 2535 if (!mOnlyCore) { 2536 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2537 SystemClock.uptimeMillis()); 2538 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2539 2540 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2541 | PackageParser.PARSE_FORWARD_LOCK, 2542 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2543 2544 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2545 | PackageParser.PARSE_IS_EPHEMERAL, 2546 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 /** 2549 * Remove disable package settings for any updated system 2550 * apps that were removed via an OTA. If they're not a 2551 * previously-updated app, remove them completely. 2552 * Otherwise, just revoke their system-level permissions. 2553 */ 2554 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2555 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2556 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2557 2558 String msg; 2559 if (deletedPkg == null) { 2560 msg = "Updated system package " + deletedAppName 2561 + " no longer exists; it's data will be wiped"; 2562 // Actual deletion of code and data will be handled by later 2563 // reconciliation step 2564 } else { 2565 msg = "Updated system app + " + deletedAppName 2566 + " no longer present; removing system privileges for " 2567 + deletedAppName; 2568 2569 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2570 2571 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2572 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2573 } 2574 logCriticalInfo(Log.WARN, msg); 2575 } 2576 2577 /** 2578 * Make sure all system apps that we expected to appear on 2579 * the userdata partition actually showed up. If they never 2580 * appeared, crawl back and revive the system version. 2581 */ 2582 for (int i = 0; i < mExpectingBetter.size(); i++) { 2583 final String packageName = mExpectingBetter.keyAt(i); 2584 if (!mPackages.containsKey(packageName)) { 2585 final File scanFile = mExpectingBetter.valueAt(i); 2586 2587 logCriticalInfo(Log.WARN, "Expected better " + packageName 2588 + " but never showed up; reverting to system"); 2589 2590 int reparseFlags = mDefParseFlags; 2591 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2592 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2593 | PackageParser.PARSE_IS_SYSTEM_DIR 2594 | PackageParser.PARSE_IS_PRIVILEGED; 2595 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2596 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2597 | PackageParser.PARSE_IS_SYSTEM_DIR; 2598 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2599 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2600 | PackageParser.PARSE_IS_SYSTEM_DIR; 2601 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2602 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2603 | PackageParser.PARSE_IS_SYSTEM_DIR; 2604 } else { 2605 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2606 continue; 2607 } 2608 2609 mSettings.enableSystemPackageLPw(packageName); 2610 2611 try { 2612 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2613 } catch (PackageManagerException e) { 2614 Slog.e(TAG, "Failed to parse original system package: " 2615 + e.getMessage()); 2616 } 2617 } 2618 } 2619 } 2620 mExpectingBetter.clear(); 2621 2622 // Resolve protected action filters. Only the setup wizard is allowed to 2623 // have a high priority filter for these actions. 2624 mSetupWizardPackage = getSetupWizardPackageName(); 2625 if (mProtectedFilters.size() > 0) { 2626 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2627 Slog.i(TAG, "No setup wizard;" 2628 + " All protected intents capped to priority 0"); 2629 } 2630 for (ActivityIntentInfo filter : mProtectedFilters) { 2631 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2632 if (DEBUG_FILTERS) { 2633 Slog.i(TAG, "Found setup wizard;" 2634 + " allow priority " + filter.getPriority() + ";" 2635 + " package: " + filter.activity.info.packageName 2636 + " activity: " + filter.activity.className 2637 + " priority: " + filter.getPriority()); 2638 } 2639 // skip setup wizard; allow it to keep the high priority filter 2640 continue; 2641 } 2642 Slog.w(TAG, "Protected action; cap priority to 0;" 2643 + " package: " + filter.activity.info.packageName 2644 + " activity: " + filter.activity.className 2645 + " origPrio: " + filter.getPriority()); 2646 filter.setPriority(0); 2647 } 2648 } 2649 mDeferProtectedFilters = false; 2650 mProtectedFilters.clear(); 2651 2652 // Now that we know all of the shared libraries, update all clients to have 2653 // the correct library paths. 2654 updateAllSharedLibrariesLPw(); 2655 2656 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2657 // NOTE: We ignore potential failures here during a system scan (like 2658 // the rest of the commands above) because there's precious little we 2659 // can do about it. A settings error is reported, though. 2660 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2661 false /* boot complete */); 2662 } 2663 2664 // Now that we know all the packages we are keeping, 2665 // read and update their last usage times. 2666 mPackageUsage.readLP(); 2667 2668 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2669 SystemClock.uptimeMillis()); 2670 Slog.i(TAG, "Time to scan packages: " 2671 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2672 + " seconds"); 2673 2674 // If the platform SDK has changed since the last time we booted, 2675 // we need to re-grant app permission to catch any new ones that 2676 // appear. This is really a hack, and means that apps can in some 2677 // cases get permissions that the user didn't initially explicitly 2678 // allow... it would be nice to have some better way to handle 2679 // this situation. 2680 int updateFlags = UPDATE_PERMISSIONS_ALL; 2681 if (ver.sdkVersion != mSdkVersion) { 2682 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2683 + mSdkVersion + "; regranting permissions for internal storage"); 2684 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2685 } 2686 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2687 ver.sdkVersion = mSdkVersion; 2688 2689 // If this is the first boot or an update from pre-M, and it is a normal 2690 // boot, then we need to initialize the default preferred apps across 2691 // all defined users. 2692 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2693 for (UserInfo user : sUserManager.getUsers(true)) { 2694 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2695 applyFactoryDefaultBrowserLPw(user.id); 2696 primeDomainVerificationsLPw(user.id); 2697 } 2698 } 2699 2700 // Prepare storage for system user really early during boot, 2701 // since core system apps like SettingsProvider and SystemUI 2702 // can't wait for user to start 2703 final int storageFlags; 2704 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2705 storageFlags = StorageManager.FLAG_STORAGE_DE; 2706 } else { 2707 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2708 } 2709 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2710 storageFlags); 2711 2712 // If this is first boot after an OTA, and a normal boot, then 2713 // we need to clear code cache directories. 2714 // Note that we do *not* clear the application profiles. These remain valid 2715 // across OTAs and are used to drive profile verification (post OTA) and 2716 // profile compilation (without waiting to collect a fresh set of profiles). 2717 if (mIsUpgrade && !onlyCore) { 2718 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2719 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2720 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2721 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2722 // No apps are running this early, so no need to freeze 2723 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2724 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2725 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2726 } 2727 } 2728 ver.fingerprint = Build.FINGERPRINT; 2729 } 2730 2731 checkDefaultBrowser(); 2732 2733 // clear only after permissions and other defaults have been updated 2734 mExistingSystemPackages.clear(); 2735 mPromoteSystemApps = false; 2736 2737 // All the changes are done during package scanning. 2738 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2739 2740 // can downgrade to reader 2741 mSettings.writeLPr(); 2742 2743 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2744 SystemClock.uptimeMillis()); 2745 2746 if (!mOnlyCore) { 2747 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2748 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2749 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2750 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2751 mIntentFilterVerifierComponent); 2752 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2753 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2754 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2755 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2756 } else { 2757 mRequiredVerifierPackage = null; 2758 mRequiredInstallerPackage = null; 2759 mIntentFilterVerifierComponent = null; 2760 mIntentFilterVerifier = null; 2761 mServicesSystemSharedLibraryPackageName = null; 2762 mSharedSystemSharedLibraryPackageName = null; 2763 } 2764 2765 mInstallerService = new PackageInstallerService(context, this); 2766 2767 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2768 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2769 // both the installer and resolver must be present to enable ephemeral 2770 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2771 if (DEBUG_EPHEMERAL) { 2772 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2773 + " installer:" + ephemeralInstallerComponent); 2774 } 2775 mEphemeralResolverComponent = ephemeralResolverComponent; 2776 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2777 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2778 mEphemeralResolverConnection = 2779 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2780 } else { 2781 if (DEBUG_EPHEMERAL) { 2782 final String missingComponent = 2783 (ephemeralResolverComponent == null) 2784 ? (ephemeralInstallerComponent == null) 2785 ? "resolver and installer" 2786 : "resolver" 2787 : "installer"; 2788 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2789 } 2790 mEphemeralResolverComponent = null; 2791 mEphemeralInstallerComponent = null; 2792 mEphemeralResolverConnection = null; 2793 } 2794 2795 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2796 } // synchronized (mPackages) 2797 } // synchronized (mInstallLock) 2798 2799 // Now after opening every single application zip, make sure they 2800 // are all flushed. Not really needed, but keeps things nice and 2801 // tidy. 2802 Runtime.getRuntime().gc(); 2803 2804 // The initial scanning above does many calls into installd while 2805 // holding the mPackages lock, but we're mostly interested in yelling 2806 // once we have a booted system. 2807 mInstaller.setWarnIfHeld(mPackages); 2808 2809 // Expose private service for system components to use. 2810 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2811 } 2812 2813 @Override 2814 public boolean isFirstBoot() { 2815 return !mRestoredSettings; 2816 } 2817 2818 @Override 2819 public boolean isOnlyCoreApps() { 2820 return mOnlyCore; 2821 } 2822 2823 @Override 2824 public boolean isUpgrade() { 2825 return mIsUpgrade; 2826 } 2827 2828 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2829 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2830 2831 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2832 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2833 UserHandle.USER_SYSTEM); 2834 if (matches.size() == 1) { 2835 return matches.get(0).getComponentInfo().packageName; 2836 } else { 2837 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2838 return null; 2839 } 2840 } 2841 2842 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2843 synchronized (mPackages) { 2844 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2845 if (libraryEntry == null) { 2846 throw new IllegalStateException("Missing required shared library:" + libraryName); 2847 } 2848 return libraryEntry.apk; 2849 } 2850 } 2851 2852 private @NonNull String getRequiredInstallerLPr() { 2853 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2854 intent.addCategory(Intent.CATEGORY_DEFAULT); 2855 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2856 2857 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2858 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2859 UserHandle.USER_SYSTEM); 2860 if (matches.size() == 1) { 2861 ResolveInfo resolveInfo = matches.get(0); 2862 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2863 throw new RuntimeException("The installer must be a privileged app"); 2864 } 2865 return matches.get(0).getComponentInfo().packageName; 2866 } else { 2867 throw new RuntimeException("There must be exactly one installer; found " + matches); 2868 } 2869 } 2870 2871 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2872 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2873 2874 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2875 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2876 UserHandle.USER_SYSTEM); 2877 ResolveInfo best = null; 2878 final int N = matches.size(); 2879 for (int i = 0; i < N; i++) { 2880 final ResolveInfo cur = matches.get(i); 2881 final String packageName = cur.getComponentInfo().packageName; 2882 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2883 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2884 continue; 2885 } 2886 2887 if (best == null || cur.priority > best.priority) { 2888 best = cur; 2889 } 2890 } 2891 2892 if (best != null) { 2893 return best.getComponentInfo().getComponentName(); 2894 } else { 2895 throw new RuntimeException("There must be at least one intent filter verifier"); 2896 } 2897 } 2898 2899 private @Nullable ComponentName getEphemeralResolverLPr() { 2900 final String[] packageArray = 2901 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2902 if (packageArray.length == 0) { 2903 if (DEBUG_EPHEMERAL) { 2904 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2905 } 2906 return null; 2907 } 2908 2909 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2910 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2911 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2912 UserHandle.USER_SYSTEM); 2913 2914 final int N = resolvers.size(); 2915 if (N == 0) { 2916 if (DEBUG_EPHEMERAL) { 2917 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2918 } 2919 return null; 2920 } 2921 2922 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2923 for (int i = 0; i < N; i++) { 2924 final ResolveInfo info = resolvers.get(i); 2925 2926 if (info.serviceInfo == null) { 2927 continue; 2928 } 2929 2930 final String packageName = info.serviceInfo.packageName; 2931 if (!possiblePackages.contains(packageName)) { 2932 if (DEBUG_EPHEMERAL) { 2933 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2934 + " pkg: " + packageName + ", info:" + info); 2935 } 2936 continue; 2937 } 2938 2939 if (DEBUG_EPHEMERAL) { 2940 Slog.v(TAG, "Ephemeral resolver found;" 2941 + " pkg: " + packageName + ", info:" + info); 2942 } 2943 return new ComponentName(packageName, info.serviceInfo.name); 2944 } 2945 if (DEBUG_EPHEMERAL) { 2946 Slog.v(TAG, "Ephemeral resolver NOT found"); 2947 } 2948 return null; 2949 } 2950 2951 private @Nullable ComponentName getEphemeralInstallerLPr() { 2952 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2953 intent.addCategory(Intent.CATEGORY_DEFAULT); 2954 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2955 2956 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2957 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2958 UserHandle.USER_SYSTEM); 2959 if (matches.size() == 0) { 2960 return null; 2961 } else if (matches.size() == 1) { 2962 return matches.get(0).getComponentInfo().getComponentName(); 2963 } else { 2964 throw new RuntimeException( 2965 "There must be at most one ephemeral installer; found " + matches); 2966 } 2967 } 2968 2969 private void primeDomainVerificationsLPw(int userId) { 2970 if (DEBUG_DOMAIN_VERIFICATION) { 2971 Slog.d(TAG, "Priming domain verifications in user " + userId); 2972 } 2973 2974 SystemConfig systemConfig = SystemConfig.getInstance(); 2975 ArraySet<String> packages = systemConfig.getLinkedApps(); 2976 ArraySet<String> domains = new ArraySet<String>(); 2977 2978 for (String packageName : packages) { 2979 PackageParser.Package pkg = mPackages.get(packageName); 2980 if (pkg != null) { 2981 if (!pkg.isSystemApp()) { 2982 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2983 continue; 2984 } 2985 2986 domains.clear(); 2987 for (PackageParser.Activity a : pkg.activities) { 2988 for (ActivityIntentInfo filter : a.intents) { 2989 if (hasValidDomains(filter)) { 2990 domains.addAll(filter.getHostsList()); 2991 } 2992 } 2993 } 2994 2995 if (domains.size() > 0) { 2996 if (DEBUG_DOMAIN_VERIFICATION) { 2997 Slog.v(TAG, " + " + packageName); 2998 } 2999 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3000 // state w.r.t. the formal app-linkage "no verification attempted" state; 3001 // and then 'always' in the per-user state actually used for intent resolution. 3002 final IntentFilterVerificationInfo ivi; 3003 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3004 new ArrayList<String>(domains)); 3005 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3006 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3007 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3008 } else { 3009 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3010 + "' does not handle web links"); 3011 } 3012 } else { 3013 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3014 } 3015 } 3016 3017 scheduleWritePackageRestrictionsLocked(userId); 3018 scheduleWriteSettingsLocked(); 3019 } 3020 3021 private void applyFactoryDefaultBrowserLPw(int userId) { 3022 // The default browser app's package name is stored in a string resource, 3023 // with a product-specific overlay used for vendor customization. 3024 String browserPkg = mContext.getResources().getString( 3025 com.android.internal.R.string.default_browser); 3026 if (!TextUtils.isEmpty(browserPkg)) { 3027 // non-empty string => required to be a known package 3028 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3029 if (ps == null) { 3030 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3031 browserPkg = null; 3032 } else { 3033 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3034 } 3035 } 3036 3037 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3038 // default. If there's more than one, just leave everything alone. 3039 if (browserPkg == null) { 3040 calculateDefaultBrowserLPw(userId); 3041 } 3042 } 3043 3044 private void calculateDefaultBrowserLPw(int userId) { 3045 List<String> allBrowsers = resolveAllBrowserApps(userId); 3046 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3047 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3048 } 3049 3050 private List<String> resolveAllBrowserApps(int userId) { 3051 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3052 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3053 PackageManager.MATCH_ALL, userId); 3054 3055 final int count = list.size(); 3056 List<String> result = new ArrayList<String>(count); 3057 for (int i=0; i<count; i++) { 3058 ResolveInfo info = list.get(i); 3059 if (info.activityInfo == null 3060 || !info.handleAllWebDataURI 3061 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3062 || result.contains(info.activityInfo.packageName)) { 3063 continue; 3064 } 3065 result.add(info.activityInfo.packageName); 3066 } 3067 3068 return result; 3069 } 3070 3071 private boolean packageIsBrowser(String packageName, int userId) { 3072 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3073 PackageManager.MATCH_ALL, userId); 3074 final int N = list.size(); 3075 for (int i = 0; i < N; i++) { 3076 ResolveInfo info = list.get(i); 3077 if (packageName.equals(info.activityInfo.packageName)) { 3078 return true; 3079 } 3080 } 3081 return false; 3082 } 3083 3084 private void checkDefaultBrowser() { 3085 final int myUserId = UserHandle.myUserId(); 3086 final String packageName = getDefaultBrowserPackageName(myUserId); 3087 if (packageName != null) { 3088 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3089 if (info == null) { 3090 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3091 synchronized (mPackages) { 3092 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3093 } 3094 } 3095 } 3096 } 3097 3098 @Override 3099 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3100 throws RemoteException { 3101 try { 3102 return super.onTransact(code, data, reply, flags); 3103 } catch (RuntimeException e) { 3104 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3105 Slog.wtf(TAG, "Package Manager Crash", e); 3106 } 3107 throw e; 3108 } 3109 } 3110 3111 static int[] appendInts(int[] cur, int[] add) { 3112 if (add == null) return cur; 3113 if (cur == null) return add; 3114 final int N = add.length; 3115 for (int i=0; i<N; i++) { 3116 cur = appendInt(cur, add[i]); 3117 } 3118 return cur; 3119 } 3120 3121 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3122 if (!sUserManager.exists(userId)) return null; 3123 if (ps == null) { 3124 return null; 3125 } 3126 final PackageParser.Package p = ps.pkg; 3127 if (p == null) { 3128 return null; 3129 } 3130 3131 final PermissionsState permissionsState = ps.getPermissionsState(); 3132 3133 final int[] gids = permissionsState.computeGids(userId); 3134 final Set<String> permissions = permissionsState.getPermissions(userId); 3135 final PackageUserState state = ps.readUserState(userId); 3136 3137 return PackageParser.generatePackageInfo(p, gids, flags, 3138 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3139 } 3140 3141 @Override 3142 public void checkPackageStartable(String packageName, int userId) { 3143 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3144 3145 synchronized (mPackages) { 3146 final PackageSetting ps = mSettings.mPackages.get(packageName); 3147 if (ps == null) { 3148 throw new SecurityException("Package " + packageName + " was not found!"); 3149 } 3150 3151 if (!ps.getInstalled(userId)) { 3152 throw new SecurityException( 3153 "Package " + packageName + " was not installed for user " + userId + "!"); 3154 } 3155 3156 if (mSafeMode && !ps.isSystem()) { 3157 throw new SecurityException("Package " + packageName + " not a system app!"); 3158 } 3159 3160 if (mFrozenPackages.contains(packageName)) { 3161 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3162 } 3163 3164 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3165 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3166 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3167 } 3168 } 3169 } 3170 3171 @Override 3172 public boolean isPackageAvailable(String packageName, int userId) { 3173 if (!sUserManager.exists(userId)) return false; 3174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3175 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3176 synchronized (mPackages) { 3177 PackageParser.Package p = mPackages.get(packageName); 3178 if (p != null) { 3179 final PackageSetting ps = (PackageSetting) p.mExtras; 3180 if (ps != null) { 3181 final PackageUserState state = ps.readUserState(userId); 3182 if (state != null) { 3183 return PackageParser.isAvailable(state); 3184 } 3185 } 3186 } 3187 } 3188 return false; 3189 } 3190 3191 @Override 3192 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3193 if (!sUserManager.exists(userId)) return null; 3194 flags = updateFlagsForPackage(flags, userId, packageName); 3195 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3196 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3197 // reader 3198 synchronized (mPackages) { 3199 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3200 PackageParser.Package p = null; 3201 if (matchFactoryOnly) { 3202 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3203 if (ps != null) { 3204 return generatePackageInfo(ps, flags, userId); 3205 } 3206 } 3207 if (p == null) { 3208 p = mPackages.get(packageName); 3209 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3210 return null; 3211 } 3212 } 3213 if (DEBUG_PACKAGE_INFO) 3214 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3215 if (p != null) { 3216 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3217 } 3218 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3219 final PackageSetting ps = mSettings.mPackages.get(packageName); 3220 return generatePackageInfo(ps, flags, userId); 3221 } 3222 } 3223 return null; 3224 } 3225 3226 @Override 3227 public String[] currentToCanonicalPackageNames(String[] names) { 3228 String[] out = new String[names.length]; 3229 // reader 3230 synchronized (mPackages) { 3231 for (int i=names.length-1; i>=0; i--) { 3232 PackageSetting ps = mSettings.mPackages.get(names[i]); 3233 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3234 } 3235 } 3236 return out; 3237 } 3238 3239 @Override 3240 public String[] canonicalToCurrentPackageNames(String[] names) { 3241 String[] out = new String[names.length]; 3242 // reader 3243 synchronized (mPackages) { 3244 for (int i=names.length-1; i>=0; i--) { 3245 String cur = mSettings.mRenamedPackages.get(names[i]); 3246 out[i] = cur != null ? cur : names[i]; 3247 } 3248 } 3249 return out; 3250 } 3251 3252 @Override 3253 public int getPackageUid(String packageName, int flags, int userId) { 3254 if (!sUserManager.exists(userId)) return -1; 3255 flags = updateFlagsForPackage(flags, userId, packageName); 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3257 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3258 3259 // reader 3260 synchronized (mPackages) { 3261 final PackageParser.Package p = mPackages.get(packageName); 3262 if (p != null && p.isMatch(flags)) { 3263 return UserHandle.getUid(userId, p.applicationInfo.uid); 3264 } 3265 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3266 final PackageSetting ps = mSettings.mPackages.get(packageName); 3267 if (ps != null && ps.isMatch(flags)) { 3268 return UserHandle.getUid(userId, ps.appId); 3269 } 3270 } 3271 } 3272 3273 return -1; 3274 } 3275 3276 @Override 3277 public int[] getPackageGids(String packageName, int flags, int userId) { 3278 if (!sUserManager.exists(userId)) return null; 3279 flags = updateFlagsForPackage(flags, userId, packageName); 3280 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3281 false /* requireFullPermission */, false /* checkShell */, 3282 "getPackageGids"); 3283 3284 // reader 3285 synchronized (mPackages) { 3286 final PackageParser.Package p = mPackages.get(packageName); 3287 if (p != null && p.isMatch(flags)) { 3288 PackageSetting ps = (PackageSetting) p.mExtras; 3289 return ps.getPermissionsState().computeGids(userId); 3290 } 3291 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3292 final PackageSetting ps = mSettings.mPackages.get(packageName); 3293 if (ps != null && ps.isMatch(flags)) { 3294 return ps.getPermissionsState().computeGids(userId); 3295 } 3296 } 3297 } 3298 3299 return null; 3300 } 3301 3302 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3303 if (bp.perm != null) { 3304 return PackageParser.generatePermissionInfo(bp.perm, flags); 3305 } 3306 PermissionInfo pi = new PermissionInfo(); 3307 pi.name = bp.name; 3308 pi.packageName = bp.sourcePackage; 3309 pi.nonLocalizedLabel = bp.name; 3310 pi.protectionLevel = bp.protectionLevel; 3311 return pi; 3312 } 3313 3314 @Override 3315 public PermissionInfo getPermissionInfo(String name, int flags) { 3316 // reader 3317 synchronized (mPackages) { 3318 final BasePermission p = mSettings.mPermissions.get(name); 3319 if (p != null) { 3320 return generatePermissionInfo(p, flags); 3321 } 3322 return null; 3323 } 3324 } 3325 3326 @Override 3327 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3328 int flags) { 3329 // reader 3330 synchronized (mPackages) { 3331 if (group != null && !mPermissionGroups.containsKey(group)) { 3332 // This is thrown as NameNotFoundException 3333 return null; 3334 } 3335 3336 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3337 for (BasePermission p : mSettings.mPermissions.values()) { 3338 if (group == null) { 3339 if (p.perm == null || p.perm.info.group == null) { 3340 out.add(generatePermissionInfo(p, flags)); 3341 } 3342 } else { 3343 if (p.perm != null && group.equals(p.perm.info.group)) { 3344 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3345 } 3346 } 3347 } 3348 return new ParceledListSlice<>(out); 3349 } 3350 } 3351 3352 @Override 3353 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3354 // reader 3355 synchronized (mPackages) { 3356 return PackageParser.generatePermissionGroupInfo( 3357 mPermissionGroups.get(name), flags); 3358 } 3359 } 3360 3361 @Override 3362 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3363 // reader 3364 synchronized (mPackages) { 3365 final int N = mPermissionGroups.size(); 3366 ArrayList<PermissionGroupInfo> out 3367 = new ArrayList<PermissionGroupInfo>(N); 3368 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3369 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3370 } 3371 return new ParceledListSlice<>(out); 3372 } 3373 } 3374 3375 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3376 int userId) { 3377 if (!sUserManager.exists(userId)) return null; 3378 PackageSetting ps = mSettings.mPackages.get(packageName); 3379 if (ps != null) { 3380 if (ps.pkg == null) { 3381 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3382 if (pInfo != null) { 3383 return pInfo.applicationInfo; 3384 } 3385 return null; 3386 } 3387 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3388 ps.readUserState(userId), userId); 3389 } 3390 return null; 3391 } 3392 3393 @Override 3394 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3395 if (!sUserManager.exists(userId)) return null; 3396 flags = updateFlagsForApplication(flags, userId, packageName); 3397 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3398 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3399 // writer 3400 synchronized (mPackages) { 3401 PackageParser.Package p = mPackages.get(packageName); 3402 if (DEBUG_PACKAGE_INFO) Log.v( 3403 TAG, "getApplicationInfo " + packageName 3404 + ": " + p); 3405 if (p != null) { 3406 PackageSetting ps = mSettings.mPackages.get(packageName); 3407 if (ps == null) return null; 3408 // Note: isEnabledLP() does not apply here - always return info 3409 return PackageParser.generateApplicationInfo( 3410 p, flags, ps.readUserState(userId), userId); 3411 } 3412 if ("android".equals(packageName)||"system".equals(packageName)) { 3413 return mAndroidApplication; 3414 } 3415 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3416 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3417 } 3418 } 3419 return null; 3420 } 3421 3422 @Override 3423 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3424 final IPackageDataObserver observer) { 3425 mContext.enforceCallingOrSelfPermission( 3426 android.Manifest.permission.CLEAR_APP_CACHE, null); 3427 // Queue up an async operation since clearing cache may take a little while. 3428 mHandler.post(new Runnable() { 3429 public void run() { 3430 mHandler.removeCallbacks(this); 3431 boolean success = true; 3432 synchronized (mInstallLock) { 3433 try { 3434 mInstaller.freeCache(volumeUuid, freeStorageSize); 3435 } catch (InstallerException e) { 3436 Slog.w(TAG, "Couldn't clear application caches: " + e); 3437 success = false; 3438 } 3439 } 3440 if (observer != null) { 3441 try { 3442 observer.onRemoveCompleted(null, success); 3443 } catch (RemoteException e) { 3444 Slog.w(TAG, "RemoveException when invoking call back"); 3445 } 3446 } 3447 } 3448 }); 3449 } 3450 3451 @Override 3452 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3453 final IntentSender pi) { 3454 mContext.enforceCallingOrSelfPermission( 3455 android.Manifest.permission.CLEAR_APP_CACHE, null); 3456 // Queue up an async operation since clearing cache may take a little while. 3457 mHandler.post(new Runnable() { 3458 public void run() { 3459 mHandler.removeCallbacks(this); 3460 boolean success = true; 3461 synchronized (mInstallLock) { 3462 try { 3463 mInstaller.freeCache(volumeUuid, freeStorageSize); 3464 } catch (InstallerException e) { 3465 Slog.w(TAG, "Couldn't clear application caches: " + e); 3466 success = false; 3467 } 3468 } 3469 if(pi != null) { 3470 try { 3471 // Callback via pending intent 3472 int code = success ? 1 : 0; 3473 pi.sendIntent(null, code, null, 3474 null, null); 3475 } catch (SendIntentException e1) { 3476 Slog.i(TAG, "Failed to send pending intent"); 3477 } 3478 } 3479 } 3480 }); 3481 } 3482 3483 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3484 synchronized (mInstallLock) { 3485 try { 3486 mInstaller.freeCache(volumeUuid, freeStorageSize); 3487 } catch (InstallerException e) { 3488 throw new IOException("Failed to free enough space", e); 3489 } 3490 } 3491 } 3492 3493 /** 3494 * Update given flags based on encryption status of current user. 3495 */ 3496 private int updateFlags(int flags, int userId) { 3497 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3498 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3499 // Caller expressed an explicit opinion about what encryption 3500 // aware/unaware components they want to see, so fall through and 3501 // give them what they want 3502 } else { 3503 // Caller expressed no opinion, so match based on user state 3504 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3505 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3506 } else { 3507 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3508 } 3509 } 3510 return flags; 3511 } 3512 3513 private UserManagerInternal getUserManagerInternal() { 3514 if (mUserManagerInternal == null) { 3515 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3516 } 3517 return mUserManagerInternal; 3518 } 3519 3520 /** 3521 * Update given flags when being used to request {@link PackageInfo}. 3522 */ 3523 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3524 boolean triaged = true; 3525 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3526 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3527 // Caller is asking for component details, so they'd better be 3528 // asking for specific encryption matching behavior, or be triaged 3529 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3530 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3531 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3532 triaged = false; 3533 } 3534 } 3535 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3536 | PackageManager.MATCH_SYSTEM_ONLY 3537 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3538 triaged = false; 3539 } 3540 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3541 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3542 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3543 } 3544 return updateFlags(flags, userId); 3545 } 3546 3547 /** 3548 * Update given flags when being used to request {@link ApplicationInfo}. 3549 */ 3550 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3551 return updateFlagsForPackage(flags, userId, cookie); 3552 } 3553 3554 /** 3555 * Update given flags when being used to request {@link ComponentInfo}. 3556 */ 3557 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3558 if (cookie instanceof Intent) { 3559 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3560 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3561 } 3562 } 3563 3564 boolean triaged = true; 3565 // Caller is asking for component details, so they'd better be 3566 // asking for specific encryption matching behavior, or be triaged 3567 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3568 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3569 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3570 triaged = false; 3571 } 3572 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3573 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3574 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3575 } 3576 3577 return updateFlags(flags, userId); 3578 } 3579 3580 /** 3581 * Update given flags when being used to request {@link ResolveInfo}. 3582 */ 3583 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3584 // Safe mode means we shouldn't match any third-party components 3585 if (mSafeMode) { 3586 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3587 } 3588 3589 return updateFlagsForComponent(flags, userId, cookie); 3590 } 3591 3592 @Override 3593 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3594 if (!sUserManager.exists(userId)) return null; 3595 flags = updateFlagsForComponent(flags, userId, component); 3596 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3597 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3598 synchronized (mPackages) { 3599 PackageParser.Activity a = mActivities.mActivities.get(component); 3600 3601 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3602 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3603 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3604 if (ps == null) return null; 3605 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3606 userId); 3607 } 3608 if (mResolveComponentName.equals(component)) { 3609 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3610 new PackageUserState(), userId); 3611 } 3612 } 3613 return null; 3614 } 3615 3616 @Override 3617 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3618 String resolvedType) { 3619 synchronized (mPackages) { 3620 if (component.equals(mResolveComponentName)) { 3621 // The resolver supports EVERYTHING! 3622 return true; 3623 } 3624 PackageParser.Activity a = mActivities.mActivities.get(component); 3625 if (a == null) { 3626 return false; 3627 } 3628 for (int i=0; i<a.intents.size(); i++) { 3629 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3630 intent.getData(), intent.getCategories(), TAG) >= 0) { 3631 return true; 3632 } 3633 } 3634 return false; 3635 } 3636 } 3637 3638 @Override 3639 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3640 if (!sUserManager.exists(userId)) return null; 3641 flags = updateFlagsForComponent(flags, userId, component); 3642 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3643 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3644 synchronized (mPackages) { 3645 PackageParser.Activity a = mReceivers.mActivities.get(component); 3646 if (DEBUG_PACKAGE_INFO) Log.v( 3647 TAG, "getReceiverInfo " + component + ": " + a); 3648 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3649 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3650 if (ps == null) return null; 3651 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3652 userId); 3653 } 3654 } 3655 return null; 3656 } 3657 3658 @Override 3659 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3660 if (!sUserManager.exists(userId)) return null; 3661 flags = updateFlagsForComponent(flags, userId, component); 3662 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3663 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3664 synchronized (mPackages) { 3665 PackageParser.Service s = mServices.mServices.get(component); 3666 if (DEBUG_PACKAGE_INFO) Log.v( 3667 TAG, "getServiceInfo " + component + ": " + s); 3668 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3669 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3670 if (ps == null) return null; 3671 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3672 userId); 3673 } 3674 } 3675 return null; 3676 } 3677 3678 @Override 3679 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3680 if (!sUserManager.exists(userId)) return null; 3681 flags = updateFlagsForComponent(flags, userId, component); 3682 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3683 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3684 synchronized (mPackages) { 3685 PackageParser.Provider p = mProviders.mProviders.get(component); 3686 if (DEBUG_PACKAGE_INFO) Log.v( 3687 TAG, "getProviderInfo " + component + ": " + p); 3688 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3689 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3690 if (ps == null) return null; 3691 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3692 userId); 3693 } 3694 } 3695 return null; 3696 } 3697 3698 @Override 3699 public String[] getSystemSharedLibraryNames() { 3700 Set<String> libSet; 3701 synchronized (mPackages) { 3702 libSet = mSharedLibraries.keySet(); 3703 int size = libSet.size(); 3704 if (size > 0) { 3705 String[] libs = new String[size]; 3706 libSet.toArray(libs); 3707 return libs; 3708 } 3709 } 3710 return null; 3711 } 3712 3713 @Override 3714 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3715 synchronized (mPackages) { 3716 return mServicesSystemSharedLibraryPackageName; 3717 } 3718 } 3719 3720 @Override 3721 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3722 synchronized (mPackages) { 3723 return mSharedSystemSharedLibraryPackageName; 3724 } 3725 } 3726 3727 @Override 3728 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3729 synchronized (mPackages) { 3730 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3731 3732 final FeatureInfo fi = new FeatureInfo(); 3733 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3734 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3735 res.add(fi); 3736 3737 return new ParceledListSlice<>(res); 3738 } 3739 } 3740 3741 @Override 3742 public boolean hasSystemFeature(String name, int version) { 3743 synchronized (mPackages) { 3744 final FeatureInfo feat = mAvailableFeatures.get(name); 3745 if (feat == null) { 3746 return false; 3747 } else { 3748 return feat.version >= version; 3749 } 3750 } 3751 } 3752 3753 @Override 3754 public int checkPermission(String permName, String pkgName, int userId) { 3755 if (!sUserManager.exists(userId)) { 3756 return PackageManager.PERMISSION_DENIED; 3757 } 3758 3759 synchronized (mPackages) { 3760 final PackageParser.Package p = mPackages.get(pkgName); 3761 if (p != null && p.mExtras != null) { 3762 final PackageSetting ps = (PackageSetting) p.mExtras; 3763 final PermissionsState permissionsState = ps.getPermissionsState(); 3764 if (permissionsState.hasPermission(permName, userId)) { 3765 return PackageManager.PERMISSION_GRANTED; 3766 } 3767 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3768 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3769 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3770 return PackageManager.PERMISSION_GRANTED; 3771 } 3772 } 3773 } 3774 3775 return PackageManager.PERMISSION_DENIED; 3776 } 3777 3778 @Override 3779 public int checkUidPermission(String permName, int uid) { 3780 final int userId = UserHandle.getUserId(uid); 3781 3782 if (!sUserManager.exists(userId)) { 3783 return PackageManager.PERMISSION_DENIED; 3784 } 3785 3786 synchronized (mPackages) { 3787 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3788 if (obj != null) { 3789 final SettingBase ps = (SettingBase) obj; 3790 final PermissionsState permissionsState = ps.getPermissionsState(); 3791 if (permissionsState.hasPermission(permName, userId)) { 3792 return PackageManager.PERMISSION_GRANTED; 3793 } 3794 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3795 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3796 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3797 return PackageManager.PERMISSION_GRANTED; 3798 } 3799 } else { 3800 ArraySet<String> perms = mSystemPermissions.get(uid); 3801 if (perms != null) { 3802 if (perms.contains(permName)) { 3803 return PackageManager.PERMISSION_GRANTED; 3804 } 3805 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3806 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3807 return PackageManager.PERMISSION_GRANTED; 3808 } 3809 } 3810 } 3811 } 3812 3813 return PackageManager.PERMISSION_DENIED; 3814 } 3815 3816 @Override 3817 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3818 if (UserHandle.getCallingUserId() != userId) { 3819 mContext.enforceCallingPermission( 3820 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3821 "isPermissionRevokedByPolicy for user " + userId); 3822 } 3823 3824 if (checkPermission(permission, packageName, userId) 3825 == PackageManager.PERMISSION_GRANTED) { 3826 return false; 3827 } 3828 3829 final long identity = Binder.clearCallingIdentity(); 3830 try { 3831 final int flags = getPermissionFlags(permission, packageName, userId); 3832 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3833 } finally { 3834 Binder.restoreCallingIdentity(identity); 3835 } 3836 } 3837 3838 @Override 3839 public String getPermissionControllerPackageName() { 3840 synchronized (mPackages) { 3841 return mRequiredInstallerPackage; 3842 } 3843 } 3844 3845 /** 3846 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3847 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3848 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3849 * @param message the message to log on security exception 3850 */ 3851 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3852 boolean checkShell, String message) { 3853 if (userId < 0) { 3854 throw new IllegalArgumentException("Invalid userId " + userId); 3855 } 3856 if (checkShell) { 3857 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3858 } 3859 if (userId == UserHandle.getUserId(callingUid)) return; 3860 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3861 if (requireFullPermission) { 3862 mContext.enforceCallingOrSelfPermission( 3863 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3864 } else { 3865 try { 3866 mContext.enforceCallingOrSelfPermission( 3867 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3868 } catch (SecurityException se) { 3869 mContext.enforceCallingOrSelfPermission( 3870 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3871 } 3872 } 3873 } 3874 } 3875 3876 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3877 if (callingUid == Process.SHELL_UID) { 3878 if (userHandle >= 0 3879 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3880 throw new SecurityException("Shell does not have permission to access user " 3881 + userHandle); 3882 } else if (userHandle < 0) { 3883 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3884 + Debug.getCallers(3)); 3885 } 3886 } 3887 } 3888 3889 private BasePermission findPermissionTreeLP(String permName) { 3890 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3891 if (permName.startsWith(bp.name) && 3892 permName.length() > bp.name.length() && 3893 permName.charAt(bp.name.length()) == '.') { 3894 return bp; 3895 } 3896 } 3897 return null; 3898 } 3899 3900 private BasePermission checkPermissionTreeLP(String permName) { 3901 if (permName != null) { 3902 BasePermission bp = findPermissionTreeLP(permName); 3903 if (bp != null) { 3904 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3905 return bp; 3906 } 3907 throw new SecurityException("Calling uid " 3908 + Binder.getCallingUid() 3909 + " is not allowed to add to permission tree " 3910 + bp.name + " owned by uid " + bp.uid); 3911 } 3912 } 3913 throw new SecurityException("No permission tree found for " + permName); 3914 } 3915 3916 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3917 if (s1 == null) { 3918 return s2 == null; 3919 } 3920 if (s2 == null) { 3921 return false; 3922 } 3923 if (s1.getClass() != s2.getClass()) { 3924 return false; 3925 } 3926 return s1.equals(s2); 3927 } 3928 3929 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3930 if (pi1.icon != pi2.icon) return false; 3931 if (pi1.logo != pi2.logo) return false; 3932 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3933 if (!compareStrings(pi1.name, pi2.name)) return false; 3934 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3935 // We'll take care of setting this one. 3936 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3937 // These are not currently stored in settings. 3938 //if (!compareStrings(pi1.group, pi2.group)) return false; 3939 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3940 //if (pi1.labelRes != pi2.labelRes) return false; 3941 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3942 return true; 3943 } 3944 3945 int permissionInfoFootprint(PermissionInfo info) { 3946 int size = info.name.length(); 3947 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3948 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3949 return size; 3950 } 3951 3952 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3953 int size = 0; 3954 for (BasePermission perm : mSettings.mPermissions.values()) { 3955 if (perm.uid == tree.uid) { 3956 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3957 } 3958 } 3959 return size; 3960 } 3961 3962 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3963 // We calculate the max size of permissions defined by this uid and throw 3964 // if that plus the size of 'info' would exceed our stated maximum. 3965 if (tree.uid != Process.SYSTEM_UID) { 3966 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3967 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3968 throw new SecurityException("Permission tree size cap exceeded"); 3969 } 3970 } 3971 } 3972 3973 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3974 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3975 throw new SecurityException("Label must be specified in permission"); 3976 } 3977 BasePermission tree = checkPermissionTreeLP(info.name); 3978 BasePermission bp = mSettings.mPermissions.get(info.name); 3979 boolean added = bp == null; 3980 boolean changed = true; 3981 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3982 if (added) { 3983 enforcePermissionCapLocked(info, tree); 3984 bp = new BasePermission(info.name, tree.sourcePackage, 3985 BasePermission.TYPE_DYNAMIC); 3986 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3987 throw new SecurityException( 3988 "Not allowed to modify non-dynamic permission " 3989 + info.name); 3990 } else { 3991 if (bp.protectionLevel == fixedLevel 3992 && bp.perm.owner.equals(tree.perm.owner) 3993 && bp.uid == tree.uid 3994 && comparePermissionInfos(bp.perm.info, info)) { 3995 changed = false; 3996 } 3997 } 3998 bp.protectionLevel = fixedLevel; 3999 info = new PermissionInfo(info); 4000 info.protectionLevel = fixedLevel; 4001 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4002 bp.perm.info.packageName = tree.perm.info.packageName; 4003 bp.uid = tree.uid; 4004 if (added) { 4005 mSettings.mPermissions.put(info.name, bp); 4006 } 4007 if (changed) { 4008 if (!async) { 4009 mSettings.writeLPr(); 4010 } else { 4011 scheduleWriteSettingsLocked(); 4012 } 4013 } 4014 return added; 4015 } 4016 4017 @Override 4018 public boolean addPermission(PermissionInfo info) { 4019 synchronized (mPackages) { 4020 return addPermissionLocked(info, false); 4021 } 4022 } 4023 4024 @Override 4025 public boolean addPermissionAsync(PermissionInfo info) { 4026 synchronized (mPackages) { 4027 return addPermissionLocked(info, true); 4028 } 4029 } 4030 4031 @Override 4032 public void removePermission(String name) { 4033 synchronized (mPackages) { 4034 checkPermissionTreeLP(name); 4035 BasePermission bp = mSettings.mPermissions.get(name); 4036 if (bp != null) { 4037 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4038 throw new SecurityException( 4039 "Not allowed to modify non-dynamic permission " 4040 + name); 4041 } 4042 mSettings.mPermissions.remove(name); 4043 mSettings.writeLPr(); 4044 } 4045 } 4046 } 4047 4048 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4049 BasePermission bp) { 4050 int index = pkg.requestedPermissions.indexOf(bp.name); 4051 if (index == -1) { 4052 throw new SecurityException("Package " + pkg.packageName 4053 + " has not requested permission " + bp.name); 4054 } 4055 if (!bp.isRuntime() && !bp.isDevelopment()) { 4056 throw new SecurityException("Permission " + bp.name 4057 + " is not a changeable permission type"); 4058 } 4059 } 4060 4061 @Override 4062 public void grantRuntimePermission(String packageName, String name, final int userId) { 4063 if (!sUserManager.exists(userId)) { 4064 Log.e(TAG, "No such user:" + userId); 4065 return; 4066 } 4067 4068 mContext.enforceCallingOrSelfPermission( 4069 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4070 "grantRuntimePermission"); 4071 4072 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4073 true /* requireFullPermission */, true /* checkShell */, 4074 "grantRuntimePermission"); 4075 4076 final int uid; 4077 final SettingBase sb; 4078 4079 synchronized (mPackages) { 4080 final PackageParser.Package pkg = mPackages.get(packageName); 4081 if (pkg == null) { 4082 throw new IllegalArgumentException("Unknown package: " + packageName); 4083 } 4084 4085 final BasePermission bp = mSettings.mPermissions.get(name); 4086 if (bp == null) { 4087 throw new IllegalArgumentException("Unknown permission: " + name); 4088 } 4089 4090 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4091 4092 // If a permission review is required for legacy apps we represent 4093 // their permissions as always granted runtime ones since we need 4094 // to keep the review required permission flag per user while an 4095 // install permission's state is shared across all users. 4096 if (Build.PERMISSIONS_REVIEW_REQUIRED 4097 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4098 && bp.isRuntime()) { 4099 return; 4100 } 4101 4102 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4103 sb = (SettingBase) pkg.mExtras; 4104 if (sb == null) { 4105 throw new IllegalArgumentException("Unknown package: " + packageName); 4106 } 4107 4108 final PermissionsState permissionsState = sb.getPermissionsState(); 4109 4110 final int flags = permissionsState.getPermissionFlags(name, userId); 4111 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4112 throw new SecurityException("Cannot grant system fixed permission " 4113 + name + " for package " + packageName); 4114 } 4115 4116 if (bp.isDevelopment()) { 4117 // Development permissions must be handled specially, since they are not 4118 // normal runtime permissions. For now they apply to all users. 4119 if (permissionsState.grantInstallPermission(bp) != 4120 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4121 scheduleWriteSettingsLocked(); 4122 } 4123 return; 4124 } 4125 4126 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4127 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4128 return; 4129 } 4130 4131 final int result = permissionsState.grantRuntimePermission(bp, userId); 4132 switch (result) { 4133 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4134 return; 4135 } 4136 4137 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4138 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4139 mHandler.post(new Runnable() { 4140 @Override 4141 public void run() { 4142 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4143 } 4144 }); 4145 } 4146 break; 4147 } 4148 4149 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4150 4151 // Not critical if that is lost - app has to request again. 4152 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4153 } 4154 4155 // Only need to do this if user is initialized. Otherwise it's a new user 4156 // and there are no processes running as the user yet and there's no need 4157 // to make an expensive call to remount processes for the changed permissions. 4158 if (READ_EXTERNAL_STORAGE.equals(name) 4159 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4160 final long token = Binder.clearCallingIdentity(); 4161 try { 4162 if (sUserManager.isInitialized(userId)) { 4163 MountServiceInternal mountServiceInternal = LocalServices.getService( 4164 MountServiceInternal.class); 4165 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4166 } 4167 } finally { 4168 Binder.restoreCallingIdentity(token); 4169 } 4170 } 4171 } 4172 4173 @Override 4174 public void revokeRuntimePermission(String packageName, String name, int userId) { 4175 if (!sUserManager.exists(userId)) { 4176 Log.e(TAG, "No such user:" + userId); 4177 return; 4178 } 4179 4180 mContext.enforceCallingOrSelfPermission( 4181 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4182 "revokeRuntimePermission"); 4183 4184 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4185 true /* requireFullPermission */, true /* checkShell */, 4186 "revokeRuntimePermission"); 4187 4188 final int appId; 4189 4190 synchronized (mPackages) { 4191 final PackageParser.Package pkg = mPackages.get(packageName); 4192 if (pkg == null) { 4193 throw new IllegalArgumentException("Unknown package: " + packageName); 4194 } 4195 4196 final BasePermission bp = mSettings.mPermissions.get(name); 4197 if (bp == null) { 4198 throw new IllegalArgumentException("Unknown permission: " + name); 4199 } 4200 4201 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4202 4203 // If a permission review is required for legacy apps we represent 4204 // their permissions as always granted runtime ones since we need 4205 // to keep the review required permission flag per user while an 4206 // install permission's state is shared across all users. 4207 if (Build.PERMISSIONS_REVIEW_REQUIRED 4208 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4209 && bp.isRuntime()) { 4210 return; 4211 } 4212 4213 SettingBase sb = (SettingBase) pkg.mExtras; 4214 if (sb == null) { 4215 throw new IllegalArgumentException("Unknown package: " + packageName); 4216 } 4217 4218 final PermissionsState permissionsState = sb.getPermissionsState(); 4219 4220 final int flags = permissionsState.getPermissionFlags(name, userId); 4221 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4222 throw new SecurityException("Cannot revoke system fixed permission " 4223 + name + " for package " + packageName); 4224 } 4225 4226 if (bp.isDevelopment()) { 4227 // Development permissions must be handled specially, since they are not 4228 // normal runtime permissions. For now they apply to all users. 4229 if (permissionsState.revokeInstallPermission(bp) != 4230 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4231 scheduleWriteSettingsLocked(); 4232 } 4233 return; 4234 } 4235 4236 if (permissionsState.revokeRuntimePermission(bp, userId) == 4237 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4238 return; 4239 } 4240 4241 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4242 4243 // Critical, after this call app should never have the permission. 4244 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4245 4246 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4247 } 4248 4249 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4250 } 4251 4252 @Override 4253 public void resetRuntimePermissions() { 4254 mContext.enforceCallingOrSelfPermission( 4255 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4256 "revokeRuntimePermission"); 4257 4258 int callingUid = Binder.getCallingUid(); 4259 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4260 mContext.enforceCallingOrSelfPermission( 4261 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4262 "resetRuntimePermissions"); 4263 } 4264 4265 synchronized (mPackages) { 4266 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4267 for (int userId : UserManagerService.getInstance().getUserIds()) { 4268 final int packageCount = mPackages.size(); 4269 for (int i = 0; i < packageCount; i++) { 4270 PackageParser.Package pkg = mPackages.valueAt(i); 4271 if (!(pkg.mExtras instanceof PackageSetting)) { 4272 continue; 4273 } 4274 PackageSetting ps = (PackageSetting) pkg.mExtras; 4275 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4276 } 4277 } 4278 } 4279 } 4280 4281 @Override 4282 public int getPermissionFlags(String name, String packageName, int userId) { 4283 if (!sUserManager.exists(userId)) { 4284 return 0; 4285 } 4286 4287 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4288 4289 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4290 true /* requireFullPermission */, false /* checkShell */, 4291 "getPermissionFlags"); 4292 4293 synchronized (mPackages) { 4294 final PackageParser.Package pkg = mPackages.get(packageName); 4295 if (pkg == null) { 4296 return 0; 4297 } 4298 4299 final BasePermission bp = mSettings.mPermissions.get(name); 4300 if (bp == null) { 4301 return 0; 4302 } 4303 4304 SettingBase sb = (SettingBase) pkg.mExtras; 4305 if (sb == null) { 4306 return 0; 4307 } 4308 4309 PermissionsState permissionsState = sb.getPermissionsState(); 4310 return permissionsState.getPermissionFlags(name, userId); 4311 } 4312 } 4313 4314 @Override 4315 public void updatePermissionFlags(String name, String packageName, int flagMask, 4316 int flagValues, int userId) { 4317 if (!sUserManager.exists(userId)) { 4318 return; 4319 } 4320 4321 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4322 4323 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4324 true /* requireFullPermission */, true /* checkShell */, 4325 "updatePermissionFlags"); 4326 4327 // Only the system can change these flags and nothing else. 4328 if (getCallingUid() != Process.SYSTEM_UID) { 4329 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4330 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4331 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4332 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4333 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4334 } 4335 4336 synchronized (mPackages) { 4337 final PackageParser.Package pkg = mPackages.get(packageName); 4338 if (pkg == null) { 4339 throw new IllegalArgumentException("Unknown package: " + packageName); 4340 } 4341 4342 final BasePermission bp = mSettings.mPermissions.get(name); 4343 if (bp == null) { 4344 throw new IllegalArgumentException("Unknown permission: " + name); 4345 } 4346 4347 SettingBase sb = (SettingBase) pkg.mExtras; 4348 if (sb == null) { 4349 throw new IllegalArgumentException("Unknown package: " + packageName); 4350 } 4351 4352 PermissionsState permissionsState = sb.getPermissionsState(); 4353 4354 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4355 4356 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4357 // Install and runtime permissions are stored in different places, 4358 // so figure out what permission changed and persist the change. 4359 if (permissionsState.getInstallPermissionState(name) != null) { 4360 scheduleWriteSettingsLocked(); 4361 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4362 || hadState) { 4363 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4364 } 4365 } 4366 } 4367 } 4368 4369 /** 4370 * Update the permission flags for all packages and runtime permissions of a user in order 4371 * to allow device or profile owner to remove POLICY_FIXED. 4372 */ 4373 @Override 4374 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4375 if (!sUserManager.exists(userId)) { 4376 return; 4377 } 4378 4379 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4380 4381 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4382 true /* requireFullPermission */, true /* checkShell */, 4383 "updatePermissionFlagsForAllApps"); 4384 4385 // Only the system can change system fixed flags. 4386 if (getCallingUid() != Process.SYSTEM_UID) { 4387 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4388 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4389 } 4390 4391 synchronized (mPackages) { 4392 boolean changed = false; 4393 final int packageCount = mPackages.size(); 4394 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4395 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4396 SettingBase sb = (SettingBase) pkg.mExtras; 4397 if (sb == null) { 4398 continue; 4399 } 4400 PermissionsState permissionsState = sb.getPermissionsState(); 4401 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4402 userId, flagMask, flagValues); 4403 } 4404 if (changed) { 4405 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4406 } 4407 } 4408 } 4409 4410 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4411 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4412 != PackageManager.PERMISSION_GRANTED 4413 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4414 != PackageManager.PERMISSION_GRANTED) { 4415 throw new SecurityException(message + " requires " 4416 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4417 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4418 } 4419 } 4420 4421 @Override 4422 public boolean shouldShowRequestPermissionRationale(String permissionName, 4423 String packageName, int userId) { 4424 if (UserHandle.getCallingUserId() != userId) { 4425 mContext.enforceCallingPermission( 4426 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4427 "canShowRequestPermissionRationale for user " + userId); 4428 } 4429 4430 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4431 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4432 return false; 4433 } 4434 4435 if (checkPermission(permissionName, packageName, userId) 4436 == PackageManager.PERMISSION_GRANTED) { 4437 return false; 4438 } 4439 4440 final int flags; 4441 4442 final long identity = Binder.clearCallingIdentity(); 4443 try { 4444 flags = getPermissionFlags(permissionName, 4445 packageName, userId); 4446 } finally { 4447 Binder.restoreCallingIdentity(identity); 4448 } 4449 4450 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4451 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4452 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4453 4454 if ((flags & fixedFlags) != 0) { 4455 return false; 4456 } 4457 4458 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4459 } 4460 4461 @Override 4462 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4463 mContext.enforceCallingOrSelfPermission( 4464 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4465 "addOnPermissionsChangeListener"); 4466 4467 synchronized (mPackages) { 4468 mOnPermissionChangeListeners.addListenerLocked(listener); 4469 } 4470 } 4471 4472 @Override 4473 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4474 synchronized (mPackages) { 4475 mOnPermissionChangeListeners.removeListenerLocked(listener); 4476 } 4477 } 4478 4479 @Override 4480 public boolean isProtectedBroadcast(String actionName) { 4481 synchronized (mPackages) { 4482 if (mProtectedBroadcasts.contains(actionName)) { 4483 return true; 4484 } else if (actionName != null) { 4485 // TODO: remove these terrible hacks 4486 if (actionName.startsWith("android.net.netmon.lingerExpired") 4487 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4488 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4489 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4490 return true; 4491 } 4492 } 4493 } 4494 return false; 4495 } 4496 4497 @Override 4498 public int checkSignatures(String pkg1, String pkg2) { 4499 synchronized (mPackages) { 4500 final PackageParser.Package p1 = mPackages.get(pkg1); 4501 final PackageParser.Package p2 = mPackages.get(pkg2); 4502 if (p1 == null || p1.mExtras == null 4503 || p2 == null || p2.mExtras == null) { 4504 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4505 } 4506 return compareSignatures(p1.mSignatures, p2.mSignatures); 4507 } 4508 } 4509 4510 @Override 4511 public int checkUidSignatures(int uid1, int uid2) { 4512 // Map to base uids. 4513 uid1 = UserHandle.getAppId(uid1); 4514 uid2 = UserHandle.getAppId(uid2); 4515 // reader 4516 synchronized (mPackages) { 4517 Signature[] s1; 4518 Signature[] s2; 4519 Object obj = mSettings.getUserIdLPr(uid1); 4520 if (obj != null) { 4521 if (obj instanceof SharedUserSetting) { 4522 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4523 } else if (obj instanceof PackageSetting) { 4524 s1 = ((PackageSetting)obj).signatures.mSignatures; 4525 } else { 4526 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4527 } 4528 } else { 4529 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4530 } 4531 obj = mSettings.getUserIdLPr(uid2); 4532 if (obj != null) { 4533 if (obj instanceof SharedUserSetting) { 4534 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4535 } else if (obj instanceof PackageSetting) { 4536 s2 = ((PackageSetting)obj).signatures.mSignatures; 4537 } else { 4538 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4539 } 4540 } else { 4541 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4542 } 4543 return compareSignatures(s1, s2); 4544 } 4545 } 4546 4547 /** 4548 * This method should typically only be used when granting or revoking 4549 * permissions, since the app may immediately restart after this call. 4550 * <p> 4551 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4552 * guard your work against the app being relaunched. 4553 */ 4554 private void killUid(int appId, int userId, String reason) { 4555 final long identity = Binder.clearCallingIdentity(); 4556 try { 4557 IActivityManager am = ActivityManagerNative.getDefault(); 4558 if (am != null) { 4559 try { 4560 am.killUid(appId, userId, reason); 4561 } catch (RemoteException e) { 4562 /* ignore - same process */ 4563 } 4564 } 4565 } finally { 4566 Binder.restoreCallingIdentity(identity); 4567 } 4568 } 4569 4570 /** 4571 * Compares two sets of signatures. Returns: 4572 * <br /> 4573 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4574 * <br /> 4575 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4576 * <br /> 4577 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4578 * <br /> 4579 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4580 * <br /> 4581 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4582 */ 4583 static int compareSignatures(Signature[] s1, Signature[] s2) { 4584 if (s1 == null) { 4585 return s2 == null 4586 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4587 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4588 } 4589 4590 if (s2 == null) { 4591 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4592 } 4593 4594 if (s1.length != s2.length) { 4595 return PackageManager.SIGNATURE_NO_MATCH; 4596 } 4597 4598 // Since both signature sets are of size 1, we can compare without HashSets. 4599 if (s1.length == 1) { 4600 return s1[0].equals(s2[0]) ? 4601 PackageManager.SIGNATURE_MATCH : 4602 PackageManager.SIGNATURE_NO_MATCH; 4603 } 4604 4605 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4606 for (Signature sig : s1) { 4607 set1.add(sig); 4608 } 4609 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4610 for (Signature sig : s2) { 4611 set2.add(sig); 4612 } 4613 // Make sure s2 contains all signatures in s1. 4614 if (set1.equals(set2)) { 4615 return PackageManager.SIGNATURE_MATCH; 4616 } 4617 return PackageManager.SIGNATURE_NO_MATCH; 4618 } 4619 4620 /** 4621 * If the database version for this type of package (internal storage or 4622 * external storage) is less than the version where package signatures 4623 * were updated, return true. 4624 */ 4625 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4626 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4627 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4628 } 4629 4630 /** 4631 * Used for backward compatibility to make sure any packages with 4632 * certificate chains get upgraded to the new style. {@code existingSigs} 4633 * will be in the old format (since they were stored on disk from before the 4634 * system upgrade) and {@code scannedSigs} will be in the newer format. 4635 */ 4636 private int compareSignaturesCompat(PackageSignatures existingSigs, 4637 PackageParser.Package scannedPkg) { 4638 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4639 return PackageManager.SIGNATURE_NO_MATCH; 4640 } 4641 4642 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4643 for (Signature sig : existingSigs.mSignatures) { 4644 existingSet.add(sig); 4645 } 4646 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4647 for (Signature sig : scannedPkg.mSignatures) { 4648 try { 4649 Signature[] chainSignatures = sig.getChainSignatures(); 4650 for (Signature chainSig : chainSignatures) { 4651 scannedCompatSet.add(chainSig); 4652 } 4653 } catch (CertificateEncodingException e) { 4654 scannedCompatSet.add(sig); 4655 } 4656 } 4657 /* 4658 * Make sure the expanded scanned set contains all signatures in the 4659 * existing one. 4660 */ 4661 if (scannedCompatSet.equals(existingSet)) { 4662 // Migrate the old signatures to the new scheme. 4663 existingSigs.assignSignatures(scannedPkg.mSignatures); 4664 // The new KeySets will be re-added later in the scanning process. 4665 synchronized (mPackages) { 4666 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4667 } 4668 return PackageManager.SIGNATURE_MATCH; 4669 } 4670 return PackageManager.SIGNATURE_NO_MATCH; 4671 } 4672 4673 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4674 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4675 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4676 } 4677 4678 private int compareSignaturesRecover(PackageSignatures existingSigs, 4679 PackageParser.Package scannedPkg) { 4680 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4681 return PackageManager.SIGNATURE_NO_MATCH; 4682 } 4683 4684 String msg = null; 4685 try { 4686 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4687 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4688 + scannedPkg.packageName); 4689 return PackageManager.SIGNATURE_MATCH; 4690 } 4691 } catch (CertificateException e) { 4692 msg = e.getMessage(); 4693 } 4694 4695 logCriticalInfo(Log.INFO, 4696 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4697 return PackageManager.SIGNATURE_NO_MATCH; 4698 } 4699 4700 @Override 4701 public List<String> getAllPackages() { 4702 synchronized (mPackages) { 4703 return new ArrayList<String>(mPackages.keySet()); 4704 } 4705 } 4706 4707 @Override 4708 public String[] getPackagesForUid(int uid) { 4709 uid = UserHandle.getAppId(uid); 4710 // reader 4711 synchronized (mPackages) { 4712 Object obj = mSettings.getUserIdLPr(uid); 4713 if (obj instanceof SharedUserSetting) { 4714 final SharedUserSetting sus = (SharedUserSetting) obj; 4715 final int N = sus.packages.size(); 4716 final String[] res = new String[N]; 4717 final Iterator<PackageSetting> it = sus.packages.iterator(); 4718 int i = 0; 4719 while (it.hasNext()) { 4720 res[i++] = it.next().name; 4721 } 4722 return res; 4723 } else if (obj instanceof PackageSetting) { 4724 final PackageSetting ps = (PackageSetting) obj; 4725 return new String[] { ps.name }; 4726 } 4727 } 4728 return null; 4729 } 4730 4731 @Override 4732 public String getNameForUid(int uid) { 4733 // reader 4734 synchronized (mPackages) { 4735 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4736 if (obj instanceof SharedUserSetting) { 4737 final SharedUserSetting sus = (SharedUserSetting) obj; 4738 return sus.name + ":" + sus.userId; 4739 } else if (obj instanceof PackageSetting) { 4740 final PackageSetting ps = (PackageSetting) obj; 4741 return ps.name; 4742 } 4743 } 4744 return null; 4745 } 4746 4747 @Override 4748 public int getUidForSharedUser(String sharedUserName) { 4749 if(sharedUserName == null) { 4750 return -1; 4751 } 4752 // reader 4753 synchronized (mPackages) { 4754 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4755 if (suid == null) { 4756 return -1; 4757 } 4758 return suid.userId; 4759 } 4760 } 4761 4762 @Override 4763 public int getFlagsForUid(int uid) { 4764 synchronized (mPackages) { 4765 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4766 if (obj instanceof SharedUserSetting) { 4767 final SharedUserSetting sus = (SharedUserSetting) obj; 4768 return sus.pkgFlags; 4769 } else if (obj instanceof PackageSetting) { 4770 final PackageSetting ps = (PackageSetting) obj; 4771 return ps.pkgFlags; 4772 } 4773 } 4774 return 0; 4775 } 4776 4777 @Override 4778 public int getPrivateFlagsForUid(int uid) { 4779 synchronized (mPackages) { 4780 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4781 if (obj instanceof SharedUserSetting) { 4782 final SharedUserSetting sus = (SharedUserSetting) obj; 4783 return sus.pkgPrivateFlags; 4784 } else if (obj instanceof PackageSetting) { 4785 final PackageSetting ps = (PackageSetting) obj; 4786 return ps.pkgPrivateFlags; 4787 } 4788 } 4789 return 0; 4790 } 4791 4792 @Override 4793 public boolean isUidPrivileged(int uid) { 4794 uid = UserHandle.getAppId(uid); 4795 // reader 4796 synchronized (mPackages) { 4797 Object obj = mSettings.getUserIdLPr(uid); 4798 if (obj instanceof SharedUserSetting) { 4799 final SharedUserSetting sus = (SharedUserSetting) obj; 4800 final Iterator<PackageSetting> it = sus.packages.iterator(); 4801 while (it.hasNext()) { 4802 if (it.next().isPrivileged()) { 4803 return true; 4804 } 4805 } 4806 } else if (obj instanceof PackageSetting) { 4807 final PackageSetting ps = (PackageSetting) obj; 4808 return ps.isPrivileged(); 4809 } 4810 } 4811 return false; 4812 } 4813 4814 @Override 4815 public String[] getAppOpPermissionPackages(String permissionName) { 4816 synchronized (mPackages) { 4817 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4818 if (pkgs == null) { 4819 return null; 4820 } 4821 return pkgs.toArray(new String[pkgs.size()]); 4822 } 4823 } 4824 4825 @Override 4826 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4827 int flags, int userId) { 4828 try { 4829 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4830 4831 if (!sUserManager.exists(userId)) return null; 4832 flags = updateFlagsForResolve(flags, userId, intent); 4833 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4834 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4835 4836 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4837 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4838 flags, userId); 4839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4840 4841 final ResolveInfo bestChoice = 4842 chooseBestActivity(intent, resolvedType, flags, query, userId); 4843 4844 if (isEphemeralAllowed(intent, query, userId)) { 4845 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4846 final EphemeralResolveInfo ai = 4847 getEphemeralResolveInfo(intent, resolvedType, userId); 4848 if (ai != null) { 4849 if (DEBUG_EPHEMERAL) { 4850 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4851 } 4852 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4853 bestChoice.ephemeralResolveInfo = ai; 4854 } 4855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4856 } 4857 return bestChoice; 4858 } finally { 4859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4860 } 4861 } 4862 4863 @Override 4864 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4865 IntentFilter filter, int match, ComponentName activity) { 4866 final int userId = UserHandle.getCallingUserId(); 4867 if (DEBUG_PREFERRED) { 4868 Log.v(TAG, "setLastChosenActivity intent=" + intent 4869 + " resolvedType=" + resolvedType 4870 + " flags=" + flags 4871 + " filter=" + filter 4872 + " match=" + match 4873 + " activity=" + activity); 4874 filter.dump(new PrintStreamPrinter(System.out), " "); 4875 } 4876 intent.setComponent(null); 4877 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4878 userId); 4879 // Find any earlier preferred or last chosen entries and nuke them 4880 findPreferredActivity(intent, resolvedType, 4881 flags, query, 0, false, true, false, userId); 4882 // Add the new activity as the last chosen for this filter 4883 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4884 "Setting last chosen"); 4885 } 4886 4887 @Override 4888 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4889 final int userId = UserHandle.getCallingUserId(); 4890 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4891 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4892 userId); 4893 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4894 false, false, false, userId); 4895 } 4896 4897 4898 private boolean isEphemeralAllowed( 4899 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4900 // Short circuit and return early if possible. 4901 if (DISABLE_EPHEMERAL_APPS) { 4902 return false; 4903 } 4904 final int callingUser = UserHandle.getCallingUserId(); 4905 if (callingUser != UserHandle.USER_SYSTEM) { 4906 return false; 4907 } 4908 if (mEphemeralResolverConnection == null) { 4909 return false; 4910 } 4911 if (intent.getComponent() != null) { 4912 return false; 4913 } 4914 if (intent.getPackage() != null) { 4915 return false; 4916 } 4917 final boolean isWebUri = hasWebURI(intent); 4918 if (!isWebUri) { 4919 return false; 4920 } 4921 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4922 synchronized (mPackages) { 4923 final int count = resolvedActivites.size(); 4924 for (int n = 0; n < count; n++) { 4925 ResolveInfo info = resolvedActivites.get(n); 4926 String packageName = info.activityInfo.packageName; 4927 PackageSetting ps = mSettings.mPackages.get(packageName); 4928 if (ps != null) { 4929 // Try to get the status from User settings first 4930 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4931 int status = (int) (packedStatus >> 32); 4932 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4933 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4934 if (DEBUG_EPHEMERAL) { 4935 Slog.v(TAG, "DENY ephemeral apps;" 4936 + " pkg: " + packageName + ", status: " + status); 4937 } 4938 return false; 4939 } 4940 } 4941 } 4942 } 4943 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4944 return true; 4945 } 4946 4947 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4948 int userId) { 4949 MessageDigest digest = null; 4950 try { 4951 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4952 } catch (NoSuchAlgorithmException e) { 4953 // If we can't create a digest, ignore ephemeral apps. 4954 return null; 4955 } 4956 4957 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4958 final byte[] digestBytes = digest.digest(hostBytes); 4959 int shaPrefix = 4960 digestBytes[0] << 24 4961 | digestBytes[1] << 16 4962 | digestBytes[2] << 8 4963 | digestBytes[3] << 0; 4964 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4965 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4966 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4967 // No hash prefix match; there are no ephemeral apps for this domain. 4968 return null; 4969 } 4970 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4971 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4972 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4973 continue; 4974 } 4975 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4976 // No filters; this should never happen. 4977 if (filters.isEmpty()) { 4978 continue; 4979 } 4980 // We have a domain match; resolve the filters to see if anything matches. 4981 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4982 for (int j = filters.size() - 1; j >= 0; --j) { 4983 final EphemeralResolveIntentInfo intentInfo = 4984 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4985 ephemeralResolver.addFilter(intentInfo); 4986 } 4987 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4988 intent, resolvedType, false /*defaultOnly*/, userId); 4989 if (!matchedResolveInfoList.isEmpty()) { 4990 return matchedResolveInfoList.get(0); 4991 } 4992 } 4993 // Hash or filter mis-match; no ephemeral apps for this domain. 4994 return null; 4995 } 4996 4997 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4998 int flags, List<ResolveInfo> query, int userId) { 4999 if (query != null) { 5000 final int N = query.size(); 5001 if (N == 1) { 5002 return query.get(0); 5003 } else if (N > 1) { 5004 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5005 // If there is more than one activity with the same priority, 5006 // then let the user decide between them. 5007 ResolveInfo r0 = query.get(0); 5008 ResolveInfo r1 = query.get(1); 5009 if (DEBUG_INTENT_MATCHING || debug) { 5010 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5011 + r1.activityInfo.name + "=" + r1.priority); 5012 } 5013 // If the first activity has a higher priority, or a different 5014 // default, then it is always desirable to pick it. 5015 if (r0.priority != r1.priority 5016 || r0.preferredOrder != r1.preferredOrder 5017 || r0.isDefault != r1.isDefault) { 5018 return query.get(0); 5019 } 5020 // If we have saved a preference for a preferred activity for 5021 // this Intent, use that. 5022 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5023 flags, query, r0.priority, true, false, debug, userId); 5024 if (ri != null) { 5025 return ri; 5026 } 5027 ri = new ResolveInfo(mResolveInfo); 5028 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5029 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5030 // If all of the options come from the same package, show the application's 5031 // label and icon instead of the generic resolver's. 5032 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5033 // and then throw away the ResolveInfo itself, meaning that the caller loses 5034 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5035 // a fallback for this case; we only set the target package's resources on 5036 // the ResolveInfo, not the ActivityInfo. 5037 final String intentPackage = intent.getPackage(); 5038 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5039 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5040 ri.resolvePackageName = intentPackage; 5041 if (userNeedsBadging(userId)) { 5042 ri.noResourceId = true; 5043 } else { 5044 ri.icon = appi.icon; 5045 } 5046 ri.iconResourceId = appi.icon; 5047 ri.labelRes = appi.labelRes; 5048 } 5049 ri.activityInfo.applicationInfo = new ApplicationInfo( 5050 ri.activityInfo.applicationInfo); 5051 if (userId != 0) { 5052 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5053 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5054 } 5055 // Make sure that the resolver is displayable in car mode 5056 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5057 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5058 return ri; 5059 } 5060 } 5061 return null; 5062 } 5063 5064 /** 5065 * Return true if the given list is not empty and all of its contents have 5066 * an activityInfo with the given package name. 5067 */ 5068 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5069 if (ArrayUtils.isEmpty(list)) { 5070 return false; 5071 } 5072 for (int i = 0, N = list.size(); i < N; i++) { 5073 final ResolveInfo ri = list.get(i); 5074 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5075 if (ai == null || !packageName.equals(ai.packageName)) { 5076 return false; 5077 } 5078 } 5079 return true; 5080 } 5081 5082 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5083 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5084 final int N = query.size(); 5085 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5086 .get(userId); 5087 // Get the list of persistent preferred activities that handle the intent 5088 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5089 List<PersistentPreferredActivity> pprefs = ppir != null 5090 ? ppir.queryIntent(intent, resolvedType, 5091 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5092 : null; 5093 if (pprefs != null && pprefs.size() > 0) { 5094 final int M = pprefs.size(); 5095 for (int i=0; i<M; i++) { 5096 final PersistentPreferredActivity ppa = pprefs.get(i); 5097 if (DEBUG_PREFERRED || debug) { 5098 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5099 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5100 + "\n component=" + ppa.mComponent); 5101 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5102 } 5103 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5104 flags | MATCH_DISABLED_COMPONENTS, userId); 5105 if (DEBUG_PREFERRED || debug) { 5106 Slog.v(TAG, "Found persistent preferred activity:"); 5107 if (ai != null) { 5108 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5109 } else { 5110 Slog.v(TAG, " null"); 5111 } 5112 } 5113 if (ai == null) { 5114 // This previously registered persistent preferred activity 5115 // component is no longer known. Ignore it and do NOT remove it. 5116 continue; 5117 } 5118 for (int j=0; j<N; j++) { 5119 final ResolveInfo ri = query.get(j); 5120 if (!ri.activityInfo.applicationInfo.packageName 5121 .equals(ai.applicationInfo.packageName)) { 5122 continue; 5123 } 5124 if (!ri.activityInfo.name.equals(ai.name)) { 5125 continue; 5126 } 5127 // Found a persistent preference that can handle the intent. 5128 if (DEBUG_PREFERRED || debug) { 5129 Slog.v(TAG, "Returning persistent preferred activity: " + 5130 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5131 } 5132 return ri; 5133 } 5134 } 5135 } 5136 return null; 5137 } 5138 5139 // TODO: handle preferred activities missing while user has amnesia 5140 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5141 List<ResolveInfo> query, int priority, boolean always, 5142 boolean removeMatches, boolean debug, int userId) { 5143 if (!sUserManager.exists(userId)) return null; 5144 flags = updateFlagsForResolve(flags, userId, intent); 5145 // writer 5146 synchronized (mPackages) { 5147 if (intent.getSelector() != null) { 5148 intent = intent.getSelector(); 5149 } 5150 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5151 5152 // Try to find a matching persistent preferred activity. 5153 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5154 debug, userId); 5155 5156 // If a persistent preferred activity matched, use it. 5157 if (pri != null) { 5158 return pri; 5159 } 5160 5161 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5162 // Get the list of preferred activities that handle the intent 5163 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5164 List<PreferredActivity> prefs = pir != null 5165 ? pir.queryIntent(intent, resolvedType, 5166 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5167 : null; 5168 if (prefs != null && prefs.size() > 0) { 5169 boolean changed = false; 5170 try { 5171 // First figure out how good the original match set is. 5172 // We will only allow preferred activities that came 5173 // from the same match quality. 5174 int match = 0; 5175 5176 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5177 5178 final int N = query.size(); 5179 for (int j=0; j<N; j++) { 5180 final ResolveInfo ri = query.get(j); 5181 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5182 + ": 0x" + Integer.toHexString(match)); 5183 if (ri.match > match) { 5184 match = ri.match; 5185 } 5186 } 5187 5188 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5189 + Integer.toHexString(match)); 5190 5191 match &= IntentFilter.MATCH_CATEGORY_MASK; 5192 final int M = prefs.size(); 5193 for (int i=0; i<M; i++) { 5194 final PreferredActivity pa = prefs.get(i); 5195 if (DEBUG_PREFERRED || debug) { 5196 Slog.v(TAG, "Checking PreferredActivity ds=" 5197 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5198 + "\n component=" + pa.mPref.mComponent); 5199 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5200 } 5201 if (pa.mPref.mMatch != match) { 5202 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5203 + Integer.toHexString(pa.mPref.mMatch)); 5204 continue; 5205 } 5206 // If it's not an "always" type preferred activity and that's what we're 5207 // looking for, skip it. 5208 if (always && !pa.mPref.mAlways) { 5209 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5210 continue; 5211 } 5212 final ActivityInfo ai = getActivityInfo( 5213 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5214 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5215 userId); 5216 if (DEBUG_PREFERRED || debug) { 5217 Slog.v(TAG, "Found preferred activity:"); 5218 if (ai != null) { 5219 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5220 } else { 5221 Slog.v(TAG, " null"); 5222 } 5223 } 5224 if (ai == null) { 5225 // This previously registered preferred activity 5226 // component is no longer known. Most likely an update 5227 // to the app was installed and in the new version this 5228 // component no longer exists. Clean it up by removing 5229 // it from the preferred activities list, and skip it. 5230 Slog.w(TAG, "Removing dangling preferred activity: " 5231 + pa.mPref.mComponent); 5232 pir.removeFilter(pa); 5233 changed = true; 5234 continue; 5235 } 5236 for (int j=0; j<N; j++) { 5237 final ResolveInfo ri = query.get(j); 5238 if (!ri.activityInfo.applicationInfo.packageName 5239 .equals(ai.applicationInfo.packageName)) { 5240 continue; 5241 } 5242 if (!ri.activityInfo.name.equals(ai.name)) { 5243 continue; 5244 } 5245 5246 if (removeMatches) { 5247 pir.removeFilter(pa); 5248 changed = true; 5249 if (DEBUG_PREFERRED) { 5250 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5251 } 5252 break; 5253 } 5254 5255 // Okay we found a previously set preferred or last chosen app. 5256 // If the result set is different from when this 5257 // was created, we need to clear it and re-ask the 5258 // user their preference, if we're looking for an "always" type entry. 5259 if (always && !pa.mPref.sameSet(query)) { 5260 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5261 + intent + " type " + resolvedType); 5262 if (DEBUG_PREFERRED) { 5263 Slog.v(TAG, "Removing preferred activity since set changed " 5264 + pa.mPref.mComponent); 5265 } 5266 pir.removeFilter(pa); 5267 // Re-add the filter as a "last chosen" entry (!always) 5268 PreferredActivity lastChosen = new PreferredActivity( 5269 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5270 pir.addFilter(lastChosen); 5271 changed = true; 5272 return null; 5273 } 5274 5275 // Yay! Either the set matched or we're looking for the last chosen 5276 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5277 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5278 return ri; 5279 } 5280 } 5281 } finally { 5282 if (changed) { 5283 if (DEBUG_PREFERRED) { 5284 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5285 } 5286 scheduleWritePackageRestrictionsLocked(userId); 5287 } 5288 } 5289 } 5290 } 5291 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5292 return null; 5293 } 5294 5295 /* 5296 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5297 */ 5298 @Override 5299 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5300 int targetUserId) { 5301 mContext.enforceCallingOrSelfPermission( 5302 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5303 List<CrossProfileIntentFilter> matches = 5304 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5305 if (matches != null) { 5306 int size = matches.size(); 5307 for (int i = 0; i < size; i++) { 5308 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5309 } 5310 } 5311 if (hasWebURI(intent)) { 5312 // cross-profile app linking works only towards the parent. 5313 final UserInfo parent = getProfileParent(sourceUserId); 5314 synchronized(mPackages) { 5315 int flags = updateFlagsForResolve(0, parent.id, intent); 5316 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5317 intent, resolvedType, flags, sourceUserId, parent.id); 5318 return xpDomainInfo != null; 5319 } 5320 } 5321 return false; 5322 } 5323 5324 private UserInfo getProfileParent(int userId) { 5325 final long identity = Binder.clearCallingIdentity(); 5326 try { 5327 return sUserManager.getProfileParent(userId); 5328 } finally { 5329 Binder.restoreCallingIdentity(identity); 5330 } 5331 } 5332 5333 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5334 String resolvedType, int userId) { 5335 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5336 if (resolver != null) { 5337 return resolver.queryIntent(intent, resolvedType, false, userId); 5338 } 5339 return null; 5340 } 5341 5342 @Override 5343 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5344 String resolvedType, int flags, int userId) { 5345 try { 5346 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5347 5348 return new ParceledListSlice<>( 5349 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5350 } finally { 5351 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5352 } 5353 } 5354 5355 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5356 String resolvedType, int flags, int userId) { 5357 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5358 flags = updateFlagsForResolve(flags, userId, intent); 5359 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5360 false /* requireFullPermission */, false /* checkShell */, 5361 "query intent activities"); 5362 ComponentName comp = intent.getComponent(); 5363 if (comp == null) { 5364 if (intent.getSelector() != null) { 5365 intent = intent.getSelector(); 5366 comp = intent.getComponent(); 5367 } 5368 } 5369 5370 if (comp != null) { 5371 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5372 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5373 if (ai != null) { 5374 final ResolveInfo ri = new ResolveInfo(); 5375 ri.activityInfo = ai; 5376 list.add(ri); 5377 } 5378 return list; 5379 } 5380 5381 // reader 5382 synchronized (mPackages) { 5383 final String pkgName = intent.getPackage(); 5384 if (pkgName == null) { 5385 List<CrossProfileIntentFilter> matchingFilters = 5386 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5387 // Check for results that need to skip the current profile. 5388 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5389 resolvedType, flags, userId); 5390 if (xpResolveInfo != null) { 5391 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5392 result.add(xpResolveInfo); 5393 return filterIfNotSystemUser(result, userId); 5394 } 5395 5396 // Check for results in the current profile. 5397 List<ResolveInfo> result = mActivities.queryIntent( 5398 intent, resolvedType, flags, userId); 5399 result = filterIfNotSystemUser(result, userId); 5400 5401 // Check for cross profile results. 5402 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5403 xpResolveInfo = queryCrossProfileIntents( 5404 matchingFilters, intent, resolvedType, flags, userId, 5405 hasNonNegativePriorityResult); 5406 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5407 boolean isVisibleToUser = filterIfNotSystemUser( 5408 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5409 if (isVisibleToUser) { 5410 result.add(xpResolveInfo); 5411 Collections.sort(result, mResolvePrioritySorter); 5412 } 5413 } 5414 if (hasWebURI(intent)) { 5415 CrossProfileDomainInfo xpDomainInfo = null; 5416 final UserInfo parent = getProfileParent(userId); 5417 if (parent != null) { 5418 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5419 flags, userId, parent.id); 5420 } 5421 if (xpDomainInfo != null) { 5422 if (xpResolveInfo != null) { 5423 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5424 // in the result. 5425 result.remove(xpResolveInfo); 5426 } 5427 if (result.size() == 0) { 5428 result.add(xpDomainInfo.resolveInfo); 5429 return result; 5430 } 5431 } else if (result.size() <= 1) { 5432 return result; 5433 } 5434 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5435 xpDomainInfo, userId); 5436 Collections.sort(result, mResolvePrioritySorter); 5437 } 5438 return result; 5439 } 5440 final PackageParser.Package pkg = mPackages.get(pkgName); 5441 if (pkg != null) { 5442 return filterIfNotSystemUser( 5443 mActivities.queryIntentForPackage( 5444 intent, resolvedType, flags, pkg.activities, userId), 5445 userId); 5446 } 5447 return new ArrayList<ResolveInfo>(); 5448 } 5449 } 5450 5451 private static class CrossProfileDomainInfo { 5452 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5453 ResolveInfo resolveInfo; 5454 /* Best domain verification status of the activities found in the other profile */ 5455 int bestDomainVerificationStatus; 5456 } 5457 5458 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5459 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5460 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5461 sourceUserId)) { 5462 return null; 5463 } 5464 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5465 resolvedType, flags, parentUserId); 5466 5467 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5468 return null; 5469 } 5470 CrossProfileDomainInfo result = null; 5471 int size = resultTargetUser.size(); 5472 for (int i = 0; i < size; i++) { 5473 ResolveInfo riTargetUser = resultTargetUser.get(i); 5474 // Intent filter verification is only for filters that specify a host. So don't return 5475 // those that handle all web uris. 5476 if (riTargetUser.handleAllWebDataURI) { 5477 continue; 5478 } 5479 String packageName = riTargetUser.activityInfo.packageName; 5480 PackageSetting ps = mSettings.mPackages.get(packageName); 5481 if (ps == null) { 5482 continue; 5483 } 5484 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5485 int status = (int)(verificationState >> 32); 5486 if (result == null) { 5487 result = new CrossProfileDomainInfo(); 5488 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5489 sourceUserId, parentUserId); 5490 result.bestDomainVerificationStatus = status; 5491 } else { 5492 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5493 result.bestDomainVerificationStatus); 5494 } 5495 } 5496 // Don't consider matches with status NEVER across profiles. 5497 if (result != null && result.bestDomainVerificationStatus 5498 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5499 return null; 5500 } 5501 return result; 5502 } 5503 5504 /** 5505 * Verification statuses are ordered from the worse to the best, except for 5506 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5507 */ 5508 private int bestDomainVerificationStatus(int status1, int status2) { 5509 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5510 return status2; 5511 } 5512 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5513 return status1; 5514 } 5515 return (int) MathUtils.max(status1, status2); 5516 } 5517 5518 private boolean isUserEnabled(int userId) { 5519 long callingId = Binder.clearCallingIdentity(); 5520 try { 5521 UserInfo userInfo = sUserManager.getUserInfo(userId); 5522 return userInfo != null && userInfo.isEnabled(); 5523 } finally { 5524 Binder.restoreCallingIdentity(callingId); 5525 } 5526 } 5527 5528 /** 5529 * Filter out activities with systemUserOnly flag set, when current user is not System. 5530 * 5531 * @return filtered list 5532 */ 5533 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5534 if (userId == UserHandle.USER_SYSTEM) { 5535 return resolveInfos; 5536 } 5537 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5538 ResolveInfo info = resolveInfos.get(i); 5539 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5540 resolveInfos.remove(i); 5541 } 5542 } 5543 return resolveInfos; 5544 } 5545 5546 /** 5547 * @param resolveInfos list of resolve infos in descending priority order 5548 * @return if the list contains a resolve info with non-negative priority 5549 */ 5550 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5551 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5552 } 5553 5554 private static boolean hasWebURI(Intent intent) { 5555 if (intent.getData() == null) { 5556 return false; 5557 } 5558 final String scheme = intent.getScheme(); 5559 if (TextUtils.isEmpty(scheme)) { 5560 return false; 5561 } 5562 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5563 } 5564 5565 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5566 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5567 int userId) { 5568 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5569 5570 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5571 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5572 candidates.size()); 5573 } 5574 5575 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5576 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5577 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5578 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5579 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5580 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5581 5582 synchronized (mPackages) { 5583 final int count = candidates.size(); 5584 // First, try to use linked apps. Partition the candidates into four lists: 5585 // one for the final results, one for the "do not use ever", one for "undefined status" 5586 // and finally one for "browser app type". 5587 for (int n=0; n<count; n++) { 5588 ResolveInfo info = candidates.get(n); 5589 String packageName = info.activityInfo.packageName; 5590 PackageSetting ps = mSettings.mPackages.get(packageName); 5591 if (ps != null) { 5592 // Add to the special match all list (Browser use case) 5593 if (info.handleAllWebDataURI) { 5594 matchAllList.add(info); 5595 continue; 5596 } 5597 // Try to get the status from User settings first 5598 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5599 int status = (int)(packedStatus >> 32); 5600 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5601 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5602 if (DEBUG_DOMAIN_VERIFICATION) { 5603 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5604 + " : linkgen=" + linkGeneration); 5605 } 5606 // Use link-enabled generation as preferredOrder, i.e. 5607 // prefer newly-enabled over earlier-enabled. 5608 info.preferredOrder = linkGeneration; 5609 alwaysList.add(info); 5610 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5611 if (DEBUG_DOMAIN_VERIFICATION) { 5612 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5613 } 5614 neverList.add(info); 5615 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5616 if (DEBUG_DOMAIN_VERIFICATION) { 5617 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5618 } 5619 alwaysAskList.add(info); 5620 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5621 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5622 if (DEBUG_DOMAIN_VERIFICATION) { 5623 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5624 } 5625 undefinedList.add(info); 5626 } 5627 } 5628 } 5629 5630 // We'll want to include browser possibilities in a few cases 5631 boolean includeBrowser = false; 5632 5633 // First try to add the "always" resolution(s) for the current user, if any 5634 if (alwaysList.size() > 0) { 5635 result.addAll(alwaysList); 5636 } else { 5637 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5638 result.addAll(undefinedList); 5639 // Maybe add one for the other profile. 5640 if (xpDomainInfo != null && ( 5641 xpDomainInfo.bestDomainVerificationStatus 5642 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5643 result.add(xpDomainInfo.resolveInfo); 5644 } 5645 includeBrowser = true; 5646 } 5647 5648 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5649 // If there were 'always' entries their preferred order has been set, so we also 5650 // back that off to make the alternatives equivalent 5651 if (alwaysAskList.size() > 0) { 5652 for (ResolveInfo i : result) { 5653 i.preferredOrder = 0; 5654 } 5655 result.addAll(alwaysAskList); 5656 includeBrowser = true; 5657 } 5658 5659 if (includeBrowser) { 5660 // Also add browsers (all of them or only the default one) 5661 if (DEBUG_DOMAIN_VERIFICATION) { 5662 Slog.v(TAG, " ...including browsers in candidate set"); 5663 } 5664 if ((matchFlags & MATCH_ALL) != 0) { 5665 result.addAll(matchAllList); 5666 } else { 5667 // Browser/generic handling case. If there's a default browser, go straight 5668 // to that (but only if there is no other higher-priority match). 5669 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5670 int maxMatchPrio = 0; 5671 ResolveInfo defaultBrowserMatch = null; 5672 final int numCandidates = matchAllList.size(); 5673 for (int n = 0; n < numCandidates; n++) { 5674 ResolveInfo info = matchAllList.get(n); 5675 // track the highest overall match priority... 5676 if (info.priority > maxMatchPrio) { 5677 maxMatchPrio = info.priority; 5678 } 5679 // ...and the highest-priority default browser match 5680 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5681 if (defaultBrowserMatch == null 5682 || (defaultBrowserMatch.priority < info.priority)) { 5683 if (debug) { 5684 Slog.v(TAG, "Considering default browser match " + info); 5685 } 5686 defaultBrowserMatch = info; 5687 } 5688 } 5689 } 5690 if (defaultBrowserMatch != null 5691 && defaultBrowserMatch.priority >= maxMatchPrio 5692 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5693 { 5694 if (debug) { 5695 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5696 } 5697 result.add(defaultBrowserMatch); 5698 } else { 5699 result.addAll(matchAllList); 5700 } 5701 } 5702 5703 // If there is nothing selected, add all candidates and remove the ones that the user 5704 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5705 if (result.size() == 0) { 5706 result.addAll(candidates); 5707 result.removeAll(neverList); 5708 } 5709 } 5710 } 5711 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5712 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5713 result.size()); 5714 for (ResolveInfo info : result) { 5715 Slog.v(TAG, " + " + info.activityInfo); 5716 } 5717 } 5718 return result; 5719 } 5720 5721 // Returns a packed value as a long: 5722 // 5723 // high 'int'-sized word: link status: undefined/ask/never/always. 5724 // low 'int'-sized word: relative priority among 'always' results. 5725 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5726 long result = ps.getDomainVerificationStatusForUser(userId); 5727 // if none available, get the master status 5728 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5729 if (ps.getIntentFilterVerificationInfo() != null) { 5730 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5731 } 5732 } 5733 return result; 5734 } 5735 5736 private ResolveInfo querySkipCurrentProfileIntents( 5737 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5738 int flags, int sourceUserId) { 5739 if (matchingFilters != null) { 5740 int size = matchingFilters.size(); 5741 for (int i = 0; i < size; i ++) { 5742 CrossProfileIntentFilter filter = matchingFilters.get(i); 5743 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5744 // Checking if there are activities in the target user that can handle the 5745 // intent. 5746 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5747 resolvedType, flags, sourceUserId); 5748 if (resolveInfo != null) { 5749 return resolveInfo; 5750 } 5751 } 5752 } 5753 } 5754 return null; 5755 } 5756 5757 // Return matching ResolveInfo in target user if any. 5758 private ResolveInfo queryCrossProfileIntents( 5759 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5760 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5761 if (matchingFilters != null) { 5762 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5763 // match the same intent. For performance reasons, it is better not to 5764 // run queryIntent twice for the same userId 5765 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5766 int size = matchingFilters.size(); 5767 for (int i = 0; i < size; i++) { 5768 CrossProfileIntentFilter filter = matchingFilters.get(i); 5769 int targetUserId = filter.getTargetUserId(); 5770 boolean skipCurrentProfile = 5771 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5772 boolean skipCurrentProfileIfNoMatchFound = 5773 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5774 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5775 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5776 // Checking if there are activities in the target user that can handle the 5777 // intent. 5778 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5779 resolvedType, flags, sourceUserId); 5780 if (resolveInfo != null) return resolveInfo; 5781 alreadyTriedUserIds.put(targetUserId, true); 5782 } 5783 } 5784 } 5785 return null; 5786 } 5787 5788 /** 5789 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5790 * will forward the intent to the filter's target user. 5791 * Otherwise, returns null. 5792 */ 5793 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5794 String resolvedType, int flags, int sourceUserId) { 5795 int targetUserId = filter.getTargetUserId(); 5796 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5797 resolvedType, flags, targetUserId); 5798 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5799 // If all the matches in the target profile are suspended, return null. 5800 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5801 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5802 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5803 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5804 targetUserId); 5805 } 5806 } 5807 } 5808 return null; 5809 } 5810 5811 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5812 int sourceUserId, int targetUserId) { 5813 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5814 long ident = Binder.clearCallingIdentity(); 5815 boolean targetIsProfile; 5816 try { 5817 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5818 } finally { 5819 Binder.restoreCallingIdentity(ident); 5820 } 5821 String className; 5822 if (targetIsProfile) { 5823 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5824 } else { 5825 className = FORWARD_INTENT_TO_PARENT; 5826 } 5827 ComponentName forwardingActivityComponentName = new ComponentName( 5828 mAndroidApplication.packageName, className); 5829 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5830 sourceUserId); 5831 if (!targetIsProfile) { 5832 forwardingActivityInfo.showUserIcon = targetUserId; 5833 forwardingResolveInfo.noResourceId = true; 5834 } 5835 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5836 forwardingResolveInfo.priority = 0; 5837 forwardingResolveInfo.preferredOrder = 0; 5838 forwardingResolveInfo.match = 0; 5839 forwardingResolveInfo.isDefault = true; 5840 forwardingResolveInfo.filter = filter; 5841 forwardingResolveInfo.targetUserId = targetUserId; 5842 return forwardingResolveInfo; 5843 } 5844 5845 @Override 5846 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5847 Intent[] specifics, String[] specificTypes, Intent intent, 5848 String resolvedType, int flags, int userId) { 5849 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5850 specificTypes, intent, resolvedType, flags, userId)); 5851 } 5852 5853 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5854 Intent[] specifics, String[] specificTypes, Intent intent, 5855 String resolvedType, int flags, int userId) { 5856 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5857 flags = updateFlagsForResolve(flags, userId, intent); 5858 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5859 false /* requireFullPermission */, false /* checkShell */, 5860 "query intent activity options"); 5861 final String resultsAction = intent.getAction(); 5862 5863 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5864 | PackageManager.GET_RESOLVED_FILTER, userId); 5865 5866 if (DEBUG_INTENT_MATCHING) { 5867 Log.v(TAG, "Query " + intent + ": " + results); 5868 } 5869 5870 int specificsPos = 0; 5871 int N; 5872 5873 // todo: note that the algorithm used here is O(N^2). This 5874 // isn't a problem in our current environment, but if we start running 5875 // into situations where we have more than 5 or 10 matches then this 5876 // should probably be changed to something smarter... 5877 5878 // First we go through and resolve each of the specific items 5879 // that were supplied, taking care of removing any corresponding 5880 // duplicate items in the generic resolve list. 5881 if (specifics != null) { 5882 for (int i=0; i<specifics.length; i++) { 5883 final Intent sintent = specifics[i]; 5884 if (sintent == null) { 5885 continue; 5886 } 5887 5888 if (DEBUG_INTENT_MATCHING) { 5889 Log.v(TAG, "Specific #" + i + ": " + sintent); 5890 } 5891 5892 String action = sintent.getAction(); 5893 if (resultsAction != null && resultsAction.equals(action)) { 5894 // If this action was explicitly requested, then don't 5895 // remove things that have it. 5896 action = null; 5897 } 5898 5899 ResolveInfo ri = null; 5900 ActivityInfo ai = null; 5901 5902 ComponentName comp = sintent.getComponent(); 5903 if (comp == null) { 5904 ri = resolveIntent( 5905 sintent, 5906 specificTypes != null ? specificTypes[i] : null, 5907 flags, userId); 5908 if (ri == null) { 5909 continue; 5910 } 5911 if (ri == mResolveInfo) { 5912 // ACK! Must do something better with this. 5913 } 5914 ai = ri.activityInfo; 5915 comp = new ComponentName(ai.applicationInfo.packageName, 5916 ai.name); 5917 } else { 5918 ai = getActivityInfo(comp, flags, userId); 5919 if (ai == null) { 5920 continue; 5921 } 5922 } 5923 5924 // Look for any generic query activities that are duplicates 5925 // of this specific one, and remove them from the results. 5926 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5927 N = results.size(); 5928 int j; 5929 for (j=specificsPos; j<N; j++) { 5930 ResolveInfo sri = results.get(j); 5931 if ((sri.activityInfo.name.equals(comp.getClassName()) 5932 && sri.activityInfo.applicationInfo.packageName.equals( 5933 comp.getPackageName())) 5934 || (action != null && sri.filter.matchAction(action))) { 5935 results.remove(j); 5936 if (DEBUG_INTENT_MATCHING) Log.v( 5937 TAG, "Removing duplicate item from " + j 5938 + " due to specific " + specificsPos); 5939 if (ri == null) { 5940 ri = sri; 5941 } 5942 j--; 5943 N--; 5944 } 5945 } 5946 5947 // Add this specific item to its proper place. 5948 if (ri == null) { 5949 ri = new ResolveInfo(); 5950 ri.activityInfo = ai; 5951 } 5952 results.add(specificsPos, ri); 5953 ri.specificIndex = i; 5954 specificsPos++; 5955 } 5956 } 5957 5958 // Now we go through the remaining generic results and remove any 5959 // duplicate actions that are found here. 5960 N = results.size(); 5961 for (int i=specificsPos; i<N-1; i++) { 5962 final ResolveInfo rii = results.get(i); 5963 if (rii.filter == null) { 5964 continue; 5965 } 5966 5967 // Iterate over all of the actions of this result's intent 5968 // filter... typically this should be just one. 5969 final Iterator<String> it = rii.filter.actionsIterator(); 5970 if (it == null) { 5971 continue; 5972 } 5973 while (it.hasNext()) { 5974 final String action = it.next(); 5975 if (resultsAction != null && resultsAction.equals(action)) { 5976 // If this action was explicitly requested, then don't 5977 // remove things that have it. 5978 continue; 5979 } 5980 for (int j=i+1; j<N; j++) { 5981 final ResolveInfo rij = results.get(j); 5982 if (rij.filter != null && rij.filter.hasAction(action)) { 5983 results.remove(j); 5984 if (DEBUG_INTENT_MATCHING) Log.v( 5985 TAG, "Removing duplicate item from " + j 5986 + " due to action " + action + " at " + i); 5987 j--; 5988 N--; 5989 } 5990 } 5991 } 5992 5993 // If the caller didn't request filter information, drop it now 5994 // so we don't have to marshall/unmarshall it. 5995 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5996 rii.filter = null; 5997 } 5998 } 5999 6000 // Filter out the caller activity if so requested. 6001 if (caller != null) { 6002 N = results.size(); 6003 for (int i=0; i<N; i++) { 6004 ActivityInfo ainfo = results.get(i).activityInfo; 6005 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6006 && caller.getClassName().equals(ainfo.name)) { 6007 results.remove(i); 6008 break; 6009 } 6010 } 6011 } 6012 6013 // If the caller didn't request filter information, 6014 // drop them now so we don't have to 6015 // marshall/unmarshall it. 6016 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6017 N = results.size(); 6018 for (int i=0; i<N; i++) { 6019 results.get(i).filter = null; 6020 } 6021 } 6022 6023 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6024 return results; 6025 } 6026 6027 @Override 6028 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6029 String resolvedType, int flags, int userId) { 6030 return new ParceledListSlice<>( 6031 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6032 } 6033 6034 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6035 String resolvedType, int flags, int userId) { 6036 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6037 flags = updateFlagsForResolve(flags, userId, intent); 6038 ComponentName comp = intent.getComponent(); 6039 if (comp == null) { 6040 if (intent.getSelector() != null) { 6041 intent = intent.getSelector(); 6042 comp = intent.getComponent(); 6043 } 6044 } 6045 if (comp != null) { 6046 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6047 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6048 if (ai != null) { 6049 ResolveInfo ri = new ResolveInfo(); 6050 ri.activityInfo = ai; 6051 list.add(ri); 6052 } 6053 return list; 6054 } 6055 6056 // reader 6057 synchronized (mPackages) { 6058 String pkgName = intent.getPackage(); 6059 if (pkgName == null) { 6060 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6061 } 6062 final PackageParser.Package pkg = mPackages.get(pkgName); 6063 if (pkg != null) { 6064 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6065 userId); 6066 } 6067 return Collections.emptyList(); 6068 } 6069 } 6070 6071 @Override 6072 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6073 if (!sUserManager.exists(userId)) return null; 6074 flags = updateFlagsForResolve(flags, userId, intent); 6075 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6076 if (query != null) { 6077 if (query.size() >= 1) { 6078 // If there is more than one service with the same priority, 6079 // just arbitrarily pick the first one. 6080 return query.get(0); 6081 } 6082 } 6083 return null; 6084 } 6085 6086 @Override 6087 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6088 String resolvedType, int flags, int userId) { 6089 return new ParceledListSlice<>( 6090 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6091 } 6092 6093 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6094 String resolvedType, int flags, int userId) { 6095 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6096 flags = updateFlagsForResolve(flags, userId, intent); 6097 ComponentName comp = intent.getComponent(); 6098 if (comp == null) { 6099 if (intent.getSelector() != null) { 6100 intent = intent.getSelector(); 6101 comp = intent.getComponent(); 6102 } 6103 } 6104 if (comp != null) { 6105 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6106 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6107 if (si != null) { 6108 final ResolveInfo ri = new ResolveInfo(); 6109 ri.serviceInfo = si; 6110 list.add(ri); 6111 } 6112 return list; 6113 } 6114 6115 // reader 6116 synchronized (mPackages) { 6117 String pkgName = intent.getPackage(); 6118 if (pkgName == null) { 6119 return mServices.queryIntent(intent, resolvedType, flags, userId); 6120 } 6121 final PackageParser.Package pkg = mPackages.get(pkgName); 6122 if (pkg != null) { 6123 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6124 userId); 6125 } 6126 return Collections.emptyList(); 6127 } 6128 } 6129 6130 @Override 6131 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6132 String resolvedType, int flags, int userId) { 6133 return new ParceledListSlice<>( 6134 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6135 } 6136 6137 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6138 Intent intent, String resolvedType, int flags, int userId) { 6139 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6140 flags = updateFlagsForResolve(flags, userId, intent); 6141 ComponentName comp = intent.getComponent(); 6142 if (comp == null) { 6143 if (intent.getSelector() != null) { 6144 intent = intent.getSelector(); 6145 comp = intent.getComponent(); 6146 } 6147 } 6148 if (comp != null) { 6149 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6150 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6151 if (pi != null) { 6152 final ResolveInfo ri = new ResolveInfo(); 6153 ri.providerInfo = pi; 6154 list.add(ri); 6155 } 6156 return list; 6157 } 6158 6159 // reader 6160 synchronized (mPackages) { 6161 String pkgName = intent.getPackage(); 6162 if (pkgName == null) { 6163 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6164 } 6165 final PackageParser.Package pkg = mPackages.get(pkgName); 6166 if (pkg != null) { 6167 return mProviders.queryIntentForPackage( 6168 intent, resolvedType, flags, pkg.providers, userId); 6169 } 6170 return Collections.emptyList(); 6171 } 6172 } 6173 6174 @Override 6175 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6176 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6177 flags = updateFlagsForPackage(flags, userId, null); 6178 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6179 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6180 true /* requireFullPermission */, false /* checkShell */, 6181 "get installed packages"); 6182 6183 // writer 6184 synchronized (mPackages) { 6185 ArrayList<PackageInfo> list; 6186 if (listUninstalled) { 6187 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6188 for (PackageSetting ps : mSettings.mPackages.values()) { 6189 final PackageInfo pi; 6190 if (ps.pkg != null) { 6191 pi = generatePackageInfo(ps, flags, userId); 6192 } else { 6193 pi = generatePackageInfo(ps, flags, userId); 6194 } 6195 if (pi != null) { 6196 list.add(pi); 6197 } 6198 } 6199 } else { 6200 list = new ArrayList<PackageInfo>(mPackages.size()); 6201 for (PackageParser.Package p : mPackages.values()) { 6202 final PackageInfo pi = 6203 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6204 if (pi != null) { 6205 list.add(pi); 6206 } 6207 } 6208 } 6209 6210 return new ParceledListSlice<PackageInfo>(list); 6211 } 6212 } 6213 6214 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6215 String[] permissions, boolean[] tmp, int flags, int userId) { 6216 int numMatch = 0; 6217 final PermissionsState permissionsState = ps.getPermissionsState(); 6218 for (int i=0; i<permissions.length; i++) { 6219 final String permission = permissions[i]; 6220 if (permissionsState.hasPermission(permission, userId)) { 6221 tmp[i] = true; 6222 numMatch++; 6223 } else { 6224 tmp[i] = false; 6225 } 6226 } 6227 if (numMatch == 0) { 6228 return; 6229 } 6230 final PackageInfo pi; 6231 if (ps.pkg != null) { 6232 pi = generatePackageInfo(ps, flags, userId); 6233 } else { 6234 pi = generatePackageInfo(ps, flags, userId); 6235 } 6236 // The above might return null in cases of uninstalled apps or install-state 6237 // skew across users/profiles. 6238 if (pi != null) { 6239 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6240 if (numMatch == permissions.length) { 6241 pi.requestedPermissions = permissions; 6242 } else { 6243 pi.requestedPermissions = new String[numMatch]; 6244 numMatch = 0; 6245 for (int i=0; i<permissions.length; i++) { 6246 if (tmp[i]) { 6247 pi.requestedPermissions[numMatch] = permissions[i]; 6248 numMatch++; 6249 } 6250 } 6251 } 6252 } 6253 list.add(pi); 6254 } 6255 } 6256 6257 @Override 6258 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6259 String[] permissions, int flags, int userId) { 6260 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6261 flags = updateFlagsForPackage(flags, userId, permissions); 6262 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6263 6264 // writer 6265 synchronized (mPackages) { 6266 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6267 boolean[] tmpBools = new boolean[permissions.length]; 6268 if (listUninstalled) { 6269 for (PackageSetting ps : mSettings.mPackages.values()) { 6270 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6271 } 6272 } else { 6273 for (PackageParser.Package pkg : mPackages.values()) { 6274 PackageSetting ps = (PackageSetting)pkg.mExtras; 6275 if (ps != null) { 6276 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6277 userId); 6278 } 6279 } 6280 } 6281 6282 return new ParceledListSlice<PackageInfo>(list); 6283 } 6284 } 6285 6286 @Override 6287 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6288 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6289 flags = updateFlagsForApplication(flags, userId, null); 6290 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6291 6292 // writer 6293 synchronized (mPackages) { 6294 ArrayList<ApplicationInfo> list; 6295 if (listUninstalled) { 6296 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6297 for (PackageSetting ps : mSettings.mPackages.values()) { 6298 ApplicationInfo ai; 6299 if (ps.pkg != null) { 6300 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6301 ps.readUserState(userId), userId); 6302 } else { 6303 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6304 } 6305 if (ai != null) { 6306 list.add(ai); 6307 } 6308 } 6309 } else { 6310 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6311 for (PackageParser.Package p : mPackages.values()) { 6312 if (p.mExtras != null) { 6313 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6314 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6315 if (ai != null) { 6316 list.add(ai); 6317 } 6318 } 6319 } 6320 } 6321 6322 return new ParceledListSlice<ApplicationInfo>(list); 6323 } 6324 } 6325 6326 @Override 6327 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6328 if (DISABLE_EPHEMERAL_APPS) { 6329 return null; 6330 } 6331 6332 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6333 "getEphemeralApplications"); 6334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6335 true /* requireFullPermission */, false /* checkShell */, 6336 "getEphemeralApplications"); 6337 synchronized (mPackages) { 6338 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6339 .getEphemeralApplicationsLPw(userId); 6340 if (ephemeralApps != null) { 6341 return new ParceledListSlice<>(ephemeralApps); 6342 } 6343 } 6344 return null; 6345 } 6346 6347 @Override 6348 public boolean isEphemeralApplication(String packageName, int userId) { 6349 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6350 true /* requireFullPermission */, false /* checkShell */, 6351 "isEphemeral"); 6352 if (DISABLE_EPHEMERAL_APPS) { 6353 return false; 6354 } 6355 6356 if (!isCallerSameApp(packageName)) { 6357 return false; 6358 } 6359 synchronized (mPackages) { 6360 PackageParser.Package pkg = mPackages.get(packageName); 6361 if (pkg != null) { 6362 return pkg.applicationInfo.isEphemeralApp(); 6363 } 6364 } 6365 return false; 6366 } 6367 6368 @Override 6369 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6370 if (DISABLE_EPHEMERAL_APPS) { 6371 return null; 6372 } 6373 6374 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6375 true /* requireFullPermission */, false /* checkShell */, 6376 "getCookie"); 6377 if (!isCallerSameApp(packageName)) { 6378 return null; 6379 } 6380 synchronized (mPackages) { 6381 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6382 packageName, userId); 6383 } 6384 } 6385 6386 @Override 6387 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6388 if (DISABLE_EPHEMERAL_APPS) { 6389 return true; 6390 } 6391 6392 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6393 true /* requireFullPermission */, true /* checkShell */, 6394 "setCookie"); 6395 if (!isCallerSameApp(packageName)) { 6396 return false; 6397 } 6398 synchronized (mPackages) { 6399 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6400 packageName, cookie, userId); 6401 } 6402 } 6403 6404 @Override 6405 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6406 if (DISABLE_EPHEMERAL_APPS) { 6407 return null; 6408 } 6409 6410 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6411 "getEphemeralApplicationIcon"); 6412 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6413 true /* requireFullPermission */, false /* checkShell */, 6414 "getEphemeralApplicationIcon"); 6415 synchronized (mPackages) { 6416 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6417 packageName, userId); 6418 } 6419 } 6420 6421 private boolean isCallerSameApp(String packageName) { 6422 PackageParser.Package pkg = mPackages.get(packageName); 6423 return pkg != null 6424 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6425 } 6426 6427 @Override 6428 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6429 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6430 } 6431 6432 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6433 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6434 6435 // reader 6436 synchronized (mPackages) { 6437 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6438 final int userId = UserHandle.getCallingUserId(); 6439 while (i.hasNext()) { 6440 final PackageParser.Package p = i.next(); 6441 if (p.applicationInfo == null) continue; 6442 6443 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6444 && !p.applicationInfo.isDirectBootAware(); 6445 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6446 && p.applicationInfo.isDirectBootAware(); 6447 6448 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6449 && (!mSafeMode || isSystemApp(p)) 6450 && (matchesUnaware || matchesAware)) { 6451 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6452 if (ps != null) { 6453 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6454 ps.readUserState(userId), userId); 6455 if (ai != null) { 6456 finalList.add(ai); 6457 } 6458 } 6459 } 6460 } 6461 } 6462 6463 return finalList; 6464 } 6465 6466 @Override 6467 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6468 if (!sUserManager.exists(userId)) return null; 6469 flags = updateFlagsForComponent(flags, userId, name); 6470 // reader 6471 synchronized (mPackages) { 6472 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6473 PackageSetting ps = provider != null 6474 ? mSettings.mPackages.get(provider.owner.packageName) 6475 : null; 6476 return ps != null 6477 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6478 ? PackageParser.generateProviderInfo(provider, flags, 6479 ps.readUserState(userId), userId) 6480 : null; 6481 } 6482 } 6483 6484 /** 6485 * @deprecated 6486 */ 6487 @Deprecated 6488 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6489 // reader 6490 synchronized (mPackages) { 6491 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6492 .entrySet().iterator(); 6493 final int userId = UserHandle.getCallingUserId(); 6494 while (i.hasNext()) { 6495 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6496 PackageParser.Provider p = entry.getValue(); 6497 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6498 6499 if (ps != null && p.syncable 6500 && (!mSafeMode || (p.info.applicationInfo.flags 6501 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6502 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6503 ps.readUserState(userId), userId); 6504 if (info != null) { 6505 outNames.add(entry.getKey()); 6506 outInfo.add(info); 6507 } 6508 } 6509 } 6510 } 6511 } 6512 6513 @Override 6514 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6515 int uid, int flags) { 6516 final int userId = processName != null ? UserHandle.getUserId(uid) 6517 : UserHandle.getCallingUserId(); 6518 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6519 flags = updateFlagsForComponent(flags, userId, processName); 6520 6521 ArrayList<ProviderInfo> finalList = null; 6522 // reader 6523 synchronized (mPackages) { 6524 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6525 while (i.hasNext()) { 6526 final PackageParser.Provider p = i.next(); 6527 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6528 if (ps != null && p.info.authority != null 6529 && (processName == null 6530 || (p.info.processName.equals(processName) 6531 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6532 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6533 if (finalList == null) { 6534 finalList = new ArrayList<ProviderInfo>(3); 6535 } 6536 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6537 ps.readUserState(userId), userId); 6538 if (info != null) { 6539 finalList.add(info); 6540 } 6541 } 6542 } 6543 } 6544 6545 if (finalList != null) { 6546 Collections.sort(finalList, mProviderInitOrderSorter); 6547 return new ParceledListSlice<ProviderInfo>(finalList); 6548 } 6549 6550 return ParceledListSlice.emptyList(); 6551 } 6552 6553 @Override 6554 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6555 // reader 6556 synchronized (mPackages) { 6557 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6558 return PackageParser.generateInstrumentationInfo(i, flags); 6559 } 6560 } 6561 6562 @Override 6563 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6564 String targetPackage, int flags) { 6565 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6566 } 6567 6568 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6569 int flags) { 6570 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6571 6572 // reader 6573 synchronized (mPackages) { 6574 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6575 while (i.hasNext()) { 6576 final PackageParser.Instrumentation p = i.next(); 6577 if (targetPackage == null 6578 || targetPackage.equals(p.info.targetPackage)) { 6579 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6580 flags); 6581 if (ii != null) { 6582 finalList.add(ii); 6583 } 6584 } 6585 } 6586 } 6587 6588 return finalList; 6589 } 6590 6591 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6592 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6593 if (overlays == null) { 6594 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6595 return; 6596 } 6597 for (PackageParser.Package opkg : overlays.values()) { 6598 // Not much to do if idmap fails: we already logged the error 6599 // and we certainly don't want to abort installation of pkg simply 6600 // because an overlay didn't fit properly. For these reasons, 6601 // ignore the return value of createIdmapForPackagePairLI. 6602 createIdmapForPackagePairLI(pkg, opkg); 6603 } 6604 } 6605 6606 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6607 PackageParser.Package opkg) { 6608 if (!opkg.mTrustedOverlay) { 6609 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6610 opkg.baseCodePath + ": overlay not trusted"); 6611 return false; 6612 } 6613 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6614 if (overlaySet == null) { 6615 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6616 opkg.baseCodePath + " but target package has no known overlays"); 6617 return false; 6618 } 6619 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6620 // TODO: generate idmap for split APKs 6621 try { 6622 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6623 } catch (InstallerException e) { 6624 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6625 + opkg.baseCodePath); 6626 return false; 6627 } 6628 PackageParser.Package[] overlayArray = 6629 overlaySet.values().toArray(new PackageParser.Package[0]); 6630 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6631 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6632 return p1.mOverlayPriority - p2.mOverlayPriority; 6633 } 6634 }; 6635 Arrays.sort(overlayArray, cmp); 6636 6637 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6638 int i = 0; 6639 for (PackageParser.Package p : overlayArray) { 6640 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6641 } 6642 return true; 6643 } 6644 6645 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6647 try { 6648 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6649 } finally { 6650 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6651 } 6652 } 6653 6654 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6655 final File[] files = dir.listFiles(); 6656 if (ArrayUtils.isEmpty(files)) { 6657 Log.d(TAG, "No files in app dir " + dir); 6658 return; 6659 } 6660 6661 if (DEBUG_PACKAGE_SCANNING) { 6662 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6663 + " flags=0x" + Integer.toHexString(parseFlags)); 6664 } 6665 6666 for (File file : files) { 6667 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6668 && !PackageInstallerService.isStageName(file.getName()); 6669 if (!isPackage) { 6670 // Ignore entries which are not packages 6671 continue; 6672 } 6673 try { 6674 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6675 scanFlags, currentTime, null); 6676 } catch (PackageManagerException e) { 6677 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6678 6679 // Delete invalid userdata apps 6680 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6681 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6682 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6683 removeCodePathLI(file); 6684 } 6685 } 6686 } 6687 } 6688 6689 private static File getSettingsProblemFile() { 6690 File dataDir = Environment.getDataDirectory(); 6691 File systemDir = new File(dataDir, "system"); 6692 File fname = new File(systemDir, "uiderrors.txt"); 6693 return fname; 6694 } 6695 6696 static void reportSettingsProblem(int priority, String msg) { 6697 logCriticalInfo(priority, msg); 6698 } 6699 6700 static void logCriticalInfo(int priority, String msg) { 6701 Slog.println(priority, TAG, msg); 6702 EventLogTags.writePmCriticalInfo(msg); 6703 try { 6704 File fname = getSettingsProblemFile(); 6705 FileOutputStream out = new FileOutputStream(fname, true); 6706 PrintWriter pw = new FastPrintWriter(out); 6707 SimpleDateFormat formatter = new SimpleDateFormat(); 6708 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6709 pw.println(dateString + ": " + msg); 6710 pw.close(); 6711 FileUtils.setPermissions( 6712 fname.toString(), 6713 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6714 -1, -1); 6715 } catch (java.io.IOException e) { 6716 } 6717 } 6718 6719 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6720 final int policyFlags) throws PackageManagerException { 6721 if (ps != null 6722 && ps.codePath.equals(srcFile) 6723 && ps.timeStamp == srcFile.lastModified() 6724 && !isCompatSignatureUpdateNeeded(pkg) 6725 && !isRecoverSignatureUpdateNeeded(pkg)) { 6726 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6727 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6728 ArraySet<PublicKey> signingKs; 6729 synchronized (mPackages) { 6730 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6731 } 6732 if (ps.signatures.mSignatures != null 6733 && ps.signatures.mSignatures.length != 0 6734 && signingKs != null) { 6735 // Optimization: reuse the existing cached certificates 6736 // if the package appears to be unchanged. 6737 pkg.mSignatures = ps.signatures.mSignatures; 6738 pkg.mSigningKeys = signingKs; 6739 return; 6740 } 6741 6742 Slog.w(TAG, "PackageSetting for " + ps.name 6743 + " is missing signatures. Collecting certs again to recover them."); 6744 } else { 6745 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6746 } 6747 6748 try { 6749 PackageParser.collectCertificates(pkg, policyFlags); 6750 } catch (PackageParserException e) { 6751 throw PackageManagerException.from(e); 6752 } 6753 } 6754 6755 /** 6756 * Traces a package scan. 6757 * @see #scanPackageLI(File, int, int, long, UserHandle) 6758 */ 6759 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6760 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6761 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6762 try { 6763 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6764 } finally { 6765 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6766 } 6767 } 6768 6769 /** 6770 * Scans a package and returns the newly parsed package. 6771 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6772 */ 6773 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6774 long currentTime, UserHandle user) throws PackageManagerException { 6775 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6776 PackageParser pp = new PackageParser(); 6777 pp.setSeparateProcesses(mSeparateProcesses); 6778 pp.setOnlyCoreApps(mOnlyCore); 6779 pp.setDisplayMetrics(mMetrics); 6780 6781 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6782 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6783 } 6784 6785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6786 final PackageParser.Package pkg; 6787 try { 6788 pkg = pp.parsePackage(scanFile, parseFlags); 6789 } catch (PackageParserException e) { 6790 throw PackageManagerException.from(e); 6791 } finally { 6792 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6793 } 6794 6795 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6796 } 6797 6798 /** 6799 * Scans a package and returns the newly parsed package. 6800 * @throws PackageManagerException on a parse error. 6801 */ 6802 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6803 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6804 throws PackageManagerException { 6805 // If the package has children and this is the first dive in the function 6806 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6807 // packages (parent and children) would be successfully scanned before the 6808 // actual scan since scanning mutates internal state and we want to atomically 6809 // install the package and its children. 6810 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6811 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6812 scanFlags |= SCAN_CHECK_ONLY; 6813 } 6814 } else { 6815 scanFlags &= ~SCAN_CHECK_ONLY; 6816 } 6817 6818 // Scan the parent 6819 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6820 scanFlags, currentTime, user); 6821 6822 // Scan the children 6823 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6824 for (int i = 0; i < childCount; i++) { 6825 PackageParser.Package childPackage = pkg.childPackages.get(i); 6826 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6827 currentTime, user); 6828 } 6829 6830 6831 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6832 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6833 } 6834 6835 return scannedPkg; 6836 } 6837 6838 /** 6839 * Scans a package and returns the newly parsed package. 6840 * @throws PackageManagerException on a parse error. 6841 */ 6842 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6843 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6844 throws PackageManagerException { 6845 PackageSetting ps = null; 6846 PackageSetting updatedPkg; 6847 // reader 6848 synchronized (mPackages) { 6849 // Look to see if we already know about this package. 6850 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6851 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6852 // This package has been renamed to its original name. Let's 6853 // use that. 6854 ps = mSettings.peekPackageLPr(oldName); 6855 } 6856 // If there was no original package, see one for the real package name. 6857 if (ps == null) { 6858 ps = mSettings.peekPackageLPr(pkg.packageName); 6859 } 6860 // Check to see if this package could be hiding/updating a system 6861 // package. Must look for it either under the original or real 6862 // package name depending on our state. 6863 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6864 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6865 6866 // If this is a package we don't know about on the system partition, we 6867 // may need to remove disabled child packages on the system partition 6868 // or may need to not add child packages if the parent apk is updated 6869 // on the data partition and no longer defines this child package. 6870 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6871 // If this is a parent package for an updated system app and this system 6872 // app got an OTA update which no longer defines some of the child packages 6873 // we have to prune them from the disabled system packages. 6874 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6875 if (disabledPs != null) { 6876 final int scannedChildCount = (pkg.childPackages != null) 6877 ? pkg.childPackages.size() : 0; 6878 final int disabledChildCount = disabledPs.childPackageNames != null 6879 ? disabledPs.childPackageNames.size() : 0; 6880 for (int i = 0; i < disabledChildCount; i++) { 6881 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6882 boolean disabledPackageAvailable = false; 6883 for (int j = 0; j < scannedChildCount; j++) { 6884 PackageParser.Package childPkg = pkg.childPackages.get(j); 6885 if (childPkg.packageName.equals(disabledChildPackageName)) { 6886 disabledPackageAvailable = true; 6887 break; 6888 } 6889 } 6890 if (!disabledPackageAvailable) { 6891 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6892 } 6893 } 6894 } 6895 } 6896 } 6897 6898 boolean updatedPkgBetter = false; 6899 // First check if this is a system package that may involve an update 6900 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6901 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6902 // it needs to drop FLAG_PRIVILEGED. 6903 if (locationIsPrivileged(scanFile)) { 6904 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6905 } else { 6906 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6907 } 6908 6909 if (ps != null && !ps.codePath.equals(scanFile)) { 6910 // The path has changed from what was last scanned... check the 6911 // version of the new path against what we have stored to determine 6912 // what to do. 6913 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6914 if (pkg.mVersionCode <= ps.versionCode) { 6915 // The system package has been updated and the code path does not match 6916 // Ignore entry. Skip it. 6917 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6918 + " ignored: updated version " + ps.versionCode 6919 + " better than this " + pkg.mVersionCode); 6920 if (!updatedPkg.codePath.equals(scanFile)) { 6921 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6922 + ps.name + " changing from " + updatedPkg.codePathString 6923 + " to " + scanFile); 6924 updatedPkg.codePath = scanFile; 6925 updatedPkg.codePathString = scanFile.toString(); 6926 updatedPkg.resourcePath = scanFile; 6927 updatedPkg.resourcePathString = scanFile.toString(); 6928 } 6929 updatedPkg.pkg = pkg; 6930 updatedPkg.versionCode = pkg.mVersionCode; 6931 6932 // Update the disabled system child packages to point to the package too. 6933 final int childCount = updatedPkg.childPackageNames != null 6934 ? updatedPkg.childPackageNames.size() : 0; 6935 for (int i = 0; i < childCount; i++) { 6936 String childPackageName = updatedPkg.childPackageNames.get(i); 6937 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6938 childPackageName); 6939 if (updatedChildPkg != null) { 6940 updatedChildPkg.pkg = pkg; 6941 updatedChildPkg.versionCode = pkg.mVersionCode; 6942 } 6943 } 6944 6945 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6946 + scanFile + " ignored: updated version " + ps.versionCode 6947 + " better than this " + pkg.mVersionCode); 6948 } else { 6949 // The current app on the system partition is better than 6950 // what we have updated to on the data partition; switch 6951 // back to the system partition version. 6952 // At this point, its safely assumed that package installation for 6953 // apps in system partition will go through. If not there won't be a working 6954 // version of the app 6955 // writer 6956 synchronized (mPackages) { 6957 // Just remove the loaded entries from package lists. 6958 mPackages.remove(ps.name); 6959 } 6960 6961 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6962 + " reverting from " + ps.codePathString 6963 + ": new version " + pkg.mVersionCode 6964 + " better than installed " + ps.versionCode); 6965 6966 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6967 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6968 synchronized (mInstallLock) { 6969 args.cleanUpResourcesLI(); 6970 } 6971 synchronized (mPackages) { 6972 mSettings.enableSystemPackageLPw(ps.name); 6973 } 6974 updatedPkgBetter = true; 6975 } 6976 } 6977 } 6978 6979 if (updatedPkg != null) { 6980 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6981 // initially 6982 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6983 6984 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6985 // flag set initially 6986 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6987 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6988 } 6989 } 6990 6991 // Verify certificates against what was last scanned 6992 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6993 6994 /* 6995 * A new system app appeared, but we already had a non-system one of the 6996 * same name installed earlier. 6997 */ 6998 boolean shouldHideSystemApp = false; 6999 if (updatedPkg == null && ps != null 7000 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7001 /* 7002 * Check to make sure the signatures match first. If they don't, 7003 * wipe the installed application and its data. 7004 */ 7005 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7006 != PackageManager.SIGNATURE_MATCH) { 7007 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7008 + " signatures don't match existing userdata copy; removing"); 7009 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7010 "scanPackageInternalLI")) { 7011 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7012 } 7013 ps = null; 7014 } else { 7015 /* 7016 * If the newly-added system app is an older version than the 7017 * already installed version, hide it. It will be scanned later 7018 * and re-added like an update. 7019 */ 7020 if (pkg.mVersionCode <= ps.versionCode) { 7021 shouldHideSystemApp = true; 7022 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7023 + " but new version " + pkg.mVersionCode + " better than installed " 7024 + ps.versionCode + "; hiding system"); 7025 } else { 7026 /* 7027 * The newly found system app is a newer version that the 7028 * one previously installed. Simply remove the 7029 * already-installed application and replace it with our own 7030 * while keeping the application data. 7031 */ 7032 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7033 + " reverting from " + ps.codePathString + ": new version " 7034 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7035 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7036 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7037 synchronized (mInstallLock) { 7038 args.cleanUpResourcesLI(); 7039 } 7040 } 7041 } 7042 } 7043 7044 // The apk is forward locked (not public) if its code and resources 7045 // are kept in different files. (except for app in either system or 7046 // vendor path). 7047 // TODO grab this value from PackageSettings 7048 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7049 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7050 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7051 } 7052 } 7053 7054 // TODO: extend to support forward-locked splits 7055 String resourcePath = null; 7056 String baseResourcePath = null; 7057 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7058 if (ps != null && ps.resourcePathString != null) { 7059 resourcePath = ps.resourcePathString; 7060 baseResourcePath = ps.resourcePathString; 7061 } else { 7062 // Should not happen at all. Just log an error. 7063 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7064 } 7065 } else { 7066 resourcePath = pkg.codePath; 7067 baseResourcePath = pkg.baseCodePath; 7068 } 7069 7070 // Set application objects path explicitly. 7071 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7072 pkg.setApplicationInfoCodePath(pkg.codePath); 7073 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7074 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7075 pkg.setApplicationInfoResourcePath(resourcePath); 7076 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7077 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7078 7079 // Note that we invoke the following method only if we are about to unpack an application 7080 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7081 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7082 7083 /* 7084 * If the system app should be overridden by a previously installed 7085 * data, hide the system app now and let the /data/app scan pick it up 7086 * again. 7087 */ 7088 if (shouldHideSystemApp) { 7089 synchronized (mPackages) { 7090 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7091 } 7092 } 7093 7094 return scannedPkg; 7095 } 7096 7097 private static String fixProcessName(String defProcessName, 7098 String processName, int uid) { 7099 if (processName == null) { 7100 return defProcessName; 7101 } 7102 return processName; 7103 } 7104 7105 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7106 throws PackageManagerException { 7107 if (pkgSetting.signatures.mSignatures != null) { 7108 // Already existing package. Make sure signatures match 7109 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7110 == PackageManager.SIGNATURE_MATCH; 7111 if (!match) { 7112 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7113 == PackageManager.SIGNATURE_MATCH; 7114 } 7115 if (!match) { 7116 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7117 == PackageManager.SIGNATURE_MATCH; 7118 } 7119 if (!match) { 7120 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7121 + pkg.packageName + " signatures do not match the " 7122 + "previously installed version; ignoring!"); 7123 } 7124 } 7125 7126 // Check for shared user signatures 7127 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7128 // Already existing package. Make sure signatures match 7129 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7130 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7131 if (!match) { 7132 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7133 == PackageManager.SIGNATURE_MATCH; 7134 } 7135 if (!match) { 7136 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7137 == PackageManager.SIGNATURE_MATCH; 7138 } 7139 if (!match) { 7140 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7141 "Package " + pkg.packageName 7142 + " has no signatures that match those in shared user " 7143 + pkgSetting.sharedUser.name + "; ignoring!"); 7144 } 7145 } 7146 } 7147 7148 /** 7149 * Enforces that only the system UID or root's UID can call a method exposed 7150 * via Binder. 7151 * 7152 * @param message used as message if SecurityException is thrown 7153 * @throws SecurityException if the caller is not system or root 7154 */ 7155 private static final void enforceSystemOrRoot(String message) { 7156 final int uid = Binder.getCallingUid(); 7157 if (uid != Process.SYSTEM_UID && uid != 0) { 7158 throw new SecurityException(message); 7159 } 7160 } 7161 7162 @Override 7163 public void performFstrimIfNeeded() { 7164 enforceSystemOrRoot("Only the system can request fstrim"); 7165 7166 // Before everything else, see whether we need to fstrim. 7167 try { 7168 IMountService ms = PackageHelper.getMountService(); 7169 if (ms != null) { 7170 final boolean isUpgrade = isUpgrade(); 7171 boolean doTrim = isUpgrade; 7172 if (doTrim) { 7173 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7174 } else { 7175 final long interval = android.provider.Settings.Global.getLong( 7176 mContext.getContentResolver(), 7177 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7178 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7179 if (interval > 0) { 7180 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7181 if (timeSinceLast > interval) { 7182 doTrim = true; 7183 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7184 + "; running immediately"); 7185 } 7186 } 7187 } 7188 if (doTrim) { 7189 if (!isFirstBoot()) { 7190 try { 7191 ActivityManagerNative.getDefault().showBootMessage( 7192 mContext.getResources().getString( 7193 R.string.android_upgrading_fstrim), true); 7194 } catch (RemoteException e) { 7195 } 7196 } 7197 ms.runMaintenance(); 7198 } 7199 } else { 7200 Slog.e(TAG, "Mount service unavailable!"); 7201 } 7202 } catch (RemoteException e) { 7203 // Can't happen; MountService is local 7204 } 7205 } 7206 7207 @Override 7208 public void updatePackagesIfNeeded() { 7209 enforceSystemOrRoot("Only the system can request package update"); 7210 7211 // We need to re-extract after an OTA. 7212 boolean causeUpgrade = isUpgrade(); 7213 7214 // First boot or factory reset. 7215 // Note: we also handle devices that are upgrading to N right now as if it is their 7216 // first boot, as they do not have profile data. 7217 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7218 7219 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7220 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7221 7222 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7223 return; 7224 } 7225 7226 List<PackageParser.Package> pkgs; 7227 synchronized (mPackages) { 7228 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7229 } 7230 7231 int numberOfPackagesVisited = 0; 7232 int numberOfPackagesOptimized = 0; 7233 int numberOfPackagesSkipped = 0; 7234 int numberOfPackagesFailed = 0; 7235 final int numberOfPackagesToDexopt = pkgs.size(); 7236 final long startTime = System.nanoTime(); 7237 7238 for (PackageParser.Package pkg : pkgs) { 7239 numberOfPackagesVisited++; 7240 7241 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7242 if (DEBUG_DEXOPT) { 7243 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7244 } 7245 numberOfPackagesSkipped++; 7246 continue; 7247 } 7248 7249 if (DEBUG_DEXOPT) { 7250 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7251 numberOfPackagesToDexopt + ": " + pkg.packageName); 7252 } 7253 7254 if (mIsPreNUpgrade) { 7255 try { 7256 ActivityManagerNative.getDefault().showBootMessage( 7257 mContext.getResources().getString(R.string.android_upgrading_apk, 7258 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7259 } catch (RemoteException e) { 7260 } 7261 } 7262 7263 // checkProfiles is false to avoid merging profiles during boot which 7264 // might interfere with background compilation (b/28612421). 7265 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7266 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7267 // trade-off worth doing to save boot time work. 7268 int dexOptStatus = performDexOptTraced(pkg.packageName, 7269 null /* instructionSet */, 7270 false /* checkProfiles */, 7271 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7272 false /* force */); 7273 switch (dexOptStatus) { 7274 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7275 numberOfPackagesOptimized++; 7276 break; 7277 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7278 numberOfPackagesSkipped++; 7279 break; 7280 case PackageDexOptimizer.DEX_OPT_FAILED: 7281 numberOfPackagesFailed++; 7282 break; 7283 default: 7284 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7285 break; 7286 } 7287 } 7288 7289 final int elapsedTimeSeconds = 7290 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7291 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7292 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7293 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7294 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7295 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7296 } 7297 7298 @Override 7299 public void notifyPackageUse(String packageName, int reason) { 7300 synchronized (mPackages) { 7301 PackageParser.Package p = mPackages.get(packageName); 7302 if (p == null) { 7303 return; 7304 } 7305 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7306 } 7307 } 7308 7309 // TODO: this is not used nor needed. Delete it. 7310 @Override 7311 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7312 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7313 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7314 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7315 } 7316 7317 @Override 7318 public boolean performDexOpt(String packageName, String instructionSet, 7319 boolean checkProfiles, int compileReason, boolean force) { 7320 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7321 getCompilerFilterForReason(compileReason), force); 7322 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7323 } 7324 7325 @Override 7326 public boolean performDexOptMode(String packageName, String instructionSet, 7327 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7328 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7329 targetCompilerFilter, force); 7330 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7331 } 7332 7333 private int performDexOptTraced(String packageName, String instructionSet, 7334 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7336 try { 7337 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7338 targetCompilerFilter, force); 7339 } finally { 7340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7341 } 7342 } 7343 7344 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7345 // if the package can now be considered up to date for the given filter. 7346 private int performDexOptInternal(String packageName, String instructionSet, 7347 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7348 PackageParser.Package p; 7349 final String targetInstructionSet; 7350 synchronized (mPackages) { 7351 p = mPackages.get(packageName); 7352 if (p == null) { 7353 // Package could not be found. Report failure. 7354 return PackageDexOptimizer.DEX_OPT_FAILED; 7355 } 7356 mPackageUsage.write(false); 7357 7358 targetInstructionSet = instructionSet != null ? instructionSet : 7359 getPrimaryInstructionSet(p.applicationInfo); 7360 } 7361 long callingId = Binder.clearCallingIdentity(); 7362 try { 7363 synchronized (mInstallLock) { 7364 final String[] instructionSets = new String[] { targetInstructionSet }; 7365 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7366 targetCompilerFilter, force); 7367 } 7368 } finally { 7369 Binder.restoreCallingIdentity(callingId); 7370 } 7371 } 7372 7373 public ArraySet<String> getOptimizablePackages() { 7374 ArraySet<String> pkgs = new ArraySet<String>(); 7375 synchronized (mPackages) { 7376 for (PackageParser.Package p : mPackages.values()) { 7377 if (PackageDexOptimizer.canOptimizePackage(p)) { 7378 pkgs.add(p.packageName); 7379 } 7380 } 7381 } 7382 return pkgs; 7383 } 7384 7385 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7386 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7387 boolean force) { 7388 // Select the dex optimizer based on the force parameter. 7389 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7390 // allocate an object here. 7391 PackageDexOptimizer pdo = force 7392 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7393 : mPackageDexOptimizer; 7394 7395 // Optimize all dependencies first. Note: we ignore the return value and march on 7396 // on errors. 7397 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7398 if (!deps.isEmpty()) { 7399 for (PackageParser.Package depPackage : deps) { 7400 // TODO: Analyze and investigate if we (should) profile libraries. 7401 // Currently this will do a full compilation of the library by default. 7402 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7403 false /* checkProfiles */, 7404 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7405 } 7406 } 7407 7408 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7409 targetCompilerFilter); 7410 } 7411 7412 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7413 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7414 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7415 Set<String> collectedNames = new HashSet<>(); 7416 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7417 7418 retValue.remove(p); 7419 7420 return retValue; 7421 } else { 7422 return Collections.emptyList(); 7423 } 7424 } 7425 7426 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7427 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7428 if (!collectedNames.contains(p.packageName)) { 7429 collectedNames.add(p.packageName); 7430 collected.add(p); 7431 7432 if (p.usesLibraries != null) { 7433 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7434 } 7435 if (p.usesOptionalLibraries != null) { 7436 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7437 collectedNames); 7438 } 7439 } 7440 } 7441 7442 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7443 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7444 for (String libName : libs) { 7445 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7446 if (libPkg != null) { 7447 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7448 } 7449 } 7450 } 7451 7452 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7453 synchronized (mPackages) { 7454 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7455 if (lib != null && lib.apk != null) { 7456 return mPackages.get(lib.apk); 7457 } 7458 } 7459 return null; 7460 } 7461 7462 public void shutdown() { 7463 mPackageUsage.write(true); 7464 } 7465 7466 @Override 7467 public void forceDexOpt(String packageName) { 7468 enforceSystemOrRoot("forceDexOpt"); 7469 7470 PackageParser.Package pkg; 7471 synchronized (mPackages) { 7472 pkg = mPackages.get(packageName); 7473 if (pkg == null) { 7474 throw new IllegalArgumentException("Unknown package: " + packageName); 7475 } 7476 } 7477 7478 synchronized (mInstallLock) { 7479 final String[] instructionSets = new String[] { 7480 getPrimaryInstructionSet(pkg.applicationInfo) }; 7481 7482 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7483 7484 // Whoever is calling forceDexOpt wants a fully compiled package. 7485 // Don't use profiles since that may cause compilation to be skipped. 7486 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7487 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7488 true /* force */); 7489 7490 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7491 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7492 throw new IllegalStateException("Failed to dexopt: " + res); 7493 } 7494 } 7495 } 7496 7497 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7498 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7499 Slog.w(TAG, "Unable to update from " + oldPkg.name 7500 + " to " + newPkg.packageName 7501 + ": old package not in system partition"); 7502 return false; 7503 } else if (mPackages.get(oldPkg.name) != null) { 7504 Slog.w(TAG, "Unable to update from " + oldPkg.name 7505 + " to " + newPkg.packageName 7506 + ": old package still exists"); 7507 return false; 7508 } 7509 return true; 7510 } 7511 7512 void removeCodePathLI(File codePath) { 7513 if (codePath.isDirectory()) { 7514 try { 7515 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7516 } catch (InstallerException e) { 7517 Slog.w(TAG, "Failed to remove code path", e); 7518 } 7519 } else { 7520 codePath.delete(); 7521 } 7522 } 7523 7524 private int[] resolveUserIds(int userId) { 7525 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7526 } 7527 7528 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7529 if (pkg == null) { 7530 Slog.wtf(TAG, "Package was null!", new Throwable()); 7531 return; 7532 } 7533 clearAppDataLeafLIF(pkg, userId, flags); 7534 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7535 for (int i = 0; i < childCount; i++) { 7536 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7537 } 7538 } 7539 7540 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7541 final PackageSetting ps; 7542 synchronized (mPackages) { 7543 ps = mSettings.mPackages.get(pkg.packageName); 7544 } 7545 for (int realUserId : resolveUserIds(userId)) { 7546 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7547 try { 7548 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7549 ceDataInode); 7550 } catch (InstallerException e) { 7551 Slog.w(TAG, String.valueOf(e)); 7552 } 7553 } 7554 } 7555 7556 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7557 if (pkg == null) { 7558 Slog.wtf(TAG, "Package was null!", new Throwable()); 7559 return; 7560 } 7561 destroyAppDataLeafLIF(pkg, userId, flags); 7562 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7563 for (int i = 0; i < childCount; i++) { 7564 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7565 } 7566 } 7567 7568 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7569 final PackageSetting ps; 7570 synchronized (mPackages) { 7571 ps = mSettings.mPackages.get(pkg.packageName); 7572 } 7573 for (int realUserId : resolveUserIds(userId)) { 7574 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7575 try { 7576 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7577 ceDataInode); 7578 } catch (InstallerException e) { 7579 Slog.w(TAG, String.valueOf(e)); 7580 } 7581 } 7582 } 7583 7584 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7585 if (pkg == null) { 7586 Slog.wtf(TAG, "Package was null!", new Throwable()); 7587 return; 7588 } 7589 destroyAppProfilesLeafLIF(pkg); 7590 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7591 for (int i = 0; i < childCount; i++) { 7592 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7593 } 7594 } 7595 7596 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7597 try { 7598 mInstaller.destroyAppProfiles(pkg.packageName); 7599 } catch (InstallerException e) { 7600 Slog.w(TAG, String.valueOf(e)); 7601 } 7602 } 7603 7604 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7605 if (pkg == null) { 7606 Slog.wtf(TAG, "Package was null!", new Throwable()); 7607 return; 7608 } 7609 clearAppProfilesLeafLIF(pkg); 7610 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7611 for (int i = 0; i < childCount; i++) { 7612 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7613 } 7614 } 7615 7616 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7617 try { 7618 mInstaller.clearAppProfiles(pkg.packageName); 7619 } catch (InstallerException e) { 7620 Slog.w(TAG, String.valueOf(e)); 7621 } 7622 } 7623 7624 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7625 long lastUpdateTime) { 7626 // Set parent install/update time 7627 PackageSetting ps = (PackageSetting) pkg.mExtras; 7628 if (ps != null) { 7629 ps.firstInstallTime = firstInstallTime; 7630 ps.lastUpdateTime = lastUpdateTime; 7631 } 7632 // Set children install/update time 7633 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7634 for (int i = 0; i < childCount; i++) { 7635 PackageParser.Package childPkg = pkg.childPackages.get(i); 7636 ps = (PackageSetting) childPkg.mExtras; 7637 if (ps != null) { 7638 ps.firstInstallTime = firstInstallTime; 7639 ps.lastUpdateTime = lastUpdateTime; 7640 } 7641 } 7642 } 7643 7644 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7645 PackageParser.Package changingLib) { 7646 if (file.path != null) { 7647 usesLibraryFiles.add(file.path); 7648 return; 7649 } 7650 PackageParser.Package p = mPackages.get(file.apk); 7651 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7652 // If we are doing this while in the middle of updating a library apk, 7653 // then we need to make sure to use that new apk for determining the 7654 // dependencies here. (We haven't yet finished committing the new apk 7655 // to the package manager state.) 7656 if (p == null || p.packageName.equals(changingLib.packageName)) { 7657 p = changingLib; 7658 } 7659 } 7660 if (p != null) { 7661 usesLibraryFiles.addAll(p.getAllCodePaths()); 7662 } 7663 } 7664 7665 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7666 PackageParser.Package changingLib) throws PackageManagerException { 7667 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7668 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7669 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7670 for (int i=0; i<N; i++) { 7671 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7672 if (file == null) { 7673 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7674 "Package " + pkg.packageName + " requires unavailable shared library " 7675 + pkg.usesLibraries.get(i) + "; failing!"); 7676 } 7677 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7678 } 7679 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7680 for (int i=0; i<N; i++) { 7681 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7682 if (file == null) { 7683 Slog.w(TAG, "Package " + pkg.packageName 7684 + " desires unavailable shared library " 7685 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7686 } else { 7687 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7688 } 7689 } 7690 N = usesLibraryFiles.size(); 7691 if (N > 0) { 7692 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7693 } else { 7694 pkg.usesLibraryFiles = null; 7695 } 7696 } 7697 } 7698 7699 private static boolean hasString(List<String> list, List<String> which) { 7700 if (list == null) { 7701 return false; 7702 } 7703 for (int i=list.size()-1; i>=0; i--) { 7704 for (int j=which.size()-1; j>=0; j--) { 7705 if (which.get(j).equals(list.get(i))) { 7706 return true; 7707 } 7708 } 7709 } 7710 return false; 7711 } 7712 7713 private void updateAllSharedLibrariesLPw() { 7714 for (PackageParser.Package pkg : mPackages.values()) { 7715 try { 7716 updateSharedLibrariesLPw(pkg, null); 7717 } catch (PackageManagerException e) { 7718 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7719 } 7720 } 7721 } 7722 7723 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7724 PackageParser.Package changingPkg) { 7725 ArrayList<PackageParser.Package> res = null; 7726 for (PackageParser.Package pkg : mPackages.values()) { 7727 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7728 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7729 if (res == null) { 7730 res = new ArrayList<PackageParser.Package>(); 7731 } 7732 res.add(pkg); 7733 try { 7734 updateSharedLibrariesLPw(pkg, changingPkg); 7735 } catch (PackageManagerException e) { 7736 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7737 } 7738 } 7739 } 7740 return res; 7741 } 7742 7743 /** 7744 * Derive the value of the {@code cpuAbiOverride} based on the provided 7745 * value and an optional stored value from the package settings. 7746 */ 7747 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7748 String cpuAbiOverride = null; 7749 7750 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7751 cpuAbiOverride = null; 7752 } else if (abiOverride != null) { 7753 cpuAbiOverride = abiOverride; 7754 } else if (settings != null) { 7755 cpuAbiOverride = settings.cpuAbiOverrideString; 7756 } 7757 7758 return cpuAbiOverride; 7759 } 7760 7761 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7762 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7763 throws PackageManagerException { 7764 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7765 // If the package has children and this is the first dive in the function 7766 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7767 // whether all packages (parent and children) would be successfully scanned 7768 // before the actual scan since scanning mutates internal state and we want 7769 // to atomically install the package and its children. 7770 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7771 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7772 scanFlags |= SCAN_CHECK_ONLY; 7773 } 7774 } else { 7775 scanFlags &= ~SCAN_CHECK_ONLY; 7776 } 7777 7778 final PackageParser.Package scannedPkg; 7779 try { 7780 // Scan the parent 7781 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7782 // Scan the children 7783 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7784 for (int i = 0; i < childCount; i++) { 7785 PackageParser.Package childPkg = pkg.childPackages.get(i); 7786 scanPackageLI(childPkg, policyFlags, 7787 scanFlags, currentTime, user); 7788 } 7789 } finally { 7790 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7791 } 7792 7793 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7794 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7795 } 7796 7797 return scannedPkg; 7798 } 7799 7800 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7801 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7802 boolean success = false; 7803 try { 7804 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7805 currentTime, user); 7806 success = true; 7807 return res; 7808 } finally { 7809 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7810 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7811 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7812 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7813 destroyAppProfilesLIF(pkg); 7814 } 7815 } 7816 } 7817 7818 /** 7819 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7820 */ 7821 private static boolean apkHasCode(String fileName) { 7822 StrictJarFile jarFile = null; 7823 try { 7824 jarFile = new StrictJarFile(fileName, 7825 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7826 return jarFile.findEntry("classes.dex") != null; 7827 } catch (IOException ignore) { 7828 } finally { 7829 try { 7830 jarFile.close(); 7831 } catch (IOException ignore) {} 7832 } 7833 return false; 7834 } 7835 7836 /** 7837 * Enforces code policy for the package. This ensures that if an APK has 7838 * declared hasCode="true" in its manifest that the APK actually contains 7839 * code. 7840 * 7841 * @throws PackageManagerException If bytecode could not be found when it should exist 7842 */ 7843 private static void enforceCodePolicy(PackageParser.Package pkg) 7844 throws PackageManagerException { 7845 final boolean shouldHaveCode = 7846 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7847 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7848 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7849 "Package " + pkg.baseCodePath + " code is missing"); 7850 } 7851 7852 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7853 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7854 final boolean splitShouldHaveCode = 7855 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7856 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7857 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7858 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7859 } 7860 } 7861 } 7862 } 7863 7864 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7865 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7866 throws PackageManagerException { 7867 final File scanFile = new File(pkg.codePath); 7868 if (pkg.applicationInfo.getCodePath() == null || 7869 pkg.applicationInfo.getResourcePath() == null) { 7870 // Bail out. The resource and code paths haven't been set. 7871 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7872 "Code and resource paths haven't been set correctly"); 7873 } 7874 7875 // Apply policy 7876 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7877 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7878 if (pkg.applicationInfo.isDirectBootAware()) { 7879 // we're direct boot aware; set for all components 7880 for (PackageParser.Service s : pkg.services) { 7881 s.info.encryptionAware = s.info.directBootAware = true; 7882 } 7883 for (PackageParser.Provider p : pkg.providers) { 7884 p.info.encryptionAware = p.info.directBootAware = true; 7885 } 7886 for (PackageParser.Activity a : pkg.activities) { 7887 a.info.encryptionAware = a.info.directBootAware = true; 7888 } 7889 for (PackageParser.Activity r : pkg.receivers) { 7890 r.info.encryptionAware = r.info.directBootAware = true; 7891 } 7892 } 7893 } else { 7894 // Only allow system apps to be flagged as core apps. 7895 pkg.coreApp = false; 7896 // clear flags not applicable to regular apps 7897 pkg.applicationInfo.privateFlags &= 7898 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7899 pkg.applicationInfo.privateFlags &= 7900 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7901 } 7902 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7903 7904 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7905 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7906 } 7907 7908 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7909 enforceCodePolicy(pkg); 7910 } 7911 7912 if (mCustomResolverComponentName != null && 7913 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7914 setUpCustomResolverActivity(pkg); 7915 } 7916 7917 if (pkg.packageName.equals("android")) { 7918 synchronized (mPackages) { 7919 if (mAndroidApplication != null) { 7920 Slog.w(TAG, "*************************************************"); 7921 Slog.w(TAG, "Core android package being redefined. Skipping."); 7922 Slog.w(TAG, " file=" + scanFile); 7923 Slog.w(TAG, "*************************************************"); 7924 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7925 "Core android package being redefined. Skipping."); 7926 } 7927 7928 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7929 // Set up information for our fall-back user intent resolution activity. 7930 mPlatformPackage = pkg; 7931 pkg.mVersionCode = mSdkVersion; 7932 mAndroidApplication = pkg.applicationInfo; 7933 7934 if (!mResolverReplaced) { 7935 mResolveActivity.applicationInfo = mAndroidApplication; 7936 mResolveActivity.name = ResolverActivity.class.getName(); 7937 mResolveActivity.packageName = mAndroidApplication.packageName; 7938 mResolveActivity.processName = "system:ui"; 7939 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7940 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7941 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7942 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7943 mResolveActivity.exported = true; 7944 mResolveActivity.enabled = true; 7945 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7946 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7947 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7948 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7949 | ActivityInfo.CONFIG_ORIENTATION 7950 | ActivityInfo.CONFIG_KEYBOARD 7951 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7952 mResolveInfo.activityInfo = mResolveActivity; 7953 mResolveInfo.priority = 0; 7954 mResolveInfo.preferredOrder = 0; 7955 mResolveInfo.match = 0; 7956 mResolveComponentName = new ComponentName( 7957 mAndroidApplication.packageName, mResolveActivity.name); 7958 } 7959 } 7960 } 7961 } 7962 7963 if (DEBUG_PACKAGE_SCANNING) { 7964 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7965 Log.d(TAG, "Scanning package " + pkg.packageName); 7966 } 7967 7968 synchronized (mPackages) { 7969 if (mPackages.containsKey(pkg.packageName) 7970 || mSharedLibraries.containsKey(pkg.packageName)) { 7971 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7972 "Application package " + pkg.packageName 7973 + " already installed. Skipping duplicate."); 7974 } 7975 7976 // If we're only installing presumed-existing packages, require that the 7977 // scanned APK is both already known and at the path previously established 7978 // for it. Previously unknown packages we pick up normally, but if we have an 7979 // a priori expectation about this package's install presence, enforce it. 7980 // With a singular exception for new system packages. When an OTA contains 7981 // a new system package, we allow the codepath to change from a system location 7982 // to the user-installed location. If we don't allow this change, any newer, 7983 // user-installed version of the application will be ignored. 7984 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7985 if (mExpectingBetter.containsKey(pkg.packageName)) { 7986 logCriticalInfo(Log.WARN, 7987 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7988 } else { 7989 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7990 if (known != null) { 7991 if (DEBUG_PACKAGE_SCANNING) { 7992 Log.d(TAG, "Examining " + pkg.codePath 7993 + " and requiring known paths " + known.codePathString 7994 + " & " + known.resourcePathString); 7995 } 7996 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7997 || !pkg.applicationInfo.getResourcePath().equals( 7998 known.resourcePathString)) { 7999 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8000 "Application package " + pkg.packageName 8001 + " found at " + pkg.applicationInfo.getCodePath() 8002 + " but expected at " + known.codePathString 8003 + "; ignoring."); 8004 } 8005 } 8006 } 8007 } 8008 } 8009 8010 // Initialize package source and resource directories 8011 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8012 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8013 8014 SharedUserSetting suid = null; 8015 PackageSetting pkgSetting = null; 8016 8017 if (!isSystemApp(pkg)) { 8018 // Only system apps can use these features. 8019 pkg.mOriginalPackages = null; 8020 pkg.mRealPackage = null; 8021 pkg.mAdoptPermissions = null; 8022 } 8023 8024 // Getting the package setting may have a side-effect, so if we 8025 // are only checking if scan would succeed, stash a copy of the 8026 // old setting to restore at the end. 8027 PackageSetting nonMutatedPs = null; 8028 8029 // writer 8030 synchronized (mPackages) { 8031 if (pkg.mSharedUserId != null) { 8032 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8033 if (suid == null) { 8034 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8035 "Creating application package " + pkg.packageName 8036 + " for shared user failed"); 8037 } 8038 if (DEBUG_PACKAGE_SCANNING) { 8039 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8040 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8041 + "): packages=" + suid.packages); 8042 } 8043 } 8044 8045 // Check if we are renaming from an original package name. 8046 PackageSetting origPackage = null; 8047 String realName = null; 8048 if (pkg.mOriginalPackages != null) { 8049 // This package may need to be renamed to a previously 8050 // installed name. Let's check on that... 8051 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8052 if (pkg.mOriginalPackages.contains(renamed)) { 8053 // This package had originally been installed as the 8054 // original name, and we have already taken care of 8055 // transitioning to the new one. Just update the new 8056 // one to continue using the old name. 8057 realName = pkg.mRealPackage; 8058 if (!pkg.packageName.equals(renamed)) { 8059 // Callers into this function may have already taken 8060 // care of renaming the package; only do it here if 8061 // it is not already done. 8062 pkg.setPackageName(renamed); 8063 } 8064 8065 } else { 8066 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8067 if ((origPackage = mSettings.peekPackageLPr( 8068 pkg.mOriginalPackages.get(i))) != null) { 8069 // We do have the package already installed under its 8070 // original name... should we use it? 8071 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8072 // New package is not compatible with original. 8073 origPackage = null; 8074 continue; 8075 } else if (origPackage.sharedUser != null) { 8076 // Make sure uid is compatible between packages. 8077 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8078 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8079 + " to " + pkg.packageName + ": old uid " 8080 + origPackage.sharedUser.name 8081 + " differs from " + pkg.mSharedUserId); 8082 origPackage = null; 8083 continue; 8084 } 8085 // TODO: Add case when shared user id is added [b/28144775] 8086 } else { 8087 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8088 + pkg.packageName + " to old name " + origPackage.name); 8089 } 8090 break; 8091 } 8092 } 8093 } 8094 } 8095 8096 if (mTransferedPackages.contains(pkg.packageName)) { 8097 Slog.w(TAG, "Package " + pkg.packageName 8098 + " was transferred to another, but its .apk remains"); 8099 } 8100 8101 // See comments in nonMutatedPs declaration 8102 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8103 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8104 if (foundPs != null) { 8105 nonMutatedPs = new PackageSetting(foundPs); 8106 } 8107 } 8108 8109 // Just create the setting, don't add it yet. For already existing packages 8110 // the PkgSetting exists already and doesn't have to be created. 8111 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8112 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8113 pkg.applicationInfo.primaryCpuAbi, 8114 pkg.applicationInfo.secondaryCpuAbi, 8115 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8116 user, false); 8117 if (pkgSetting == null) { 8118 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8119 "Creating application package " + pkg.packageName + " failed"); 8120 } 8121 8122 if (pkgSetting.origPackage != null) { 8123 // If we are first transitioning from an original package, 8124 // fix up the new package's name now. We need to do this after 8125 // looking up the package under its new name, so getPackageLP 8126 // can take care of fiddling things correctly. 8127 pkg.setPackageName(origPackage.name); 8128 8129 // File a report about this. 8130 String msg = "New package " + pkgSetting.realName 8131 + " renamed to replace old package " + pkgSetting.name; 8132 reportSettingsProblem(Log.WARN, msg); 8133 8134 // Make a note of it. 8135 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8136 mTransferedPackages.add(origPackage.name); 8137 } 8138 8139 // No longer need to retain this. 8140 pkgSetting.origPackage = null; 8141 } 8142 8143 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8144 // Make a note of it. 8145 mTransferedPackages.add(pkg.packageName); 8146 } 8147 8148 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8149 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8150 } 8151 8152 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8153 // Check all shared libraries and map to their actual file path. 8154 // We only do this here for apps not on a system dir, because those 8155 // are the only ones that can fail an install due to this. We 8156 // will take care of the system apps by updating all of their 8157 // library paths after the scan is done. 8158 updateSharedLibrariesLPw(pkg, null); 8159 } 8160 8161 if (mFoundPolicyFile) { 8162 SELinuxMMAC.assignSeinfoValue(pkg); 8163 } 8164 8165 pkg.applicationInfo.uid = pkgSetting.appId; 8166 pkg.mExtras = pkgSetting; 8167 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8168 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8169 // We just determined the app is signed correctly, so bring 8170 // over the latest parsed certs. 8171 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8172 } else { 8173 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8174 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8175 "Package " + pkg.packageName + " upgrade keys do not match the " 8176 + "previously installed version"); 8177 } else { 8178 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8179 String msg = "System package " + pkg.packageName 8180 + " signature changed; retaining data."; 8181 reportSettingsProblem(Log.WARN, msg); 8182 } 8183 } 8184 } else { 8185 try { 8186 verifySignaturesLP(pkgSetting, pkg); 8187 // We just determined the app is signed correctly, so bring 8188 // over the latest parsed certs. 8189 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8190 } catch (PackageManagerException e) { 8191 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8192 throw e; 8193 } 8194 // The signature has changed, but this package is in the system 8195 // image... let's recover! 8196 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8197 // However... if this package is part of a shared user, but it 8198 // doesn't match the signature of the shared user, let's fail. 8199 // What this means is that you can't change the signatures 8200 // associated with an overall shared user, which doesn't seem all 8201 // that unreasonable. 8202 if (pkgSetting.sharedUser != null) { 8203 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8204 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8205 throw new PackageManagerException( 8206 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8207 "Signature mismatch for shared user: " 8208 + pkgSetting.sharedUser); 8209 } 8210 } 8211 // File a report about this. 8212 String msg = "System package " + pkg.packageName 8213 + " signature changed; retaining data."; 8214 reportSettingsProblem(Log.WARN, msg); 8215 } 8216 } 8217 // Verify that this new package doesn't have any content providers 8218 // that conflict with existing packages. Only do this if the 8219 // package isn't already installed, since we don't want to break 8220 // things that are installed. 8221 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8222 final int N = pkg.providers.size(); 8223 int i; 8224 for (i=0; i<N; i++) { 8225 PackageParser.Provider p = pkg.providers.get(i); 8226 if (p.info.authority != null) { 8227 String names[] = p.info.authority.split(";"); 8228 for (int j = 0; j < names.length; j++) { 8229 if (mProvidersByAuthority.containsKey(names[j])) { 8230 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8231 final String otherPackageName = 8232 ((other != null && other.getComponentName() != null) ? 8233 other.getComponentName().getPackageName() : "?"); 8234 throw new PackageManagerException( 8235 INSTALL_FAILED_CONFLICTING_PROVIDER, 8236 "Can't install because provider name " + names[j] 8237 + " (in package " + pkg.applicationInfo.packageName 8238 + ") is already used by " + otherPackageName); 8239 } 8240 } 8241 } 8242 } 8243 } 8244 8245 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8246 // This package wants to adopt ownership of permissions from 8247 // another package. 8248 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8249 final String origName = pkg.mAdoptPermissions.get(i); 8250 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8251 if (orig != null) { 8252 if (verifyPackageUpdateLPr(orig, pkg)) { 8253 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8254 + pkg.packageName); 8255 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8256 } 8257 } 8258 } 8259 } 8260 } 8261 8262 final String pkgName = pkg.packageName; 8263 8264 final long scanFileTime = scanFile.lastModified(); 8265 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8266 pkg.applicationInfo.processName = fixProcessName( 8267 pkg.applicationInfo.packageName, 8268 pkg.applicationInfo.processName, 8269 pkg.applicationInfo.uid); 8270 8271 if (pkg != mPlatformPackage) { 8272 // Get all of our default paths setup 8273 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8274 } 8275 8276 final String path = scanFile.getPath(); 8277 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8278 8279 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8280 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8281 8282 // Some system apps still use directory structure for native libraries 8283 // in which case we might end up not detecting abi solely based on apk 8284 // structure. Try to detect abi based on directory structure. 8285 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8286 pkg.applicationInfo.primaryCpuAbi == null) { 8287 setBundledAppAbisAndRoots(pkg, pkgSetting); 8288 setNativeLibraryPaths(pkg); 8289 } 8290 8291 } else { 8292 if ((scanFlags & SCAN_MOVE) != 0) { 8293 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8294 // but we already have this packages package info in the PackageSetting. We just 8295 // use that and derive the native library path based on the new codepath. 8296 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8297 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8298 } 8299 8300 // Set native library paths again. For moves, the path will be updated based on the 8301 // ABIs we've determined above. For non-moves, the path will be updated based on the 8302 // ABIs we determined during compilation, but the path will depend on the final 8303 // package path (after the rename away from the stage path). 8304 setNativeLibraryPaths(pkg); 8305 } 8306 8307 // This is a special case for the "system" package, where the ABI is 8308 // dictated by the zygote configuration (and init.rc). We should keep track 8309 // of this ABI so that we can deal with "normal" applications that run under 8310 // the same UID correctly. 8311 if (mPlatformPackage == pkg) { 8312 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8313 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8314 } 8315 8316 // If there's a mismatch between the abi-override in the package setting 8317 // and the abiOverride specified for the install. Warn about this because we 8318 // would've already compiled the app without taking the package setting into 8319 // account. 8320 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8321 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8322 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8323 " for package " + pkg.packageName); 8324 } 8325 } 8326 8327 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8328 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8329 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8330 8331 // Copy the derived override back to the parsed package, so that we can 8332 // update the package settings accordingly. 8333 pkg.cpuAbiOverride = cpuAbiOverride; 8334 8335 if (DEBUG_ABI_SELECTION) { 8336 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8337 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8338 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8339 } 8340 8341 // Push the derived path down into PackageSettings so we know what to 8342 // clean up at uninstall time. 8343 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8344 8345 if (DEBUG_ABI_SELECTION) { 8346 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8347 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8348 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8349 } 8350 8351 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8352 // We don't do this here during boot because we can do it all 8353 // at once after scanning all existing packages. 8354 // 8355 // We also do this *before* we perform dexopt on this package, so that 8356 // we can avoid redundant dexopts, and also to make sure we've got the 8357 // code and package path correct. 8358 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8359 pkg, true /* boot complete */); 8360 } 8361 8362 if (mFactoryTest && pkg.requestedPermissions.contains( 8363 android.Manifest.permission.FACTORY_TEST)) { 8364 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8365 } 8366 8367 ArrayList<PackageParser.Package> clientLibPkgs = null; 8368 8369 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8370 if (nonMutatedPs != null) { 8371 synchronized (mPackages) { 8372 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8373 } 8374 } 8375 return pkg; 8376 } 8377 8378 // Only privileged apps and updated privileged apps can add child packages. 8379 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8380 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8381 throw new PackageManagerException("Only privileged apps and updated " 8382 + "privileged apps can add child packages. Ignoring package " 8383 + pkg.packageName); 8384 } 8385 final int childCount = pkg.childPackages.size(); 8386 for (int i = 0; i < childCount; i++) { 8387 PackageParser.Package childPkg = pkg.childPackages.get(i); 8388 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8389 childPkg.packageName)) { 8390 throw new PackageManagerException("Cannot override a child package of " 8391 + "another disabled system app. Ignoring package " + pkg.packageName); 8392 } 8393 } 8394 } 8395 8396 // writer 8397 synchronized (mPackages) { 8398 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8399 // Only system apps can add new shared libraries. 8400 if (pkg.libraryNames != null) { 8401 for (int i=0; i<pkg.libraryNames.size(); i++) { 8402 String name = pkg.libraryNames.get(i); 8403 boolean allowed = false; 8404 if (pkg.isUpdatedSystemApp()) { 8405 // New library entries can only be added through the 8406 // system image. This is important to get rid of a lot 8407 // of nasty edge cases: for example if we allowed a non- 8408 // system update of the app to add a library, then uninstalling 8409 // the update would make the library go away, and assumptions 8410 // we made such as through app install filtering would now 8411 // have allowed apps on the device which aren't compatible 8412 // with it. Better to just have the restriction here, be 8413 // conservative, and create many fewer cases that can negatively 8414 // impact the user experience. 8415 final PackageSetting sysPs = mSettings 8416 .getDisabledSystemPkgLPr(pkg.packageName); 8417 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8418 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8419 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8420 allowed = true; 8421 break; 8422 } 8423 } 8424 } 8425 } else { 8426 allowed = true; 8427 } 8428 if (allowed) { 8429 if (!mSharedLibraries.containsKey(name)) { 8430 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8431 } else if (!name.equals(pkg.packageName)) { 8432 Slog.w(TAG, "Package " + pkg.packageName + " library " 8433 + name + " already exists; skipping"); 8434 } 8435 } else { 8436 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8437 + name + " that is not declared on system image; skipping"); 8438 } 8439 } 8440 if ((scanFlags & SCAN_BOOTING) == 0) { 8441 // If we are not booting, we need to update any applications 8442 // that are clients of our shared library. If we are booting, 8443 // this will all be done once the scan is complete. 8444 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8445 } 8446 } 8447 } 8448 } 8449 8450 if ((scanFlags & SCAN_BOOTING) != 0) { 8451 // No apps can run during boot scan, so they don't need to be frozen 8452 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8453 // Caller asked to not kill app, so it's probably not frozen 8454 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8455 // Caller asked us to ignore frozen check for some reason; they 8456 // probably didn't know the package name 8457 } else { 8458 // We're doing major surgery on this package, so it better be frozen 8459 // right now to keep it from launching 8460 checkPackageFrozen(pkgName); 8461 } 8462 8463 // Also need to kill any apps that are dependent on the library. 8464 if (clientLibPkgs != null) { 8465 for (int i=0; i<clientLibPkgs.size(); i++) { 8466 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8467 killApplication(clientPkg.applicationInfo.packageName, 8468 clientPkg.applicationInfo.uid, "update lib"); 8469 } 8470 } 8471 8472 // Make sure we're not adding any bogus keyset info 8473 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8474 ksms.assertScannedPackageValid(pkg); 8475 8476 // writer 8477 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8478 8479 boolean createIdmapFailed = false; 8480 synchronized (mPackages) { 8481 // We don't expect installation to fail beyond this point 8482 8483 // Add the new setting to mSettings 8484 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8485 // Add the new setting to mPackages 8486 mPackages.put(pkg.applicationInfo.packageName, pkg); 8487 // Make sure we don't accidentally delete its data. 8488 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8489 while (iter.hasNext()) { 8490 PackageCleanItem item = iter.next(); 8491 if (pkgName.equals(item.packageName)) { 8492 iter.remove(); 8493 } 8494 } 8495 8496 // Take care of first install / last update times. 8497 if (currentTime != 0) { 8498 if (pkgSetting.firstInstallTime == 0) { 8499 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8500 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8501 pkgSetting.lastUpdateTime = currentTime; 8502 } 8503 } else if (pkgSetting.firstInstallTime == 0) { 8504 // We need *something*. Take time time stamp of the file. 8505 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8506 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8507 if (scanFileTime != pkgSetting.timeStamp) { 8508 // A package on the system image has changed; consider this 8509 // to be an update. 8510 pkgSetting.lastUpdateTime = scanFileTime; 8511 } 8512 } 8513 8514 // Add the package's KeySets to the global KeySetManagerService 8515 ksms.addScannedPackageLPw(pkg); 8516 8517 int N = pkg.providers.size(); 8518 StringBuilder r = null; 8519 int i; 8520 for (i=0; i<N; i++) { 8521 PackageParser.Provider p = pkg.providers.get(i); 8522 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8523 p.info.processName, pkg.applicationInfo.uid); 8524 mProviders.addProvider(p); 8525 p.syncable = p.info.isSyncable; 8526 if (p.info.authority != null) { 8527 String names[] = p.info.authority.split(";"); 8528 p.info.authority = null; 8529 for (int j = 0; j < names.length; j++) { 8530 if (j == 1 && p.syncable) { 8531 // We only want the first authority for a provider to possibly be 8532 // syncable, so if we already added this provider using a different 8533 // authority clear the syncable flag. We copy the provider before 8534 // changing it because the mProviders object contains a reference 8535 // to a provider that we don't want to change. 8536 // Only do this for the second authority since the resulting provider 8537 // object can be the same for all future authorities for this provider. 8538 p = new PackageParser.Provider(p); 8539 p.syncable = false; 8540 } 8541 if (!mProvidersByAuthority.containsKey(names[j])) { 8542 mProvidersByAuthority.put(names[j], p); 8543 if (p.info.authority == null) { 8544 p.info.authority = names[j]; 8545 } else { 8546 p.info.authority = p.info.authority + ";" + names[j]; 8547 } 8548 if (DEBUG_PACKAGE_SCANNING) { 8549 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8550 Log.d(TAG, "Registered content provider: " + names[j] 8551 + ", className = " + p.info.name + ", isSyncable = " 8552 + p.info.isSyncable); 8553 } 8554 } else { 8555 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8556 Slog.w(TAG, "Skipping provider name " + names[j] + 8557 " (in package " + pkg.applicationInfo.packageName + 8558 "): name already used by " 8559 + ((other != null && other.getComponentName() != null) 8560 ? other.getComponentName().getPackageName() : "?")); 8561 } 8562 } 8563 } 8564 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8565 if (r == null) { 8566 r = new StringBuilder(256); 8567 } else { 8568 r.append(' '); 8569 } 8570 r.append(p.info.name); 8571 } 8572 } 8573 if (r != null) { 8574 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8575 } 8576 8577 N = pkg.services.size(); 8578 r = null; 8579 for (i=0; i<N; i++) { 8580 PackageParser.Service s = pkg.services.get(i); 8581 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8582 s.info.processName, pkg.applicationInfo.uid); 8583 mServices.addService(s); 8584 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8585 if (r == null) { 8586 r = new StringBuilder(256); 8587 } else { 8588 r.append(' '); 8589 } 8590 r.append(s.info.name); 8591 } 8592 } 8593 if (r != null) { 8594 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8595 } 8596 8597 N = pkg.receivers.size(); 8598 r = null; 8599 for (i=0; i<N; i++) { 8600 PackageParser.Activity a = pkg.receivers.get(i); 8601 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8602 a.info.processName, pkg.applicationInfo.uid); 8603 mReceivers.addActivity(a, "receiver"); 8604 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8605 if (r == null) { 8606 r = new StringBuilder(256); 8607 } else { 8608 r.append(' '); 8609 } 8610 r.append(a.info.name); 8611 } 8612 } 8613 if (r != null) { 8614 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8615 } 8616 8617 N = pkg.activities.size(); 8618 r = null; 8619 for (i=0; i<N; i++) { 8620 PackageParser.Activity a = pkg.activities.get(i); 8621 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8622 a.info.processName, pkg.applicationInfo.uid); 8623 mActivities.addActivity(a, "activity"); 8624 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8625 if (r == null) { 8626 r = new StringBuilder(256); 8627 } else { 8628 r.append(' '); 8629 } 8630 r.append(a.info.name); 8631 } 8632 } 8633 if (r != null) { 8634 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8635 } 8636 8637 N = pkg.permissionGroups.size(); 8638 r = null; 8639 for (i=0; i<N; i++) { 8640 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8641 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8642 if (cur == null) { 8643 mPermissionGroups.put(pg.info.name, pg); 8644 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8645 if (r == null) { 8646 r = new StringBuilder(256); 8647 } else { 8648 r.append(' '); 8649 } 8650 r.append(pg.info.name); 8651 } 8652 } else { 8653 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8654 + pg.info.packageName + " ignored: original from " 8655 + cur.info.packageName); 8656 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8657 if (r == null) { 8658 r = new StringBuilder(256); 8659 } else { 8660 r.append(' '); 8661 } 8662 r.append("DUP:"); 8663 r.append(pg.info.name); 8664 } 8665 } 8666 } 8667 if (r != null) { 8668 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8669 } 8670 8671 N = pkg.permissions.size(); 8672 r = null; 8673 for (i=0; i<N; i++) { 8674 PackageParser.Permission p = pkg.permissions.get(i); 8675 8676 // Assume by default that we did not install this permission into the system. 8677 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8678 8679 // Now that permission groups have a special meaning, we ignore permission 8680 // groups for legacy apps to prevent unexpected behavior. In particular, 8681 // permissions for one app being granted to someone just becase they happen 8682 // to be in a group defined by another app (before this had no implications). 8683 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8684 p.group = mPermissionGroups.get(p.info.group); 8685 // Warn for a permission in an unknown group. 8686 if (p.info.group != null && p.group == null) { 8687 Slog.w(TAG, "Permission " + p.info.name + " from package " 8688 + p.info.packageName + " in an unknown group " + p.info.group); 8689 } 8690 } 8691 8692 ArrayMap<String, BasePermission> permissionMap = 8693 p.tree ? mSettings.mPermissionTrees 8694 : mSettings.mPermissions; 8695 BasePermission bp = permissionMap.get(p.info.name); 8696 8697 // Allow system apps to redefine non-system permissions 8698 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8699 final boolean currentOwnerIsSystem = (bp.perm != null 8700 && isSystemApp(bp.perm.owner)); 8701 if (isSystemApp(p.owner)) { 8702 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8703 // It's a built-in permission and no owner, take ownership now 8704 bp.packageSetting = pkgSetting; 8705 bp.perm = p; 8706 bp.uid = pkg.applicationInfo.uid; 8707 bp.sourcePackage = p.info.packageName; 8708 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8709 } else if (!currentOwnerIsSystem) { 8710 String msg = "New decl " + p.owner + " of permission " 8711 + p.info.name + " is system; overriding " + bp.sourcePackage; 8712 reportSettingsProblem(Log.WARN, msg); 8713 bp = null; 8714 } 8715 } 8716 } 8717 8718 if (bp == null) { 8719 bp = new BasePermission(p.info.name, p.info.packageName, 8720 BasePermission.TYPE_NORMAL); 8721 permissionMap.put(p.info.name, bp); 8722 } 8723 8724 if (bp.perm == null) { 8725 if (bp.sourcePackage == null 8726 || bp.sourcePackage.equals(p.info.packageName)) { 8727 BasePermission tree = findPermissionTreeLP(p.info.name); 8728 if (tree == null 8729 || tree.sourcePackage.equals(p.info.packageName)) { 8730 bp.packageSetting = pkgSetting; 8731 bp.perm = p; 8732 bp.uid = pkg.applicationInfo.uid; 8733 bp.sourcePackage = p.info.packageName; 8734 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8735 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8736 if (r == null) { 8737 r = new StringBuilder(256); 8738 } else { 8739 r.append(' '); 8740 } 8741 r.append(p.info.name); 8742 } 8743 } else { 8744 Slog.w(TAG, "Permission " + p.info.name + " from package " 8745 + p.info.packageName + " ignored: base tree " 8746 + tree.name + " is from package " 8747 + tree.sourcePackage); 8748 } 8749 } else { 8750 Slog.w(TAG, "Permission " + p.info.name + " from package " 8751 + p.info.packageName + " ignored: original from " 8752 + bp.sourcePackage); 8753 } 8754 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8755 if (r == null) { 8756 r = new StringBuilder(256); 8757 } else { 8758 r.append(' '); 8759 } 8760 r.append("DUP:"); 8761 r.append(p.info.name); 8762 } 8763 if (bp.perm == p) { 8764 bp.protectionLevel = p.info.protectionLevel; 8765 } 8766 } 8767 8768 if (r != null) { 8769 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8770 } 8771 8772 N = pkg.instrumentation.size(); 8773 r = null; 8774 for (i=0; i<N; i++) { 8775 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8776 a.info.packageName = pkg.applicationInfo.packageName; 8777 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8778 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8779 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8780 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8781 a.info.dataDir = pkg.applicationInfo.dataDir; 8782 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8783 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8784 8785 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8786 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8787 mInstrumentation.put(a.getComponentName(), a); 8788 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8789 if (r == null) { 8790 r = new StringBuilder(256); 8791 } else { 8792 r.append(' '); 8793 } 8794 r.append(a.info.name); 8795 } 8796 } 8797 if (r != null) { 8798 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8799 } 8800 8801 if (pkg.protectedBroadcasts != null) { 8802 N = pkg.protectedBroadcasts.size(); 8803 for (i=0; i<N; i++) { 8804 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8805 } 8806 } 8807 8808 pkgSetting.setTimeStamp(scanFileTime); 8809 8810 // Create idmap files for pairs of (packages, overlay packages). 8811 // Note: "android", ie framework-res.apk, is handled by native layers. 8812 if (pkg.mOverlayTarget != null) { 8813 // This is an overlay package. 8814 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8815 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8816 mOverlays.put(pkg.mOverlayTarget, 8817 new ArrayMap<String, PackageParser.Package>()); 8818 } 8819 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8820 map.put(pkg.packageName, pkg); 8821 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8822 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8823 createIdmapFailed = true; 8824 } 8825 } 8826 } else if (mOverlays.containsKey(pkg.packageName) && 8827 !pkg.packageName.equals("android")) { 8828 // This is a regular package, with one or more known overlay packages. 8829 createIdmapsForPackageLI(pkg); 8830 } 8831 } 8832 8833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8834 8835 if (createIdmapFailed) { 8836 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8837 "scanPackageLI failed to createIdmap"); 8838 } 8839 return pkg; 8840 } 8841 8842 /** 8843 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8844 * is derived purely on the basis of the contents of {@code scanFile} and 8845 * {@code cpuAbiOverride}. 8846 * 8847 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8848 */ 8849 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8850 String cpuAbiOverride, boolean extractLibs) 8851 throws PackageManagerException { 8852 // TODO: We can probably be smarter about this stuff. For installed apps, 8853 // we can calculate this information at install time once and for all. For 8854 // system apps, we can probably assume that this information doesn't change 8855 // after the first boot scan. As things stand, we do lots of unnecessary work. 8856 8857 // Give ourselves some initial paths; we'll come back for another 8858 // pass once we've determined ABI below. 8859 setNativeLibraryPaths(pkg); 8860 8861 // We would never need to extract libs for forward-locked and external packages, 8862 // since the container service will do it for us. We shouldn't attempt to 8863 // extract libs from system app when it was not updated. 8864 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8865 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8866 extractLibs = false; 8867 } 8868 8869 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8870 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8871 8872 NativeLibraryHelper.Handle handle = null; 8873 try { 8874 handle = NativeLibraryHelper.Handle.create(pkg); 8875 // TODO(multiArch): This can be null for apps that didn't go through the 8876 // usual installation process. We can calculate it again, like we 8877 // do during install time. 8878 // 8879 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8880 // unnecessary. 8881 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8882 8883 // Null out the abis so that they can be recalculated. 8884 pkg.applicationInfo.primaryCpuAbi = null; 8885 pkg.applicationInfo.secondaryCpuAbi = null; 8886 if (isMultiArch(pkg.applicationInfo)) { 8887 // Warn if we've set an abiOverride for multi-lib packages.. 8888 // By definition, we need to copy both 32 and 64 bit libraries for 8889 // such packages. 8890 if (pkg.cpuAbiOverride != null 8891 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8892 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8893 } 8894 8895 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8896 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8897 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8898 if (extractLibs) { 8899 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8900 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8901 useIsaSpecificSubdirs); 8902 } else { 8903 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8904 } 8905 } 8906 8907 maybeThrowExceptionForMultiArchCopy( 8908 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8909 8910 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8911 if (extractLibs) { 8912 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8913 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8914 useIsaSpecificSubdirs); 8915 } else { 8916 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8917 } 8918 } 8919 8920 maybeThrowExceptionForMultiArchCopy( 8921 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8922 8923 if (abi64 >= 0) { 8924 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8925 } 8926 8927 if (abi32 >= 0) { 8928 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8929 if (abi64 >= 0) { 8930 if (pkg.use32bitAbi) { 8931 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8932 pkg.applicationInfo.primaryCpuAbi = abi; 8933 } else { 8934 pkg.applicationInfo.secondaryCpuAbi = abi; 8935 } 8936 } else { 8937 pkg.applicationInfo.primaryCpuAbi = abi; 8938 } 8939 } 8940 8941 } else { 8942 String[] abiList = (cpuAbiOverride != null) ? 8943 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8944 8945 // Enable gross and lame hacks for apps that are built with old 8946 // SDK tools. We must scan their APKs for renderscript bitcode and 8947 // not launch them if it's present. Don't bother checking on devices 8948 // that don't have 64 bit support. 8949 boolean needsRenderScriptOverride = false; 8950 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8951 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8952 abiList = Build.SUPPORTED_32_BIT_ABIS; 8953 needsRenderScriptOverride = true; 8954 } 8955 8956 final int copyRet; 8957 if (extractLibs) { 8958 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8959 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8960 } else { 8961 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8962 } 8963 8964 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8965 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8966 "Error unpackaging native libs for app, errorCode=" + copyRet); 8967 } 8968 8969 if (copyRet >= 0) { 8970 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8971 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8972 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8973 } else if (needsRenderScriptOverride) { 8974 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8975 } 8976 } 8977 } catch (IOException ioe) { 8978 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8979 } finally { 8980 IoUtils.closeQuietly(handle); 8981 } 8982 8983 // Now that we've calculated the ABIs and determined if it's an internal app, 8984 // we will go ahead and populate the nativeLibraryPath. 8985 setNativeLibraryPaths(pkg); 8986 } 8987 8988 /** 8989 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8990 * i.e, so that all packages can be run inside a single process if required. 8991 * 8992 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8993 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8994 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8995 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8996 * updating a package that belongs to a shared user. 8997 * 8998 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8999 * adds unnecessary complexity. 9000 */ 9001 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9002 PackageParser.Package scannedPackage, boolean bootComplete) { 9003 String requiredInstructionSet = null; 9004 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9005 requiredInstructionSet = VMRuntime.getInstructionSet( 9006 scannedPackage.applicationInfo.primaryCpuAbi); 9007 } 9008 9009 PackageSetting requirer = null; 9010 for (PackageSetting ps : packagesForUser) { 9011 // If packagesForUser contains scannedPackage, we skip it. This will happen 9012 // when scannedPackage is an update of an existing package. Without this check, 9013 // we will never be able to change the ABI of any package belonging to a shared 9014 // user, even if it's compatible with other packages. 9015 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9016 if (ps.primaryCpuAbiString == null) { 9017 continue; 9018 } 9019 9020 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9021 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9022 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9023 // this but there's not much we can do. 9024 String errorMessage = "Instruction set mismatch, " 9025 + ((requirer == null) ? "[caller]" : requirer) 9026 + " requires " + requiredInstructionSet + " whereas " + ps 9027 + " requires " + instructionSet; 9028 Slog.w(TAG, errorMessage); 9029 } 9030 9031 if (requiredInstructionSet == null) { 9032 requiredInstructionSet = instructionSet; 9033 requirer = ps; 9034 } 9035 } 9036 } 9037 9038 if (requiredInstructionSet != null) { 9039 String adjustedAbi; 9040 if (requirer != null) { 9041 // requirer != null implies that either scannedPackage was null or that scannedPackage 9042 // did not require an ABI, in which case we have to adjust scannedPackage to match 9043 // the ABI of the set (which is the same as requirer's ABI) 9044 adjustedAbi = requirer.primaryCpuAbiString; 9045 if (scannedPackage != null) { 9046 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9047 } 9048 } else { 9049 // requirer == null implies that we're updating all ABIs in the set to 9050 // match scannedPackage. 9051 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9052 } 9053 9054 for (PackageSetting ps : packagesForUser) { 9055 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9056 if (ps.primaryCpuAbiString != null) { 9057 continue; 9058 } 9059 9060 ps.primaryCpuAbiString = adjustedAbi; 9061 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9062 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9063 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9064 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9065 + " (requirer=" 9066 + (requirer == null ? "null" : requirer.pkg.packageName) 9067 + ", scannedPackage=" 9068 + (scannedPackage != null ? scannedPackage.packageName : "null") 9069 + ")"); 9070 try { 9071 mInstaller.rmdex(ps.codePathString, 9072 getDexCodeInstructionSet(getPreferredInstructionSet())); 9073 } catch (InstallerException ignored) { 9074 } 9075 } 9076 } 9077 } 9078 } 9079 } 9080 9081 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9082 synchronized (mPackages) { 9083 mResolverReplaced = true; 9084 // Set up information for custom user intent resolution activity. 9085 mResolveActivity.applicationInfo = pkg.applicationInfo; 9086 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9087 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9088 mResolveActivity.processName = pkg.applicationInfo.packageName; 9089 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9090 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9091 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9092 mResolveActivity.theme = 0; 9093 mResolveActivity.exported = true; 9094 mResolveActivity.enabled = true; 9095 mResolveInfo.activityInfo = mResolveActivity; 9096 mResolveInfo.priority = 0; 9097 mResolveInfo.preferredOrder = 0; 9098 mResolveInfo.match = 0; 9099 mResolveComponentName = mCustomResolverComponentName; 9100 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9101 mResolveComponentName); 9102 } 9103 } 9104 9105 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9106 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9107 9108 // Set up information for ephemeral installer activity 9109 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9110 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9111 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9112 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9113 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9114 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9115 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9116 mEphemeralInstallerActivity.theme = 0; 9117 mEphemeralInstallerActivity.exported = true; 9118 mEphemeralInstallerActivity.enabled = true; 9119 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9120 mEphemeralInstallerInfo.priority = 0; 9121 mEphemeralInstallerInfo.preferredOrder = 0; 9122 mEphemeralInstallerInfo.match = 0; 9123 9124 if (DEBUG_EPHEMERAL) { 9125 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9126 } 9127 } 9128 9129 private static String calculateBundledApkRoot(final String codePathString) { 9130 final File codePath = new File(codePathString); 9131 final File codeRoot; 9132 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9133 codeRoot = Environment.getRootDirectory(); 9134 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9135 codeRoot = Environment.getOemDirectory(); 9136 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9137 codeRoot = Environment.getVendorDirectory(); 9138 } else { 9139 // Unrecognized code path; take its top real segment as the apk root: 9140 // e.g. /something/app/blah.apk => /something 9141 try { 9142 File f = codePath.getCanonicalFile(); 9143 File parent = f.getParentFile(); // non-null because codePath is a file 9144 File tmp; 9145 while ((tmp = parent.getParentFile()) != null) { 9146 f = parent; 9147 parent = tmp; 9148 } 9149 codeRoot = f; 9150 Slog.w(TAG, "Unrecognized code path " 9151 + codePath + " - using " + codeRoot); 9152 } catch (IOException e) { 9153 // Can't canonicalize the code path -- shenanigans? 9154 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9155 return Environment.getRootDirectory().getPath(); 9156 } 9157 } 9158 return codeRoot.getPath(); 9159 } 9160 9161 /** 9162 * Derive and set the location of native libraries for the given package, 9163 * which varies depending on where and how the package was installed. 9164 */ 9165 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9166 final ApplicationInfo info = pkg.applicationInfo; 9167 final String codePath = pkg.codePath; 9168 final File codeFile = new File(codePath); 9169 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9170 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9171 9172 info.nativeLibraryRootDir = null; 9173 info.nativeLibraryRootRequiresIsa = false; 9174 info.nativeLibraryDir = null; 9175 info.secondaryNativeLibraryDir = null; 9176 9177 if (isApkFile(codeFile)) { 9178 // Monolithic install 9179 if (bundledApp) { 9180 // If "/system/lib64/apkname" exists, assume that is the per-package 9181 // native library directory to use; otherwise use "/system/lib/apkname". 9182 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9183 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9184 getPrimaryInstructionSet(info)); 9185 9186 // This is a bundled system app so choose the path based on the ABI. 9187 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9188 // is just the default path. 9189 final String apkName = deriveCodePathName(codePath); 9190 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9191 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9192 apkName).getAbsolutePath(); 9193 9194 if (info.secondaryCpuAbi != null) { 9195 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9196 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9197 secondaryLibDir, apkName).getAbsolutePath(); 9198 } 9199 } else if (asecApp) { 9200 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9201 .getAbsolutePath(); 9202 } else { 9203 final String apkName = deriveCodePathName(codePath); 9204 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9205 .getAbsolutePath(); 9206 } 9207 9208 info.nativeLibraryRootRequiresIsa = false; 9209 info.nativeLibraryDir = info.nativeLibraryRootDir; 9210 } else { 9211 // Cluster install 9212 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9213 info.nativeLibraryRootRequiresIsa = true; 9214 9215 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9216 getPrimaryInstructionSet(info)).getAbsolutePath(); 9217 9218 if (info.secondaryCpuAbi != null) { 9219 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9220 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9221 } 9222 } 9223 } 9224 9225 /** 9226 * Calculate the abis and roots for a bundled app. These can uniquely 9227 * be determined from the contents of the system partition, i.e whether 9228 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9229 * of this information, and instead assume that the system was built 9230 * sensibly. 9231 */ 9232 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9233 PackageSetting pkgSetting) { 9234 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9235 9236 // If "/system/lib64/apkname" exists, assume that is the per-package 9237 // native library directory to use; otherwise use "/system/lib/apkname". 9238 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9239 setBundledAppAbi(pkg, apkRoot, apkName); 9240 // pkgSetting might be null during rescan following uninstall of updates 9241 // to a bundled app, so accommodate that possibility. The settings in 9242 // that case will be established later from the parsed package. 9243 // 9244 // If the settings aren't null, sync them up with what we've just derived. 9245 // note that apkRoot isn't stored in the package settings. 9246 if (pkgSetting != null) { 9247 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9248 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9249 } 9250 } 9251 9252 /** 9253 * Deduces the ABI of a bundled app and sets the relevant fields on the 9254 * parsed pkg object. 9255 * 9256 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9257 * under which system libraries are installed. 9258 * @param apkName the name of the installed package. 9259 */ 9260 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9261 final File codeFile = new File(pkg.codePath); 9262 9263 final boolean has64BitLibs; 9264 final boolean has32BitLibs; 9265 if (isApkFile(codeFile)) { 9266 // Monolithic install 9267 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9268 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9269 } else { 9270 // Cluster install 9271 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9272 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9273 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9274 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9275 has64BitLibs = (new File(rootDir, isa)).exists(); 9276 } else { 9277 has64BitLibs = false; 9278 } 9279 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9280 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9281 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9282 has32BitLibs = (new File(rootDir, isa)).exists(); 9283 } else { 9284 has32BitLibs = false; 9285 } 9286 } 9287 9288 if (has64BitLibs && !has32BitLibs) { 9289 // The package has 64 bit libs, but not 32 bit libs. Its primary 9290 // ABI should be 64 bit. We can safely assume here that the bundled 9291 // native libraries correspond to the most preferred ABI in the list. 9292 9293 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9294 pkg.applicationInfo.secondaryCpuAbi = null; 9295 } else if (has32BitLibs && !has64BitLibs) { 9296 // The package has 32 bit libs but not 64 bit libs. Its primary 9297 // ABI should be 32 bit. 9298 9299 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9300 pkg.applicationInfo.secondaryCpuAbi = null; 9301 } else if (has32BitLibs && has64BitLibs) { 9302 // The application has both 64 and 32 bit bundled libraries. We check 9303 // here that the app declares multiArch support, and warn if it doesn't. 9304 // 9305 // We will be lenient here and record both ABIs. The primary will be the 9306 // ABI that's higher on the list, i.e, a device that's configured to prefer 9307 // 64 bit apps will see a 64 bit primary ABI, 9308 9309 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9310 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9311 } 9312 9313 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9314 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9315 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9316 } else { 9317 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9318 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9319 } 9320 } else { 9321 pkg.applicationInfo.primaryCpuAbi = null; 9322 pkg.applicationInfo.secondaryCpuAbi = null; 9323 } 9324 } 9325 9326 private void killApplication(String pkgName, int appId, String reason) { 9327 // Request the ActivityManager to kill the process(only for existing packages) 9328 // so that we do not end up in a confused state while the user is still using the older 9329 // version of the application while the new one gets installed. 9330 final long token = Binder.clearCallingIdentity(); 9331 try { 9332 IActivityManager am = ActivityManagerNative.getDefault(); 9333 if (am != null) { 9334 try { 9335 am.killApplicationWithAppId(pkgName, appId, reason); 9336 } catch (RemoteException e) { 9337 } 9338 } 9339 } finally { 9340 Binder.restoreCallingIdentity(token); 9341 } 9342 } 9343 9344 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9345 // Remove the parent package setting 9346 PackageSetting ps = (PackageSetting) pkg.mExtras; 9347 if (ps != null) { 9348 removePackageLI(ps, chatty); 9349 } 9350 // Remove the child package setting 9351 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9352 for (int i = 0; i < childCount; i++) { 9353 PackageParser.Package childPkg = pkg.childPackages.get(i); 9354 ps = (PackageSetting) childPkg.mExtras; 9355 if (ps != null) { 9356 removePackageLI(ps, chatty); 9357 } 9358 } 9359 } 9360 9361 void removePackageLI(PackageSetting ps, boolean chatty) { 9362 if (DEBUG_INSTALL) { 9363 if (chatty) 9364 Log.d(TAG, "Removing package " + ps.name); 9365 } 9366 9367 // writer 9368 synchronized (mPackages) { 9369 mPackages.remove(ps.name); 9370 final PackageParser.Package pkg = ps.pkg; 9371 if (pkg != null) { 9372 cleanPackageDataStructuresLILPw(pkg, chatty); 9373 } 9374 } 9375 } 9376 9377 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9378 if (DEBUG_INSTALL) { 9379 if (chatty) 9380 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9381 } 9382 9383 // writer 9384 synchronized (mPackages) { 9385 // Remove the parent package 9386 mPackages.remove(pkg.applicationInfo.packageName); 9387 cleanPackageDataStructuresLILPw(pkg, chatty); 9388 9389 // Remove the child packages 9390 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9391 for (int i = 0; i < childCount; i++) { 9392 PackageParser.Package childPkg = pkg.childPackages.get(i); 9393 mPackages.remove(childPkg.applicationInfo.packageName); 9394 cleanPackageDataStructuresLILPw(childPkg, chatty); 9395 } 9396 } 9397 } 9398 9399 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9400 int N = pkg.providers.size(); 9401 StringBuilder r = null; 9402 int i; 9403 for (i=0; i<N; i++) { 9404 PackageParser.Provider p = pkg.providers.get(i); 9405 mProviders.removeProvider(p); 9406 if (p.info.authority == null) { 9407 9408 /* There was another ContentProvider with this authority when 9409 * this app was installed so this authority is null, 9410 * Ignore it as we don't have to unregister the provider. 9411 */ 9412 continue; 9413 } 9414 String names[] = p.info.authority.split(";"); 9415 for (int j = 0; j < names.length; j++) { 9416 if (mProvidersByAuthority.get(names[j]) == p) { 9417 mProvidersByAuthority.remove(names[j]); 9418 if (DEBUG_REMOVE) { 9419 if (chatty) 9420 Log.d(TAG, "Unregistered content provider: " + names[j] 9421 + ", className = " + p.info.name + ", isSyncable = " 9422 + p.info.isSyncable); 9423 } 9424 } 9425 } 9426 if (DEBUG_REMOVE && chatty) { 9427 if (r == null) { 9428 r = new StringBuilder(256); 9429 } else { 9430 r.append(' '); 9431 } 9432 r.append(p.info.name); 9433 } 9434 } 9435 if (r != null) { 9436 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9437 } 9438 9439 N = pkg.services.size(); 9440 r = null; 9441 for (i=0; i<N; i++) { 9442 PackageParser.Service s = pkg.services.get(i); 9443 mServices.removeService(s); 9444 if (chatty) { 9445 if (r == null) { 9446 r = new StringBuilder(256); 9447 } else { 9448 r.append(' '); 9449 } 9450 r.append(s.info.name); 9451 } 9452 } 9453 if (r != null) { 9454 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9455 } 9456 9457 N = pkg.receivers.size(); 9458 r = null; 9459 for (i=0; i<N; i++) { 9460 PackageParser.Activity a = pkg.receivers.get(i); 9461 mReceivers.removeActivity(a, "receiver"); 9462 if (DEBUG_REMOVE && chatty) { 9463 if (r == null) { 9464 r = new StringBuilder(256); 9465 } else { 9466 r.append(' '); 9467 } 9468 r.append(a.info.name); 9469 } 9470 } 9471 if (r != null) { 9472 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9473 } 9474 9475 N = pkg.activities.size(); 9476 r = null; 9477 for (i=0; i<N; i++) { 9478 PackageParser.Activity a = pkg.activities.get(i); 9479 mActivities.removeActivity(a, "activity"); 9480 if (DEBUG_REMOVE && chatty) { 9481 if (r == null) { 9482 r = new StringBuilder(256); 9483 } else { 9484 r.append(' '); 9485 } 9486 r.append(a.info.name); 9487 } 9488 } 9489 if (r != null) { 9490 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9491 } 9492 9493 N = pkg.permissions.size(); 9494 r = null; 9495 for (i=0; i<N; i++) { 9496 PackageParser.Permission p = pkg.permissions.get(i); 9497 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9498 if (bp == null) { 9499 bp = mSettings.mPermissionTrees.get(p.info.name); 9500 } 9501 if (bp != null && bp.perm == p) { 9502 bp.perm = null; 9503 if (DEBUG_REMOVE && chatty) { 9504 if (r == null) { 9505 r = new StringBuilder(256); 9506 } else { 9507 r.append(' '); 9508 } 9509 r.append(p.info.name); 9510 } 9511 } 9512 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9513 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9514 if (appOpPkgs != null) { 9515 appOpPkgs.remove(pkg.packageName); 9516 } 9517 } 9518 } 9519 if (r != null) { 9520 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9521 } 9522 9523 N = pkg.requestedPermissions.size(); 9524 r = null; 9525 for (i=0; i<N; i++) { 9526 String perm = pkg.requestedPermissions.get(i); 9527 BasePermission bp = mSettings.mPermissions.get(perm); 9528 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9529 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9530 if (appOpPkgs != null) { 9531 appOpPkgs.remove(pkg.packageName); 9532 if (appOpPkgs.isEmpty()) { 9533 mAppOpPermissionPackages.remove(perm); 9534 } 9535 } 9536 } 9537 } 9538 if (r != null) { 9539 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9540 } 9541 9542 N = pkg.instrumentation.size(); 9543 r = null; 9544 for (i=0; i<N; i++) { 9545 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9546 mInstrumentation.remove(a.getComponentName()); 9547 if (DEBUG_REMOVE && chatty) { 9548 if (r == null) { 9549 r = new StringBuilder(256); 9550 } else { 9551 r.append(' '); 9552 } 9553 r.append(a.info.name); 9554 } 9555 } 9556 if (r != null) { 9557 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9558 } 9559 9560 r = null; 9561 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9562 // Only system apps can hold shared libraries. 9563 if (pkg.libraryNames != null) { 9564 for (i=0; i<pkg.libraryNames.size(); i++) { 9565 String name = pkg.libraryNames.get(i); 9566 SharedLibraryEntry cur = mSharedLibraries.get(name); 9567 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9568 mSharedLibraries.remove(name); 9569 if (DEBUG_REMOVE && chatty) { 9570 if (r == null) { 9571 r = new StringBuilder(256); 9572 } else { 9573 r.append(' '); 9574 } 9575 r.append(name); 9576 } 9577 } 9578 } 9579 } 9580 } 9581 if (r != null) { 9582 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9583 } 9584 } 9585 9586 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9587 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9588 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9589 return true; 9590 } 9591 } 9592 return false; 9593 } 9594 9595 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9596 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9597 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9598 9599 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9600 // Update the parent permissions 9601 updatePermissionsLPw(pkg.packageName, pkg, flags); 9602 // Update the child permissions 9603 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9604 for (int i = 0; i < childCount; i++) { 9605 PackageParser.Package childPkg = pkg.childPackages.get(i); 9606 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9607 } 9608 } 9609 9610 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9611 int flags) { 9612 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9613 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9614 } 9615 9616 private void updatePermissionsLPw(String changingPkg, 9617 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9618 // Make sure there are no dangling permission trees. 9619 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9620 while (it.hasNext()) { 9621 final BasePermission bp = it.next(); 9622 if (bp.packageSetting == null) { 9623 // We may not yet have parsed the package, so just see if 9624 // we still know about its settings. 9625 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9626 } 9627 if (bp.packageSetting == null) { 9628 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9629 + " from package " + bp.sourcePackage); 9630 it.remove(); 9631 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9632 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9633 Slog.i(TAG, "Removing old permission tree: " + bp.name 9634 + " from package " + bp.sourcePackage); 9635 flags |= UPDATE_PERMISSIONS_ALL; 9636 it.remove(); 9637 } 9638 } 9639 } 9640 9641 // Make sure all dynamic permissions have been assigned to a package, 9642 // and make sure there are no dangling permissions. 9643 it = mSettings.mPermissions.values().iterator(); 9644 while (it.hasNext()) { 9645 final BasePermission bp = it.next(); 9646 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9647 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9648 + bp.name + " pkg=" + bp.sourcePackage 9649 + " info=" + bp.pendingInfo); 9650 if (bp.packageSetting == null && bp.pendingInfo != null) { 9651 final BasePermission tree = findPermissionTreeLP(bp.name); 9652 if (tree != null && tree.perm != null) { 9653 bp.packageSetting = tree.packageSetting; 9654 bp.perm = new PackageParser.Permission(tree.perm.owner, 9655 new PermissionInfo(bp.pendingInfo)); 9656 bp.perm.info.packageName = tree.perm.info.packageName; 9657 bp.perm.info.name = bp.name; 9658 bp.uid = tree.uid; 9659 } 9660 } 9661 } 9662 if (bp.packageSetting == null) { 9663 // We may not yet have parsed the package, so just see if 9664 // we still know about its settings. 9665 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9666 } 9667 if (bp.packageSetting == null) { 9668 Slog.w(TAG, "Removing dangling permission: " + bp.name 9669 + " from package " + bp.sourcePackage); 9670 it.remove(); 9671 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9672 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9673 Slog.i(TAG, "Removing old permission: " + bp.name 9674 + " from package " + bp.sourcePackage); 9675 flags |= UPDATE_PERMISSIONS_ALL; 9676 it.remove(); 9677 } 9678 } 9679 } 9680 9681 // Now update the permissions for all packages, in particular 9682 // replace the granted permissions of the system packages. 9683 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9684 for (PackageParser.Package pkg : mPackages.values()) { 9685 if (pkg != pkgInfo) { 9686 // Only replace for packages on requested volume 9687 final String volumeUuid = getVolumeUuidForPackage(pkg); 9688 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9689 && Objects.equals(replaceVolumeUuid, volumeUuid); 9690 grantPermissionsLPw(pkg, replace, changingPkg); 9691 } 9692 } 9693 } 9694 9695 if (pkgInfo != null) { 9696 // Only replace for packages on requested volume 9697 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9698 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9699 && Objects.equals(replaceVolumeUuid, volumeUuid); 9700 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9701 } 9702 } 9703 9704 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9705 String packageOfInterest) { 9706 // IMPORTANT: There are two types of permissions: install and runtime. 9707 // Install time permissions are granted when the app is installed to 9708 // all device users and users added in the future. Runtime permissions 9709 // are granted at runtime explicitly to specific users. Normal and signature 9710 // protected permissions are install time permissions. Dangerous permissions 9711 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9712 // otherwise they are runtime permissions. This function does not manage 9713 // runtime permissions except for the case an app targeting Lollipop MR1 9714 // being upgraded to target a newer SDK, in which case dangerous permissions 9715 // are transformed from install time to runtime ones. 9716 9717 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9718 if (ps == null) { 9719 return; 9720 } 9721 9722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9723 9724 PermissionsState permissionsState = ps.getPermissionsState(); 9725 PermissionsState origPermissions = permissionsState; 9726 9727 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9728 9729 boolean runtimePermissionsRevoked = false; 9730 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9731 9732 boolean changedInstallPermission = false; 9733 9734 if (replace) { 9735 ps.installPermissionsFixed = false; 9736 if (!ps.isSharedUser()) { 9737 origPermissions = new PermissionsState(permissionsState); 9738 permissionsState.reset(); 9739 } else { 9740 // We need to know only about runtime permission changes since the 9741 // calling code always writes the install permissions state but 9742 // the runtime ones are written only if changed. The only cases of 9743 // changed runtime permissions here are promotion of an install to 9744 // runtime and revocation of a runtime from a shared user. 9745 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9746 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9747 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9748 runtimePermissionsRevoked = true; 9749 } 9750 } 9751 } 9752 9753 permissionsState.setGlobalGids(mGlobalGids); 9754 9755 final int N = pkg.requestedPermissions.size(); 9756 for (int i=0; i<N; i++) { 9757 final String name = pkg.requestedPermissions.get(i); 9758 final BasePermission bp = mSettings.mPermissions.get(name); 9759 9760 if (DEBUG_INSTALL) { 9761 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9762 } 9763 9764 if (bp == null || bp.packageSetting == null) { 9765 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9766 Slog.w(TAG, "Unknown permission " + name 9767 + " in package " + pkg.packageName); 9768 } 9769 continue; 9770 } 9771 9772 final String perm = bp.name; 9773 boolean allowedSig = false; 9774 int grant = GRANT_DENIED; 9775 9776 // Keep track of app op permissions. 9777 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9778 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9779 if (pkgs == null) { 9780 pkgs = new ArraySet<>(); 9781 mAppOpPermissionPackages.put(bp.name, pkgs); 9782 } 9783 pkgs.add(pkg.packageName); 9784 } 9785 9786 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9787 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9788 >= Build.VERSION_CODES.M; 9789 switch (level) { 9790 case PermissionInfo.PROTECTION_NORMAL: { 9791 // For all apps normal permissions are install time ones. 9792 grant = GRANT_INSTALL; 9793 } break; 9794 9795 case PermissionInfo.PROTECTION_DANGEROUS: { 9796 // If a permission review is required for legacy apps we represent 9797 // their permissions as always granted runtime ones since we need 9798 // to keep the review required permission flag per user while an 9799 // install permission's state is shared across all users. 9800 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9801 // For legacy apps dangerous permissions are install time ones. 9802 grant = GRANT_INSTALL; 9803 } else if (origPermissions.hasInstallPermission(bp.name)) { 9804 // For legacy apps that became modern, install becomes runtime. 9805 grant = GRANT_UPGRADE; 9806 } else if (mPromoteSystemApps 9807 && isSystemApp(ps) 9808 && mExistingSystemPackages.contains(ps.name)) { 9809 // For legacy system apps, install becomes runtime. 9810 // We cannot check hasInstallPermission() for system apps since those 9811 // permissions were granted implicitly and not persisted pre-M. 9812 grant = GRANT_UPGRADE; 9813 } else { 9814 // For modern apps keep runtime permissions unchanged. 9815 grant = GRANT_RUNTIME; 9816 } 9817 } break; 9818 9819 case PermissionInfo.PROTECTION_SIGNATURE: { 9820 // For all apps signature permissions are install time ones. 9821 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9822 if (allowedSig) { 9823 grant = GRANT_INSTALL; 9824 } 9825 } break; 9826 } 9827 9828 if (DEBUG_INSTALL) { 9829 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9830 } 9831 9832 if (grant != GRANT_DENIED) { 9833 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9834 // If this is an existing, non-system package, then 9835 // we can't add any new permissions to it. 9836 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9837 // Except... if this is a permission that was added 9838 // to the platform (note: need to only do this when 9839 // updating the platform). 9840 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9841 grant = GRANT_DENIED; 9842 } 9843 } 9844 } 9845 9846 switch (grant) { 9847 case GRANT_INSTALL: { 9848 // Revoke this as runtime permission to handle the case of 9849 // a runtime permission being downgraded to an install one. 9850 // Also in permission review mode we keep dangerous permissions 9851 // for legacy apps 9852 for (int userId : UserManagerService.getInstance().getUserIds()) { 9853 if (origPermissions.getRuntimePermissionState( 9854 bp.name, userId) != null) { 9855 // Revoke the runtime permission and clear the flags. 9856 origPermissions.revokeRuntimePermission(bp, userId); 9857 origPermissions.updatePermissionFlags(bp, userId, 9858 PackageManager.MASK_PERMISSION_FLAGS, 0); 9859 // If we revoked a permission permission, we have to write. 9860 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9861 changedRuntimePermissionUserIds, userId); 9862 } 9863 } 9864 // Grant an install permission. 9865 if (permissionsState.grantInstallPermission(bp) != 9866 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9867 changedInstallPermission = true; 9868 } 9869 } break; 9870 9871 case GRANT_RUNTIME: { 9872 // Grant previously granted runtime permissions. 9873 for (int userId : UserManagerService.getInstance().getUserIds()) { 9874 PermissionState permissionState = origPermissions 9875 .getRuntimePermissionState(bp.name, userId); 9876 int flags = permissionState != null 9877 ? permissionState.getFlags() : 0; 9878 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9879 if (permissionsState.grantRuntimePermission(bp, userId) == 9880 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9881 // If we cannot put the permission as it was, we have to write. 9882 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9883 changedRuntimePermissionUserIds, userId); 9884 } 9885 // If the app supports runtime permissions no need for a review. 9886 if (Build.PERMISSIONS_REVIEW_REQUIRED 9887 && appSupportsRuntimePermissions 9888 && (flags & PackageManager 9889 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9890 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9891 // Since we changed the flags, we have to write. 9892 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9893 changedRuntimePermissionUserIds, userId); 9894 } 9895 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9896 && !appSupportsRuntimePermissions) { 9897 // For legacy apps that need a permission review, every new 9898 // runtime permission is granted but it is pending a review. 9899 // We also need to review only platform defined runtime 9900 // permissions as these are the only ones the platform knows 9901 // how to disable the API to simulate revocation as legacy 9902 // apps don't expect to run with revoked permissions. 9903 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9904 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9905 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9906 // We changed the flags, hence have to write. 9907 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9908 changedRuntimePermissionUserIds, userId); 9909 } 9910 } 9911 if (permissionsState.grantRuntimePermission(bp, userId) 9912 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9913 // We changed the permission, hence have to write. 9914 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9915 changedRuntimePermissionUserIds, userId); 9916 } 9917 } 9918 // Propagate the permission flags. 9919 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9920 } 9921 } break; 9922 9923 case GRANT_UPGRADE: { 9924 // Grant runtime permissions for a previously held install permission. 9925 PermissionState permissionState = origPermissions 9926 .getInstallPermissionState(bp.name); 9927 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9928 9929 if (origPermissions.revokeInstallPermission(bp) 9930 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9931 // We will be transferring the permission flags, so clear them. 9932 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9933 PackageManager.MASK_PERMISSION_FLAGS, 0); 9934 changedInstallPermission = true; 9935 } 9936 9937 // If the permission is not to be promoted to runtime we ignore it and 9938 // also its other flags as they are not applicable to install permissions. 9939 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9940 for (int userId : currentUserIds) { 9941 if (permissionsState.grantRuntimePermission(bp, userId) != 9942 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9943 // Transfer the permission flags. 9944 permissionsState.updatePermissionFlags(bp, userId, 9945 flags, flags); 9946 // If we granted the permission, we have to write. 9947 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9948 changedRuntimePermissionUserIds, userId); 9949 } 9950 } 9951 } 9952 } break; 9953 9954 default: { 9955 if (packageOfInterest == null 9956 || packageOfInterest.equals(pkg.packageName)) { 9957 Slog.w(TAG, "Not granting permission " + perm 9958 + " to package " + pkg.packageName 9959 + " because it was previously installed without"); 9960 } 9961 } break; 9962 } 9963 } else { 9964 if (permissionsState.revokeInstallPermission(bp) != 9965 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9966 // Also drop the permission flags. 9967 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9968 PackageManager.MASK_PERMISSION_FLAGS, 0); 9969 changedInstallPermission = true; 9970 Slog.i(TAG, "Un-granting permission " + perm 9971 + " from package " + pkg.packageName 9972 + " (protectionLevel=" + bp.protectionLevel 9973 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9974 + ")"); 9975 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9976 // Don't print warning for app op permissions, since it is fine for them 9977 // not to be granted, there is a UI for the user to decide. 9978 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9979 Slog.w(TAG, "Not granting permission " + perm 9980 + " to package " + pkg.packageName 9981 + " (protectionLevel=" + bp.protectionLevel 9982 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9983 + ")"); 9984 } 9985 } 9986 } 9987 } 9988 9989 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9990 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9991 // This is the first that we have heard about this package, so the 9992 // permissions we have now selected are fixed until explicitly 9993 // changed. 9994 ps.installPermissionsFixed = true; 9995 } 9996 9997 // Persist the runtime permissions state for users with changes. If permissions 9998 // were revoked because no app in the shared user declares them we have to 9999 // write synchronously to avoid losing runtime permissions state. 10000 for (int userId : changedRuntimePermissionUserIds) { 10001 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10002 } 10003 10004 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10005 } 10006 10007 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10008 boolean allowed = false; 10009 final int NP = PackageParser.NEW_PERMISSIONS.length; 10010 for (int ip=0; ip<NP; ip++) { 10011 final PackageParser.NewPermissionInfo npi 10012 = PackageParser.NEW_PERMISSIONS[ip]; 10013 if (npi.name.equals(perm) 10014 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10015 allowed = true; 10016 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10017 + pkg.packageName); 10018 break; 10019 } 10020 } 10021 return allowed; 10022 } 10023 10024 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10025 BasePermission bp, PermissionsState origPermissions) { 10026 boolean allowed; 10027 allowed = (compareSignatures( 10028 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10029 == PackageManager.SIGNATURE_MATCH) 10030 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10031 == PackageManager.SIGNATURE_MATCH); 10032 if (!allowed && (bp.protectionLevel 10033 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10034 if (isSystemApp(pkg)) { 10035 // For updated system applications, a system permission 10036 // is granted only if it had been defined by the original application. 10037 if (pkg.isUpdatedSystemApp()) { 10038 final PackageSetting sysPs = mSettings 10039 .getDisabledSystemPkgLPr(pkg.packageName); 10040 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10041 // If the original was granted this permission, we take 10042 // that grant decision as read and propagate it to the 10043 // update. 10044 if (sysPs.isPrivileged()) { 10045 allowed = true; 10046 } 10047 } else { 10048 // The system apk may have been updated with an older 10049 // version of the one on the data partition, but which 10050 // granted a new system permission that it didn't have 10051 // before. In this case we do want to allow the app to 10052 // now get the new permission if the ancestral apk is 10053 // privileged to get it. 10054 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10055 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10056 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10057 allowed = true; 10058 break; 10059 } 10060 } 10061 } 10062 // Also if a privileged parent package on the system image or any of 10063 // its children requested a privileged permission, the updated child 10064 // packages can also get the permission. 10065 if (pkg.parentPackage != null) { 10066 final PackageSetting disabledSysParentPs = mSettings 10067 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10068 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10069 && disabledSysParentPs.isPrivileged()) { 10070 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10071 allowed = true; 10072 } else if (disabledSysParentPs.pkg.childPackages != null) { 10073 final int count = disabledSysParentPs.pkg.childPackages.size(); 10074 for (int i = 0; i < count; i++) { 10075 PackageParser.Package disabledSysChildPkg = 10076 disabledSysParentPs.pkg.childPackages.get(i); 10077 if (isPackageRequestingPermission(disabledSysChildPkg, 10078 perm)) { 10079 allowed = true; 10080 break; 10081 } 10082 } 10083 } 10084 } 10085 } 10086 } 10087 } else { 10088 allowed = isPrivilegedApp(pkg); 10089 } 10090 } 10091 } 10092 if (!allowed) { 10093 if (!allowed && (bp.protectionLevel 10094 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10095 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10096 // If this was a previously normal/dangerous permission that got moved 10097 // to a system permission as part of the runtime permission redesign, then 10098 // we still want to blindly grant it to old apps. 10099 allowed = true; 10100 } 10101 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10102 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10103 // If this permission is to be granted to the system installer and 10104 // this app is an installer, then it gets the permission. 10105 allowed = true; 10106 } 10107 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10108 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10109 // If this permission is to be granted to the system verifier and 10110 // this app is a verifier, then it gets the permission. 10111 allowed = true; 10112 } 10113 if (!allowed && (bp.protectionLevel 10114 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10115 && isSystemApp(pkg)) { 10116 // Any pre-installed system app is allowed to get this permission. 10117 allowed = true; 10118 } 10119 if (!allowed && (bp.protectionLevel 10120 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10121 // For development permissions, a development permission 10122 // is granted only if it was already granted. 10123 allowed = origPermissions.hasInstallPermission(perm); 10124 } 10125 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10126 && pkg.packageName.equals(mSetupWizardPackage)) { 10127 // If this permission is to be granted to the system setup wizard and 10128 // this app is a setup wizard, then it gets the permission. 10129 allowed = true; 10130 } 10131 } 10132 return allowed; 10133 } 10134 10135 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10136 final int permCount = pkg.requestedPermissions.size(); 10137 for (int j = 0; j < permCount; j++) { 10138 String requestedPermission = pkg.requestedPermissions.get(j); 10139 if (permission.equals(requestedPermission)) { 10140 return true; 10141 } 10142 } 10143 return false; 10144 } 10145 10146 final class ActivityIntentResolver 10147 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10148 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10149 boolean defaultOnly, int userId) { 10150 if (!sUserManager.exists(userId)) return null; 10151 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10152 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10153 } 10154 10155 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10156 int userId) { 10157 if (!sUserManager.exists(userId)) return null; 10158 mFlags = flags; 10159 return super.queryIntent(intent, resolvedType, 10160 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10161 } 10162 10163 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10164 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10165 if (!sUserManager.exists(userId)) return null; 10166 if (packageActivities == null) { 10167 return null; 10168 } 10169 mFlags = flags; 10170 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10171 final int N = packageActivities.size(); 10172 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10173 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10174 10175 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10176 for (int i = 0; i < N; ++i) { 10177 intentFilters = packageActivities.get(i).intents; 10178 if (intentFilters != null && intentFilters.size() > 0) { 10179 PackageParser.ActivityIntentInfo[] array = 10180 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10181 intentFilters.toArray(array); 10182 listCut.add(array); 10183 } 10184 } 10185 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10186 } 10187 10188 /** 10189 * Finds a privileged activity that matches the specified activity names. 10190 */ 10191 private PackageParser.Activity findMatchingActivity( 10192 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10193 for (PackageParser.Activity sysActivity : activityList) { 10194 if (sysActivity.info.name.equals(activityInfo.name)) { 10195 return sysActivity; 10196 } 10197 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10198 return sysActivity; 10199 } 10200 if (sysActivity.info.targetActivity != null) { 10201 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10202 return sysActivity; 10203 } 10204 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10205 return sysActivity; 10206 } 10207 } 10208 } 10209 return null; 10210 } 10211 10212 public class IterGenerator<E> { 10213 public Iterator<E> generate(ActivityIntentInfo info) { 10214 return null; 10215 } 10216 } 10217 10218 public class ActionIterGenerator extends IterGenerator<String> { 10219 @Override 10220 public Iterator<String> generate(ActivityIntentInfo info) { 10221 return info.actionsIterator(); 10222 } 10223 } 10224 10225 public class CategoriesIterGenerator extends IterGenerator<String> { 10226 @Override 10227 public Iterator<String> generate(ActivityIntentInfo info) { 10228 return info.categoriesIterator(); 10229 } 10230 } 10231 10232 public class SchemesIterGenerator extends IterGenerator<String> { 10233 @Override 10234 public Iterator<String> generate(ActivityIntentInfo info) { 10235 return info.schemesIterator(); 10236 } 10237 } 10238 10239 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10240 @Override 10241 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10242 return info.authoritiesIterator(); 10243 } 10244 } 10245 10246 /** 10247 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10248 * MODIFIED. Do not pass in a list that should not be changed. 10249 */ 10250 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10251 IterGenerator<T> generator, Iterator<T> searchIterator) { 10252 // loop through the set of actions; every one must be found in the intent filter 10253 while (searchIterator.hasNext()) { 10254 // we must have at least one filter in the list to consider a match 10255 if (intentList.size() == 0) { 10256 break; 10257 } 10258 10259 final T searchAction = searchIterator.next(); 10260 10261 // loop through the set of intent filters 10262 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10263 while (intentIter.hasNext()) { 10264 final ActivityIntentInfo intentInfo = intentIter.next(); 10265 boolean selectionFound = false; 10266 10267 // loop through the intent filter's selection criteria; at least one 10268 // of them must match the searched criteria 10269 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10270 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10271 final T intentSelection = intentSelectionIter.next(); 10272 if (intentSelection != null && intentSelection.equals(searchAction)) { 10273 selectionFound = true; 10274 break; 10275 } 10276 } 10277 10278 // the selection criteria wasn't found in this filter's set; this filter 10279 // is not a potential match 10280 if (!selectionFound) { 10281 intentIter.remove(); 10282 } 10283 } 10284 } 10285 } 10286 10287 private boolean isProtectedAction(ActivityIntentInfo filter) { 10288 final Iterator<String> actionsIter = filter.actionsIterator(); 10289 while (actionsIter != null && actionsIter.hasNext()) { 10290 final String filterAction = actionsIter.next(); 10291 if (PROTECTED_ACTIONS.contains(filterAction)) { 10292 return true; 10293 } 10294 } 10295 return false; 10296 } 10297 10298 /** 10299 * Adjusts the priority of the given intent filter according to policy. 10300 * <p> 10301 * <ul> 10302 * <li>The priority for non privileged applications is capped to '0'</li> 10303 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10304 * <li>The priority for unbundled updates to privileged applications is capped to the 10305 * priority defined on the system partition</li> 10306 * </ul> 10307 * <p> 10308 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10309 * allowed to obtain any priority on any action. 10310 */ 10311 private void adjustPriority( 10312 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10313 // nothing to do; priority is fine as-is 10314 if (intent.getPriority() <= 0) { 10315 return; 10316 } 10317 10318 final ActivityInfo activityInfo = intent.activity.info; 10319 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10320 10321 final boolean privilegedApp = 10322 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10323 if (!privilegedApp) { 10324 // non-privileged applications can never define a priority >0 10325 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10326 + " package: " + applicationInfo.packageName 10327 + " activity: " + intent.activity.className 10328 + " origPrio: " + intent.getPriority()); 10329 intent.setPriority(0); 10330 return; 10331 } 10332 10333 if (systemActivities == null) { 10334 // the system package is not disabled; we're parsing the system partition 10335 if (isProtectedAction(intent)) { 10336 if (mDeferProtectedFilters) { 10337 // We can't deal with these just yet. No component should ever obtain a 10338 // >0 priority for a protected actions, with ONE exception -- the setup 10339 // wizard. The setup wizard, however, cannot be known until we're able to 10340 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10341 // until all intent filters have been processed. Chicken, meet egg. 10342 // Let the filter temporarily have a high priority and rectify the 10343 // priorities after all system packages have been scanned. 10344 mProtectedFilters.add(intent); 10345 if (DEBUG_FILTERS) { 10346 Slog.i(TAG, "Protected action; save for later;" 10347 + " package: " + applicationInfo.packageName 10348 + " activity: " + intent.activity.className 10349 + " origPrio: " + intent.getPriority()); 10350 } 10351 return; 10352 } else { 10353 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10354 Slog.i(TAG, "No setup wizard;" 10355 + " All protected intents capped to priority 0"); 10356 } 10357 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10358 if (DEBUG_FILTERS) { 10359 Slog.i(TAG, "Found setup wizard;" 10360 + " allow priority " + intent.getPriority() + ";" 10361 + " package: " + intent.activity.info.packageName 10362 + " activity: " + intent.activity.className 10363 + " priority: " + intent.getPriority()); 10364 } 10365 // setup wizard gets whatever it wants 10366 return; 10367 } 10368 Slog.w(TAG, "Protected action; cap priority to 0;" 10369 + " package: " + intent.activity.info.packageName 10370 + " activity: " + intent.activity.className 10371 + " origPrio: " + intent.getPriority()); 10372 intent.setPriority(0); 10373 return; 10374 } 10375 } 10376 // privileged apps on the system image get whatever priority they request 10377 return; 10378 } 10379 10380 // privileged app unbundled update ... try to find the same activity 10381 final PackageParser.Activity foundActivity = 10382 findMatchingActivity(systemActivities, activityInfo); 10383 if (foundActivity == null) { 10384 // this is a new activity; it cannot obtain >0 priority 10385 if (DEBUG_FILTERS) { 10386 Slog.i(TAG, "New activity; cap priority to 0;" 10387 + " package: " + applicationInfo.packageName 10388 + " activity: " + intent.activity.className 10389 + " origPrio: " + intent.getPriority()); 10390 } 10391 intent.setPriority(0); 10392 return; 10393 } 10394 10395 // found activity, now check for filter equivalence 10396 10397 // a shallow copy is enough; we modify the list, not its contents 10398 final List<ActivityIntentInfo> intentListCopy = 10399 new ArrayList<>(foundActivity.intents); 10400 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10401 10402 // find matching action subsets 10403 final Iterator<String> actionsIterator = intent.actionsIterator(); 10404 if (actionsIterator != null) { 10405 getIntentListSubset( 10406 intentListCopy, new ActionIterGenerator(), actionsIterator); 10407 if (intentListCopy.size() == 0) { 10408 // no more intents to match; we're not equivalent 10409 if (DEBUG_FILTERS) { 10410 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10411 + " package: " + applicationInfo.packageName 10412 + " activity: " + intent.activity.className 10413 + " origPrio: " + intent.getPriority()); 10414 } 10415 intent.setPriority(0); 10416 return; 10417 } 10418 } 10419 10420 // find matching category subsets 10421 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10422 if (categoriesIterator != null) { 10423 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10424 categoriesIterator); 10425 if (intentListCopy.size() == 0) { 10426 // no more intents to match; we're not equivalent 10427 if (DEBUG_FILTERS) { 10428 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10429 + " package: " + applicationInfo.packageName 10430 + " activity: " + intent.activity.className 10431 + " origPrio: " + intent.getPriority()); 10432 } 10433 intent.setPriority(0); 10434 return; 10435 } 10436 } 10437 10438 // find matching schemes subsets 10439 final Iterator<String> schemesIterator = intent.schemesIterator(); 10440 if (schemesIterator != null) { 10441 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10442 schemesIterator); 10443 if (intentListCopy.size() == 0) { 10444 // no more intents to match; we're not equivalent 10445 if (DEBUG_FILTERS) { 10446 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10447 + " package: " + applicationInfo.packageName 10448 + " activity: " + intent.activity.className 10449 + " origPrio: " + intent.getPriority()); 10450 } 10451 intent.setPriority(0); 10452 return; 10453 } 10454 } 10455 10456 // find matching authorities subsets 10457 final Iterator<IntentFilter.AuthorityEntry> 10458 authoritiesIterator = intent.authoritiesIterator(); 10459 if (authoritiesIterator != null) { 10460 getIntentListSubset(intentListCopy, 10461 new AuthoritiesIterGenerator(), 10462 authoritiesIterator); 10463 if (intentListCopy.size() == 0) { 10464 // no more intents to match; we're not equivalent 10465 if (DEBUG_FILTERS) { 10466 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10467 + " package: " + applicationInfo.packageName 10468 + " activity: " + intent.activity.className 10469 + " origPrio: " + intent.getPriority()); 10470 } 10471 intent.setPriority(0); 10472 return; 10473 } 10474 } 10475 10476 // we found matching filter(s); app gets the max priority of all intents 10477 int cappedPriority = 0; 10478 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10479 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10480 } 10481 if (intent.getPriority() > cappedPriority) { 10482 if (DEBUG_FILTERS) { 10483 Slog.i(TAG, "Found matching filter(s);" 10484 + " cap priority to " + cappedPriority + ";" 10485 + " package: " + applicationInfo.packageName 10486 + " activity: " + intent.activity.className 10487 + " origPrio: " + intent.getPriority()); 10488 } 10489 intent.setPriority(cappedPriority); 10490 return; 10491 } 10492 // all this for nothing; the requested priority was <= what was on the system 10493 } 10494 10495 public final void addActivity(PackageParser.Activity a, String type) { 10496 mActivities.put(a.getComponentName(), a); 10497 if (DEBUG_SHOW_INFO) 10498 Log.v( 10499 TAG, " " + type + " " + 10500 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10501 if (DEBUG_SHOW_INFO) 10502 Log.v(TAG, " Class=" + a.info.name); 10503 final int NI = a.intents.size(); 10504 for (int j=0; j<NI; j++) { 10505 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10506 if ("activity".equals(type)) { 10507 final PackageSetting ps = 10508 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10509 final List<PackageParser.Activity> systemActivities = 10510 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10511 adjustPriority(systemActivities, intent); 10512 } 10513 if (DEBUG_SHOW_INFO) { 10514 Log.v(TAG, " IntentFilter:"); 10515 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10516 } 10517 if (!intent.debugCheck()) { 10518 Log.w(TAG, "==> For Activity " + a.info.name); 10519 } 10520 addFilter(intent); 10521 } 10522 } 10523 10524 public final void removeActivity(PackageParser.Activity a, String type) { 10525 mActivities.remove(a.getComponentName()); 10526 if (DEBUG_SHOW_INFO) { 10527 Log.v(TAG, " " + type + " " 10528 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10529 : a.info.name) + ":"); 10530 Log.v(TAG, " Class=" + a.info.name); 10531 } 10532 final int NI = a.intents.size(); 10533 for (int j=0; j<NI; j++) { 10534 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10535 if (DEBUG_SHOW_INFO) { 10536 Log.v(TAG, " IntentFilter:"); 10537 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10538 } 10539 removeFilter(intent); 10540 } 10541 } 10542 10543 @Override 10544 protected boolean allowFilterResult( 10545 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10546 ActivityInfo filterAi = filter.activity.info; 10547 for (int i=dest.size()-1; i>=0; i--) { 10548 ActivityInfo destAi = dest.get(i).activityInfo; 10549 if (destAi.name == filterAi.name 10550 && destAi.packageName == filterAi.packageName) { 10551 return false; 10552 } 10553 } 10554 return true; 10555 } 10556 10557 @Override 10558 protected ActivityIntentInfo[] newArray(int size) { 10559 return new ActivityIntentInfo[size]; 10560 } 10561 10562 @Override 10563 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10564 if (!sUserManager.exists(userId)) return true; 10565 PackageParser.Package p = filter.activity.owner; 10566 if (p != null) { 10567 PackageSetting ps = (PackageSetting)p.mExtras; 10568 if (ps != null) { 10569 // System apps are never considered stopped for purposes of 10570 // filtering, because there may be no way for the user to 10571 // actually re-launch them. 10572 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10573 && ps.getStopped(userId); 10574 } 10575 } 10576 return false; 10577 } 10578 10579 @Override 10580 protected boolean isPackageForFilter(String packageName, 10581 PackageParser.ActivityIntentInfo info) { 10582 return packageName.equals(info.activity.owner.packageName); 10583 } 10584 10585 @Override 10586 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10587 int match, int userId) { 10588 if (!sUserManager.exists(userId)) return null; 10589 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10590 return null; 10591 } 10592 final PackageParser.Activity activity = info.activity; 10593 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10594 if (ps == null) { 10595 return null; 10596 } 10597 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10598 ps.readUserState(userId), userId); 10599 if (ai == null) { 10600 return null; 10601 } 10602 final ResolveInfo res = new ResolveInfo(); 10603 res.activityInfo = ai; 10604 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10605 res.filter = info; 10606 } 10607 if (info != null) { 10608 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10609 } 10610 res.priority = info.getPriority(); 10611 res.preferredOrder = activity.owner.mPreferredOrder; 10612 //System.out.println("Result: " + res.activityInfo.className + 10613 // " = " + res.priority); 10614 res.match = match; 10615 res.isDefault = info.hasDefault; 10616 res.labelRes = info.labelRes; 10617 res.nonLocalizedLabel = info.nonLocalizedLabel; 10618 if (userNeedsBadging(userId)) { 10619 res.noResourceId = true; 10620 } else { 10621 res.icon = info.icon; 10622 } 10623 res.iconResourceId = info.icon; 10624 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10625 return res; 10626 } 10627 10628 @Override 10629 protected void sortResults(List<ResolveInfo> results) { 10630 Collections.sort(results, mResolvePrioritySorter); 10631 } 10632 10633 @Override 10634 protected void dumpFilter(PrintWriter out, String prefix, 10635 PackageParser.ActivityIntentInfo filter) { 10636 out.print(prefix); out.print( 10637 Integer.toHexString(System.identityHashCode(filter.activity))); 10638 out.print(' '); 10639 filter.activity.printComponentShortName(out); 10640 out.print(" filter "); 10641 out.println(Integer.toHexString(System.identityHashCode(filter))); 10642 } 10643 10644 @Override 10645 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10646 return filter.activity; 10647 } 10648 10649 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10650 PackageParser.Activity activity = (PackageParser.Activity)label; 10651 out.print(prefix); out.print( 10652 Integer.toHexString(System.identityHashCode(activity))); 10653 out.print(' '); 10654 activity.printComponentShortName(out); 10655 if (count > 1) { 10656 out.print(" ("); out.print(count); out.print(" filters)"); 10657 } 10658 out.println(); 10659 } 10660 10661 // Keys are String (activity class name), values are Activity. 10662 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10663 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10664 private int mFlags; 10665 } 10666 10667 private final class ServiceIntentResolver 10668 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10669 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10670 boolean defaultOnly, int userId) { 10671 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10672 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10673 } 10674 10675 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10676 int userId) { 10677 if (!sUserManager.exists(userId)) return null; 10678 mFlags = flags; 10679 return super.queryIntent(intent, resolvedType, 10680 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10681 } 10682 10683 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10684 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10685 if (!sUserManager.exists(userId)) return null; 10686 if (packageServices == null) { 10687 return null; 10688 } 10689 mFlags = flags; 10690 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10691 final int N = packageServices.size(); 10692 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10693 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10694 10695 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10696 for (int i = 0; i < N; ++i) { 10697 intentFilters = packageServices.get(i).intents; 10698 if (intentFilters != null && intentFilters.size() > 0) { 10699 PackageParser.ServiceIntentInfo[] array = 10700 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10701 intentFilters.toArray(array); 10702 listCut.add(array); 10703 } 10704 } 10705 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10706 } 10707 10708 public final void addService(PackageParser.Service s) { 10709 mServices.put(s.getComponentName(), s); 10710 if (DEBUG_SHOW_INFO) { 10711 Log.v(TAG, " " 10712 + (s.info.nonLocalizedLabel != null 10713 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10714 Log.v(TAG, " Class=" + s.info.name); 10715 } 10716 final int NI = s.intents.size(); 10717 int j; 10718 for (j=0; j<NI; j++) { 10719 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10720 if (DEBUG_SHOW_INFO) { 10721 Log.v(TAG, " IntentFilter:"); 10722 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10723 } 10724 if (!intent.debugCheck()) { 10725 Log.w(TAG, "==> For Service " + s.info.name); 10726 } 10727 addFilter(intent); 10728 } 10729 } 10730 10731 public final void removeService(PackageParser.Service s) { 10732 mServices.remove(s.getComponentName()); 10733 if (DEBUG_SHOW_INFO) { 10734 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10735 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10736 Log.v(TAG, " Class=" + s.info.name); 10737 } 10738 final int NI = s.intents.size(); 10739 int j; 10740 for (j=0; j<NI; j++) { 10741 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10742 if (DEBUG_SHOW_INFO) { 10743 Log.v(TAG, " IntentFilter:"); 10744 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10745 } 10746 removeFilter(intent); 10747 } 10748 } 10749 10750 @Override 10751 protected boolean allowFilterResult( 10752 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10753 ServiceInfo filterSi = filter.service.info; 10754 for (int i=dest.size()-1; i>=0; i--) { 10755 ServiceInfo destAi = dest.get(i).serviceInfo; 10756 if (destAi.name == filterSi.name 10757 && destAi.packageName == filterSi.packageName) { 10758 return false; 10759 } 10760 } 10761 return true; 10762 } 10763 10764 @Override 10765 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10766 return new PackageParser.ServiceIntentInfo[size]; 10767 } 10768 10769 @Override 10770 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10771 if (!sUserManager.exists(userId)) return true; 10772 PackageParser.Package p = filter.service.owner; 10773 if (p != null) { 10774 PackageSetting ps = (PackageSetting)p.mExtras; 10775 if (ps != null) { 10776 // System apps are never considered stopped for purposes of 10777 // filtering, because there may be no way for the user to 10778 // actually re-launch them. 10779 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10780 && ps.getStopped(userId); 10781 } 10782 } 10783 return false; 10784 } 10785 10786 @Override 10787 protected boolean isPackageForFilter(String packageName, 10788 PackageParser.ServiceIntentInfo info) { 10789 return packageName.equals(info.service.owner.packageName); 10790 } 10791 10792 @Override 10793 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10794 int match, int userId) { 10795 if (!sUserManager.exists(userId)) return null; 10796 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10797 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10798 return null; 10799 } 10800 final PackageParser.Service service = info.service; 10801 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10802 if (ps == null) { 10803 return null; 10804 } 10805 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10806 ps.readUserState(userId), userId); 10807 if (si == null) { 10808 return null; 10809 } 10810 final ResolveInfo res = new ResolveInfo(); 10811 res.serviceInfo = si; 10812 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10813 res.filter = filter; 10814 } 10815 res.priority = info.getPriority(); 10816 res.preferredOrder = service.owner.mPreferredOrder; 10817 res.match = match; 10818 res.isDefault = info.hasDefault; 10819 res.labelRes = info.labelRes; 10820 res.nonLocalizedLabel = info.nonLocalizedLabel; 10821 res.icon = info.icon; 10822 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10823 return res; 10824 } 10825 10826 @Override 10827 protected void sortResults(List<ResolveInfo> results) { 10828 Collections.sort(results, mResolvePrioritySorter); 10829 } 10830 10831 @Override 10832 protected void dumpFilter(PrintWriter out, String prefix, 10833 PackageParser.ServiceIntentInfo filter) { 10834 out.print(prefix); out.print( 10835 Integer.toHexString(System.identityHashCode(filter.service))); 10836 out.print(' '); 10837 filter.service.printComponentShortName(out); 10838 out.print(" filter "); 10839 out.println(Integer.toHexString(System.identityHashCode(filter))); 10840 } 10841 10842 @Override 10843 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10844 return filter.service; 10845 } 10846 10847 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10848 PackageParser.Service service = (PackageParser.Service)label; 10849 out.print(prefix); out.print( 10850 Integer.toHexString(System.identityHashCode(service))); 10851 out.print(' '); 10852 service.printComponentShortName(out); 10853 if (count > 1) { 10854 out.print(" ("); out.print(count); out.print(" filters)"); 10855 } 10856 out.println(); 10857 } 10858 10859// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10860// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10861// final List<ResolveInfo> retList = Lists.newArrayList(); 10862// while (i.hasNext()) { 10863// final ResolveInfo resolveInfo = (ResolveInfo) i; 10864// if (isEnabledLP(resolveInfo.serviceInfo)) { 10865// retList.add(resolveInfo); 10866// } 10867// } 10868// return retList; 10869// } 10870 10871 // Keys are String (activity class name), values are Activity. 10872 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10873 = new ArrayMap<ComponentName, PackageParser.Service>(); 10874 private int mFlags; 10875 }; 10876 10877 private final class ProviderIntentResolver 10878 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10879 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10880 boolean defaultOnly, int userId) { 10881 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10882 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10883 } 10884 10885 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10886 int userId) { 10887 if (!sUserManager.exists(userId)) 10888 return null; 10889 mFlags = flags; 10890 return super.queryIntent(intent, resolvedType, 10891 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10892 } 10893 10894 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10895 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10896 if (!sUserManager.exists(userId)) 10897 return null; 10898 if (packageProviders == null) { 10899 return null; 10900 } 10901 mFlags = flags; 10902 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10903 final int N = packageProviders.size(); 10904 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10905 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10906 10907 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10908 for (int i = 0; i < N; ++i) { 10909 intentFilters = packageProviders.get(i).intents; 10910 if (intentFilters != null && intentFilters.size() > 0) { 10911 PackageParser.ProviderIntentInfo[] array = 10912 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10913 intentFilters.toArray(array); 10914 listCut.add(array); 10915 } 10916 } 10917 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10918 } 10919 10920 public final void addProvider(PackageParser.Provider p) { 10921 if (mProviders.containsKey(p.getComponentName())) { 10922 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10923 return; 10924 } 10925 10926 mProviders.put(p.getComponentName(), p); 10927 if (DEBUG_SHOW_INFO) { 10928 Log.v(TAG, " " 10929 + (p.info.nonLocalizedLabel != null 10930 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10931 Log.v(TAG, " Class=" + p.info.name); 10932 } 10933 final int NI = p.intents.size(); 10934 int j; 10935 for (j = 0; j < NI; j++) { 10936 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10937 if (DEBUG_SHOW_INFO) { 10938 Log.v(TAG, " IntentFilter:"); 10939 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10940 } 10941 if (!intent.debugCheck()) { 10942 Log.w(TAG, "==> For Provider " + p.info.name); 10943 } 10944 addFilter(intent); 10945 } 10946 } 10947 10948 public final void removeProvider(PackageParser.Provider p) { 10949 mProviders.remove(p.getComponentName()); 10950 if (DEBUG_SHOW_INFO) { 10951 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10952 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10953 Log.v(TAG, " Class=" + p.info.name); 10954 } 10955 final int NI = p.intents.size(); 10956 int j; 10957 for (j = 0; j < NI; j++) { 10958 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10959 if (DEBUG_SHOW_INFO) { 10960 Log.v(TAG, " IntentFilter:"); 10961 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10962 } 10963 removeFilter(intent); 10964 } 10965 } 10966 10967 @Override 10968 protected boolean allowFilterResult( 10969 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10970 ProviderInfo filterPi = filter.provider.info; 10971 for (int i = dest.size() - 1; i >= 0; i--) { 10972 ProviderInfo destPi = dest.get(i).providerInfo; 10973 if (destPi.name == filterPi.name 10974 && destPi.packageName == filterPi.packageName) { 10975 return false; 10976 } 10977 } 10978 return true; 10979 } 10980 10981 @Override 10982 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10983 return new PackageParser.ProviderIntentInfo[size]; 10984 } 10985 10986 @Override 10987 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10988 if (!sUserManager.exists(userId)) 10989 return true; 10990 PackageParser.Package p = filter.provider.owner; 10991 if (p != null) { 10992 PackageSetting ps = (PackageSetting) p.mExtras; 10993 if (ps != null) { 10994 // System apps are never considered stopped for purposes of 10995 // filtering, because there may be no way for the user to 10996 // actually re-launch them. 10997 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10998 && ps.getStopped(userId); 10999 } 11000 } 11001 return false; 11002 } 11003 11004 @Override 11005 protected boolean isPackageForFilter(String packageName, 11006 PackageParser.ProviderIntentInfo info) { 11007 return packageName.equals(info.provider.owner.packageName); 11008 } 11009 11010 @Override 11011 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11012 int match, int userId) { 11013 if (!sUserManager.exists(userId)) 11014 return null; 11015 final PackageParser.ProviderIntentInfo info = filter; 11016 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11017 return null; 11018 } 11019 final PackageParser.Provider provider = info.provider; 11020 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11021 if (ps == null) { 11022 return null; 11023 } 11024 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11025 ps.readUserState(userId), userId); 11026 if (pi == null) { 11027 return null; 11028 } 11029 final ResolveInfo res = new ResolveInfo(); 11030 res.providerInfo = pi; 11031 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11032 res.filter = filter; 11033 } 11034 res.priority = info.getPriority(); 11035 res.preferredOrder = provider.owner.mPreferredOrder; 11036 res.match = match; 11037 res.isDefault = info.hasDefault; 11038 res.labelRes = info.labelRes; 11039 res.nonLocalizedLabel = info.nonLocalizedLabel; 11040 res.icon = info.icon; 11041 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11042 return res; 11043 } 11044 11045 @Override 11046 protected void sortResults(List<ResolveInfo> results) { 11047 Collections.sort(results, mResolvePrioritySorter); 11048 } 11049 11050 @Override 11051 protected void dumpFilter(PrintWriter out, String prefix, 11052 PackageParser.ProviderIntentInfo filter) { 11053 out.print(prefix); 11054 out.print( 11055 Integer.toHexString(System.identityHashCode(filter.provider))); 11056 out.print(' '); 11057 filter.provider.printComponentShortName(out); 11058 out.print(" filter "); 11059 out.println(Integer.toHexString(System.identityHashCode(filter))); 11060 } 11061 11062 @Override 11063 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11064 return filter.provider; 11065 } 11066 11067 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11068 PackageParser.Provider provider = (PackageParser.Provider)label; 11069 out.print(prefix); out.print( 11070 Integer.toHexString(System.identityHashCode(provider))); 11071 out.print(' '); 11072 provider.printComponentShortName(out); 11073 if (count > 1) { 11074 out.print(" ("); out.print(count); out.print(" filters)"); 11075 } 11076 out.println(); 11077 } 11078 11079 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11080 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11081 private int mFlags; 11082 } 11083 11084 private static final class EphemeralIntentResolver 11085 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11086 @Override 11087 protected EphemeralResolveIntentInfo[] newArray(int size) { 11088 return new EphemeralResolveIntentInfo[size]; 11089 } 11090 11091 @Override 11092 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11093 return true; 11094 } 11095 11096 @Override 11097 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11098 int userId) { 11099 if (!sUserManager.exists(userId)) { 11100 return null; 11101 } 11102 return info.getEphemeralResolveInfo(); 11103 } 11104 } 11105 11106 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11107 new Comparator<ResolveInfo>() { 11108 public int compare(ResolveInfo r1, ResolveInfo r2) { 11109 int v1 = r1.priority; 11110 int v2 = r2.priority; 11111 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11112 if (v1 != v2) { 11113 return (v1 > v2) ? -1 : 1; 11114 } 11115 v1 = r1.preferredOrder; 11116 v2 = r2.preferredOrder; 11117 if (v1 != v2) { 11118 return (v1 > v2) ? -1 : 1; 11119 } 11120 if (r1.isDefault != r2.isDefault) { 11121 return r1.isDefault ? -1 : 1; 11122 } 11123 v1 = r1.match; 11124 v2 = r2.match; 11125 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11126 if (v1 != v2) { 11127 return (v1 > v2) ? -1 : 1; 11128 } 11129 if (r1.system != r2.system) { 11130 return r1.system ? -1 : 1; 11131 } 11132 if (r1.activityInfo != null) { 11133 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11134 } 11135 if (r1.serviceInfo != null) { 11136 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11137 } 11138 if (r1.providerInfo != null) { 11139 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11140 } 11141 return 0; 11142 } 11143 }; 11144 11145 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11146 new Comparator<ProviderInfo>() { 11147 public int compare(ProviderInfo p1, ProviderInfo p2) { 11148 final int v1 = p1.initOrder; 11149 final int v2 = p2.initOrder; 11150 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11151 } 11152 }; 11153 11154 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11155 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11156 final int[] userIds) { 11157 mHandler.post(new Runnable() { 11158 @Override 11159 public void run() { 11160 try { 11161 final IActivityManager am = ActivityManagerNative.getDefault(); 11162 if (am == null) return; 11163 final int[] resolvedUserIds; 11164 if (userIds == null) { 11165 resolvedUserIds = am.getRunningUserIds(); 11166 } else { 11167 resolvedUserIds = userIds; 11168 } 11169 for (int id : resolvedUserIds) { 11170 final Intent intent = new Intent(action, 11171 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11172 if (extras != null) { 11173 intent.putExtras(extras); 11174 } 11175 if (targetPkg != null) { 11176 intent.setPackage(targetPkg); 11177 } 11178 // Modify the UID when posting to other users 11179 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11180 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11181 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11182 intent.putExtra(Intent.EXTRA_UID, uid); 11183 } 11184 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11185 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11186 if (DEBUG_BROADCASTS) { 11187 RuntimeException here = new RuntimeException("here"); 11188 here.fillInStackTrace(); 11189 Slog.d(TAG, "Sending to user " + id + ": " 11190 + intent.toShortString(false, true, false, false) 11191 + " " + intent.getExtras(), here); 11192 } 11193 am.broadcastIntent(null, intent, null, finishedReceiver, 11194 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11195 null, finishedReceiver != null, false, id); 11196 } 11197 } catch (RemoteException ex) { 11198 } 11199 } 11200 }); 11201 } 11202 11203 /** 11204 * Check if the external storage media is available. This is true if there 11205 * is a mounted external storage medium or if the external storage is 11206 * emulated. 11207 */ 11208 private boolean isExternalMediaAvailable() { 11209 return mMediaMounted || Environment.isExternalStorageEmulated(); 11210 } 11211 11212 @Override 11213 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11214 // writer 11215 synchronized (mPackages) { 11216 if (!isExternalMediaAvailable()) { 11217 // If the external storage is no longer mounted at this point, 11218 // the caller may not have been able to delete all of this 11219 // packages files and can not delete any more. Bail. 11220 return null; 11221 } 11222 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11223 if (lastPackage != null) { 11224 pkgs.remove(lastPackage); 11225 } 11226 if (pkgs.size() > 0) { 11227 return pkgs.get(0); 11228 } 11229 } 11230 return null; 11231 } 11232 11233 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11234 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11235 userId, andCode ? 1 : 0, packageName); 11236 if (mSystemReady) { 11237 msg.sendToTarget(); 11238 } else { 11239 if (mPostSystemReadyMessages == null) { 11240 mPostSystemReadyMessages = new ArrayList<>(); 11241 } 11242 mPostSystemReadyMessages.add(msg); 11243 } 11244 } 11245 11246 void startCleaningPackages() { 11247 // reader 11248 if (!isExternalMediaAvailable()) { 11249 return; 11250 } 11251 synchronized (mPackages) { 11252 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11253 return; 11254 } 11255 } 11256 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11257 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11258 IActivityManager am = ActivityManagerNative.getDefault(); 11259 if (am != null) { 11260 try { 11261 am.startService(null, intent, null, mContext.getOpPackageName(), 11262 UserHandle.USER_SYSTEM); 11263 } catch (RemoteException e) { 11264 } 11265 } 11266 } 11267 11268 @Override 11269 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11270 int installFlags, String installerPackageName, int userId) { 11271 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11272 11273 final int callingUid = Binder.getCallingUid(); 11274 enforceCrossUserPermission(callingUid, userId, 11275 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11276 11277 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11278 try { 11279 if (observer != null) { 11280 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11281 } 11282 } catch (RemoteException re) { 11283 } 11284 return; 11285 } 11286 11287 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11288 installFlags |= PackageManager.INSTALL_FROM_ADB; 11289 11290 } else { 11291 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11292 // about installerPackageName. 11293 11294 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11295 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11296 } 11297 11298 UserHandle user; 11299 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11300 user = UserHandle.ALL; 11301 } else { 11302 user = new UserHandle(userId); 11303 } 11304 11305 // Only system components can circumvent runtime permissions when installing. 11306 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11307 && mContext.checkCallingOrSelfPermission(Manifest.permission 11308 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11309 throw new SecurityException("You need the " 11310 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11311 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11312 } 11313 11314 final File originFile = new File(originPath); 11315 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11316 11317 final Message msg = mHandler.obtainMessage(INIT_COPY); 11318 final VerificationInfo verificationInfo = new VerificationInfo( 11319 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11320 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11321 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11322 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11323 null /*certificates*/); 11324 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11325 msg.obj = params; 11326 11327 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11328 System.identityHashCode(msg.obj)); 11329 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11330 System.identityHashCode(msg.obj)); 11331 11332 mHandler.sendMessage(msg); 11333 } 11334 11335 void installStage(String packageName, File stagedDir, String stagedCid, 11336 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11337 String installerPackageName, int installerUid, UserHandle user, 11338 Certificate[][] certificates) { 11339 if (DEBUG_EPHEMERAL) { 11340 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11341 Slog.d(TAG, "Ephemeral install of " + packageName); 11342 } 11343 } 11344 final VerificationInfo verificationInfo = new VerificationInfo( 11345 sessionParams.originatingUri, sessionParams.referrerUri, 11346 sessionParams.originatingUid, installerUid); 11347 11348 final OriginInfo origin; 11349 if (stagedDir != null) { 11350 origin = OriginInfo.fromStagedFile(stagedDir); 11351 } else { 11352 origin = OriginInfo.fromStagedContainer(stagedCid); 11353 } 11354 11355 final Message msg = mHandler.obtainMessage(INIT_COPY); 11356 final InstallParams params = new InstallParams(origin, null, observer, 11357 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11358 verificationInfo, user, sessionParams.abiOverride, 11359 sessionParams.grantedRuntimePermissions, certificates); 11360 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11361 msg.obj = params; 11362 11363 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11364 System.identityHashCode(msg.obj)); 11365 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11366 System.identityHashCode(msg.obj)); 11367 11368 mHandler.sendMessage(msg); 11369 } 11370 11371 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11372 int userId) { 11373 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11374 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11375 } 11376 11377 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11378 int appId, int userId) { 11379 Bundle extras = new Bundle(1); 11380 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11381 11382 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11383 packageName, extras, 0, null, null, new int[] {userId}); 11384 try { 11385 IActivityManager am = ActivityManagerNative.getDefault(); 11386 if (isSystem && am.isUserRunning(userId, 0)) { 11387 // The just-installed/enabled app is bundled on the system, so presumed 11388 // to be able to run automatically without needing an explicit launch. 11389 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11390 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11391 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11392 .setPackage(packageName); 11393 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11394 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11395 } 11396 } catch (RemoteException e) { 11397 // shouldn't happen 11398 Slog.w(TAG, "Unable to bootstrap installed package", e); 11399 } 11400 } 11401 11402 @Override 11403 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11404 int userId) { 11405 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11406 PackageSetting pkgSetting; 11407 final int uid = Binder.getCallingUid(); 11408 enforceCrossUserPermission(uid, userId, 11409 true /* requireFullPermission */, true /* checkShell */, 11410 "setApplicationHiddenSetting for user " + userId); 11411 11412 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11413 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11414 return false; 11415 } 11416 11417 long callingId = Binder.clearCallingIdentity(); 11418 try { 11419 boolean sendAdded = false; 11420 boolean sendRemoved = false; 11421 // writer 11422 synchronized (mPackages) { 11423 pkgSetting = mSettings.mPackages.get(packageName); 11424 if (pkgSetting == null) { 11425 return false; 11426 } 11427 if (pkgSetting.getHidden(userId) != hidden) { 11428 pkgSetting.setHidden(hidden, userId); 11429 mSettings.writePackageRestrictionsLPr(userId); 11430 if (hidden) { 11431 sendRemoved = true; 11432 } else { 11433 sendAdded = true; 11434 } 11435 } 11436 } 11437 if (sendAdded) { 11438 sendPackageAddedForUser(packageName, pkgSetting, userId); 11439 return true; 11440 } 11441 if (sendRemoved) { 11442 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11443 "hiding pkg"); 11444 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11445 return true; 11446 } 11447 } finally { 11448 Binder.restoreCallingIdentity(callingId); 11449 } 11450 return false; 11451 } 11452 11453 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11454 int userId) { 11455 final PackageRemovedInfo info = new PackageRemovedInfo(); 11456 info.removedPackage = packageName; 11457 info.removedUsers = new int[] {userId}; 11458 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11459 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11460 } 11461 11462 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11463 if (pkgList.length > 0) { 11464 Bundle extras = new Bundle(1); 11465 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11466 11467 sendPackageBroadcast( 11468 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11469 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11470 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11471 new int[] {userId}); 11472 } 11473 } 11474 11475 /** 11476 * Returns true if application is not found or there was an error. Otherwise it returns 11477 * the hidden state of the package for the given user. 11478 */ 11479 @Override 11480 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11481 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11482 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11483 true /* requireFullPermission */, false /* checkShell */, 11484 "getApplicationHidden for user " + userId); 11485 PackageSetting pkgSetting; 11486 long callingId = Binder.clearCallingIdentity(); 11487 try { 11488 // writer 11489 synchronized (mPackages) { 11490 pkgSetting = mSettings.mPackages.get(packageName); 11491 if (pkgSetting == null) { 11492 return true; 11493 } 11494 return pkgSetting.getHidden(userId); 11495 } 11496 } finally { 11497 Binder.restoreCallingIdentity(callingId); 11498 } 11499 } 11500 11501 /** 11502 * @hide 11503 */ 11504 @Override 11505 public int installExistingPackageAsUser(String packageName, int userId) { 11506 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11507 null); 11508 PackageSetting pkgSetting; 11509 final int uid = Binder.getCallingUid(); 11510 enforceCrossUserPermission(uid, userId, 11511 true /* requireFullPermission */, true /* checkShell */, 11512 "installExistingPackage for user " + userId); 11513 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11514 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11515 } 11516 11517 long callingId = Binder.clearCallingIdentity(); 11518 try { 11519 boolean installed = false; 11520 11521 // writer 11522 synchronized (mPackages) { 11523 pkgSetting = mSettings.mPackages.get(packageName); 11524 if (pkgSetting == null) { 11525 return PackageManager.INSTALL_FAILED_INVALID_URI; 11526 } 11527 if (!pkgSetting.getInstalled(userId)) { 11528 pkgSetting.setInstalled(true, userId); 11529 pkgSetting.setHidden(false, userId); 11530 mSettings.writePackageRestrictionsLPr(userId); 11531 installed = true; 11532 } 11533 } 11534 11535 if (installed) { 11536 if (pkgSetting.pkg != null) { 11537 synchronized (mInstallLock) { 11538 // We don't need to freeze for a brand new install 11539 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11540 } 11541 } 11542 sendPackageAddedForUser(packageName, pkgSetting, userId); 11543 } 11544 } finally { 11545 Binder.restoreCallingIdentity(callingId); 11546 } 11547 11548 return PackageManager.INSTALL_SUCCEEDED; 11549 } 11550 11551 boolean isUserRestricted(int userId, String restrictionKey) { 11552 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11553 if (restrictions.getBoolean(restrictionKey, false)) { 11554 Log.w(TAG, "User is restricted: " + restrictionKey); 11555 return true; 11556 } 11557 return false; 11558 } 11559 11560 @Override 11561 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11562 int userId) { 11563 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11564 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11565 true /* requireFullPermission */, true /* checkShell */, 11566 "setPackagesSuspended for user " + userId); 11567 11568 if (ArrayUtils.isEmpty(packageNames)) { 11569 return packageNames; 11570 } 11571 11572 // List of package names for whom the suspended state has changed. 11573 List<String> changedPackages = new ArrayList<>(packageNames.length); 11574 // List of package names for whom the suspended state is not set as requested in this 11575 // method. 11576 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11577 long callingId = Binder.clearCallingIdentity(); 11578 try { 11579 for (int i = 0; i < packageNames.length; i++) { 11580 String packageName = packageNames[i]; 11581 boolean changed = false; 11582 final int appId; 11583 synchronized (mPackages) { 11584 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11585 if (pkgSetting == null) { 11586 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11587 + "\". Skipping suspending/un-suspending."); 11588 unactionedPackages.add(packageName); 11589 continue; 11590 } 11591 appId = pkgSetting.appId; 11592 if (pkgSetting.getSuspended(userId) != suspended) { 11593 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11594 unactionedPackages.add(packageName); 11595 continue; 11596 } 11597 pkgSetting.setSuspended(suspended, userId); 11598 mSettings.writePackageRestrictionsLPr(userId); 11599 changed = true; 11600 changedPackages.add(packageName); 11601 } 11602 } 11603 11604 if (changed && suspended) { 11605 killApplication(packageName, UserHandle.getUid(userId, appId), 11606 "suspending package"); 11607 } 11608 } 11609 } finally { 11610 Binder.restoreCallingIdentity(callingId); 11611 } 11612 11613 if (!changedPackages.isEmpty()) { 11614 sendPackagesSuspendedForUser(changedPackages.toArray( 11615 new String[changedPackages.size()]), userId, suspended); 11616 } 11617 11618 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11619 } 11620 11621 @Override 11622 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11623 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11624 true /* requireFullPermission */, false /* checkShell */, 11625 "isPackageSuspendedForUser for user " + userId); 11626 synchronized (mPackages) { 11627 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11628 if (pkgSetting == null) { 11629 throw new IllegalArgumentException("Unknown target package: " + packageName); 11630 } 11631 return pkgSetting.getSuspended(userId); 11632 } 11633 } 11634 11635 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11636 if (isPackageDeviceAdmin(packageName, userId)) { 11637 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11638 + "\": has an active device admin"); 11639 return false; 11640 } 11641 11642 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11643 if (packageName.equals(activeLauncherPackageName)) { 11644 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11645 + "\": contains the active launcher"); 11646 return false; 11647 } 11648 11649 if (packageName.equals(mRequiredInstallerPackage)) { 11650 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11651 + "\": required for package installation"); 11652 return false; 11653 } 11654 11655 if (packageName.equals(mRequiredVerifierPackage)) { 11656 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11657 + "\": required for package verification"); 11658 return false; 11659 } 11660 11661 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11662 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11663 + "\": is the default dialer"); 11664 return false; 11665 } 11666 11667 return true; 11668 } 11669 11670 private String getActiveLauncherPackageName(int userId) { 11671 Intent intent = new Intent(Intent.ACTION_MAIN); 11672 intent.addCategory(Intent.CATEGORY_HOME); 11673 ResolveInfo resolveInfo = resolveIntent( 11674 intent, 11675 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11676 PackageManager.MATCH_DEFAULT_ONLY, 11677 userId); 11678 11679 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11680 } 11681 11682 private String getDefaultDialerPackageName(int userId) { 11683 synchronized (mPackages) { 11684 return mSettings.getDefaultDialerPackageNameLPw(userId); 11685 } 11686 } 11687 11688 @Override 11689 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11690 mContext.enforceCallingOrSelfPermission( 11691 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11692 "Only package verification agents can verify applications"); 11693 11694 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11695 final PackageVerificationResponse response = new PackageVerificationResponse( 11696 verificationCode, Binder.getCallingUid()); 11697 msg.arg1 = id; 11698 msg.obj = response; 11699 mHandler.sendMessage(msg); 11700 } 11701 11702 @Override 11703 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11704 long millisecondsToDelay) { 11705 mContext.enforceCallingOrSelfPermission( 11706 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11707 "Only package verification agents can extend verification timeouts"); 11708 11709 final PackageVerificationState state = mPendingVerification.get(id); 11710 final PackageVerificationResponse response = new PackageVerificationResponse( 11711 verificationCodeAtTimeout, Binder.getCallingUid()); 11712 11713 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11714 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11715 } 11716 if (millisecondsToDelay < 0) { 11717 millisecondsToDelay = 0; 11718 } 11719 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11720 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11721 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11722 } 11723 11724 if ((state != null) && !state.timeoutExtended()) { 11725 state.extendTimeout(); 11726 11727 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11728 msg.arg1 = id; 11729 msg.obj = response; 11730 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11731 } 11732 } 11733 11734 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11735 int verificationCode, UserHandle user) { 11736 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11737 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11738 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11739 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11740 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11741 11742 mContext.sendBroadcastAsUser(intent, user, 11743 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11744 } 11745 11746 private ComponentName matchComponentForVerifier(String packageName, 11747 List<ResolveInfo> receivers) { 11748 ActivityInfo targetReceiver = null; 11749 11750 final int NR = receivers.size(); 11751 for (int i = 0; i < NR; i++) { 11752 final ResolveInfo info = receivers.get(i); 11753 if (info.activityInfo == null) { 11754 continue; 11755 } 11756 11757 if (packageName.equals(info.activityInfo.packageName)) { 11758 targetReceiver = info.activityInfo; 11759 break; 11760 } 11761 } 11762 11763 if (targetReceiver == null) { 11764 return null; 11765 } 11766 11767 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11768 } 11769 11770 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11771 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11772 if (pkgInfo.verifiers.length == 0) { 11773 return null; 11774 } 11775 11776 final int N = pkgInfo.verifiers.length; 11777 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11778 for (int i = 0; i < N; i++) { 11779 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11780 11781 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11782 receivers); 11783 if (comp == null) { 11784 continue; 11785 } 11786 11787 final int verifierUid = getUidForVerifier(verifierInfo); 11788 if (verifierUid == -1) { 11789 continue; 11790 } 11791 11792 if (DEBUG_VERIFY) { 11793 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11794 + " with the correct signature"); 11795 } 11796 sufficientVerifiers.add(comp); 11797 verificationState.addSufficientVerifier(verifierUid); 11798 } 11799 11800 return sufficientVerifiers; 11801 } 11802 11803 private int getUidForVerifier(VerifierInfo verifierInfo) { 11804 synchronized (mPackages) { 11805 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11806 if (pkg == null) { 11807 return -1; 11808 } else if (pkg.mSignatures.length != 1) { 11809 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11810 + " has more than one signature; ignoring"); 11811 return -1; 11812 } 11813 11814 /* 11815 * If the public key of the package's signature does not match 11816 * our expected public key, then this is a different package and 11817 * we should skip. 11818 */ 11819 11820 final byte[] expectedPublicKey; 11821 try { 11822 final Signature verifierSig = pkg.mSignatures[0]; 11823 final PublicKey publicKey = verifierSig.getPublicKey(); 11824 expectedPublicKey = publicKey.getEncoded(); 11825 } catch (CertificateException e) { 11826 return -1; 11827 } 11828 11829 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11830 11831 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11832 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11833 + " does not have the expected public key; ignoring"); 11834 return -1; 11835 } 11836 11837 return pkg.applicationInfo.uid; 11838 } 11839 } 11840 11841 @Override 11842 public void finishPackageInstall(int token, boolean didLaunch) { 11843 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11844 11845 if (DEBUG_INSTALL) { 11846 Slog.v(TAG, "BM finishing package install for " + token); 11847 } 11848 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11849 11850 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11851 mHandler.sendMessage(msg); 11852 } 11853 11854 /** 11855 * Get the verification agent timeout. 11856 * 11857 * @return verification timeout in milliseconds 11858 */ 11859 private long getVerificationTimeout() { 11860 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11861 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11862 DEFAULT_VERIFICATION_TIMEOUT); 11863 } 11864 11865 /** 11866 * Get the default verification agent response code. 11867 * 11868 * @return default verification response code 11869 */ 11870 private int getDefaultVerificationResponse() { 11871 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11872 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11873 DEFAULT_VERIFICATION_RESPONSE); 11874 } 11875 11876 /** 11877 * Check whether or not package verification has been enabled. 11878 * 11879 * @return true if verification should be performed 11880 */ 11881 private boolean isVerificationEnabled(int userId, int installFlags) { 11882 if (!DEFAULT_VERIFY_ENABLE) { 11883 return false; 11884 } 11885 // Ephemeral apps don't get the full verification treatment 11886 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11887 if (DEBUG_EPHEMERAL) { 11888 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11889 } 11890 return false; 11891 } 11892 11893 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11894 11895 // Check if installing from ADB 11896 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11897 // Do not run verification in a test harness environment 11898 if (ActivityManager.isRunningInTestHarness()) { 11899 return false; 11900 } 11901 if (ensureVerifyAppsEnabled) { 11902 return true; 11903 } 11904 // Check if the developer does not want package verification for ADB installs 11905 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11906 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11907 return false; 11908 } 11909 } 11910 11911 if (ensureVerifyAppsEnabled) { 11912 return true; 11913 } 11914 11915 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11916 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11917 } 11918 11919 @Override 11920 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11921 throws RemoteException { 11922 mContext.enforceCallingOrSelfPermission( 11923 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11924 "Only intentfilter verification agents can verify applications"); 11925 11926 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11927 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11928 Binder.getCallingUid(), verificationCode, failedDomains); 11929 msg.arg1 = id; 11930 msg.obj = response; 11931 mHandler.sendMessage(msg); 11932 } 11933 11934 @Override 11935 public int getIntentVerificationStatus(String packageName, int userId) { 11936 synchronized (mPackages) { 11937 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11938 } 11939 } 11940 11941 @Override 11942 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11943 mContext.enforceCallingOrSelfPermission( 11944 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11945 11946 boolean result = false; 11947 synchronized (mPackages) { 11948 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11949 } 11950 if (result) { 11951 scheduleWritePackageRestrictionsLocked(userId); 11952 } 11953 return result; 11954 } 11955 11956 @Override 11957 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11958 String packageName) { 11959 synchronized (mPackages) { 11960 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11961 } 11962 } 11963 11964 @Override 11965 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11966 if (TextUtils.isEmpty(packageName)) { 11967 return ParceledListSlice.emptyList(); 11968 } 11969 synchronized (mPackages) { 11970 PackageParser.Package pkg = mPackages.get(packageName); 11971 if (pkg == null || pkg.activities == null) { 11972 return ParceledListSlice.emptyList(); 11973 } 11974 final int count = pkg.activities.size(); 11975 ArrayList<IntentFilter> result = new ArrayList<>(); 11976 for (int n=0; n<count; n++) { 11977 PackageParser.Activity activity = pkg.activities.get(n); 11978 if (activity.intents != null && activity.intents.size() > 0) { 11979 result.addAll(activity.intents); 11980 } 11981 } 11982 return new ParceledListSlice<>(result); 11983 } 11984 } 11985 11986 @Override 11987 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11988 mContext.enforceCallingOrSelfPermission( 11989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11990 11991 synchronized (mPackages) { 11992 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11993 if (packageName != null) { 11994 result |= updateIntentVerificationStatus(packageName, 11995 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11996 userId); 11997 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11998 packageName, userId); 11999 } 12000 return result; 12001 } 12002 } 12003 12004 @Override 12005 public String getDefaultBrowserPackageName(int userId) { 12006 synchronized (mPackages) { 12007 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12008 } 12009 } 12010 12011 /** 12012 * Get the "allow unknown sources" setting. 12013 * 12014 * @return the current "allow unknown sources" setting 12015 */ 12016 private int getUnknownSourcesSettings() { 12017 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12018 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12019 -1); 12020 } 12021 12022 @Override 12023 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12024 final int uid = Binder.getCallingUid(); 12025 // writer 12026 synchronized (mPackages) { 12027 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12028 if (targetPackageSetting == null) { 12029 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12030 } 12031 12032 PackageSetting installerPackageSetting; 12033 if (installerPackageName != null) { 12034 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12035 if (installerPackageSetting == null) { 12036 throw new IllegalArgumentException("Unknown installer package: " 12037 + installerPackageName); 12038 } 12039 } else { 12040 installerPackageSetting = null; 12041 } 12042 12043 Signature[] callerSignature; 12044 Object obj = mSettings.getUserIdLPr(uid); 12045 if (obj != null) { 12046 if (obj instanceof SharedUserSetting) { 12047 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12048 } else if (obj instanceof PackageSetting) { 12049 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12050 } else { 12051 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12052 } 12053 } else { 12054 throw new SecurityException("Unknown calling UID: " + uid); 12055 } 12056 12057 // Verify: can't set installerPackageName to a package that is 12058 // not signed with the same cert as the caller. 12059 if (installerPackageSetting != null) { 12060 if (compareSignatures(callerSignature, 12061 installerPackageSetting.signatures.mSignatures) 12062 != PackageManager.SIGNATURE_MATCH) { 12063 throw new SecurityException( 12064 "Caller does not have same cert as new installer package " 12065 + installerPackageName); 12066 } 12067 } 12068 12069 // Verify: if target already has an installer package, it must 12070 // be signed with the same cert as the caller. 12071 if (targetPackageSetting.installerPackageName != null) { 12072 PackageSetting setting = mSettings.mPackages.get( 12073 targetPackageSetting.installerPackageName); 12074 // If the currently set package isn't valid, then it's always 12075 // okay to change it. 12076 if (setting != null) { 12077 if (compareSignatures(callerSignature, 12078 setting.signatures.mSignatures) 12079 != PackageManager.SIGNATURE_MATCH) { 12080 throw new SecurityException( 12081 "Caller does not have same cert as old installer package " 12082 + targetPackageSetting.installerPackageName); 12083 } 12084 } 12085 } 12086 12087 // Okay! 12088 targetPackageSetting.installerPackageName = installerPackageName; 12089 if (installerPackageName != null) { 12090 mSettings.mInstallerPackages.add(installerPackageName); 12091 } 12092 scheduleWriteSettingsLocked(); 12093 } 12094 } 12095 12096 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12097 // Queue up an async operation since the package installation may take a little while. 12098 mHandler.post(new Runnable() { 12099 public void run() { 12100 mHandler.removeCallbacks(this); 12101 // Result object to be returned 12102 PackageInstalledInfo res = new PackageInstalledInfo(); 12103 res.setReturnCode(currentStatus); 12104 res.uid = -1; 12105 res.pkg = null; 12106 res.removedInfo = null; 12107 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12108 args.doPreInstall(res.returnCode); 12109 synchronized (mInstallLock) { 12110 installPackageTracedLI(args, res); 12111 } 12112 args.doPostInstall(res.returnCode, res.uid); 12113 } 12114 12115 // A restore should be performed at this point if (a) the install 12116 // succeeded, (b) the operation is not an update, and (c) the new 12117 // package has not opted out of backup participation. 12118 final boolean update = res.removedInfo != null 12119 && res.removedInfo.removedPackage != null; 12120 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12121 boolean doRestore = !update 12122 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12123 12124 // Set up the post-install work request bookkeeping. This will be used 12125 // and cleaned up by the post-install event handling regardless of whether 12126 // there's a restore pass performed. Token values are >= 1. 12127 int token; 12128 if (mNextInstallToken < 0) mNextInstallToken = 1; 12129 token = mNextInstallToken++; 12130 12131 PostInstallData data = new PostInstallData(args, res); 12132 mRunningInstalls.put(token, data); 12133 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12134 12135 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12136 // Pass responsibility to the Backup Manager. It will perform a 12137 // restore if appropriate, then pass responsibility back to the 12138 // Package Manager to run the post-install observer callbacks 12139 // and broadcasts. 12140 IBackupManager bm = IBackupManager.Stub.asInterface( 12141 ServiceManager.getService(Context.BACKUP_SERVICE)); 12142 if (bm != null) { 12143 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12144 + " to BM for possible restore"); 12145 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12146 try { 12147 // TODO: http://b/22388012 12148 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12149 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12150 } else { 12151 doRestore = false; 12152 } 12153 } catch (RemoteException e) { 12154 // can't happen; the backup manager is local 12155 } catch (Exception e) { 12156 Slog.e(TAG, "Exception trying to enqueue restore", e); 12157 doRestore = false; 12158 } 12159 } else { 12160 Slog.e(TAG, "Backup Manager not found!"); 12161 doRestore = false; 12162 } 12163 } 12164 12165 if (!doRestore) { 12166 // No restore possible, or the Backup Manager was mysteriously not 12167 // available -- just fire the post-install work request directly. 12168 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12169 12170 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12171 12172 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12173 mHandler.sendMessage(msg); 12174 } 12175 } 12176 }); 12177 } 12178 12179 /** 12180 * Callback from PackageSettings whenever an app is first transitioned out of the 12181 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12182 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12183 * here whether the app is the target of an ongoing install, and only send the 12184 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12185 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12186 * handling. 12187 */ 12188 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12189 // Serialize this with the rest of the install-process message chain. In the 12190 // restore-at-install case, this Runnable will necessarily run before the 12191 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12192 // are coherent. In the non-restore case, the app has already completed install 12193 // and been launched through some other means, so it is not in a problematic 12194 // state for observers to see the FIRST_LAUNCH signal. 12195 mHandler.post(new Runnable() { 12196 @Override 12197 public void run() { 12198 for (int i = 0; i < mRunningInstalls.size(); i++) { 12199 final PostInstallData data = mRunningInstalls.valueAt(i); 12200 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12201 // right package; but is it for the right user? 12202 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12203 if (userId == data.res.newUsers[uIndex]) { 12204 if (DEBUG_BACKUP) { 12205 Slog.i(TAG, "Package " + pkgName 12206 + " being restored so deferring FIRST_LAUNCH"); 12207 } 12208 return; 12209 } 12210 } 12211 } 12212 } 12213 // didn't find it, so not being restored 12214 if (DEBUG_BACKUP) { 12215 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12216 } 12217 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12218 } 12219 }); 12220 } 12221 12222 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12223 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12224 installerPkg, null, userIds); 12225 } 12226 12227 private abstract class HandlerParams { 12228 private static final int MAX_RETRIES = 4; 12229 12230 /** 12231 * Number of times startCopy() has been attempted and had a non-fatal 12232 * error. 12233 */ 12234 private int mRetries = 0; 12235 12236 /** User handle for the user requesting the information or installation. */ 12237 private final UserHandle mUser; 12238 String traceMethod; 12239 int traceCookie; 12240 12241 HandlerParams(UserHandle user) { 12242 mUser = user; 12243 } 12244 12245 UserHandle getUser() { 12246 return mUser; 12247 } 12248 12249 HandlerParams setTraceMethod(String traceMethod) { 12250 this.traceMethod = traceMethod; 12251 return this; 12252 } 12253 12254 HandlerParams setTraceCookie(int traceCookie) { 12255 this.traceCookie = traceCookie; 12256 return this; 12257 } 12258 12259 final boolean startCopy() { 12260 boolean res; 12261 try { 12262 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12263 12264 if (++mRetries > MAX_RETRIES) { 12265 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12266 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12267 handleServiceError(); 12268 return false; 12269 } else { 12270 handleStartCopy(); 12271 res = true; 12272 } 12273 } catch (RemoteException e) { 12274 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12275 mHandler.sendEmptyMessage(MCS_RECONNECT); 12276 res = false; 12277 } 12278 handleReturnCode(); 12279 return res; 12280 } 12281 12282 final void serviceError() { 12283 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12284 handleServiceError(); 12285 handleReturnCode(); 12286 } 12287 12288 abstract void handleStartCopy() throws RemoteException; 12289 abstract void handleServiceError(); 12290 abstract void handleReturnCode(); 12291 } 12292 12293 class MeasureParams extends HandlerParams { 12294 private final PackageStats mStats; 12295 private boolean mSuccess; 12296 12297 private final IPackageStatsObserver mObserver; 12298 12299 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12300 super(new UserHandle(stats.userHandle)); 12301 mObserver = observer; 12302 mStats = stats; 12303 } 12304 12305 @Override 12306 public String toString() { 12307 return "MeasureParams{" 12308 + Integer.toHexString(System.identityHashCode(this)) 12309 + " " + mStats.packageName + "}"; 12310 } 12311 12312 @Override 12313 void handleStartCopy() throws RemoteException { 12314 synchronized (mInstallLock) { 12315 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12316 } 12317 12318 if (mSuccess) { 12319 final boolean mounted; 12320 if (Environment.isExternalStorageEmulated()) { 12321 mounted = true; 12322 } else { 12323 final String status = Environment.getExternalStorageState(); 12324 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12325 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12326 } 12327 12328 if (mounted) { 12329 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12330 12331 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12332 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12333 12334 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12335 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12336 12337 // Always subtract cache size, since it's a subdirectory 12338 mStats.externalDataSize -= mStats.externalCacheSize; 12339 12340 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12341 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12342 12343 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12344 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12345 } 12346 } 12347 } 12348 12349 @Override 12350 void handleReturnCode() { 12351 if (mObserver != null) { 12352 try { 12353 mObserver.onGetStatsCompleted(mStats, mSuccess); 12354 } catch (RemoteException e) { 12355 Slog.i(TAG, "Observer no longer exists."); 12356 } 12357 } 12358 } 12359 12360 @Override 12361 void handleServiceError() { 12362 Slog.e(TAG, "Could not measure application " + mStats.packageName 12363 + " external storage"); 12364 } 12365 } 12366 12367 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12368 throws RemoteException { 12369 long result = 0; 12370 for (File path : paths) { 12371 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12372 } 12373 return result; 12374 } 12375 12376 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12377 for (File path : paths) { 12378 try { 12379 mcs.clearDirectory(path.getAbsolutePath()); 12380 } catch (RemoteException e) { 12381 } 12382 } 12383 } 12384 12385 static class OriginInfo { 12386 /** 12387 * Location where install is coming from, before it has been 12388 * copied/renamed into place. This could be a single monolithic APK 12389 * file, or a cluster directory. This location may be untrusted. 12390 */ 12391 final File file; 12392 final String cid; 12393 12394 /** 12395 * Flag indicating that {@link #file} or {@link #cid} has already been 12396 * staged, meaning downstream users don't need to defensively copy the 12397 * contents. 12398 */ 12399 final boolean staged; 12400 12401 /** 12402 * Flag indicating that {@link #file} or {@link #cid} is an already 12403 * installed app that is being moved. 12404 */ 12405 final boolean existing; 12406 12407 final String resolvedPath; 12408 final File resolvedFile; 12409 12410 static OriginInfo fromNothing() { 12411 return new OriginInfo(null, null, false, false); 12412 } 12413 12414 static OriginInfo fromUntrustedFile(File file) { 12415 return new OriginInfo(file, null, false, false); 12416 } 12417 12418 static OriginInfo fromExistingFile(File file) { 12419 return new OriginInfo(file, null, false, true); 12420 } 12421 12422 static OriginInfo fromStagedFile(File file) { 12423 return new OriginInfo(file, null, true, false); 12424 } 12425 12426 static OriginInfo fromStagedContainer(String cid) { 12427 return new OriginInfo(null, cid, true, false); 12428 } 12429 12430 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12431 this.file = file; 12432 this.cid = cid; 12433 this.staged = staged; 12434 this.existing = existing; 12435 12436 if (cid != null) { 12437 resolvedPath = PackageHelper.getSdDir(cid); 12438 resolvedFile = new File(resolvedPath); 12439 } else if (file != null) { 12440 resolvedPath = file.getAbsolutePath(); 12441 resolvedFile = file; 12442 } else { 12443 resolvedPath = null; 12444 resolvedFile = null; 12445 } 12446 } 12447 } 12448 12449 static class MoveInfo { 12450 final int moveId; 12451 final String fromUuid; 12452 final String toUuid; 12453 final String packageName; 12454 final String dataAppName; 12455 final int appId; 12456 final String seinfo; 12457 final int targetSdkVersion; 12458 12459 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12460 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12461 this.moveId = moveId; 12462 this.fromUuid = fromUuid; 12463 this.toUuid = toUuid; 12464 this.packageName = packageName; 12465 this.dataAppName = dataAppName; 12466 this.appId = appId; 12467 this.seinfo = seinfo; 12468 this.targetSdkVersion = targetSdkVersion; 12469 } 12470 } 12471 12472 static class VerificationInfo { 12473 /** A constant used to indicate that a uid value is not present. */ 12474 public static final int NO_UID = -1; 12475 12476 /** URI referencing where the package was downloaded from. */ 12477 final Uri originatingUri; 12478 12479 /** HTTP referrer URI associated with the originatingURI. */ 12480 final Uri referrer; 12481 12482 /** UID of the application that the install request originated from. */ 12483 final int originatingUid; 12484 12485 /** UID of application requesting the install */ 12486 final int installerUid; 12487 12488 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12489 this.originatingUri = originatingUri; 12490 this.referrer = referrer; 12491 this.originatingUid = originatingUid; 12492 this.installerUid = installerUid; 12493 } 12494 } 12495 12496 class InstallParams extends HandlerParams { 12497 final OriginInfo origin; 12498 final MoveInfo move; 12499 final IPackageInstallObserver2 observer; 12500 int installFlags; 12501 final String installerPackageName; 12502 final String volumeUuid; 12503 private InstallArgs mArgs; 12504 private int mRet; 12505 final String packageAbiOverride; 12506 final String[] grantedRuntimePermissions; 12507 final VerificationInfo verificationInfo; 12508 final Certificate[][] certificates; 12509 12510 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12511 int installFlags, String installerPackageName, String volumeUuid, 12512 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12513 String[] grantedPermissions, Certificate[][] certificates) { 12514 super(user); 12515 this.origin = origin; 12516 this.move = move; 12517 this.observer = observer; 12518 this.installFlags = installFlags; 12519 this.installerPackageName = installerPackageName; 12520 this.volumeUuid = volumeUuid; 12521 this.verificationInfo = verificationInfo; 12522 this.packageAbiOverride = packageAbiOverride; 12523 this.grantedRuntimePermissions = grantedPermissions; 12524 this.certificates = certificates; 12525 } 12526 12527 @Override 12528 public String toString() { 12529 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12530 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12531 } 12532 12533 private int installLocationPolicy(PackageInfoLite pkgLite) { 12534 String packageName = pkgLite.packageName; 12535 int installLocation = pkgLite.installLocation; 12536 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12537 // reader 12538 synchronized (mPackages) { 12539 // Currently installed package which the new package is attempting to replace or 12540 // null if no such package is installed. 12541 PackageParser.Package installedPkg = mPackages.get(packageName); 12542 // Package which currently owns the data which the new package will own if installed. 12543 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12544 // will be null whereas dataOwnerPkg will contain information about the package 12545 // which was uninstalled while keeping its data. 12546 PackageParser.Package dataOwnerPkg = installedPkg; 12547 if (dataOwnerPkg == null) { 12548 PackageSetting ps = mSettings.mPackages.get(packageName); 12549 if (ps != null) { 12550 dataOwnerPkg = ps.pkg; 12551 } 12552 } 12553 12554 if (dataOwnerPkg != null) { 12555 // If installed, the package will get access to data left on the device by its 12556 // predecessor. As a security measure, this is permited only if this is not a 12557 // version downgrade or if the predecessor package is marked as debuggable and 12558 // a downgrade is explicitly requested. 12559 // 12560 // On debuggable platform builds, downgrades are permitted even for 12561 // non-debuggable packages to make testing easier. Debuggable platform builds do 12562 // not offer security guarantees and thus it's OK to disable some security 12563 // mechanisms to make debugging/testing easier on those builds. However, even on 12564 // debuggable builds downgrades of packages are permitted only if requested via 12565 // installFlags. This is because we aim to keep the behavior of debuggable 12566 // platform builds as close as possible to the behavior of non-debuggable 12567 // platform builds. 12568 final boolean downgradeRequested = 12569 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12570 final boolean packageDebuggable = 12571 (dataOwnerPkg.applicationInfo.flags 12572 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12573 final boolean downgradePermitted = 12574 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12575 if (!downgradePermitted) { 12576 try { 12577 checkDowngrade(dataOwnerPkg, pkgLite); 12578 } catch (PackageManagerException e) { 12579 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12580 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12581 } 12582 } 12583 } 12584 12585 if (installedPkg != null) { 12586 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12587 // Check for updated system application. 12588 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12589 if (onSd) { 12590 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12591 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12592 } 12593 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12594 } else { 12595 if (onSd) { 12596 // Install flag overrides everything. 12597 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12598 } 12599 // If current upgrade specifies particular preference 12600 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12601 // Application explicitly specified internal. 12602 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12603 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12604 // App explictly prefers external. Let policy decide 12605 } else { 12606 // Prefer previous location 12607 if (isExternal(installedPkg)) { 12608 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12609 } 12610 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12611 } 12612 } 12613 } else { 12614 // Invalid install. Return error code 12615 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12616 } 12617 } 12618 } 12619 // All the special cases have been taken care of. 12620 // Return result based on recommended install location. 12621 if (onSd) { 12622 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12623 } 12624 return pkgLite.recommendedInstallLocation; 12625 } 12626 12627 /* 12628 * Invoke remote method to get package information and install 12629 * location values. Override install location based on default 12630 * policy if needed and then create install arguments based 12631 * on the install location. 12632 */ 12633 public void handleStartCopy() throws RemoteException { 12634 int ret = PackageManager.INSTALL_SUCCEEDED; 12635 12636 // If we're already staged, we've firmly committed to an install location 12637 if (origin.staged) { 12638 if (origin.file != null) { 12639 installFlags |= PackageManager.INSTALL_INTERNAL; 12640 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12641 } else if (origin.cid != null) { 12642 installFlags |= PackageManager.INSTALL_EXTERNAL; 12643 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12644 } else { 12645 throw new IllegalStateException("Invalid stage location"); 12646 } 12647 } 12648 12649 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12650 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12651 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12652 PackageInfoLite pkgLite = null; 12653 12654 if (onInt && onSd) { 12655 // Check if both bits are set. 12656 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12657 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12658 } else if (onSd && ephemeral) { 12659 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12660 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12661 } else { 12662 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12663 packageAbiOverride); 12664 12665 if (DEBUG_EPHEMERAL && ephemeral) { 12666 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12667 } 12668 12669 /* 12670 * If we have too little free space, try to free cache 12671 * before giving up. 12672 */ 12673 if (!origin.staged && pkgLite.recommendedInstallLocation 12674 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12675 // TODO: focus freeing disk space on the target device 12676 final StorageManager storage = StorageManager.from(mContext); 12677 final long lowThreshold = storage.getStorageLowBytes( 12678 Environment.getDataDirectory()); 12679 12680 final long sizeBytes = mContainerService.calculateInstalledSize( 12681 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12682 12683 try { 12684 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12685 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12686 installFlags, packageAbiOverride); 12687 } catch (InstallerException e) { 12688 Slog.w(TAG, "Failed to free cache", e); 12689 } 12690 12691 /* 12692 * The cache free must have deleted the file we 12693 * downloaded to install. 12694 * 12695 * TODO: fix the "freeCache" call to not delete 12696 * the file we care about. 12697 */ 12698 if (pkgLite.recommendedInstallLocation 12699 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12700 pkgLite.recommendedInstallLocation 12701 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12702 } 12703 } 12704 } 12705 12706 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12707 int loc = pkgLite.recommendedInstallLocation; 12708 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12709 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12710 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12711 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12712 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12713 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12714 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12715 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12716 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12717 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12718 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12719 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12720 } else { 12721 // Override with defaults if needed. 12722 loc = installLocationPolicy(pkgLite); 12723 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12724 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12725 } else if (!onSd && !onInt) { 12726 // Override install location with flags 12727 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12728 // Set the flag to install on external media. 12729 installFlags |= PackageManager.INSTALL_EXTERNAL; 12730 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12731 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12732 if (DEBUG_EPHEMERAL) { 12733 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12734 } 12735 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12736 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12737 |PackageManager.INSTALL_INTERNAL); 12738 } else { 12739 // Make sure the flag for installing on external 12740 // media is unset 12741 installFlags |= PackageManager.INSTALL_INTERNAL; 12742 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12743 } 12744 } 12745 } 12746 } 12747 12748 final InstallArgs args = createInstallArgs(this); 12749 mArgs = args; 12750 12751 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12752 // TODO: http://b/22976637 12753 // Apps installed for "all" users use the device owner to verify the app 12754 UserHandle verifierUser = getUser(); 12755 if (verifierUser == UserHandle.ALL) { 12756 verifierUser = UserHandle.SYSTEM; 12757 } 12758 12759 /* 12760 * Determine if we have any installed package verifiers. If we 12761 * do, then we'll defer to them to verify the packages. 12762 */ 12763 final int requiredUid = mRequiredVerifierPackage == null ? -1 12764 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12765 verifierUser.getIdentifier()); 12766 if (!origin.existing && requiredUid != -1 12767 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12768 final Intent verification = new Intent( 12769 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12770 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12771 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12772 PACKAGE_MIME_TYPE); 12773 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12774 12775 // Query all live verifiers based on current user state 12776 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12777 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12778 12779 if (DEBUG_VERIFY) { 12780 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12781 + verification.toString() + " with " + pkgLite.verifiers.length 12782 + " optional verifiers"); 12783 } 12784 12785 final int verificationId = mPendingVerificationToken++; 12786 12787 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12788 12789 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12790 installerPackageName); 12791 12792 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12793 installFlags); 12794 12795 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12796 pkgLite.packageName); 12797 12798 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12799 pkgLite.versionCode); 12800 12801 if (verificationInfo != null) { 12802 if (verificationInfo.originatingUri != null) { 12803 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12804 verificationInfo.originatingUri); 12805 } 12806 if (verificationInfo.referrer != null) { 12807 verification.putExtra(Intent.EXTRA_REFERRER, 12808 verificationInfo.referrer); 12809 } 12810 if (verificationInfo.originatingUid >= 0) { 12811 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12812 verificationInfo.originatingUid); 12813 } 12814 if (verificationInfo.installerUid >= 0) { 12815 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12816 verificationInfo.installerUid); 12817 } 12818 } 12819 12820 final PackageVerificationState verificationState = new PackageVerificationState( 12821 requiredUid, args); 12822 12823 mPendingVerification.append(verificationId, verificationState); 12824 12825 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12826 receivers, verificationState); 12827 12828 /* 12829 * If any sufficient verifiers were listed in the package 12830 * manifest, attempt to ask them. 12831 */ 12832 if (sufficientVerifiers != null) { 12833 final int N = sufficientVerifiers.size(); 12834 if (N == 0) { 12835 Slog.i(TAG, "Additional verifiers required, but none installed."); 12836 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12837 } else { 12838 for (int i = 0; i < N; i++) { 12839 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12840 12841 final Intent sufficientIntent = new Intent(verification); 12842 sufficientIntent.setComponent(verifierComponent); 12843 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12844 } 12845 } 12846 } 12847 12848 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12849 mRequiredVerifierPackage, receivers); 12850 if (ret == PackageManager.INSTALL_SUCCEEDED 12851 && mRequiredVerifierPackage != null) { 12852 Trace.asyncTraceBegin( 12853 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12854 /* 12855 * Send the intent to the required verification agent, 12856 * but only start the verification timeout after the 12857 * target BroadcastReceivers have run. 12858 */ 12859 verification.setComponent(requiredVerifierComponent); 12860 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12861 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12862 new BroadcastReceiver() { 12863 @Override 12864 public void onReceive(Context context, Intent intent) { 12865 final Message msg = mHandler 12866 .obtainMessage(CHECK_PENDING_VERIFICATION); 12867 msg.arg1 = verificationId; 12868 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12869 } 12870 }, null, 0, null, null); 12871 12872 /* 12873 * We don't want the copy to proceed until verification 12874 * succeeds, so null out this field. 12875 */ 12876 mArgs = null; 12877 } 12878 } else { 12879 /* 12880 * No package verification is enabled, so immediately start 12881 * the remote call to initiate copy using temporary file. 12882 */ 12883 ret = args.copyApk(mContainerService, true); 12884 } 12885 } 12886 12887 mRet = ret; 12888 } 12889 12890 @Override 12891 void handleReturnCode() { 12892 // If mArgs is null, then MCS couldn't be reached. When it 12893 // reconnects, it will try again to install. At that point, this 12894 // will succeed. 12895 if (mArgs != null) { 12896 processPendingInstall(mArgs, mRet); 12897 } 12898 } 12899 12900 @Override 12901 void handleServiceError() { 12902 mArgs = createInstallArgs(this); 12903 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12904 } 12905 12906 public boolean isForwardLocked() { 12907 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12908 } 12909 } 12910 12911 /** 12912 * Used during creation of InstallArgs 12913 * 12914 * @param installFlags package installation flags 12915 * @return true if should be installed on external storage 12916 */ 12917 private static boolean installOnExternalAsec(int installFlags) { 12918 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12919 return false; 12920 } 12921 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12922 return true; 12923 } 12924 return false; 12925 } 12926 12927 /** 12928 * Used during creation of InstallArgs 12929 * 12930 * @param installFlags package installation flags 12931 * @return true if should be installed as forward locked 12932 */ 12933 private static boolean installForwardLocked(int installFlags) { 12934 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12935 } 12936 12937 private InstallArgs createInstallArgs(InstallParams params) { 12938 if (params.move != null) { 12939 return new MoveInstallArgs(params); 12940 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12941 return new AsecInstallArgs(params); 12942 } else { 12943 return new FileInstallArgs(params); 12944 } 12945 } 12946 12947 /** 12948 * Create args that describe an existing installed package. Typically used 12949 * when cleaning up old installs, or used as a move source. 12950 */ 12951 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12952 String resourcePath, String[] instructionSets) { 12953 final boolean isInAsec; 12954 if (installOnExternalAsec(installFlags)) { 12955 /* Apps on SD card are always in ASEC containers. */ 12956 isInAsec = true; 12957 } else if (installForwardLocked(installFlags) 12958 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12959 /* 12960 * Forward-locked apps are only in ASEC containers if they're the 12961 * new style 12962 */ 12963 isInAsec = true; 12964 } else { 12965 isInAsec = false; 12966 } 12967 12968 if (isInAsec) { 12969 return new AsecInstallArgs(codePath, instructionSets, 12970 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12971 } else { 12972 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12973 } 12974 } 12975 12976 static abstract class InstallArgs { 12977 /** @see InstallParams#origin */ 12978 final OriginInfo origin; 12979 /** @see InstallParams#move */ 12980 final MoveInfo move; 12981 12982 final IPackageInstallObserver2 observer; 12983 // Always refers to PackageManager flags only 12984 final int installFlags; 12985 final String installerPackageName; 12986 final String volumeUuid; 12987 final UserHandle user; 12988 final String abiOverride; 12989 final String[] installGrantPermissions; 12990 /** If non-null, drop an async trace when the install completes */ 12991 final String traceMethod; 12992 final int traceCookie; 12993 final Certificate[][] certificates; 12994 12995 // The list of instruction sets supported by this app. This is currently 12996 // only used during the rmdex() phase to clean up resources. We can get rid of this 12997 // if we move dex files under the common app path. 12998 /* nullable */ String[] instructionSets; 12999 13000 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13001 int installFlags, String installerPackageName, String volumeUuid, 13002 UserHandle user, String[] instructionSets, 13003 String abiOverride, String[] installGrantPermissions, 13004 String traceMethod, int traceCookie, Certificate[][] certificates) { 13005 this.origin = origin; 13006 this.move = move; 13007 this.installFlags = installFlags; 13008 this.observer = observer; 13009 this.installerPackageName = installerPackageName; 13010 this.volumeUuid = volumeUuid; 13011 this.user = user; 13012 this.instructionSets = instructionSets; 13013 this.abiOverride = abiOverride; 13014 this.installGrantPermissions = installGrantPermissions; 13015 this.traceMethod = traceMethod; 13016 this.traceCookie = traceCookie; 13017 this.certificates = certificates; 13018 } 13019 13020 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13021 abstract int doPreInstall(int status); 13022 13023 /** 13024 * Rename package into final resting place. All paths on the given 13025 * scanned package should be updated to reflect the rename. 13026 */ 13027 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13028 abstract int doPostInstall(int status, int uid); 13029 13030 /** @see PackageSettingBase#codePathString */ 13031 abstract String getCodePath(); 13032 /** @see PackageSettingBase#resourcePathString */ 13033 abstract String getResourcePath(); 13034 13035 // Need installer lock especially for dex file removal. 13036 abstract void cleanUpResourcesLI(); 13037 abstract boolean doPostDeleteLI(boolean delete); 13038 13039 /** 13040 * Called before the source arguments are copied. This is used mostly 13041 * for MoveParams when it needs to read the source file to put it in the 13042 * destination. 13043 */ 13044 int doPreCopy() { 13045 return PackageManager.INSTALL_SUCCEEDED; 13046 } 13047 13048 /** 13049 * Called after the source arguments are copied. This is used mostly for 13050 * MoveParams when it needs to read the source file to put it in the 13051 * destination. 13052 */ 13053 int doPostCopy(int uid) { 13054 return PackageManager.INSTALL_SUCCEEDED; 13055 } 13056 13057 protected boolean isFwdLocked() { 13058 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13059 } 13060 13061 protected boolean isExternalAsec() { 13062 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13063 } 13064 13065 protected boolean isEphemeral() { 13066 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13067 } 13068 13069 UserHandle getUser() { 13070 return user; 13071 } 13072 } 13073 13074 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13075 if (!allCodePaths.isEmpty()) { 13076 if (instructionSets == null) { 13077 throw new IllegalStateException("instructionSet == null"); 13078 } 13079 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13080 for (String codePath : allCodePaths) { 13081 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13082 try { 13083 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13084 } catch (InstallerException ignored) { 13085 } 13086 } 13087 } 13088 } 13089 } 13090 13091 /** 13092 * Logic to handle installation of non-ASEC applications, including copying 13093 * and renaming logic. 13094 */ 13095 class FileInstallArgs extends InstallArgs { 13096 private File codeFile; 13097 private File resourceFile; 13098 13099 // Example topology: 13100 // /data/app/com.example/base.apk 13101 // /data/app/com.example/split_foo.apk 13102 // /data/app/com.example/lib/arm/libfoo.so 13103 // /data/app/com.example/lib/arm64/libfoo.so 13104 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13105 13106 /** New install */ 13107 FileInstallArgs(InstallParams params) { 13108 super(params.origin, params.move, params.observer, params.installFlags, 13109 params.installerPackageName, params.volumeUuid, 13110 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13111 params.grantedRuntimePermissions, 13112 params.traceMethod, params.traceCookie, params.certificates); 13113 if (isFwdLocked()) { 13114 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13115 } 13116 } 13117 13118 /** Existing install */ 13119 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13120 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13121 null, null, null, 0, null /*certificates*/); 13122 this.codeFile = (codePath != null) ? new File(codePath) : null; 13123 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13124 } 13125 13126 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13127 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13128 try { 13129 return doCopyApk(imcs, temp); 13130 } finally { 13131 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13132 } 13133 } 13134 13135 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13136 if (origin.staged) { 13137 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13138 codeFile = origin.file; 13139 resourceFile = origin.file; 13140 return PackageManager.INSTALL_SUCCEEDED; 13141 } 13142 13143 try { 13144 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13145 final File tempDir = 13146 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13147 codeFile = tempDir; 13148 resourceFile = tempDir; 13149 } catch (IOException e) { 13150 Slog.w(TAG, "Failed to create copy file: " + e); 13151 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13152 } 13153 13154 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13155 @Override 13156 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13157 if (!FileUtils.isValidExtFilename(name)) { 13158 throw new IllegalArgumentException("Invalid filename: " + name); 13159 } 13160 try { 13161 final File file = new File(codeFile, name); 13162 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13163 O_RDWR | O_CREAT, 0644); 13164 Os.chmod(file.getAbsolutePath(), 0644); 13165 return new ParcelFileDescriptor(fd); 13166 } catch (ErrnoException e) { 13167 throw new RemoteException("Failed to open: " + e.getMessage()); 13168 } 13169 } 13170 }; 13171 13172 int ret = PackageManager.INSTALL_SUCCEEDED; 13173 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13174 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13175 Slog.e(TAG, "Failed to copy package"); 13176 return ret; 13177 } 13178 13179 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13180 NativeLibraryHelper.Handle handle = null; 13181 try { 13182 handle = NativeLibraryHelper.Handle.create(codeFile); 13183 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13184 abiOverride); 13185 } catch (IOException e) { 13186 Slog.e(TAG, "Copying native libraries failed", e); 13187 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13188 } finally { 13189 IoUtils.closeQuietly(handle); 13190 } 13191 13192 return ret; 13193 } 13194 13195 int doPreInstall(int status) { 13196 if (status != PackageManager.INSTALL_SUCCEEDED) { 13197 cleanUp(); 13198 } 13199 return status; 13200 } 13201 13202 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13203 if (status != PackageManager.INSTALL_SUCCEEDED) { 13204 cleanUp(); 13205 return false; 13206 } 13207 13208 final File targetDir = codeFile.getParentFile(); 13209 final File beforeCodeFile = codeFile; 13210 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13211 13212 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13213 try { 13214 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13215 } catch (ErrnoException e) { 13216 Slog.w(TAG, "Failed to rename", e); 13217 return false; 13218 } 13219 13220 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13221 Slog.w(TAG, "Failed to restorecon"); 13222 return false; 13223 } 13224 13225 // Reflect the rename internally 13226 codeFile = afterCodeFile; 13227 resourceFile = afterCodeFile; 13228 13229 // Reflect the rename in scanned details 13230 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13231 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13232 afterCodeFile, pkg.baseCodePath)); 13233 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13234 afterCodeFile, pkg.splitCodePaths)); 13235 13236 // Reflect the rename in app info 13237 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13238 pkg.setApplicationInfoCodePath(pkg.codePath); 13239 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13240 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13241 pkg.setApplicationInfoResourcePath(pkg.codePath); 13242 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13243 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13244 13245 return true; 13246 } 13247 13248 int doPostInstall(int status, int uid) { 13249 if (status != PackageManager.INSTALL_SUCCEEDED) { 13250 cleanUp(); 13251 } 13252 return status; 13253 } 13254 13255 @Override 13256 String getCodePath() { 13257 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13258 } 13259 13260 @Override 13261 String getResourcePath() { 13262 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13263 } 13264 13265 private boolean cleanUp() { 13266 if (codeFile == null || !codeFile.exists()) { 13267 return false; 13268 } 13269 13270 removeCodePathLI(codeFile); 13271 13272 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13273 resourceFile.delete(); 13274 } 13275 13276 return true; 13277 } 13278 13279 void cleanUpResourcesLI() { 13280 // Try enumerating all code paths before deleting 13281 List<String> allCodePaths = Collections.EMPTY_LIST; 13282 if (codeFile != null && codeFile.exists()) { 13283 try { 13284 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13285 allCodePaths = pkg.getAllCodePaths(); 13286 } catch (PackageParserException e) { 13287 // Ignored; we tried our best 13288 } 13289 } 13290 13291 cleanUp(); 13292 removeDexFiles(allCodePaths, instructionSets); 13293 } 13294 13295 boolean doPostDeleteLI(boolean delete) { 13296 // XXX err, shouldn't we respect the delete flag? 13297 cleanUpResourcesLI(); 13298 return true; 13299 } 13300 } 13301 13302 private boolean isAsecExternal(String cid) { 13303 final String asecPath = PackageHelper.getSdFilesystem(cid); 13304 return !asecPath.startsWith(mAsecInternalPath); 13305 } 13306 13307 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13308 PackageManagerException { 13309 if (copyRet < 0) { 13310 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13311 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13312 throw new PackageManagerException(copyRet, message); 13313 } 13314 } 13315 } 13316 13317 /** 13318 * Extract the MountService "container ID" from the full code path of an 13319 * .apk. 13320 */ 13321 static String cidFromCodePath(String fullCodePath) { 13322 int eidx = fullCodePath.lastIndexOf("/"); 13323 String subStr1 = fullCodePath.substring(0, eidx); 13324 int sidx = subStr1.lastIndexOf("/"); 13325 return subStr1.substring(sidx+1, eidx); 13326 } 13327 13328 /** 13329 * Logic to handle installation of ASEC applications, including copying and 13330 * renaming logic. 13331 */ 13332 class AsecInstallArgs extends InstallArgs { 13333 static final String RES_FILE_NAME = "pkg.apk"; 13334 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13335 13336 String cid; 13337 String packagePath; 13338 String resourcePath; 13339 13340 /** New install */ 13341 AsecInstallArgs(InstallParams params) { 13342 super(params.origin, params.move, params.observer, params.installFlags, 13343 params.installerPackageName, params.volumeUuid, 13344 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13345 params.grantedRuntimePermissions, 13346 params.traceMethod, params.traceCookie, params.certificates); 13347 } 13348 13349 /** Existing install */ 13350 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13351 boolean isExternal, boolean isForwardLocked) { 13352 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13353 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13354 instructionSets, null, null, null, 0, null /*certificates*/); 13355 // Hackily pretend we're still looking at a full code path 13356 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13357 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13358 } 13359 13360 // Extract cid from fullCodePath 13361 int eidx = fullCodePath.lastIndexOf("/"); 13362 String subStr1 = fullCodePath.substring(0, eidx); 13363 int sidx = subStr1.lastIndexOf("/"); 13364 cid = subStr1.substring(sidx+1, eidx); 13365 setMountPath(subStr1); 13366 } 13367 13368 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13369 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13370 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13371 instructionSets, null, null, null, 0, null /*certificates*/); 13372 this.cid = cid; 13373 setMountPath(PackageHelper.getSdDir(cid)); 13374 } 13375 13376 void createCopyFile() { 13377 cid = mInstallerService.allocateExternalStageCidLegacy(); 13378 } 13379 13380 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13381 if (origin.staged && origin.cid != null) { 13382 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13383 cid = origin.cid; 13384 setMountPath(PackageHelper.getSdDir(cid)); 13385 return PackageManager.INSTALL_SUCCEEDED; 13386 } 13387 13388 if (temp) { 13389 createCopyFile(); 13390 } else { 13391 /* 13392 * Pre-emptively destroy the container since it's destroyed if 13393 * copying fails due to it existing anyway. 13394 */ 13395 PackageHelper.destroySdDir(cid); 13396 } 13397 13398 final String newMountPath = imcs.copyPackageToContainer( 13399 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13400 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13401 13402 if (newMountPath != null) { 13403 setMountPath(newMountPath); 13404 return PackageManager.INSTALL_SUCCEEDED; 13405 } else { 13406 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13407 } 13408 } 13409 13410 @Override 13411 String getCodePath() { 13412 return packagePath; 13413 } 13414 13415 @Override 13416 String getResourcePath() { 13417 return resourcePath; 13418 } 13419 13420 int doPreInstall(int status) { 13421 if (status != PackageManager.INSTALL_SUCCEEDED) { 13422 // Destroy container 13423 PackageHelper.destroySdDir(cid); 13424 } else { 13425 boolean mounted = PackageHelper.isContainerMounted(cid); 13426 if (!mounted) { 13427 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13428 Process.SYSTEM_UID); 13429 if (newMountPath != null) { 13430 setMountPath(newMountPath); 13431 } else { 13432 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13433 } 13434 } 13435 } 13436 return status; 13437 } 13438 13439 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13440 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13441 String newMountPath = null; 13442 if (PackageHelper.isContainerMounted(cid)) { 13443 // Unmount the container 13444 if (!PackageHelper.unMountSdDir(cid)) { 13445 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13446 return false; 13447 } 13448 } 13449 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13450 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13451 " which might be stale. Will try to clean up."); 13452 // Clean up the stale container and proceed to recreate. 13453 if (!PackageHelper.destroySdDir(newCacheId)) { 13454 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13455 return false; 13456 } 13457 // Successfully cleaned up stale container. Try to rename again. 13458 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13459 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13460 + " inspite of cleaning it up."); 13461 return false; 13462 } 13463 } 13464 if (!PackageHelper.isContainerMounted(newCacheId)) { 13465 Slog.w(TAG, "Mounting container " + newCacheId); 13466 newMountPath = PackageHelper.mountSdDir(newCacheId, 13467 getEncryptKey(), Process.SYSTEM_UID); 13468 } else { 13469 newMountPath = PackageHelper.getSdDir(newCacheId); 13470 } 13471 if (newMountPath == null) { 13472 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13473 return false; 13474 } 13475 Log.i(TAG, "Succesfully renamed " + cid + 13476 " to " + newCacheId + 13477 " at new path: " + newMountPath); 13478 cid = newCacheId; 13479 13480 final File beforeCodeFile = new File(packagePath); 13481 setMountPath(newMountPath); 13482 final File afterCodeFile = new File(packagePath); 13483 13484 // Reflect the rename in scanned details 13485 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13486 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13487 afterCodeFile, pkg.baseCodePath)); 13488 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13489 afterCodeFile, pkg.splitCodePaths)); 13490 13491 // Reflect the rename in app info 13492 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13493 pkg.setApplicationInfoCodePath(pkg.codePath); 13494 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13495 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13496 pkg.setApplicationInfoResourcePath(pkg.codePath); 13497 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13498 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13499 13500 return true; 13501 } 13502 13503 private void setMountPath(String mountPath) { 13504 final File mountFile = new File(mountPath); 13505 13506 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13507 if (monolithicFile.exists()) { 13508 packagePath = monolithicFile.getAbsolutePath(); 13509 if (isFwdLocked()) { 13510 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13511 } else { 13512 resourcePath = packagePath; 13513 } 13514 } else { 13515 packagePath = mountFile.getAbsolutePath(); 13516 resourcePath = packagePath; 13517 } 13518 } 13519 13520 int doPostInstall(int status, int uid) { 13521 if (status != PackageManager.INSTALL_SUCCEEDED) { 13522 cleanUp(); 13523 } else { 13524 final int groupOwner; 13525 final String protectedFile; 13526 if (isFwdLocked()) { 13527 groupOwner = UserHandle.getSharedAppGid(uid); 13528 protectedFile = RES_FILE_NAME; 13529 } else { 13530 groupOwner = -1; 13531 protectedFile = null; 13532 } 13533 13534 if (uid < Process.FIRST_APPLICATION_UID 13535 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13536 Slog.e(TAG, "Failed to finalize " + cid); 13537 PackageHelper.destroySdDir(cid); 13538 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13539 } 13540 13541 boolean mounted = PackageHelper.isContainerMounted(cid); 13542 if (!mounted) { 13543 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13544 } 13545 } 13546 return status; 13547 } 13548 13549 private void cleanUp() { 13550 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13551 13552 // Destroy secure container 13553 PackageHelper.destroySdDir(cid); 13554 } 13555 13556 private List<String> getAllCodePaths() { 13557 final File codeFile = new File(getCodePath()); 13558 if (codeFile != null && codeFile.exists()) { 13559 try { 13560 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13561 return pkg.getAllCodePaths(); 13562 } catch (PackageParserException e) { 13563 // Ignored; we tried our best 13564 } 13565 } 13566 return Collections.EMPTY_LIST; 13567 } 13568 13569 void cleanUpResourcesLI() { 13570 // Enumerate all code paths before deleting 13571 cleanUpResourcesLI(getAllCodePaths()); 13572 } 13573 13574 private void cleanUpResourcesLI(List<String> allCodePaths) { 13575 cleanUp(); 13576 removeDexFiles(allCodePaths, instructionSets); 13577 } 13578 13579 String getPackageName() { 13580 return getAsecPackageName(cid); 13581 } 13582 13583 boolean doPostDeleteLI(boolean delete) { 13584 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13585 final List<String> allCodePaths = getAllCodePaths(); 13586 boolean mounted = PackageHelper.isContainerMounted(cid); 13587 if (mounted) { 13588 // Unmount first 13589 if (PackageHelper.unMountSdDir(cid)) { 13590 mounted = false; 13591 } 13592 } 13593 if (!mounted && delete) { 13594 cleanUpResourcesLI(allCodePaths); 13595 } 13596 return !mounted; 13597 } 13598 13599 @Override 13600 int doPreCopy() { 13601 if (isFwdLocked()) { 13602 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13603 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13604 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13605 } 13606 } 13607 13608 return PackageManager.INSTALL_SUCCEEDED; 13609 } 13610 13611 @Override 13612 int doPostCopy(int uid) { 13613 if (isFwdLocked()) { 13614 if (uid < Process.FIRST_APPLICATION_UID 13615 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13616 RES_FILE_NAME)) { 13617 Slog.e(TAG, "Failed to finalize " + cid); 13618 PackageHelper.destroySdDir(cid); 13619 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13620 } 13621 } 13622 13623 return PackageManager.INSTALL_SUCCEEDED; 13624 } 13625 } 13626 13627 /** 13628 * Logic to handle movement of existing installed applications. 13629 */ 13630 class MoveInstallArgs extends InstallArgs { 13631 private File codeFile; 13632 private File resourceFile; 13633 13634 /** New install */ 13635 MoveInstallArgs(InstallParams params) { 13636 super(params.origin, params.move, params.observer, params.installFlags, 13637 params.installerPackageName, params.volumeUuid, 13638 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13639 params.grantedRuntimePermissions, 13640 params.traceMethod, params.traceCookie, params.certificates); 13641 } 13642 13643 int copyApk(IMediaContainerService imcs, boolean temp) { 13644 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13645 + move.fromUuid + " to " + move.toUuid); 13646 synchronized (mInstaller) { 13647 try { 13648 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13649 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13650 } catch (InstallerException e) { 13651 Slog.w(TAG, "Failed to move app", e); 13652 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13653 } 13654 } 13655 13656 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13657 resourceFile = codeFile; 13658 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13659 13660 return PackageManager.INSTALL_SUCCEEDED; 13661 } 13662 13663 int doPreInstall(int status) { 13664 if (status != PackageManager.INSTALL_SUCCEEDED) { 13665 cleanUp(move.toUuid); 13666 } 13667 return status; 13668 } 13669 13670 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13671 if (status != PackageManager.INSTALL_SUCCEEDED) { 13672 cleanUp(move.toUuid); 13673 return false; 13674 } 13675 13676 // Reflect the move in app info 13677 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13678 pkg.setApplicationInfoCodePath(pkg.codePath); 13679 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13680 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13681 pkg.setApplicationInfoResourcePath(pkg.codePath); 13682 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13683 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13684 13685 return true; 13686 } 13687 13688 int doPostInstall(int status, int uid) { 13689 if (status == PackageManager.INSTALL_SUCCEEDED) { 13690 cleanUp(move.fromUuid); 13691 } else { 13692 cleanUp(move.toUuid); 13693 } 13694 return status; 13695 } 13696 13697 @Override 13698 String getCodePath() { 13699 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13700 } 13701 13702 @Override 13703 String getResourcePath() { 13704 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13705 } 13706 13707 private boolean cleanUp(String volumeUuid) { 13708 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13709 move.dataAppName); 13710 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13711 final int[] userIds = sUserManager.getUserIds(); 13712 synchronized (mInstallLock) { 13713 // Clean up both app data and code 13714 // All package moves are frozen until finished 13715 for (int userId : userIds) { 13716 try { 13717 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13718 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13719 } catch (InstallerException e) { 13720 Slog.w(TAG, String.valueOf(e)); 13721 } 13722 } 13723 removeCodePathLI(codeFile); 13724 } 13725 return true; 13726 } 13727 13728 void cleanUpResourcesLI() { 13729 throw new UnsupportedOperationException(); 13730 } 13731 13732 boolean doPostDeleteLI(boolean delete) { 13733 throw new UnsupportedOperationException(); 13734 } 13735 } 13736 13737 static String getAsecPackageName(String packageCid) { 13738 int idx = packageCid.lastIndexOf("-"); 13739 if (idx == -1) { 13740 return packageCid; 13741 } 13742 return packageCid.substring(0, idx); 13743 } 13744 13745 // Utility method used to create code paths based on package name and available index. 13746 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13747 String idxStr = ""; 13748 int idx = 1; 13749 // Fall back to default value of idx=1 if prefix is not 13750 // part of oldCodePath 13751 if (oldCodePath != null) { 13752 String subStr = oldCodePath; 13753 // Drop the suffix right away 13754 if (suffix != null && subStr.endsWith(suffix)) { 13755 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13756 } 13757 // If oldCodePath already contains prefix find out the 13758 // ending index to either increment or decrement. 13759 int sidx = subStr.lastIndexOf(prefix); 13760 if (sidx != -1) { 13761 subStr = subStr.substring(sidx + prefix.length()); 13762 if (subStr != null) { 13763 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13764 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13765 } 13766 try { 13767 idx = Integer.parseInt(subStr); 13768 if (idx <= 1) { 13769 idx++; 13770 } else { 13771 idx--; 13772 } 13773 } catch(NumberFormatException e) { 13774 } 13775 } 13776 } 13777 } 13778 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13779 return prefix + idxStr; 13780 } 13781 13782 private File getNextCodePath(File targetDir, String packageName) { 13783 int suffix = 1; 13784 File result; 13785 do { 13786 result = new File(targetDir, packageName + "-" + suffix); 13787 suffix++; 13788 } while (result.exists()); 13789 return result; 13790 } 13791 13792 // Utility method that returns the relative package path with respect 13793 // to the installation directory. Like say for /data/data/com.test-1.apk 13794 // string com.test-1 is returned. 13795 static String deriveCodePathName(String codePath) { 13796 if (codePath == null) { 13797 return null; 13798 } 13799 final File codeFile = new File(codePath); 13800 final String name = codeFile.getName(); 13801 if (codeFile.isDirectory()) { 13802 return name; 13803 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13804 final int lastDot = name.lastIndexOf('.'); 13805 return name.substring(0, lastDot); 13806 } else { 13807 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13808 return null; 13809 } 13810 } 13811 13812 static class PackageInstalledInfo { 13813 String name; 13814 int uid; 13815 // The set of users that originally had this package installed. 13816 int[] origUsers; 13817 // The set of users that now have this package installed. 13818 int[] newUsers; 13819 PackageParser.Package pkg; 13820 int returnCode; 13821 String returnMsg; 13822 PackageRemovedInfo removedInfo; 13823 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13824 13825 public void setError(int code, String msg) { 13826 setReturnCode(code); 13827 setReturnMessage(msg); 13828 Slog.w(TAG, msg); 13829 } 13830 13831 public void setError(String msg, PackageParserException e) { 13832 setReturnCode(e.error); 13833 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13834 Slog.w(TAG, msg, e); 13835 } 13836 13837 public void setError(String msg, PackageManagerException e) { 13838 returnCode = e.error; 13839 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13840 Slog.w(TAG, msg, e); 13841 } 13842 13843 public void setReturnCode(int returnCode) { 13844 this.returnCode = returnCode; 13845 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13846 for (int i = 0; i < childCount; i++) { 13847 addedChildPackages.valueAt(i).returnCode = returnCode; 13848 } 13849 } 13850 13851 private void setReturnMessage(String returnMsg) { 13852 this.returnMsg = returnMsg; 13853 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13854 for (int i = 0; i < childCount; i++) { 13855 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13856 } 13857 } 13858 13859 // In some error cases we want to convey more info back to the observer 13860 String origPackage; 13861 String origPermission; 13862 } 13863 13864 /* 13865 * Install a non-existing package. 13866 */ 13867 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13868 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13869 PackageInstalledInfo res) { 13870 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13871 13872 // Remember this for later, in case we need to rollback this install 13873 String pkgName = pkg.packageName; 13874 13875 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13876 13877 synchronized(mPackages) { 13878 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13879 // A package with the same name is already installed, though 13880 // it has been renamed to an older name. The package we 13881 // are trying to install should be installed as an update to 13882 // the existing one, but that has not been requested, so bail. 13883 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13884 + " without first uninstalling package running as " 13885 + mSettings.mRenamedPackages.get(pkgName)); 13886 return; 13887 } 13888 if (mPackages.containsKey(pkgName)) { 13889 // Don't allow installation over an existing package with the same name. 13890 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13891 + " without first uninstalling."); 13892 return; 13893 } 13894 } 13895 13896 try { 13897 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13898 System.currentTimeMillis(), user); 13899 13900 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13901 13902 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13903 prepareAppDataAfterInstallLIF(newPackage); 13904 13905 } else { 13906 // Remove package from internal structures, but keep around any 13907 // data that might have already existed 13908 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13909 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13910 } 13911 } catch (PackageManagerException e) { 13912 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13913 } 13914 13915 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13916 } 13917 13918 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13919 // Can't rotate keys during boot or if sharedUser. 13920 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13921 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13922 return false; 13923 } 13924 // app is using upgradeKeySets; make sure all are valid 13925 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13926 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13927 for (int i = 0; i < upgradeKeySets.length; i++) { 13928 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13929 Slog.wtf(TAG, "Package " 13930 + (oldPs.name != null ? oldPs.name : "<null>") 13931 + " contains upgrade-key-set reference to unknown key-set: " 13932 + upgradeKeySets[i] 13933 + " reverting to signatures check."); 13934 return false; 13935 } 13936 } 13937 return true; 13938 } 13939 13940 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13941 // Upgrade keysets are being used. Determine if new package has a superset of the 13942 // required keys. 13943 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13944 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13945 for (int i = 0; i < upgradeKeySets.length; i++) { 13946 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13947 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13948 return true; 13949 } 13950 } 13951 return false; 13952 } 13953 13954 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13955 try (DigestInputStream digestStream = 13956 new DigestInputStream(new FileInputStream(file), digest)) { 13957 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13958 } 13959 } 13960 13961 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13962 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13963 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13964 13965 final PackageParser.Package oldPackage; 13966 final String pkgName = pkg.packageName; 13967 final int[] allUsers; 13968 final int[] installedUsers; 13969 13970 synchronized(mPackages) { 13971 oldPackage = mPackages.get(pkgName); 13972 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13973 13974 // don't allow upgrade to target a release SDK from a pre-release SDK 13975 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13976 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13977 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13978 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13979 if (oldTargetsPreRelease 13980 && !newTargetsPreRelease 13981 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13982 Slog.w(TAG, "Can't install package targeting released sdk"); 13983 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13984 return; 13985 } 13986 13987 // don't allow an upgrade from full to ephemeral 13988 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13989 if (isEphemeral && !oldIsEphemeral) { 13990 // can't downgrade from full to ephemeral 13991 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13992 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13993 return; 13994 } 13995 13996 // verify signatures are valid 13997 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13998 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13999 if (!checkUpgradeKeySetLP(ps, pkg)) { 14000 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14001 "New package not signed by keys specified by upgrade-keysets: " 14002 + pkgName); 14003 return; 14004 } 14005 } else { 14006 // default to original signature matching 14007 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14008 != PackageManager.SIGNATURE_MATCH) { 14009 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14010 "New package has a different signature: " + pkgName); 14011 return; 14012 } 14013 } 14014 14015 // don't allow a system upgrade unless the upgrade hash matches 14016 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14017 byte[] digestBytes = null; 14018 try { 14019 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14020 updateDigest(digest, new File(pkg.baseCodePath)); 14021 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14022 for (String path : pkg.splitCodePaths) { 14023 updateDigest(digest, new File(path)); 14024 } 14025 } 14026 digestBytes = digest.digest(); 14027 } catch (NoSuchAlgorithmException | IOException e) { 14028 res.setError(INSTALL_FAILED_INVALID_APK, 14029 "Could not compute hash: " + pkgName); 14030 return; 14031 } 14032 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14033 res.setError(INSTALL_FAILED_INVALID_APK, 14034 "New package fails restrict-update check: " + pkgName); 14035 return; 14036 } 14037 // retain upgrade restriction 14038 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14039 } 14040 14041 // Check for shared user id changes 14042 String invalidPackageName = 14043 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14044 if (invalidPackageName != null) { 14045 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14046 "Package " + invalidPackageName + " tried to change user " 14047 + oldPackage.mSharedUserId); 14048 return; 14049 } 14050 14051 // In case of rollback, remember per-user/profile install state 14052 allUsers = sUserManager.getUserIds(); 14053 installedUsers = ps.queryInstalledUsers(allUsers, true); 14054 } 14055 14056 // Update what is removed 14057 res.removedInfo = new PackageRemovedInfo(); 14058 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14059 res.removedInfo.removedPackage = oldPackage.packageName; 14060 res.removedInfo.isUpdate = true; 14061 res.removedInfo.origUsers = installedUsers; 14062 final int childCount = (oldPackage.childPackages != null) 14063 ? oldPackage.childPackages.size() : 0; 14064 for (int i = 0; i < childCount; i++) { 14065 boolean childPackageUpdated = false; 14066 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14067 if (res.addedChildPackages != null) { 14068 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14069 if (childRes != null) { 14070 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14071 childRes.removedInfo.removedPackage = childPkg.packageName; 14072 childRes.removedInfo.isUpdate = true; 14073 childPackageUpdated = true; 14074 } 14075 } 14076 if (!childPackageUpdated) { 14077 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14078 childRemovedRes.removedPackage = childPkg.packageName; 14079 childRemovedRes.isUpdate = false; 14080 childRemovedRes.dataRemoved = true; 14081 synchronized (mPackages) { 14082 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14083 if (childPs != null) { 14084 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14085 } 14086 } 14087 if (res.removedInfo.removedChildPackages == null) { 14088 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14089 } 14090 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14091 } 14092 } 14093 14094 boolean sysPkg = (isSystemApp(oldPackage)); 14095 if (sysPkg) { 14096 // Set the system/privileged flags as needed 14097 final boolean privileged = 14098 (oldPackage.applicationInfo.privateFlags 14099 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14100 final int systemPolicyFlags = policyFlags 14101 | PackageParser.PARSE_IS_SYSTEM 14102 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14103 14104 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14105 user, allUsers, installerPackageName, res); 14106 } else { 14107 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14108 user, allUsers, installerPackageName, res); 14109 } 14110 } 14111 14112 public List<String> getPreviousCodePaths(String packageName) { 14113 final PackageSetting ps = mSettings.mPackages.get(packageName); 14114 final List<String> result = new ArrayList<String>(); 14115 if (ps != null && ps.oldCodePaths != null) { 14116 result.addAll(ps.oldCodePaths); 14117 } 14118 return result; 14119 } 14120 14121 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14122 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14123 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14124 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14125 + deletedPackage); 14126 14127 String pkgName = deletedPackage.packageName; 14128 boolean deletedPkg = true; 14129 boolean addedPkg = false; 14130 boolean updatedSettings = false; 14131 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14132 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14133 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14134 14135 final long origUpdateTime = (pkg.mExtras != null) 14136 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14137 14138 // First delete the existing package while retaining the data directory 14139 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14140 res.removedInfo, true, pkg)) { 14141 // If the existing package wasn't successfully deleted 14142 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14143 deletedPkg = false; 14144 } else { 14145 // Successfully deleted the old package; proceed with replace. 14146 14147 // If deleted package lived in a container, give users a chance to 14148 // relinquish resources before killing. 14149 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14150 if (DEBUG_INSTALL) { 14151 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14152 } 14153 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14154 final ArrayList<String> pkgList = new ArrayList<String>(1); 14155 pkgList.add(deletedPackage.applicationInfo.packageName); 14156 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14157 } 14158 14159 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14160 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14161 clearAppProfilesLIF(pkg); 14162 14163 try { 14164 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14165 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14166 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14167 14168 // Update the in-memory copy of the previous code paths. 14169 PackageSetting ps = mSettings.mPackages.get(pkgName); 14170 if (!killApp) { 14171 if (ps.oldCodePaths == null) { 14172 ps.oldCodePaths = new ArraySet<>(); 14173 } 14174 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14175 if (deletedPackage.splitCodePaths != null) { 14176 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14177 } 14178 } else { 14179 ps.oldCodePaths = null; 14180 } 14181 if (ps.childPackageNames != null) { 14182 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14183 final String childPkgName = ps.childPackageNames.get(i); 14184 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14185 childPs.oldCodePaths = ps.oldCodePaths; 14186 } 14187 } 14188 prepareAppDataAfterInstallLIF(newPackage); 14189 addedPkg = true; 14190 } catch (PackageManagerException e) { 14191 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14192 } 14193 } 14194 14195 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14196 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14197 14198 // Revert all internal state mutations and added folders for the failed install 14199 if (addedPkg) { 14200 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14201 res.removedInfo, true, null); 14202 } 14203 14204 // Restore the old package 14205 if (deletedPkg) { 14206 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14207 File restoreFile = new File(deletedPackage.codePath); 14208 // Parse old package 14209 boolean oldExternal = isExternal(deletedPackage); 14210 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14211 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14212 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14213 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14214 try { 14215 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14216 null); 14217 } catch (PackageManagerException e) { 14218 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14219 + e.getMessage()); 14220 return; 14221 } 14222 14223 synchronized (mPackages) { 14224 // Ensure the installer package name up to date 14225 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14226 14227 // Update permissions for restored package 14228 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14229 14230 mSettings.writeLPr(); 14231 } 14232 14233 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14234 } 14235 } else { 14236 synchronized (mPackages) { 14237 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14238 if (ps != null) { 14239 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14240 if (res.removedInfo.removedChildPackages != null) { 14241 final int childCount = res.removedInfo.removedChildPackages.size(); 14242 // Iterate in reverse as we may modify the collection 14243 for (int i = childCount - 1; i >= 0; i--) { 14244 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14245 if (res.addedChildPackages.containsKey(childPackageName)) { 14246 res.removedInfo.removedChildPackages.removeAt(i); 14247 } else { 14248 PackageRemovedInfo childInfo = res.removedInfo 14249 .removedChildPackages.valueAt(i); 14250 childInfo.removedForAllUsers = mPackages.get( 14251 childInfo.removedPackage) == null; 14252 } 14253 } 14254 } 14255 } 14256 } 14257 } 14258 } 14259 14260 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14261 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14262 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14263 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14264 + ", old=" + deletedPackage); 14265 14266 final boolean disabledSystem; 14267 14268 // Remove existing system package 14269 removePackageLI(deletedPackage, true); 14270 14271 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14272 if (!disabledSystem) { 14273 // We didn't need to disable the .apk as a current system package, 14274 // which means we are replacing another update that is already 14275 // installed. We need to make sure to delete the older one's .apk. 14276 res.removedInfo.args = createInstallArgsForExisting(0, 14277 deletedPackage.applicationInfo.getCodePath(), 14278 deletedPackage.applicationInfo.getResourcePath(), 14279 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14280 } else { 14281 res.removedInfo.args = null; 14282 } 14283 14284 // Successfully disabled the old package. Now proceed with re-installation 14285 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14286 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14287 clearAppProfilesLIF(pkg); 14288 14289 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14290 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14291 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14292 14293 PackageParser.Package newPackage = null; 14294 try { 14295 // Add the package to the internal data structures 14296 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14297 14298 // Set the update and install times 14299 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14300 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14301 System.currentTimeMillis()); 14302 14303 // Update the package dynamic state if succeeded 14304 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14305 // Now that the install succeeded make sure we remove data 14306 // directories for any child package the update removed. 14307 final int deletedChildCount = (deletedPackage.childPackages != null) 14308 ? deletedPackage.childPackages.size() : 0; 14309 final int newChildCount = (newPackage.childPackages != null) 14310 ? newPackage.childPackages.size() : 0; 14311 for (int i = 0; i < deletedChildCount; i++) { 14312 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14313 boolean childPackageDeleted = true; 14314 for (int j = 0; j < newChildCount; j++) { 14315 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14316 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14317 childPackageDeleted = false; 14318 break; 14319 } 14320 } 14321 if (childPackageDeleted) { 14322 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14323 deletedChildPkg.packageName); 14324 if (ps != null && res.removedInfo.removedChildPackages != null) { 14325 PackageRemovedInfo removedChildRes = res.removedInfo 14326 .removedChildPackages.get(deletedChildPkg.packageName); 14327 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14328 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14329 } 14330 } 14331 } 14332 14333 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14334 prepareAppDataAfterInstallLIF(newPackage); 14335 } 14336 } catch (PackageManagerException e) { 14337 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14338 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14339 } 14340 14341 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14342 // Re installation failed. Restore old information 14343 // Remove new pkg information 14344 if (newPackage != null) { 14345 removeInstalledPackageLI(newPackage, true); 14346 } 14347 // Add back the old system package 14348 try { 14349 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14350 } catch (PackageManagerException e) { 14351 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14352 } 14353 14354 synchronized (mPackages) { 14355 if (disabledSystem) { 14356 enableSystemPackageLPw(deletedPackage); 14357 } 14358 14359 // Ensure the installer package name up to date 14360 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14361 14362 // Update permissions for restored package 14363 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14364 14365 mSettings.writeLPr(); 14366 } 14367 14368 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14369 + " after failed upgrade"); 14370 } 14371 } 14372 14373 /** 14374 * Checks whether the parent or any of the child packages have a change shared 14375 * user. For a package to be a valid update the shred users of the parent and 14376 * the children should match. We may later support changing child shared users. 14377 * @param oldPkg The updated package. 14378 * @param newPkg The update package. 14379 * @return The shared user that change between the versions. 14380 */ 14381 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14382 PackageParser.Package newPkg) { 14383 // Check parent shared user 14384 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14385 return newPkg.packageName; 14386 } 14387 // Check child shared users 14388 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14389 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14390 for (int i = 0; i < newChildCount; i++) { 14391 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14392 // If this child was present, did it have the same shared user? 14393 for (int j = 0; j < oldChildCount; j++) { 14394 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14395 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14396 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14397 return newChildPkg.packageName; 14398 } 14399 } 14400 } 14401 return null; 14402 } 14403 14404 private void removeNativeBinariesLI(PackageSetting ps) { 14405 // Remove the lib path for the parent package 14406 if (ps != null) { 14407 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14408 // Remove the lib path for the child packages 14409 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14410 for (int i = 0; i < childCount; i++) { 14411 PackageSetting childPs = null; 14412 synchronized (mPackages) { 14413 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14414 } 14415 if (childPs != null) { 14416 NativeLibraryHelper.removeNativeBinariesLI(childPs 14417 .legacyNativeLibraryPathString); 14418 } 14419 } 14420 } 14421 } 14422 14423 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14424 // Enable the parent package 14425 mSettings.enableSystemPackageLPw(pkg.packageName); 14426 // Enable the child packages 14427 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14428 for (int i = 0; i < childCount; i++) { 14429 PackageParser.Package childPkg = pkg.childPackages.get(i); 14430 mSettings.enableSystemPackageLPw(childPkg.packageName); 14431 } 14432 } 14433 14434 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14435 PackageParser.Package newPkg) { 14436 // Disable the parent package (parent always replaced) 14437 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14438 // Disable the child packages 14439 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14440 for (int i = 0; i < childCount; i++) { 14441 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14442 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14443 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14444 } 14445 return disabled; 14446 } 14447 14448 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14449 String installerPackageName) { 14450 // Enable the parent package 14451 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14452 // Enable the child packages 14453 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14454 for (int i = 0; i < childCount; i++) { 14455 PackageParser.Package childPkg = pkg.childPackages.get(i); 14456 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14457 } 14458 } 14459 14460 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14461 // Collect all used permissions in the UID 14462 ArraySet<String> usedPermissions = new ArraySet<>(); 14463 final int packageCount = su.packages.size(); 14464 for (int i = 0; i < packageCount; i++) { 14465 PackageSetting ps = su.packages.valueAt(i); 14466 if (ps.pkg == null) { 14467 continue; 14468 } 14469 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14470 for (int j = 0; j < requestedPermCount; j++) { 14471 String permission = ps.pkg.requestedPermissions.get(j); 14472 BasePermission bp = mSettings.mPermissions.get(permission); 14473 if (bp != null) { 14474 usedPermissions.add(permission); 14475 } 14476 } 14477 } 14478 14479 PermissionsState permissionsState = su.getPermissionsState(); 14480 // Prune install permissions 14481 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14482 final int installPermCount = installPermStates.size(); 14483 for (int i = installPermCount - 1; i >= 0; i--) { 14484 PermissionState permissionState = installPermStates.get(i); 14485 if (!usedPermissions.contains(permissionState.getName())) { 14486 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14487 if (bp != null) { 14488 permissionsState.revokeInstallPermission(bp); 14489 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14490 PackageManager.MASK_PERMISSION_FLAGS, 0); 14491 } 14492 } 14493 } 14494 14495 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14496 14497 // Prune runtime permissions 14498 for (int userId : allUserIds) { 14499 List<PermissionState> runtimePermStates = permissionsState 14500 .getRuntimePermissionStates(userId); 14501 final int runtimePermCount = runtimePermStates.size(); 14502 for (int i = runtimePermCount - 1; i >= 0; i--) { 14503 PermissionState permissionState = runtimePermStates.get(i); 14504 if (!usedPermissions.contains(permissionState.getName())) { 14505 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14506 if (bp != null) { 14507 permissionsState.revokeRuntimePermission(bp, userId); 14508 permissionsState.updatePermissionFlags(bp, userId, 14509 PackageManager.MASK_PERMISSION_FLAGS, 0); 14510 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14511 runtimePermissionChangedUserIds, userId); 14512 } 14513 } 14514 } 14515 } 14516 14517 return runtimePermissionChangedUserIds; 14518 } 14519 14520 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14521 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14522 // Update the parent package setting 14523 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14524 res, user); 14525 // Update the child packages setting 14526 final int childCount = (newPackage.childPackages != null) 14527 ? newPackage.childPackages.size() : 0; 14528 for (int i = 0; i < childCount; i++) { 14529 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14530 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14531 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14532 childRes.origUsers, childRes, user); 14533 } 14534 } 14535 14536 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14537 String installerPackageName, int[] allUsers, int[] installedForUsers, 14538 PackageInstalledInfo res, UserHandle user) { 14539 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14540 14541 String pkgName = newPackage.packageName; 14542 synchronized (mPackages) { 14543 //write settings. the installStatus will be incomplete at this stage. 14544 //note that the new package setting would have already been 14545 //added to mPackages. It hasn't been persisted yet. 14546 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14548 mSettings.writeLPr(); 14549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14550 } 14551 14552 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14553 synchronized (mPackages) { 14554 updatePermissionsLPw(newPackage.packageName, newPackage, 14555 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14556 ? UPDATE_PERMISSIONS_ALL : 0)); 14557 // For system-bundled packages, we assume that installing an upgraded version 14558 // of the package implies that the user actually wants to run that new code, 14559 // so we enable the package. 14560 PackageSetting ps = mSettings.mPackages.get(pkgName); 14561 final int userId = user.getIdentifier(); 14562 if (ps != null) { 14563 if (isSystemApp(newPackage)) { 14564 if (DEBUG_INSTALL) { 14565 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14566 } 14567 // Enable system package for requested users 14568 if (res.origUsers != null) { 14569 for (int origUserId : res.origUsers) { 14570 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14571 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14572 origUserId, installerPackageName); 14573 } 14574 } 14575 } 14576 // Also convey the prior install/uninstall state 14577 if (allUsers != null && installedForUsers != null) { 14578 for (int currentUserId : allUsers) { 14579 final boolean installed = ArrayUtils.contains( 14580 installedForUsers, currentUserId); 14581 if (DEBUG_INSTALL) { 14582 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14583 } 14584 ps.setInstalled(installed, currentUserId); 14585 } 14586 // these install state changes will be persisted in the 14587 // upcoming call to mSettings.writeLPr(). 14588 } 14589 } 14590 // It's implied that when a user requests installation, they want the app to be 14591 // installed and enabled. 14592 if (userId != UserHandle.USER_ALL) { 14593 ps.setInstalled(true, userId); 14594 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14595 } 14596 } 14597 res.name = pkgName; 14598 res.uid = newPackage.applicationInfo.uid; 14599 res.pkg = newPackage; 14600 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14601 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14602 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14603 //to update install status 14604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14605 mSettings.writeLPr(); 14606 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14607 } 14608 14609 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14610 } 14611 14612 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14613 try { 14614 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14615 installPackageLI(args, res); 14616 } finally { 14617 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14618 } 14619 } 14620 14621 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14622 final int installFlags = args.installFlags; 14623 final String installerPackageName = args.installerPackageName; 14624 final String volumeUuid = args.volumeUuid; 14625 final File tmpPackageFile = new File(args.getCodePath()); 14626 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14627 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14628 || (args.volumeUuid != null)); 14629 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14630 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14631 boolean replace = false; 14632 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14633 if (args.move != null) { 14634 // moving a complete application; perform an initial scan on the new install location 14635 scanFlags |= SCAN_INITIAL; 14636 } 14637 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14638 scanFlags |= SCAN_DONT_KILL_APP; 14639 } 14640 14641 // Result object to be returned 14642 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14643 14644 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14645 14646 // Sanity check 14647 if (ephemeral && (forwardLocked || onExternal)) { 14648 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14649 + " external=" + onExternal); 14650 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14651 return; 14652 } 14653 14654 // Retrieve PackageSettings and parse package 14655 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14656 | PackageParser.PARSE_ENFORCE_CODE 14657 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14658 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14659 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14660 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14661 PackageParser pp = new PackageParser(); 14662 pp.setSeparateProcesses(mSeparateProcesses); 14663 pp.setDisplayMetrics(mMetrics); 14664 14665 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14666 final PackageParser.Package pkg; 14667 try { 14668 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14669 } catch (PackageParserException e) { 14670 res.setError("Failed parse during installPackageLI", e); 14671 return; 14672 } finally { 14673 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14674 } 14675 14676 // If we are installing a clustered package add results for the children 14677 if (pkg.childPackages != null) { 14678 synchronized (mPackages) { 14679 final int childCount = pkg.childPackages.size(); 14680 for (int i = 0; i < childCount; i++) { 14681 PackageParser.Package childPkg = pkg.childPackages.get(i); 14682 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14683 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14684 childRes.pkg = childPkg; 14685 childRes.name = childPkg.packageName; 14686 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14687 if (childPs != null) { 14688 childRes.origUsers = childPs.queryInstalledUsers( 14689 sUserManager.getUserIds(), true); 14690 } 14691 if ((mPackages.containsKey(childPkg.packageName))) { 14692 childRes.removedInfo = new PackageRemovedInfo(); 14693 childRes.removedInfo.removedPackage = childPkg.packageName; 14694 } 14695 if (res.addedChildPackages == null) { 14696 res.addedChildPackages = new ArrayMap<>(); 14697 } 14698 res.addedChildPackages.put(childPkg.packageName, childRes); 14699 } 14700 } 14701 } 14702 14703 // If package doesn't declare API override, mark that we have an install 14704 // time CPU ABI override. 14705 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14706 pkg.cpuAbiOverride = args.abiOverride; 14707 } 14708 14709 String pkgName = res.name = pkg.packageName; 14710 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14711 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14712 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14713 return; 14714 } 14715 } 14716 14717 try { 14718 // either use what we've been given or parse directly from the APK 14719 if (args.certificates != null) { 14720 try { 14721 PackageParser.populateCertificates(pkg, args.certificates); 14722 } catch (PackageParserException e) { 14723 // there was something wrong with the certificates we were given; 14724 // try to pull them from the APK 14725 PackageParser.collectCertificates(pkg, parseFlags); 14726 } 14727 } else { 14728 PackageParser.collectCertificates(pkg, parseFlags); 14729 } 14730 } catch (PackageParserException e) { 14731 res.setError("Failed collect during installPackageLI", e); 14732 return; 14733 } 14734 14735 // Get rid of all references to package scan path via parser. 14736 pp = null; 14737 String oldCodePath = null; 14738 boolean systemApp = false; 14739 synchronized (mPackages) { 14740 // Check if installing already existing package 14741 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14742 String oldName = mSettings.mRenamedPackages.get(pkgName); 14743 if (pkg.mOriginalPackages != null 14744 && pkg.mOriginalPackages.contains(oldName) 14745 && mPackages.containsKey(oldName)) { 14746 // This package is derived from an original package, 14747 // and this device has been updating from that original 14748 // name. We must continue using the original name, so 14749 // rename the new package here. 14750 pkg.setPackageName(oldName); 14751 pkgName = pkg.packageName; 14752 replace = true; 14753 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14754 + oldName + " pkgName=" + pkgName); 14755 } else if (mPackages.containsKey(pkgName)) { 14756 // This package, under its official name, already exists 14757 // on the device; we should replace it. 14758 replace = true; 14759 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14760 } 14761 14762 // Child packages are installed through the parent package 14763 if (pkg.parentPackage != null) { 14764 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14765 "Package " + pkg.packageName + " is child of package " 14766 + pkg.parentPackage.parentPackage + ". Child packages " 14767 + "can be updated only through the parent package."); 14768 return; 14769 } 14770 14771 if (replace) { 14772 // Prevent apps opting out from runtime permissions 14773 PackageParser.Package oldPackage = mPackages.get(pkgName); 14774 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14775 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14776 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14777 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14778 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14779 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14780 + " doesn't support runtime permissions but the old" 14781 + " target SDK " + oldTargetSdk + " does."); 14782 return; 14783 } 14784 14785 // Prevent installing of child packages 14786 if (oldPackage.parentPackage != null) { 14787 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14788 "Package " + pkg.packageName + " is child of package " 14789 + oldPackage.parentPackage + ". Child packages " 14790 + "can be updated only through the parent package."); 14791 return; 14792 } 14793 } 14794 } 14795 14796 PackageSetting ps = mSettings.mPackages.get(pkgName); 14797 if (ps != null) { 14798 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14799 14800 // Quick sanity check that we're signed correctly if updating; 14801 // we'll check this again later when scanning, but we want to 14802 // bail early here before tripping over redefined permissions. 14803 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14804 if (!checkUpgradeKeySetLP(ps, pkg)) { 14805 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14806 + pkg.packageName + " upgrade keys do not match the " 14807 + "previously installed version"); 14808 return; 14809 } 14810 } else { 14811 try { 14812 verifySignaturesLP(ps, pkg); 14813 } catch (PackageManagerException e) { 14814 res.setError(e.error, e.getMessage()); 14815 return; 14816 } 14817 } 14818 14819 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14820 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14821 systemApp = (ps.pkg.applicationInfo.flags & 14822 ApplicationInfo.FLAG_SYSTEM) != 0; 14823 } 14824 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14825 } 14826 14827 // Check whether the newly-scanned package wants to define an already-defined perm 14828 int N = pkg.permissions.size(); 14829 for (int i = N-1; i >= 0; i--) { 14830 PackageParser.Permission perm = pkg.permissions.get(i); 14831 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14832 if (bp != null) { 14833 // If the defining package is signed with our cert, it's okay. This 14834 // also includes the "updating the same package" case, of course. 14835 // "updating same package" could also involve key-rotation. 14836 final boolean sigsOk; 14837 if (bp.sourcePackage.equals(pkg.packageName) 14838 && (bp.packageSetting instanceof PackageSetting) 14839 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14840 scanFlags))) { 14841 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14842 } else { 14843 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14844 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14845 } 14846 if (!sigsOk) { 14847 // If the owning package is the system itself, we log but allow 14848 // install to proceed; we fail the install on all other permission 14849 // redefinitions. 14850 if (!bp.sourcePackage.equals("android")) { 14851 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14852 + pkg.packageName + " attempting to redeclare permission " 14853 + perm.info.name + " already owned by " + bp.sourcePackage); 14854 res.origPermission = perm.info.name; 14855 res.origPackage = bp.sourcePackage; 14856 return; 14857 } else { 14858 Slog.w(TAG, "Package " + pkg.packageName 14859 + " attempting to redeclare system permission " 14860 + perm.info.name + "; ignoring new declaration"); 14861 pkg.permissions.remove(i); 14862 } 14863 } 14864 } 14865 } 14866 } 14867 14868 if (systemApp) { 14869 if (onExternal) { 14870 // Abort update; system app can't be replaced with app on sdcard 14871 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14872 "Cannot install updates to system apps on sdcard"); 14873 return; 14874 } else if (ephemeral) { 14875 // Abort update; system app can't be replaced with an ephemeral app 14876 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14877 "Cannot update a system app with an ephemeral app"); 14878 return; 14879 } 14880 } 14881 14882 if (args.move != null) { 14883 // We did an in-place move, so dex is ready to roll 14884 scanFlags |= SCAN_NO_DEX; 14885 scanFlags |= SCAN_MOVE; 14886 14887 synchronized (mPackages) { 14888 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14889 if (ps == null) { 14890 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14891 "Missing settings for moved package " + pkgName); 14892 } 14893 14894 // We moved the entire application as-is, so bring over the 14895 // previously derived ABI information. 14896 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14897 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14898 } 14899 14900 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14901 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14902 scanFlags |= SCAN_NO_DEX; 14903 14904 try { 14905 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14906 args.abiOverride : pkg.cpuAbiOverride); 14907 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14908 true /* extract libs */); 14909 } catch (PackageManagerException pme) { 14910 Slog.e(TAG, "Error deriving application ABI", pme); 14911 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14912 return; 14913 } 14914 14915 // Shared libraries for the package need to be updated. 14916 synchronized (mPackages) { 14917 try { 14918 updateSharedLibrariesLPw(pkg, null); 14919 } catch (PackageManagerException e) { 14920 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14921 } 14922 } 14923 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14924 // Do not run PackageDexOptimizer through the local performDexOpt 14925 // method because `pkg` is not in `mPackages` yet. 14926 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14927 null /* instructionSets */, false /* checkProfiles */, 14928 getCompilerFilterForReason(REASON_INSTALL)); 14929 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14930 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14931 String msg = "Extracting package failed for " + pkgName; 14932 res.setError(INSTALL_FAILED_DEXOPT, msg); 14933 return; 14934 } 14935 14936 // Notify BackgroundDexOptService that the package has been changed. 14937 // If this is an update of a package which used to fail to compile, 14938 // BDOS will remove it from its blacklist. 14939 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14940 } 14941 14942 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14943 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14944 return; 14945 } 14946 14947 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14948 14949 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14950 "installPackageLI")) { 14951 if (replace) { 14952 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14953 installerPackageName, res); 14954 } else { 14955 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14956 args.user, installerPackageName, volumeUuid, res); 14957 } 14958 } 14959 synchronized (mPackages) { 14960 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14961 if (ps != null) { 14962 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14963 } 14964 14965 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14966 for (int i = 0; i < childCount; i++) { 14967 PackageParser.Package childPkg = pkg.childPackages.get(i); 14968 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14969 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14970 if (childPs != null) { 14971 childRes.newUsers = childPs.queryInstalledUsers( 14972 sUserManager.getUserIds(), true); 14973 } 14974 } 14975 } 14976 } 14977 14978 private void startIntentFilterVerifications(int userId, boolean replacing, 14979 PackageParser.Package pkg) { 14980 if (mIntentFilterVerifierComponent == null) { 14981 Slog.w(TAG, "No IntentFilter verification will not be done as " 14982 + "there is no IntentFilterVerifier available!"); 14983 return; 14984 } 14985 14986 final int verifierUid = getPackageUid( 14987 mIntentFilterVerifierComponent.getPackageName(), 14988 MATCH_DEBUG_TRIAGED_MISSING, 14989 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14990 14991 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14992 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14993 mHandler.sendMessage(msg); 14994 14995 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14996 for (int i = 0; i < childCount; i++) { 14997 PackageParser.Package childPkg = pkg.childPackages.get(i); 14998 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14999 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15000 mHandler.sendMessage(msg); 15001 } 15002 } 15003 15004 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15005 PackageParser.Package pkg) { 15006 int size = pkg.activities.size(); 15007 if (size == 0) { 15008 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15009 "No activity, so no need to verify any IntentFilter!"); 15010 return; 15011 } 15012 15013 final boolean hasDomainURLs = hasDomainURLs(pkg); 15014 if (!hasDomainURLs) { 15015 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15016 "No domain URLs, so no need to verify any IntentFilter!"); 15017 return; 15018 } 15019 15020 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15021 + " if any IntentFilter from the " + size 15022 + " Activities needs verification ..."); 15023 15024 int count = 0; 15025 final String packageName = pkg.packageName; 15026 15027 synchronized (mPackages) { 15028 // If this is a new install and we see that we've already run verification for this 15029 // package, we have nothing to do: it means the state was restored from backup. 15030 if (!replacing) { 15031 IntentFilterVerificationInfo ivi = 15032 mSettings.getIntentFilterVerificationLPr(packageName); 15033 if (ivi != null) { 15034 if (DEBUG_DOMAIN_VERIFICATION) { 15035 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15036 + ivi.getStatusString()); 15037 } 15038 return; 15039 } 15040 } 15041 15042 // If any filters need to be verified, then all need to be. 15043 boolean needToVerify = false; 15044 for (PackageParser.Activity a : pkg.activities) { 15045 for (ActivityIntentInfo filter : a.intents) { 15046 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15047 if (DEBUG_DOMAIN_VERIFICATION) { 15048 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15049 } 15050 needToVerify = true; 15051 break; 15052 } 15053 } 15054 } 15055 15056 if (needToVerify) { 15057 final int verificationId = mIntentFilterVerificationToken++; 15058 for (PackageParser.Activity a : pkg.activities) { 15059 for (ActivityIntentInfo filter : a.intents) { 15060 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15061 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15062 "Verification needed for IntentFilter:" + filter.toString()); 15063 mIntentFilterVerifier.addOneIntentFilterVerification( 15064 verifierUid, userId, verificationId, filter, packageName); 15065 count++; 15066 } 15067 } 15068 } 15069 } 15070 } 15071 15072 if (count > 0) { 15073 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15074 + " IntentFilter verification" + (count > 1 ? "s" : "") 15075 + " for userId:" + userId); 15076 mIntentFilterVerifier.startVerifications(userId); 15077 } else { 15078 if (DEBUG_DOMAIN_VERIFICATION) { 15079 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15080 } 15081 } 15082 } 15083 15084 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15085 final ComponentName cn = filter.activity.getComponentName(); 15086 final String packageName = cn.getPackageName(); 15087 15088 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15089 packageName); 15090 if (ivi == null) { 15091 return true; 15092 } 15093 int status = ivi.getStatus(); 15094 switch (status) { 15095 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15096 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15097 return true; 15098 15099 default: 15100 // Nothing to do 15101 return false; 15102 } 15103 } 15104 15105 private static boolean isMultiArch(ApplicationInfo info) { 15106 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15107 } 15108 15109 private static boolean isExternal(PackageParser.Package pkg) { 15110 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15111 } 15112 15113 private static boolean isExternal(PackageSetting ps) { 15114 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15115 } 15116 15117 private static boolean isEphemeral(PackageParser.Package pkg) { 15118 return pkg.applicationInfo.isEphemeralApp(); 15119 } 15120 15121 private static boolean isEphemeral(PackageSetting ps) { 15122 return ps.pkg != null && isEphemeral(ps.pkg); 15123 } 15124 15125 private static boolean isSystemApp(PackageParser.Package pkg) { 15126 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15127 } 15128 15129 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15130 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15131 } 15132 15133 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15134 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15135 } 15136 15137 private static boolean isSystemApp(PackageSetting ps) { 15138 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15139 } 15140 15141 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15142 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15143 } 15144 15145 private int packageFlagsToInstallFlags(PackageSetting ps) { 15146 int installFlags = 0; 15147 if (isEphemeral(ps)) { 15148 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15149 } 15150 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15151 // This existing package was an external ASEC install when we have 15152 // the external flag without a UUID 15153 installFlags |= PackageManager.INSTALL_EXTERNAL; 15154 } 15155 if (ps.isForwardLocked()) { 15156 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15157 } 15158 return installFlags; 15159 } 15160 15161 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15162 if (isExternal(pkg)) { 15163 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15164 return StorageManager.UUID_PRIMARY_PHYSICAL; 15165 } else { 15166 return pkg.volumeUuid; 15167 } 15168 } else { 15169 return StorageManager.UUID_PRIVATE_INTERNAL; 15170 } 15171 } 15172 15173 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15174 if (isExternal(pkg)) { 15175 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15176 return mSettings.getExternalVersion(); 15177 } else { 15178 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15179 } 15180 } else { 15181 return mSettings.getInternalVersion(); 15182 } 15183 } 15184 15185 private void deleteTempPackageFiles() { 15186 final FilenameFilter filter = new FilenameFilter() { 15187 public boolean accept(File dir, String name) { 15188 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15189 } 15190 }; 15191 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15192 file.delete(); 15193 } 15194 } 15195 15196 @Override 15197 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15198 int flags) { 15199 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15200 flags); 15201 } 15202 15203 @Override 15204 public void deletePackage(final String packageName, 15205 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15206 mContext.enforceCallingOrSelfPermission( 15207 android.Manifest.permission.DELETE_PACKAGES, null); 15208 Preconditions.checkNotNull(packageName); 15209 Preconditions.checkNotNull(observer); 15210 final int uid = Binder.getCallingUid(); 15211 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15212 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15213 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15214 mContext.enforceCallingOrSelfPermission( 15215 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15216 "deletePackage for user " + userId); 15217 } 15218 15219 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15220 try { 15221 observer.onPackageDeleted(packageName, 15222 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15223 } catch (RemoteException re) { 15224 } 15225 return; 15226 } 15227 15228 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15229 try { 15230 observer.onPackageDeleted(packageName, 15231 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15232 } catch (RemoteException re) { 15233 } 15234 return; 15235 } 15236 15237 if (DEBUG_REMOVE) { 15238 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15239 + " deleteAllUsers: " + deleteAllUsers ); 15240 } 15241 // Queue up an async operation since the package deletion may take a little while. 15242 mHandler.post(new Runnable() { 15243 public void run() { 15244 mHandler.removeCallbacks(this); 15245 int returnCode; 15246 if (!deleteAllUsers) { 15247 returnCode = deletePackageX(packageName, userId, deleteFlags); 15248 } else { 15249 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15250 // If nobody is blocking uninstall, proceed with delete for all users 15251 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15252 returnCode = deletePackageX(packageName, userId, deleteFlags); 15253 } else { 15254 // Otherwise uninstall individually for users with blockUninstalls=false 15255 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15256 for (int userId : users) { 15257 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15258 returnCode = deletePackageX(packageName, userId, userFlags); 15259 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15260 Slog.w(TAG, "Package delete failed for user " + userId 15261 + ", returnCode " + returnCode); 15262 } 15263 } 15264 } 15265 // The app has only been marked uninstalled for certain users. 15266 // We still need to report that delete was blocked 15267 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15268 } 15269 } 15270 try { 15271 observer.onPackageDeleted(packageName, returnCode, null); 15272 } catch (RemoteException e) { 15273 Log.i(TAG, "Observer no longer exists."); 15274 } //end catch 15275 } //end run 15276 }); 15277 } 15278 15279 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15280 int[] result = EMPTY_INT_ARRAY; 15281 for (int userId : userIds) { 15282 if (getBlockUninstallForUser(packageName, userId)) { 15283 result = ArrayUtils.appendInt(result, userId); 15284 } 15285 } 15286 return result; 15287 } 15288 15289 @Override 15290 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15291 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15292 } 15293 15294 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15295 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15296 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15297 try { 15298 if (dpm != null) { 15299 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15300 /* callingUserOnly =*/ false); 15301 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15302 : deviceOwnerComponentName.getPackageName(); 15303 // Does the package contains the device owner? 15304 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15305 // this check is probably not needed, since DO should be registered as a device 15306 // admin on some user too. (Original bug for this: b/17657954) 15307 if (packageName.equals(deviceOwnerPackageName)) { 15308 return true; 15309 } 15310 // Does it contain a device admin for any user? 15311 int[] users; 15312 if (userId == UserHandle.USER_ALL) { 15313 users = sUserManager.getUserIds(); 15314 } else { 15315 users = new int[]{userId}; 15316 } 15317 for (int i = 0; i < users.length; ++i) { 15318 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15319 return true; 15320 } 15321 } 15322 } 15323 } catch (RemoteException e) { 15324 } 15325 return false; 15326 } 15327 15328 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15329 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15330 } 15331 15332 /** 15333 * This method is an internal method that could be get invoked either 15334 * to delete an installed package or to clean up a failed installation. 15335 * After deleting an installed package, a broadcast is sent to notify any 15336 * listeners that the package has been removed. For cleaning up a failed 15337 * installation, the broadcast is not necessary since the package's 15338 * installation wouldn't have sent the initial broadcast either 15339 * The key steps in deleting a package are 15340 * deleting the package information in internal structures like mPackages, 15341 * deleting the packages base directories through installd 15342 * updating mSettings to reflect current status 15343 * persisting settings for later use 15344 * sending a broadcast if necessary 15345 */ 15346 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15347 final PackageRemovedInfo info = new PackageRemovedInfo(); 15348 final boolean res; 15349 15350 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15351 ? UserHandle.ALL : new UserHandle(userId); 15352 15353 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15354 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15355 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15356 } 15357 15358 PackageSetting uninstalledPs = null; 15359 15360 // for the uninstall-updates case and restricted profiles, remember the per- 15361 // user handle installed state 15362 int[] allUsers; 15363 synchronized (mPackages) { 15364 uninstalledPs = mSettings.mPackages.get(packageName); 15365 if (uninstalledPs == null) { 15366 Slog.w(TAG, "Not removing non-existent package " + packageName); 15367 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15368 } 15369 allUsers = sUserManager.getUserIds(); 15370 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15371 } 15372 15373 synchronized (mInstallLock) { 15374 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15375 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15376 "deletePackageX")) { 15377 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15378 deleteFlags | REMOVE_CHATTY, info, true, null); 15379 } 15380 synchronized (mPackages) { 15381 if (res) { 15382 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15383 } 15384 } 15385 } 15386 15387 if (res) { 15388 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15389 info.sendPackageRemovedBroadcasts(killApp); 15390 info.sendSystemPackageUpdatedBroadcasts(); 15391 info.sendSystemPackageAppearedBroadcasts(); 15392 } 15393 // Force a gc here. 15394 Runtime.getRuntime().gc(); 15395 // Delete the resources here after sending the broadcast to let 15396 // other processes clean up before deleting resources. 15397 if (info.args != null) { 15398 synchronized (mInstallLock) { 15399 info.args.doPostDeleteLI(true); 15400 } 15401 } 15402 15403 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15404 } 15405 15406 class PackageRemovedInfo { 15407 String removedPackage; 15408 int uid = -1; 15409 int removedAppId = -1; 15410 int[] origUsers; 15411 int[] removedUsers = null; 15412 boolean isRemovedPackageSystemUpdate = false; 15413 boolean isUpdate; 15414 boolean dataRemoved; 15415 boolean removedForAllUsers; 15416 // Clean up resources deleted packages. 15417 InstallArgs args = null; 15418 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15419 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15420 15421 void sendPackageRemovedBroadcasts(boolean killApp) { 15422 sendPackageRemovedBroadcastInternal(killApp); 15423 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15424 for (int i = 0; i < childCount; i++) { 15425 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15426 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15427 } 15428 } 15429 15430 void sendSystemPackageUpdatedBroadcasts() { 15431 if (isRemovedPackageSystemUpdate) { 15432 sendSystemPackageUpdatedBroadcastsInternal(); 15433 final int childCount = (removedChildPackages != null) 15434 ? removedChildPackages.size() : 0; 15435 for (int i = 0; i < childCount; i++) { 15436 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15437 if (childInfo.isRemovedPackageSystemUpdate) { 15438 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15439 } 15440 } 15441 } 15442 } 15443 15444 void sendSystemPackageAppearedBroadcasts() { 15445 final int packageCount = (appearedChildPackages != null) 15446 ? appearedChildPackages.size() : 0; 15447 for (int i = 0; i < packageCount; i++) { 15448 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15449 for (int userId : installedInfo.newUsers) { 15450 sendPackageAddedForUser(installedInfo.name, true, 15451 UserHandle.getAppId(installedInfo.uid), userId); 15452 } 15453 } 15454 } 15455 15456 private void sendSystemPackageUpdatedBroadcastsInternal() { 15457 Bundle extras = new Bundle(2); 15458 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15459 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15460 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15461 extras, 0, null, null, null); 15462 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15463 extras, 0, null, null, null); 15464 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15465 null, 0, removedPackage, null, null); 15466 } 15467 15468 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15469 Bundle extras = new Bundle(2); 15470 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15471 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15472 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15473 if (isUpdate || isRemovedPackageSystemUpdate) { 15474 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15475 } 15476 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15477 if (removedPackage != null) { 15478 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15479 extras, 0, null, null, removedUsers); 15480 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15481 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15482 removedPackage, extras, 0, null, null, removedUsers); 15483 } 15484 } 15485 if (removedAppId >= 0) { 15486 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15487 removedUsers); 15488 } 15489 } 15490 } 15491 15492 /* 15493 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15494 * flag is not set, the data directory is removed as well. 15495 * make sure this flag is set for partially installed apps. If not its meaningless to 15496 * delete a partially installed application. 15497 */ 15498 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15499 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15500 String packageName = ps.name; 15501 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15502 // Retrieve object to delete permissions for shared user later on 15503 final PackageParser.Package deletedPkg; 15504 final PackageSetting deletedPs; 15505 // reader 15506 synchronized (mPackages) { 15507 deletedPkg = mPackages.get(packageName); 15508 deletedPs = mSettings.mPackages.get(packageName); 15509 if (outInfo != null) { 15510 outInfo.removedPackage = packageName; 15511 outInfo.removedUsers = deletedPs != null 15512 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15513 : null; 15514 } 15515 } 15516 15517 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15518 15519 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15520 final PackageParser.Package resolvedPkg; 15521 if (deletedPkg != null) { 15522 resolvedPkg = deletedPkg; 15523 } else { 15524 // We don't have a parsed package when it lives on an ejected 15525 // adopted storage device, so fake something together 15526 resolvedPkg = new PackageParser.Package(ps.name); 15527 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15528 } 15529 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15530 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15531 destroyAppProfilesLIF(resolvedPkg); 15532 if (outInfo != null) { 15533 outInfo.dataRemoved = true; 15534 } 15535 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15536 } 15537 15538 // writer 15539 synchronized (mPackages) { 15540 if (deletedPs != null) { 15541 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15542 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15543 clearDefaultBrowserIfNeeded(packageName); 15544 if (outInfo != null) { 15545 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15546 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15547 } 15548 updatePermissionsLPw(deletedPs.name, null, 0); 15549 if (deletedPs.sharedUser != null) { 15550 // Remove permissions associated with package. Since runtime 15551 // permissions are per user we have to kill the removed package 15552 // or packages running under the shared user of the removed 15553 // package if revoking the permissions requested only by the removed 15554 // package is successful and this causes a change in gids. 15555 for (int userId : UserManagerService.getInstance().getUserIds()) { 15556 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15557 userId); 15558 if (userIdToKill == UserHandle.USER_ALL 15559 || userIdToKill >= UserHandle.USER_SYSTEM) { 15560 // If gids changed for this user, kill all affected packages. 15561 mHandler.post(new Runnable() { 15562 @Override 15563 public void run() { 15564 // This has to happen with no lock held. 15565 killApplication(deletedPs.name, deletedPs.appId, 15566 KILL_APP_REASON_GIDS_CHANGED); 15567 } 15568 }); 15569 break; 15570 } 15571 } 15572 } 15573 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15574 } 15575 // make sure to preserve per-user disabled state if this removal was just 15576 // a downgrade of a system app to the factory package 15577 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15578 if (DEBUG_REMOVE) { 15579 Slog.d(TAG, "Propagating install state across downgrade"); 15580 } 15581 for (int userId : allUserHandles) { 15582 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15583 if (DEBUG_REMOVE) { 15584 Slog.d(TAG, " user " + userId + " => " + installed); 15585 } 15586 ps.setInstalled(installed, userId); 15587 } 15588 } 15589 } 15590 // can downgrade to reader 15591 if (writeSettings) { 15592 // Save settings now 15593 mSettings.writeLPr(); 15594 } 15595 } 15596 if (outInfo != null) { 15597 // A user ID was deleted here. Go through all users and remove it 15598 // from KeyStore. 15599 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15600 } 15601 } 15602 15603 static boolean locationIsPrivileged(File path) { 15604 try { 15605 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15606 .getCanonicalPath(); 15607 return path.getCanonicalPath().startsWith(privilegedAppDir); 15608 } catch (IOException e) { 15609 Slog.e(TAG, "Unable to access code path " + path); 15610 } 15611 return false; 15612 } 15613 15614 /* 15615 * Tries to delete system package. 15616 */ 15617 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15618 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15619 boolean writeSettings) { 15620 if (deletedPs.parentPackageName != null) { 15621 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15622 return false; 15623 } 15624 15625 final boolean applyUserRestrictions 15626 = (allUserHandles != null) && (outInfo.origUsers != null); 15627 final PackageSetting disabledPs; 15628 // Confirm if the system package has been updated 15629 // An updated system app can be deleted. This will also have to restore 15630 // the system pkg from system partition 15631 // reader 15632 synchronized (mPackages) { 15633 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15634 } 15635 15636 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15637 + " disabledPs=" + disabledPs); 15638 15639 if (disabledPs == null) { 15640 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15641 return false; 15642 } else if (DEBUG_REMOVE) { 15643 Slog.d(TAG, "Deleting system pkg from data partition"); 15644 } 15645 15646 if (DEBUG_REMOVE) { 15647 if (applyUserRestrictions) { 15648 Slog.d(TAG, "Remembering install states:"); 15649 for (int userId : allUserHandles) { 15650 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15651 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15652 } 15653 } 15654 } 15655 15656 // Delete the updated package 15657 outInfo.isRemovedPackageSystemUpdate = true; 15658 if (outInfo.removedChildPackages != null) { 15659 final int childCount = (deletedPs.childPackageNames != null) 15660 ? deletedPs.childPackageNames.size() : 0; 15661 for (int i = 0; i < childCount; i++) { 15662 String childPackageName = deletedPs.childPackageNames.get(i); 15663 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15664 .contains(childPackageName)) { 15665 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15666 childPackageName); 15667 if (childInfo != null) { 15668 childInfo.isRemovedPackageSystemUpdate = true; 15669 } 15670 } 15671 } 15672 } 15673 15674 if (disabledPs.versionCode < deletedPs.versionCode) { 15675 // Delete data for downgrades 15676 flags &= ~PackageManager.DELETE_KEEP_DATA; 15677 } else { 15678 // Preserve data by setting flag 15679 flags |= PackageManager.DELETE_KEEP_DATA; 15680 } 15681 15682 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15683 outInfo, writeSettings, disabledPs.pkg); 15684 if (!ret) { 15685 return false; 15686 } 15687 15688 // writer 15689 synchronized (mPackages) { 15690 // Reinstate the old system package 15691 enableSystemPackageLPw(disabledPs.pkg); 15692 // Remove any native libraries from the upgraded package. 15693 removeNativeBinariesLI(deletedPs); 15694 } 15695 15696 // Install the system package 15697 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15698 int parseFlags = mDefParseFlags 15699 | PackageParser.PARSE_MUST_BE_APK 15700 | PackageParser.PARSE_IS_SYSTEM 15701 | PackageParser.PARSE_IS_SYSTEM_DIR; 15702 if (locationIsPrivileged(disabledPs.codePath)) { 15703 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15704 } 15705 15706 final PackageParser.Package newPkg; 15707 try { 15708 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15709 } catch (PackageManagerException e) { 15710 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15711 + e.getMessage()); 15712 return false; 15713 } 15714 15715 prepareAppDataAfterInstallLIF(newPkg); 15716 15717 // writer 15718 synchronized (mPackages) { 15719 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15720 15721 // Propagate the permissions state as we do not want to drop on the floor 15722 // runtime permissions. The update permissions method below will take 15723 // care of removing obsolete permissions and grant install permissions. 15724 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15725 updatePermissionsLPw(newPkg.packageName, newPkg, 15726 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15727 15728 if (applyUserRestrictions) { 15729 if (DEBUG_REMOVE) { 15730 Slog.d(TAG, "Propagating install state across reinstall"); 15731 } 15732 for (int userId : allUserHandles) { 15733 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15734 if (DEBUG_REMOVE) { 15735 Slog.d(TAG, " user " + userId + " => " + installed); 15736 } 15737 ps.setInstalled(installed, userId); 15738 15739 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15740 } 15741 // Regardless of writeSettings we need to ensure that this restriction 15742 // state propagation is persisted 15743 mSettings.writeAllUsersPackageRestrictionsLPr(); 15744 } 15745 // can downgrade to reader here 15746 if (writeSettings) { 15747 mSettings.writeLPr(); 15748 } 15749 } 15750 return true; 15751 } 15752 15753 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15754 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15755 PackageRemovedInfo outInfo, boolean writeSettings, 15756 PackageParser.Package replacingPackage) { 15757 synchronized (mPackages) { 15758 if (outInfo != null) { 15759 outInfo.uid = ps.appId; 15760 } 15761 15762 if (outInfo != null && outInfo.removedChildPackages != null) { 15763 final int childCount = (ps.childPackageNames != null) 15764 ? ps.childPackageNames.size() : 0; 15765 for (int i = 0; i < childCount; i++) { 15766 String childPackageName = ps.childPackageNames.get(i); 15767 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15768 if (childPs == null) { 15769 return false; 15770 } 15771 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15772 childPackageName); 15773 if (childInfo != null) { 15774 childInfo.uid = childPs.appId; 15775 } 15776 } 15777 } 15778 } 15779 15780 // Delete package data from internal structures and also remove data if flag is set 15781 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15782 15783 // Delete the child packages data 15784 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15785 for (int i = 0; i < childCount; i++) { 15786 PackageSetting childPs; 15787 synchronized (mPackages) { 15788 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15789 } 15790 if (childPs != null) { 15791 PackageRemovedInfo childOutInfo = (outInfo != null 15792 && outInfo.removedChildPackages != null) 15793 ? outInfo.removedChildPackages.get(childPs.name) : null; 15794 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15795 && (replacingPackage != null 15796 && !replacingPackage.hasChildPackage(childPs.name)) 15797 ? flags & ~DELETE_KEEP_DATA : flags; 15798 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15799 deleteFlags, writeSettings); 15800 } 15801 } 15802 15803 // Delete application code and resources only for parent packages 15804 if (ps.parentPackageName == null) { 15805 if (deleteCodeAndResources && (outInfo != null)) { 15806 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15807 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15808 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15809 } 15810 } 15811 15812 return true; 15813 } 15814 15815 @Override 15816 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15817 int userId) { 15818 mContext.enforceCallingOrSelfPermission( 15819 android.Manifest.permission.DELETE_PACKAGES, null); 15820 synchronized (mPackages) { 15821 PackageSetting ps = mSettings.mPackages.get(packageName); 15822 if (ps == null) { 15823 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15824 return false; 15825 } 15826 if (!ps.getInstalled(userId)) { 15827 // Can't block uninstall for an app that is not installed or enabled. 15828 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15829 return false; 15830 } 15831 ps.setBlockUninstall(blockUninstall, userId); 15832 mSettings.writePackageRestrictionsLPr(userId); 15833 } 15834 return true; 15835 } 15836 15837 @Override 15838 public boolean getBlockUninstallForUser(String packageName, int userId) { 15839 synchronized (mPackages) { 15840 PackageSetting ps = mSettings.mPackages.get(packageName); 15841 if (ps == null) { 15842 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15843 return false; 15844 } 15845 return ps.getBlockUninstall(userId); 15846 } 15847 } 15848 15849 @Override 15850 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15851 int callingUid = Binder.getCallingUid(); 15852 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15853 throw new SecurityException( 15854 "setRequiredForSystemUser can only be run by the system or root"); 15855 } 15856 synchronized (mPackages) { 15857 PackageSetting ps = mSettings.mPackages.get(packageName); 15858 if (ps == null) { 15859 Log.w(TAG, "Package doesn't exist: " + packageName); 15860 return false; 15861 } 15862 if (systemUserApp) { 15863 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15864 } else { 15865 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15866 } 15867 mSettings.writeLPr(); 15868 } 15869 return true; 15870 } 15871 15872 /* 15873 * This method handles package deletion in general 15874 */ 15875 private boolean deletePackageLIF(String packageName, UserHandle user, 15876 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15877 PackageRemovedInfo outInfo, boolean writeSettings, 15878 PackageParser.Package replacingPackage) { 15879 if (packageName == null) { 15880 Slog.w(TAG, "Attempt to delete null packageName."); 15881 return false; 15882 } 15883 15884 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15885 15886 PackageSetting ps; 15887 15888 synchronized (mPackages) { 15889 ps = mSettings.mPackages.get(packageName); 15890 if (ps == null) { 15891 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15892 return false; 15893 } 15894 15895 if (ps.parentPackageName != null && (!isSystemApp(ps) 15896 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15897 if (DEBUG_REMOVE) { 15898 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15899 + ((user == null) ? UserHandle.USER_ALL : user)); 15900 } 15901 final int removedUserId = (user != null) ? user.getIdentifier() 15902 : UserHandle.USER_ALL; 15903 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15904 return false; 15905 } 15906 markPackageUninstalledForUserLPw(ps, user); 15907 scheduleWritePackageRestrictionsLocked(user); 15908 return true; 15909 } 15910 } 15911 15912 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15913 && user.getIdentifier() != UserHandle.USER_ALL)) { 15914 // The caller is asking that the package only be deleted for a single 15915 // user. To do this, we just mark its uninstalled state and delete 15916 // its data. If this is a system app, we only allow this to happen if 15917 // they have set the special DELETE_SYSTEM_APP which requests different 15918 // semantics than normal for uninstalling system apps. 15919 markPackageUninstalledForUserLPw(ps, user); 15920 15921 if (!isSystemApp(ps)) { 15922 // Do not uninstall the APK if an app should be cached 15923 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15924 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15925 // Other user still have this package installed, so all 15926 // we need to do is clear this user's data and save that 15927 // it is uninstalled. 15928 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15929 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15930 return false; 15931 } 15932 scheduleWritePackageRestrictionsLocked(user); 15933 return true; 15934 } else { 15935 // We need to set it back to 'installed' so the uninstall 15936 // broadcasts will be sent correctly. 15937 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15938 ps.setInstalled(true, user.getIdentifier()); 15939 } 15940 } else { 15941 // This is a system app, so we assume that the 15942 // other users still have this package installed, so all 15943 // we need to do is clear this user's data and save that 15944 // it is uninstalled. 15945 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15946 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15947 return false; 15948 } 15949 scheduleWritePackageRestrictionsLocked(user); 15950 return true; 15951 } 15952 } 15953 15954 // If we are deleting a composite package for all users, keep track 15955 // of result for each child. 15956 if (ps.childPackageNames != null && outInfo != null) { 15957 synchronized (mPackages) { 15958 final int childCount = ps.childPackageNames.size(); 15959 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15960 for (int i = 0; i < childCount; i++) { 15961 String childPackageName = ps.childPackageNames.get(i); 15962 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15963 childInfo.removedPackage = childPackageName; 15964 outInfo.removedChildPackages.put(childPackageName, childInfo); 15965 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15966 if (childPs != null) { 15967 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15968 } 15969 } 15970 } 15971 } 15972 15973 boolean ret = false; 15974 if (isSystemApp(ps)) { 15975 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15976 // When an updated system application is deleted we delete the existing resources 15977 // as well and fall back to existing code in system partition 15978 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15979 } else { 15980 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15981 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15982 outInfo, writeSettings, replacingPackage); 15983 } 15984 15985 // Take a note whether we deleted the package for all users 15986 if (outInfo != null) { 15987 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15988 if (outInfo.removedChildPackages != null) { 15989 synchronized (mPackages) { 15990 final int childCount = outInfo.removedChildPackages.size(); 15991 for (int i = 0; i < childCount; i++) { 15992 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15993 if (childInfo != null) { 15994 childInfo.removedForAllUsers = mPackages.get( 15995 childInfo.removedPackage) == null; 15996 } 15997 } 15998 } 15999 } 16000 // If we uninstalled an update to a system app there may be some 16001 // child packages that appeared as they are declared in the system 16002 // app but were not declared in the update. 16003 if (isSystemApp(ps)) { 16004 synchronized (mPackages) { 16005 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16006 final int childCount = (updatedPs.childPackageNames != null) 16007 ? updatedPs.childPackageNames.size() : 0; 16008 for (int i = 0; i < childCount; i++) { 16009 String childPackageName = updatedPs.childPackageNames.get(i); 16010 if (outInfo.removedChildPackages == null 16011 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16012 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16013 if (childPs == null) { 16014 continue; 16015 } 16016 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16017 installRes.name = childPackageName; 16018 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16019 installRes.pkg = mPackages.get(childPackageName); 16020 installRes.uid = childPs.pkg.applicationInfo.uid; 16021 if (outInfo.appearedChildPackages == null) { 16022 outInfo.appearedChildPackages = new ArrayMap<>(); 16023 } 16024 outInfo.appearedChildPackages.put(childPackageName, installRes); 16025 } 16026 } 16027 } 16028 } 16029 } 16030 16031 return ret; 16032 } 16033 16034 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16035 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16036 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16037 for (int nextUserId : userIds) { 16038 if (DEBUG_REMOVE) { 16039 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16040 } 16041 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16042 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16043 false /*hidden*/, false /*suspended*/, null, null, null, 16044 false /*blockUninstall*/, 16045 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16046 } 16047 } 16048 16049 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16050 PackageRemovedInfo outInfo) { 16051 final PackageParser.Package pkg; 16052 synchronized (mPackages) { 16053 pkg = mPackages.get(ps.name); 16054 } 16055 16056 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16057 : new int[] {userId}; 16058 for (int nextUserId : userIds) { 16059 if (DEBUG_REMOVE) { 16060 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16061 + nextUserId); 16062 } 16063 16064 destroyAppDataLIF(pkg, userId, 16065 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16066 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16067 schedulePackageCleaning(ps.name, nextUserId, false); 16068 synchronized (mPackages) { 16069 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16070 scheduleWritePackageRestrictionsLocked(nextUserId); 16071 } 16072 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16073 } 16074 } 16075 16076 if (outInfo != null) { 16077 outInfo.removedPackage = ps.name; 16078 outInfo.removedAppId = ps.appId; 16079 outInfo.removedUsers = userIds; 16080 } 16081 16082 return true; 16083 } 16084 16085 private final class ClearStorageConnection implements ServiceConnection { 16086 IMediaContainerService mContainerService; 16087 16088 @Override 16089 public void onServiceConnected(ComponentName name, IBinder service) { 16090 synchronized (this) { 16091 mContainerService = IMediaContainerService.Stub.asInterface(service); 16092 notifyAll(); 16093 } 16094 } 16095 16096 @Override 16097 public void onServiceDisconnected(ComponentName name) { 16098 } 16099 } 16100 16101 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16102 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16103 16104 final boolean mounted; 16105 if (Environment.isExternalStorageEmulated()) { 16106 mounted = true; 16107 } else { 16108 final String status = Environment.getExternalStorageState(); 16109 16110 mounted = status.equals(Environment.MEDIA_MOUNTED) 16111 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16112 } 16113 16114 if (!mounted) { 16115 return; 16116 } 16117 16118 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16119 int[] users; 16120 if (userId == UserHandle.USER_ALL) { 16121 users = sUserManager.getUserIds(); 16122 } else { 16123 users = new int[] { userId }; 16124 } 16125 final ClearStorageConnection conn = new ClearStorageConnection(); 16126 if (mContext.bindServiceAsUser( 16127 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16128 try { 16129 for (int curUser : users) { 16130 long timeout = SystemClock.uptimeMillis() + 5000; 16131 synchronized (conn) { 16132 long now = SystemClock.uptimeMillis(); 16133 while (conn.mContainerService == null && now < timeout) { 16134 try { 16135 conn.wait(timeout - now); 16136 } catch (InterruptedException e) { 16137 } 16138 } 16139 } 16140 if (conn.mContainerService == null) { 16141 return; 16142 } 16143 16144 final UserEnvironment userEnv = new UserEnvironment(curUser); 16145 clearDirectory(conn.mContainerService, 16146 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16147 if (allData) { 16148 clearDirectory(conn.mContainerService, 16149 userEnv.buildExternalStorageAppDataDirs(packageName)); 16150 clearDirectory(conn.mContainerService, 16151 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16152 } 16153 } 16154 } finally { 16155 mContext.unbindService(conn); 16156 } 16157 } 16158 } 16159 16160 @Override 16161 public void clearApplicationProfileData(String packageName) { 16162 enforceSystemOrRoot("Only the system can clear all profile data"); 16163 16164 final PackageParser.Package pkg; 16165 synchronized (mPackages) { 16166 pkg = mPackages.get(packageName); 16167 } 16168 16169 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16170 synchronized (mInstallLock) { 16171 clearAppProfilesLIF(pkg); 16172 } 16173 } 16174 } 16175 16176 @Override 16177 public void clearApplicationUserData(final String packageName, 16178 final IPackageDataObserver observer, final int userId) { 16179 mContext.enforceCallingOrSelfPermission( 16180 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16181 16182 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16183 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16184 16185 final DevicePolicyManagerInternal dpmi = LocalServices 16186 .getService(DevicePolicyManagerInternal.class); 16187 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16188 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16189 } 16190 // Queue up an async operation since the package deletion may take a little while. 16191 mHandler.post(new Runnable() { 16192 public void run() { 16193 mHandler.removeCallbacks(this); 16194 final boolean succeeded; 16195 try (PackageFreezer freezer = freezePackage(packageName, 16196 "clearApplicationUserData")) { 16197 synchronized (mInstallLock) { 16198 succeeded = clearApplicationUserDataLIF(packageName, userId); 16199 } 16200 clearExternalStorageDataSync(packageName, userId, true); 16201 } 16202 if (succeeded) { 16203 // invoke DeviceStorageMonitor's update method to clear any notifications 16204 DeviceStorageMonitorInternal dsm = LocalServices 16205 .getService(DeviceStorageMonitorInternal.class); 16206 if (dsm != null) { 16207 dsm.checkMemory(); 16208 } 16209 } 16210 if(observer != null) { 16211 try { 16212 observer.onRemoveCompleted(packageName, succeeded); 16213 } catch (RemoteException e) { 16214 Log.i(TAG, "Observer no longer exists."); 16215 } 16216 } //end if observer 16217 } //end run 16218 }); 16219 } 16220 16221 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16222 if (packageName == null) { 16223 Slog.w(TAG, "Attempt to delete null packageName."); 16224 return false; 16225 } 16226 16227 // Try finding details about the requested package 16228 PackageParser.Package pkg; 16229 synchronized (mPackages) { 16230 pkg = mPackages.get(packageName); 16231 if (pkg == null) { 16232 final PackageSetting ps = mSettings.mPackages.get(packageName); 16233 if (ps != null) { 16234 pkg = ps.pkg; 16235 } 16236 } 16237 16238 if (pkg == null) { 16239 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16240 return false; 16241 } 16242 16243 PackageSetting ps = (PackageSetting) pkg.mExtras; 16244 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16245 } 16246 16247 clearAppDataLIF(pkg, userId, 16248 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16249 16250 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16251 removeKeystoreDataIfNeeded(userId, appId); 16252 16253 final UserManager um = mContext.getSystemService(UserManager.class); 16254 final int flags; 16255 if (um.isUserUnlockingOrUnlocked(userId)) { 16256 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16257 } else if (um.isUserRunning(userId)) { 16258 flags = StorageManager.FLAG_STORAGE_DE; 16259 } else { 16260 flags = 0; 16261 } 16262 prepareAppDataContentsLIF(pkg, userId, flags); 16263 16264 return true; 16265 } 16266 16267 /** 16268 * Reverts user permission state changes (permissions and flags) in 16269 * all packages for a given user. 16270 * 16271 * @param userId The device user for which to do a reset. 16272 */ 16273 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16274 final int packageCount = mPackages.size(); 16275 for (int i = 0; i < packageCount; i++) { 16276 PackageParser.Package pkg = mPackages.valueAt(i); 16277 PackageSetting ps = (PackageSetting) pkg.mExtras; 16278 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16279 } 16280 } 16281 16282 private void resetNetworkPolicies(int userId) { 16283 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16284 } 16285 16286 /** 16287 * Reverts user permission state changes (permissions and flags). 16288 * 16289 * @param ps The package for which to reset. 16290 * @param userId The device user for which to do a reset. 16291 */ 16292 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16293 final PackageSetting ps, final int userId) { 16294 if (ps.pkg == null) { 16295 return; 16296 } 16297 16298 // These are flags that can change base on user actions. 16299 final int userSettableMask = FLAG_PERMISSION_USER_SET 16300 | FLAG_PERMISSION_USER_FIXED 16301 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16302 | FLAG_PERMISSION_REVIEW_REQUIRED; 16303 16304 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16305 | FLAG_PERMISSION_POLICY_FIXED; 16306 16307 boolean writeInstallPermissions = false; 16308 boolean writeRuntimePermissions = false; 16309 16310 final int permissionCount = ps.pkg.requestedPermissions.size(); 16311 for (int i = 0; i < permissionCount; i++) { 16312 String permission = ps.pkg.requestedPermissions.get(i); 16313 16314 BasePermission bp = mSettings.mPermissions.get(permission); 16315 if (bp == null) { 16316 continue; 16317 } 16318 16319 // If shared user we just reset the state to which only this app contributed. 16320 if (ps.sharedUser != null) { 16321 boolean used = false; 16322 final int packageCount = ps.sharedUser.packages.size(); 16323 for (int j = 0; j < packageCount; j++) { 16324 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16325 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16326 && pkg.pkg.requestedPermissions.contains(permission)) { 16327 used = true; 16328 break; 16329 } 16330 } 16331 if (used) { 16332 continue; 16333 } 16334 } 16335 16336 PermissionsState permissionsState = ps.getPermissionsState(); 16337 16338 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16339 16340 // Always clear the user settable flags. 16341 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16342 bp.name) != null; 16343 // If permission review is enabled and this is a legacy app, mark the 16344 // permission as requiring a review as this is the initial state. 16345 int flags = 0; 16346 if (Build.PERMISSIONS_REVIEW_REQUIRED 16347 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16348 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16349 } 16350 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16351 if (hasInstallState) { 16352 writeInstallPermissions = true; 16353 } else { 16354 writeRuntimePermissions = true; 16355 } 16356 } 16357 16358 // Below is only runtime permission handling. 16359 if (!bp.isRuntime()) { 16360 continue; 16361 } 16362 16363 // Never clobber system or policy. 16364 if ((oldFlags & policyOrSystemFlags) != 0) { 16365 continue; 16366 } 16367 16368 // If this permission was granted by default, make sure it is. 16369 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16370 if (permissionsState.grantRuntimePermission(bp, userId) 16371 != PERMISSION_OPERATION_FAILURE) { 16372 writeRuntimePermissions = true; 16373 } 16374 // If permission review is enabled the permissions for a legacy apps 16375 // are represented as constantly granted runtime ones, so don't revoke. 16376 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16377 // Otherwise, reset the permission. 16378 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16379 switch (revokeResult) { 16380 case PERMISSION_OPERATION_SUCCESS: 16381 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16382 writeRuntimePermissions = true; 16383 final int appId = ps.appId; 16384 mHandler.post(new Runnable() { 16385 @Override 16386 public void run() { 16387 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16388 } 16389 }); 16390 } break; 16391 } 16392 } 16393 } 16394 16395 // Synchronously write as we are taking permissions away. 16396 if (writeRuntimePermissions) { 16397 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16398 } 16399 16400 // Synchronously write as we are taking permissions away. 16401 if (writeInstallPermissions) { 16402 mSettings.writeLPr(); 16403 } 16404 } 16405 16406 /** 16407 * Remove entries from the keystore daemon. Will only remove it if the 16408 * {@code appId} is valid. 16409 */ 16410 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16411 if (appId < 0) { 16412 return; 16413 } 16414 16415 final KeyStore keyStore = KeyStore.getInstance(); 16416 if (keyStore != null) { 16417 if (userId == UserHandle.USER_ALL) { 16418 for (final int individual : sUserManager.getUserIds()) { 16419 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16420 } 16421 } else { 16422 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16423 } 16424 } else { 16425 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16426 } 16427 } 16428 16429 @Override 16430 public void deleteApplicationCacheFiles(final String packageName, 16431 final IPackageDataObserver observer) { 16432 final int userId = UserHandle.getCallingUserId(); 16433 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16434 } 16435 16436 @Override 16437 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16438 final IPackageDataObserver observer) { 16439 mContext.enforceCallingOrSelfPermission( 16440 android.Manifest.permission.DELETE_CACHE_FILES, null); 16441 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16442 /* requireFullPermission= */ true, /* checkShell= */ false, 16443 "delete application cache files"); 16444 16445 final PackageParser.Package pkg; 16446 synchronized (mPackages) { 16447 pkg = mPackages.get(packageName); 16448 } 16449 16450 // Queue up an async operation since the package deletion may take a little while. 16451 mHandler.post(new Runnable() { 16452 public void run() { 16453 synchronized (mInstallLock) { 16454 final int flags = StorageManager.FLAG_STORAGE_DE 16455 | StorageManager.FLAG_STORAGE_CE; 16456 // We're only clearing cache files, so we don't care if the 16457 // app is unfrozen and still able to run 16458 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16459 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16460 } 16461 clearExternalStorageDataSync(packageName, userId, false); 16462 if (observer != null) { 16463 try { 16464 observer.onRemoveCompleted(packageName, true); 16465 } catch (RemoteException e) { 16466 Log.i(TAG, "Observer no longer exists."); 16467 } 16468 } 16469 } 16470 }); 16471 } 16472 16473 @Override 16474 public void getPackageSizeInfo(final String packageName, int userHandle, 16475 final IPackageStatsObserver observer) { 16476 mContext.enforceCallingOrSelfPermission( 16477 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16478 if (packageName == null) { 16479 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16480 } 16481 16482 PackageStats stats = new PackageStats(packageName, userHandle); 16483 16484 /* 16485 * Queue up an async operation since the package measurement may take a 16486 * little while. 16487 */ 16488 Message msg = mHandler.obtainMessage(INIT_COPY); 16489 msg.obj = new MeasureParams(stats, observer); 16490 mHandler.sendMessage(msg); 16491 } 16492 16493 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16494 final PackageSetting ps; 16495 synchronized (mPackages) { 16496 ps = mSettings.mPackages.get(packageName); 16497 if (ps == null) { 16498 Slog.w(TAG, "Failed to find settings for " + packageName); 16499 return false; 16500 } 16501 } 16502 try { 16503 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16504 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16505 ps.getCeDataInode(userId), ps.codePathString, stats); 16506 } catch (InstallerException e) { 16507 Slog.w(TAG, String.valueOf(e)); 16508 return false; 16509 } 16510 16511 // For now, ignore code size of packages on system partition 16512 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16513 stats.codeSize = 0; 16514 } 16515 16516 return true; 16517 } 16518 16519 private int getUidTargetSdkVersionLockedLPr(int uid) { 16520 Object obj = mSettings.getUserIdLPr(uid); 16521 if (obj instanceof SharedUserSetting) { 16522 final SharedUserSetting sus = (SharedUserSetting) obj; 16523 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16524 final Iterator<PackageSetting> it = sus.packages.iterator(); 16525 while (it.hasNext()) { 16526 final PackageSetting ps = it.next(); 16527 if (ps.pkg != null) { 16528 int v = ps.pkg.applicationInfo.targetSdkVersion; 16529 if (v < vers) vers = v; 16530 } 16531 } 16532 return vers; 16533 } else if (obj instanceof PackageSetting) { 16534 final PackageSetting ps = (PackageSetting) obj; 16535 if (ps.pkg != null) { 16536 return ps.pkg.applicationInfo.targetSdkVersion; 16537 } 16538 } 16539 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16540 } 16541 16542 @Override 16543 public void addPreferredActivity(IntentFilter filter, int match, 16544 ComponentName[] set, ComponentName activity, int userId) { 16545 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16546 "Adding preferred"); 16547 } 16548 16549 private void addPreferredActivityInternal(IntentFilter filter, int match, 16550 ComponentName[] set, ComponentName activity, boolean always, int userId, 16551 String opname) { 16552 // writer 16553 int callingUid = Binder.getCallingUid(); 16554 enforceCrossUserPermission(callingUid, userId, 16555 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16556 if (filter.countActions() == 0) { 16557 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16558 return; 16559 } 16560 synchronized (mPackages) { 16561 if (mContext.checkCallingOrSelfPermission( 16562 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16563 != PackageManager.PERMISSION_GRANTED) { 16564 if (getUidTargetSdkVersionLockedLPr(callingUid) 16565 < Build.VERSION_CODES.FROYO) { 16566 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16567 + callingUid); 16568 return; 16569 } 16570 mContext.enforceCallingOrSelfPermission( 16571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16572 } 16573 16574 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16575 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16576 + userId + ":"); 16577 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16578 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16579 scheduleWritePackageRestrictionsLocked(userId); 16580 } 16581 } 16582 16583 @Override 16584 public void replacePreferredActivity(IntentFilter filter, int match, 16585 ComponentName[] set, ComponentName activity, int userId) { 16586 if (filter.countActions() != 1) { 16587 throw new IllegalArgumentException( 16588 "replacePreferredActivity expects filter to have only 1 action."); 16589 } 16590 if (filter.countDataAuthorities() != 0 16591 || filter.countDataPaths() != 0 16592 || filter.countDataSchemes() > 1 16593 || filter.countDataTypes() != 0) { 16594 throw new IllegalArgumentException( 16595 "replacePreferredActivity expects filter to have no data authorities, " + 16596 "paths, or types; and at most one scheme."); 16597 } 16598 16599 final int callingUid = Binder.getCallingUid(); 16600 enforceCrossUserPermission(callingUid, userId, 16601 true /* requireFullPermission */, false /* checkShell */, 16602 "replace preferred activity"); 16603 synchronized (mPackages) { 16604 if (mContext.checkCallingOrSelfPermission( 16605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16606 != PackageManager.PERMISSION_GRANTED) { 16607 if (getUidTargetSdkVersionLockedLPr(callingUid) 16608 < Build.VERSION_CODES.FROYO) { 16609 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16610 + Binder.getCallingUid()); 16611 return; 16612 } 16613 mContext.enforceCallingOrSelfPermission( 16614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16615 } 16616 16617 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16618 if (pir != null) { 16619 // Get all of the existing entries that exactly match this filter. 16620 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16621 if (existing != null && existing.size() == 1) { 16622 PreferredActivity cur = existing.get(0); 16623 if (DEBUG_PREFERRED) { 16624 Slog.i(TAG, "Checking replace of preferred:"); 16625 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16626 if (!cur.mPref.mAlways) { 16627 Slog.i(TAG, " -- CUR; not mAlways!"); 16628 } else { 16629 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16630 Slog.i(TAG, " -- CUR: mSet=" 16631 + Arrays.toString(cur.mPref.mSetComponents)); 16632 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16633 Slog.i(TAG, " -- NEW: mMatch=" 16634 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16635 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16636 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16637 } 16638 } 16639 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16640 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16641 && cur.mPref.sameSet(set)) { 16642 // Setting the preferred activity to what it happens to be already 16643 if (DEBUG_PREFERRED) { 16644 Slog.i(TAG, "Replacing with same preferred activity " 16645 + cur.mPref.mShortComponent + " for user " 16646 + userId + ":"); 16647 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16648 } 16649 return; 16650 } 16651 } 16652 16653 if (existing != null) { 16654 if (DEBUG_PREFERRED) { 16655 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16656 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16657 } 16658 for (int i = 0; i < existing.size(); i++) { 16659 PreferredActivity pa = existing.get(i); 16660 if (DEBUG_PREFERRED) { 16661 Slog.i(TAG, "Removing existing preferred activity " 16662 + pa.mPref.mComponent + ":"); 16663 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16664 } 16665 pir.removeFilter(pa); 16666 } 16667 } 16668 } 16669 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16670 "Replacing preferred"); 16671 } 16672 } 16673 16674 @Override 16675 public void clearPackagePreferredActivities(String packageName) { 16676 final int uid = Binder.getCallingUid(); 16677 // writer 16678 synchronized (mPackages) { 16679 PackageParser.Package pkg = mPackages.get(packageName); 16680 if (pkg == null || pkg.applicationInfo.uid != uid) { 16681 if (mContext.checkCallingOrSelfPermission( 16682 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16683 != PackageManager.PERMISSION_GRANTED) { 16684 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16685 < Build.VERSION_CODES.FROYO) { 16686 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16687 + Binder.getCallingUid()); 16688 return; 16689 } 16690 mContext.enforceCallingOrSelfPermission( 16691 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16692 } 16693 } 16694 16695 int user = UserHandle.getCallingUserId(); 16696 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16697 scheduleWritePackageRestrictionsLocked(user); 16698 } 16699 } 16700 } 16701 16702 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16703 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16704 ArrayList<PreferredActivity> removed = null; 16705 boolean changed = false; 16706 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16707 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16708 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16709 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16710 continue; 16711 } 16712 Iterator<PreferredActivity> it = pir.filterIterator(); 16713 while (it.hasNext()) { 16714 PreferredActivity pa = it.next(); 16715 // Mark entry for removal only if it matches the package name 16716 // and the entry is of type "always". 16717 if (packageName == null || 16718 (pa.mPref.mComponent.getPackageName().equals(packageName) 16719 && pa.mPref.mAlways)) { 16720 if (removed == null) { 16721 removed = new ArrayList<PreferredActivity>(); 16722 } 16723 removed.add(pa); 16724 } 16725 } 16726 if (removed != null) { 16727 for (int j=0; j<removed.size(); j++) { 16728 PreferredActivity pa = removed.get(j); 16729 pir.removeFilter(pa); 16730 } 16731 changed = true; 16732 } 16733 } 16734 return changed; 16735 } 16736 16737 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16738 private void clearIntentFilterVerificationsLPw(int userId) { 16739 final int packageCount = mPackages.size(); 16740 for (int i = 0; i < packageCount; i++) { 16741 PackageParser.Package pkg = mPackages.valueAt(i); 16742 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16743 } 16744 } 16745 16746 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16747 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16748 if (userId == UserHandle.USER_ALL) { 16749 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16750 sUserManager.getUserIds())) { 16751 for (int oneUserId : sUserManager.getUserIds()) { 16752 scheduleWritePackageRestrictionsLocked(oneUserId); 16753 } 16754 } 16755 } else { 16756 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16757 scheduleWritePackageRestrictionsLocked(userId); 16758 } 16759 } 16760 } 16761 16762 void clearDefaultBrowserIfNeeded(String packageName) { 16763 for (int oneUserId : sUserManager.getUserIds()) { 16764 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16765 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16766 if (packageName.equals(defaultBrowserPackageName)) { 16767 setDefaultBrowserPackageName(null, oneUserId); 16768 } 16769 } 16770 } 16771 16772 @Override 16773 public void resetApplicationPreferences(int userId) { 16774 mContext.enforceCallingOrSelfPermission( 16775 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16776 final long identity = Binder.clearCallingIdentity(); 16777 // writer 16778 try { 16779 synchronized (mPackages) { 16780 clearPackagePreferredActivitiesLPw(null, userId); 16781 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16782 // TODO: We have to reset the default SMS and Phone. This requires 16783 // significant refactoring to keep all default apps in the package 16784 // manager (cleaner but more work) or have the services provide 16785 // callbacks to the package manager to request a default app reset. 16786 applyFactoryDefaultBrowserLPw(userId); 16787 clearIntentFilterVerificationsLPw(userId); 16788 primeDomainVerificationsLPw(userId); 16789 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16790 scheduleWritePackageRestrictionsLocked(userId); 16791 } 16792 resetNetworkPolicies(userId); 16793 } finally { 16794 Binder.restoreCallingIdentity(identity); 16795 } 16796 } 16797 16798 @Override 16799 public int getPreferredActivities(List<IntentFilter> outFilters, 16800 List<ComponentName> outActivities, String packageName) { 16801 16802 int num = 0; 16803 final int userId = UserHandle.getCallingUserId(); 16804 // reader 16805 synchronized (mPackages) { 16806 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16807 if (pir != null) { 16808 final Iterator<PreferredActivity> it = pir.filterIterator(); 16809 while (it.hasNext()) { 16810 final PreferredActivity pa = it.next(); 16811 if (packageName == null 16812 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16813 && pa.mPref.mAlways)) { 16814 if (outFilters != null) { 16815 outFilters.add(new IntentFilter(pa)); 16816 } 16817 if (outActivities != null) { 16818 outActivities.add(pa.mPref.mComponent); 16819 } 16820 } 16821 } 16822 } 16823 } 16824 16825 return num; 16826 } 16827 16828 @Override 16829 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16830 int userId) { 16831 int callingUid = Binder.getCallingUid(); 16832 if (callingUid != Process.SYSTEM_UID) { 16833 throw new SecurityException( 16834 "addPersistentPreferredActivity can only be run by the system"); 16835 } 16836 if (filter.countActions() == 0) { 16837 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16838 return; 16839 } 16840 synchronized (mPackages) { 16841 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16842 ":"); 16843 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16844 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16845 new PersistentPreferredActivity(filter, activity)); 16846 scheduleWritePackageRestrictionsLocked(userId); 16847 } 16848 } 16849 16850 @Override 16851 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16852 int callingUid = Binder.getCallingUid(); 16853 if (callingUid != Process.SYSTEM_UID) { 16854 throw new SecurityException( 16855 "clearPackagePersistentPreferredActivities can only be run by the system"); 16856 } 16857 ArrayList<PersistentPreferredActivity> removed = null; 16858 boolean changed = false; 16859 synchronized (mPackages) { 16860 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16861 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16862 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16863 .valueAt(i); 16864 if (userId != thisUserId) { 16865 continue; 16866 } 16867 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16868 while (it.hasNext()) { 16869 PersistentPreferredActivity ppa = it.next(); 16870 // Mark entry for removal only if it matches the package name. 16871 if (ppa.mComponent.getPackageName().equals(packageName)) { 16872 if (removed == null) { 16873 removed = new ArrayList<PersistentPreferredActivity>(); 16874 } 16875 removed.add(ppa); 16876 } 16877 } 16878 if (removed != null) { 16879 for (int j=0; j<removed.size(); j++) { 16880 PersistentPreferredActivity ppa = removed.get(j); 16881 ppir.removeFilter(ppa); 16882 } 16883 changed = true; 16884 } 16885 } 16886 16887 if (changed) { 16888 scheduleWritePackageRestrictionsLocked(userId); 16889 } 16890 } 16891 } 16892 16893 /** 16894 * Common machinery for picking apart a restored XML blob and passing 16895 * it to a caller-supplied functor to be applied to the running system. 16896 */ 16897 private void restoreFromXml(XmlPullParser parser, int userId, 16898 String expectedStartTag, BlobXmlRestorer functor) 16899 throws IOException, XmlPullParserException { 16900 int type; 16901 while ((type = parser.next()) != XmlPullParser.START_TAG 16902 && type != XmlPullParser.END_DOCUMENT) { 16903 } 16904 if (type != XmlPullParser.START_TAG) { 16905 // oops didn't find a start tag?! 16906 if (DEBUG_BACKUP) { 16907 Slog.e(TAG, "Didn't find start tag during restore"); 16908 } 16909 return; 16910 } 16911Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16912 // this is supposed to be TAG_PREFERRED_BACKUP 16913 if (!expectedStartTag.equals(parser.getName())) { 16914 if (DEBUG_BACKUP) { 16915 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16916 } 16917 return; 16918 } 16919 16920 // skip interfering stuff, then we're aligned with the backing implementation 16921 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16922Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16923 functor.apply(parser, userId); 16924 } 16925 16926 private interface BlobXmlRestorer { 16927 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16928 } 16929 16930 /** 16931 * Non-Binder method, support for the backup/restore mechanism: write the 16932 * full set of preferred activities in its canonical XML format. Returns the 16933 * XML output as a byte array, or null if there is none. 16934 */ 16935 @Override 16936 public byte[] getPreferredActivityBackup(int userId) { 16937 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16938 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16939 } 16940 16941 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16942 try { 16943 final XmlSerializer serializer = new FastXmlSerializer(); 16944 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16945 serializer.startDocument(null, true); 16946 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16947 16948 synchronized (mPackages) { 16949 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16950 } 16951 16952 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16953 serializer.endDocument(); 16954 serializer.flush(); 16955 } catch (Exception e) { 16956 if (DEBUG_BACKUP) { 16957 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16958 } 16959 return null; 16960 } 16961 16962 return dataStream.toByteArray(); 16963 } 16964 16965 @Override 16966 public void restorePreferredActivities(byte[] backup, int userId) { 16967 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16968 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16969 } 16970 16971 try { 16972 final XmlPullParser parser = Xml.newPullParser(); 16973 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16974 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16975 new BlobXmlRestorer() { 16976 @Override 16977 public void apply(XmlPullParser parser, int userId) 16978 throws XmlPullParserException, IOException { 16979 synchronized (mPackages) { 16980 mSettings.readPreferredActivitiesLPw(parser, userId); 16981 } 16982 } 16983 } ); 16984 } catch (Exception e) { 16985 if (DEBUG_BACKUP) { 16986 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16987 } 16988 } 16989 } 16990 16991 /** 16992 * Non-Binder method, support for the backup/restore mechanism: write the 16993 * default browser (etc) settings in its canonical XML format. Returns the default 16994 * browser XML representation as a byte array, or null if there is none. 16995 */ 16996 @Override 16997 public byte[] getDefaultAppsBackup(int userId) { 16998 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16999 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17000 } 17001 17002 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17003 try { 17004 final XmlSerializer serializer = new FastXmlSerializer(); 17005 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17006 serializer.startDocument(null, true); 17007 serializer.startTag(null, TAG_DEFAULT_APPS); 17008 17009 synchronized (mPackages) { 17010 mSettings.writeDefaultAppsLPr(serializer, userId); 17011 } 17012 17013 serializer.endTag(null, TAG_DEFAULT_APPS); 17014 serializer.endDocument(); 17015 serializer.flush(); 17016 } catch (Exception e) { 17017 if (DEBUG_BACKUP) { 17018 Slog.e(TAG, "Unable to write default apps for backup", e); 17019 } 17020 return null; 17021 } 17022 17023 return dataStream.toByteArray(); 17024 } 17025 17026 @Override 17027 public void restoreDefaultApps(byte[] backup, int userId) { 17028 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17029 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17030 } 17031 17032 try { 17033 final XmlPullParser parser = Xml.newPullParser(); 17034 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17035 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17036 new BlobXmlRestorer() { 17037 @Override 17038 public void apply(XmlPullParser parser, int userId) 17039 throws XmlPullParserException, IOException { 17040 synchronized (mPackages) { 17041 mSettings.readDefaultAppsLPw(parser, userId); 17042 } 17043 } 17044 } ); 17045 } catch (Exception e) { 17046 if (DEBUG_BACKUP) { 17047 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17048 } 17049 } 17050 } 17051 17052 @Override 17053 public byte[] getIntentFilterVerificationBackup(int userId) { 17054 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17055 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17056 } 17057 17058 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17059 try { 17060 final XmlSerializer serializer = new FastXmlSerializer(); 17061 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17062 serializer.startDocument(null, true); 17063 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17064 17065 synchronized (mPackages) { 17066 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17067 } 17068 17069 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17070 serializer.endDocument(); 17071 serializer.flush(); 17072 } catch (Exception e) { 17073 if (DEBUG_BACKUP) { 17074 Slog.e(TAG, "Unable to write default apps for backup", e); 17075 } 17076 return null; 17077 } 17078 17079 return dataStream.toByteArray(); 17080 } 17081 17082 @Override 17083 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17084 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17085 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17086 } 17087 17088 try { 17089 final XmlPullParser parser = Xml.newPullParser(); 17090 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17091 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17092 new BlobXmlRestorer() { 17093 @Override 17094 public void apply(XmlPullParser parser, int userId) 17095 throws XmlPullParserException, IOException { 17096 synchronized (mPackages) { 17097 mSettings.readAllDomainVerificationsLPr(parser, userId); 17098 mSettings.writeLPr(); 17099 } 17100 } 17101 } ); 17102 } catch (Exception e) { 17103 if (DEBUG_BACKUP) { 17104 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17105 } 17106 } 17107 } 17108 17109 @Override 17110 public byte[] getPermissionGrantBackup(int userId) { 17111 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17112 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17113 } 17114 17115 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17116 try { 17117 final XmlSerializer serializer = new FastXmlSerializer(); 17118 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17119 serializer.startDocument(null, true); 17120 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17121 17122 synchronized (mPackages) { 17123 serializeRuntimePermissionGrantsLPr(serializer, userId); 17124 } 17125 17126 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17127 serializer.endDocument(); 17128 serializer.flush(); 17129 } catch (Exception e) { 17130 if (DEBUG_BACKUP) { 17131 Slog.e(TAG, "Unable to write default apps for backup", e); 17132 } 17133 return null; 17134 } 17135 17136 return dataStream.toByteArray(); 17137 } 17138 17139 @Override 17140 public void restorePermissionGrants(byte[] backup, int userId) { 17141 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17142 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17143 } 17144 17145 try { 17146 final XmlPullParser parser = Xml.newPullParser(); 17147 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17148 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17149 new BlobXmlRestorer() { 17150 @Override 17151 public void apply(XmlPullParser parser, int userId) 17152 throws XmlPullParserException, IOException { 17153 synchronized (mPackages) { 17154 processRestoredPermissionGrantsLPr(parser, userId); 17155 } 17156 } 17157 } ); 17158 } catch (Exception e) { 17159 if (DEBUG_BACKUP) { 17160 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17161 } 17162 } 17163 } 17164 17165 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17166 throws IOException { 17167 serializer.startTag(null, TAG_ALL_GRANTS); 17168 17169 final int N = mSettings.mPackages.size(); 17170 for (int i = 0; i < N; i++) { 17171 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17172 boolean pkgGrantsKnown = false; 17173 17174 PermissionsState packagePerms = ps.getPermissionsState(); 17175 17176 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17177 final int grantFlags = state.getFlags(); 17178 // only look at grants that are not system/policy fixed 17179 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17180 final boolean isGranted = state.isGranted(); 17181 // And only back up the user-twiddled state bits 17182 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17183 final String packageName = mSettings.mPackages.keyAt(i); 17184 if (!pkgGrantsKnown) { 17185 serializer.startTag(null, TAG_GRANT); 17186 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17187 pkgGrantsKnown = true; 17188 } 17189 17190 final boolean userSet = 17191 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17192 final boolean userFixed = 17193 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17194 final boolean revoke = 17195 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17196 17197 serializer.startTag(null, TAG_PERMISSION); 17198 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17199 if (isGranted) { 17200 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17201 } 17202 if (userSet) { 17203 serializer.attribute(null, ATTR_USER_SET, "true"); 17204 } 17205 if (userFixed) { 17206 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17207 } 17208 if (revoke) { 17209 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17210 } 17211 serializer.endTag(null, TAG_PERMISSION); 17212 } 17213 } 17214 } 17215 17216 if (pkgGrantsKnown) { 17217 serializer.endTag(null, TAG_GRANT); 17218 } 17219 } 17220 17221 serializer.endTag(null, TAG_ALL_GRANTS); 17222 } 17223 17224 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17225 throws XmlPullParserException, IOException { 17226 String pkgName = null; 17227 int outerDepth = parser.getDepth(); 17228 int type; 17229 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17230 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17231 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17232 continue; 17233 } 17234 17235 final String tagName = parser.getName(); 17236 if (tagName.equals(TAG_GRANT)) { 17237 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17238 if (DEBUG_BACKUP) { 17239 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17240 } 17241 } else if (tagName.equals(TAG_PERMISSION)) { 17242 17243 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17244 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17245 17246 int newFlagSet = 0; 17247 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17248 newFlagSet |= FLAG_PERMISSION_USER_SET; 17249 } 17250 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17251 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17252 } 17253 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17254 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17255 } 17256 if (DEBUG_BACKUP) { 17257 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17258 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17259 } 17260 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17261 if (ps != null) { 17262 // Already installed so we apply the grant immediately 17263 if (DEBUG_BACKUP) { 17264 Slog.v(TAG, " + already installed; applying"); 17265 } 17266 PermissionsState perms = ps.getPermissionsState(); 17267 BasePermission bp = mSettings.mPermissions.get(permName); 17268 if (bp != null) { 17269 if (isGranted) { 17270 perms.grantRuntimePermission(bp, userId); 17271 } 17272 if (newFlagSet != 0) { 17273 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17274 } 17275 } 17276 } else { 17277 // Need to wait for post-restore install to apply the grant 17278 if (DEBUG_BACKUP) { 17279 Slog.v(TAG, " - not yet installed; saving for later"); 17280 } 17281 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17282 isGranted, newFlagSet, userId); 17283 } 17284 } else { 17285 PackageManagerService.reportSettingsProblem(Log.WARN, 17286 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17287 XmlUtils.skipCurrentTag(parser); 17288 } 17289 } 17290 17291 scheduleWriteSettingsLocked(); 17292 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17293 } 17294 17295 @Override 17296 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17297 int sourceUserId, int targetUserId, int flags) { 17298 mContext.enforceCallingOrSelfPermission( 17299 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17300 int callingUid = Binder.getCallingUid(); 17301 enforceOwnerRights(ownerPackage, callingUid); 17302 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17303 if (intentFilter.countActions() == 0) { 17304 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17305 return; 17306 } 17307 synchronized (mPackages) { 17308 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17309 ownerPackage, targetUserId, flags); 17310 CrossProfileIntentResolver resolver = 17311 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17312 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17313 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17314 if (existing != null) { 17315 int size = existing.size(); 17316 for (int i = 0; i < size; i++) { 17317 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17318 return; 17319 } 17320 } 17321 } 17322 resolver.addFilter(newFilter); 17323 scheduleWritePackageRestrictionsLocked(sourceUserId); 17324 } 17325 } 17326 17327 @Override 17328 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17329 mContext.enforceCallingOrSelfPermission( 17330 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17331 int callingUid = Binder.getCallingUid(); 17332 enforceOwnerRights(ownerPackage, callingUid); 17333 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17334 synchronized (mPackages) { 17335 CrossProfileIntentResolver resolver = 17336 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17337 ArraySet<CrossProfileIntentFilter> set = 17338 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17339 for (CrossProfileIntentFilter filter : set) { 17340 if (filter.getOwnerPackage().equals(ownerPackage)) { 17341 resolver.removeFilter(filter); 17342 } 17343 } 17344 scheduleWritePackageRestrictionsLocked(sourceUserId); 17345 } 17346 } 17347 17348 // Enforcing that callingUid is owning pkg on userId 17349 private void enforceOwnerRights(String pkg, int callingUid) { 17350 // The system owns everything. 17351 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17352 return; 17353 } 17354 int callingUserId = UserHandle.getUserId(callingUid); 17355 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17356 if (pi == null) { 17357 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17358 + callingUserId); 17359 } 17360 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17361 throw new SecurityException("Calling uid " + callingUid 17362 + " does not own package " + pkg); 17363 } 17364 } 17365 17366 @Override 17367 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17368 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17369 } 17370 17371 private Intent getHomeIntent() { 17372 Intent intent = new Intent(Intent.ACTION_MAIN); 17373 intent.addCategory(Intent.CATEGORY_HOME); 17374 return intent; 17375 } 17376 17377 private IntentFilter getHomeFilter() { 17378 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17379 filter.addCategory(Intent.CATEGORY_HOME); 17380 filter.addCategory(Intent.CATEGORY_DEFAULT); 17381 return filter; 17382 } 17383 17384 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17385 int userId) { 17386 Intent intent = getHomeIntent(); 17387 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17388 PackageManager.GET_META_DATA, userId); 17389 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17390 true, false, false, userId); 17391 17392 allHomeCandidates.clear(); 17393 if (list != null) { 17394 for (ResolveInfo ri : list) { 17395 allHomeCandidates.add(ri); 17396 } 17397 } 17398 return (preferred == null || preferred.activityInfo == null) 17399 ? null 17400 : new ComponentName(preferred.activityInfo.packageName, 17401 preferred.activityInfo.name); 17402 } 17403 17404 @Override 17405 public void setHomeActivity(ComponentName comp, int userId) { 17406 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17407 getHomeActivitiesAsUser(homeActivities, userId); 17408 17409 boolean found = false; 17410 17411 final int size = homeActivities.size(); 17412 final ComponentName[] set = new ComponentName[size]; 17413 for (int i = 0; i < size; i++) { 17414 final ResolveInfo candidate = homeActivities.get(i); 17415 final ActivityInfo info = candidate.activityInfo; 17416 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17417 set[i] = activityName; 17418 if (!found && activityName.equals(comp)) { 17419 found = true; 17420 } 17421 } 17422 if (!found) { 17423 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17424 + userId); 17425 } 17426 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17427 set, comp, userId); 17428 } 17429 17430 private @Nullable String getSetupWizardPackageName() { 17431 final Intent intent = new Intent(Intent.ACTION_MAIN); 17432 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17433 17434 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17435 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17436 | MATCH_DISABLED_COMPONENTS, 17437 UserHandle.myUserId()); 17438 if (matches.size() == 1) { 17439 return matches.get(0).getComponentInfo().packageName; 17440 } else { 17441 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17442 + ": matches=" + matches); 17443 return null; 17444 } 17445 } 17446 17447 @Override 17448 public void setApplicationEnabledSetting(String appPackageName, 17449 int newState, int flags, int userId, String callingPackage) { 17450 if (!sUserManager.exists(userId)) return; 17451 if (callingPackage == null) { 17452 callingPackage = Integer.toString(Binder.getCallingUid()); 17453 } 17454 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17455 } 17456 17457 @Override 17458 public void setComponentEnabledSetting(ComponentName componentName, 17459 int newState, int flags, int userId) { 17460 if (!sUserManager.exists(userId)) return; 17461 setEnabledSetting(componentName.getPackageName(), 17462 componentName.getClassName(), newState, flags, userId, null); 17463 } 17464 17465 private void setEnabledSetting(final String packageName, String className, int newState, 17466 final int flags, int userId, String callingPackage) { 17467 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17468 || newState == COMPONENT_ENABLED_STATE_ENABLED 17469 || newState == COMPONENT_ENABLED_STATE_DISABLED 17470 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17471 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17472 throw new IllegalArgumentException("Invalid new component state: " 17473 + newState); 17474 } 17475 PackageSetting pkgSetting; 17476 final int uid = Binder.getCallingUid(); 17477 final int permission; 17478 if (uid == Process.SYSTEM_UID) { 17479 permission = PackageManager.PERMISSION_GRANTED; 17480 } else { 17481 permission = mContext.checkCallingOrSelfPermission( 17482 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17483 } 17484 enforceCrossUserPermission(uid, userId, 17485 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17486 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17487 boolean sendNow = false; 17488 boolean isApp = (className == null); 17489 String componentName = isApp ? packageName : className; 17490 int packageUid = -1; 17491 ArrayList<String> components; 17492 17493 // writer 17494 synchronized (mPackages) { 17495 pkgSetting = mSettings.mPackages.get(packageName); 17496 if (pkgSetting == null) { 17497 if (className == null) { 17498 throw new IllegalArgumentException("Unknown package: " + packageName); 17499 } 17500 throw new IllegalArgumentException( 17501 "Unknown component: " + packageName + "/" + className); 17502 } 17503 // Allow root and verify that userId is not being specified by a different user 17504 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17505 throw new SecurityException( 17506 "Permission Denial: attempt to change component state from pid=" 17507 + Binder.getCallingPid() 17508 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17509 } 17510 if (className == null) { 17511 // We're dealing with an application/package level state change 17512 if (pkgSetting.getEnabled(userId) == newState) { 17513 // Nothing to do 17514 return; 17515 } 17516 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17517 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17518 // Don't care about who enables an app. 17519 callingPackage = null; 17520 } 17521 pkgSetting.setEnabled(newState, userId, callingPackage); 17522 // pkgSetting.pkg.mSetEnabled = newState; 17523 } else { 17524 // We're dealing with a component level state change 17525 // First, verify that this is a valid class name. 17526 PackageParser.Package pkg = pkgSetting.pkg; 17527 if (pkg == null || !pkg.hasComponentClassName(className)) { 17528 if (pkg != null && 17529 pkg.applicationInfo.targetSdkVersion >= 17530 Build.VERSION_CODES.JELLY_BEAN) { 17531 throw new IllegalArgumentException("Component class " + className 17532 + " does not exist in " + packageName); 17533 } else { 17534 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17535 + className + " does not exist in " + packageName); 17536 } 17537 } 17538 switch (newState) { 17539 case COMPONENT_ENABLED_STATE_ENABLED: 17540 if (!pkgSetting.enableComponentLPw(className, userId)) { 17541 return; 17542 } 17543 break; 17544 case COMPONENT_ENABLED_STATE_DISABLED: 17545 if (!pkgSetting.disableComponentLPw(className, userId)) { 17546 return; 17547 } 17548 break; 17549 case COMPONENT_ENABLED_STATE_DEFAULT: 17550 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17551 return; 17552 } 17553 break; 17554 default: 17555 Slog.e(TAG, "Invalid new component state: " + newState); 17556 return; 17557 } 17558 } 17559 scheduleWritePackageRestrictionsLocked(userId); 17560 components = mPendingBroadcasts.get(userId, packageName); 17561 final boolean newPackage = components == null; 17562 if (newPackage) { 17563 components = new ArrayList<String>(); 17564 } 17565 if (!components.contains(componentName)) { 17566 components.add(componentName); 17567 } 17568 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17569 sendNow = true; 17570 // Purge entry from pending broadcast list if another one exists already 17571 // since we are sending one right away. 17572 mPendingBroadcasts.remove(userId, packageName); 17573 } else { 17574 if (newPackage) { 17575 mPendingBroadcasts.put(userId, packageName, components); 17576 } 17577 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17578 // Schedule a message 17579 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17580 } 17581 } 17582 } 17583 17584 long callingId = Binder.clearCallingIdentity(); 17585 try { 17586 if (sendNow) { 17587 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17588 sendPackageChangedBroadcast(packageName, 17589 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17590 } 17591 } finally { 17592 Binder.restoreCallingIdentity(callingId); 17593 } 17594 } 17595 17596 @Override 17597 public void flushPackageRestrictionsAsUser(int userId) { 17598 if (!sUserManager.exists(userId)) { 17599 return; 17600 } 17601 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17602 false /* checkShell */, "flushPackageRestrictions"); 17603 synchronized (mPackages) { 17604 mSettings.writePackageRestrictionsLPr(userId); 17605 mDirtyUsers.remove(userId); 17606 if (mDirtyUsers.isEmpty()) { 17607 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17608 } 17609 } 17610 } 17611 17612 private void sendPackageChangedBroadcast(String packageName, 17613 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17614 if (DEBUG_INSTALL) 17615 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17616 + componentNames); 17617 Bundle extras = new Bundle(4); 17618 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17619 String nameList[] = new String[componentNames.size()]; 17620 componentNames.toArray(nameList); 17621 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17622 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17623 extras.putInt(Intent.EXTRA_UID, packageUid); 17624 // If this is not reporting a change of the overall package, then only send it 17625 // to registered receivers. We don't want to launch a swath of apps for every 17626 // little component state change. 17627 final int flags = !componentNames.contains(packageName) 17628 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17629 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17630 new int[] {UserHandle.getUserId(packageUid)}); 17631 } 17632 17633 @Override 17634 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17635 if (!sUserManager.exists(userId)) return; 17636 final int uid = Binder.getCallingUid(); 17637 final int permission = mContext.checkCallingOrSelfPermission( 17638 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17639 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17640 enforceCrossUserPermission(uid, userId, 17641 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17642 // writer 17643 synchronized (mPackages) { 17644 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17645 allowedByPermission, uid, userId)) { 17646 scheduleWritePackageRestrictionsLocked(userId); 17647 } 17648 } 17649 } 17650 17651 @Override 17652 public String getInstallerPackageName(String packageName) { 17653 // reader 17654 synchronized (mPackages) { 17655 return mSettings.getInstallerPackageNameLPr(packageName); 17656 } 17657 } 17658 17659 public boolean isOrphaned(String packageName) { 17660 // reader 17661 synchronized (mPackages) { 17662 return mSettings.isOrphaned(packageName); 17663 } 17664 } 17665 17666 @Override 17667 public int getApplicationEnabledSetting(String packageName, int userId) { 17668 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17669 int uid = Binder.getCallingUid(); 17670 enforceCrossUserPermission(uid, userId, 17671 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17672 // reader 17673 synchronized (mPackages) { 17674 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17675 } 17676 } 17677 17678 @Override 17679 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17680 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17681 int uid = Binder.getCallingUid(); 17682 enforceCrossUserPermission(uid, userId, 17683 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17684 // reader 17685 synchronized (mPackages) { 17686 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17687 } 17688 } 17689 17690 @Override 17691 public void enterSafeMode() { 17692 enforceSystemOrRoot("Only the system can request entering safe mode"); 17693 17694 if (!mSystemReady) { 17695 mSafeMode = true; 17696 } 17697 } 17698 17699 @Override 17700 public void systemReady() { 17701 mSystemReady = true; 17702 17703 // Read the compatibilty setting when the system is ready. 17704 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17705 mContext.getContentResolver(), 17706 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17707 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17708 if (DEBUG_SETTINGS) { 17709 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17710 } 17711 17712 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17713 17714 synchronized (mPackages) { 17715 // Verify that all of the preferred activity components actually 17716 // exist. It is possible for applications to be updated and at 17717 // that point remove a previously declared activity component that 17718 // had been set as a preferred activity. We try to clean this up 17719 // the next time we encounter that preferred activity, but it is 17720 // possible for the user flow to never be able to return to that 17721 // situation so here we do a sanity check to make sure we haven't 17722 // left any junk around. 17723 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17724 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17725 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17726 removed.clear(); 17727 for (PreferredActivity pa : pir.filterSet()) { 17728 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17729 removed.add(pa); 17730 } 17731 } 17732 if (removed.size() > 0) { 17733 for (int r=0; r<removed.size(); r++) { 17734 PreferredActivity pa = removed.get(r); 17735 Slog.w(TAG, "Removing dangling preferred activity: " 17736 + pa.mPref.mComponent); 17737 pir.removeFilter(pa); 17738 } 17739 mSettings.writePackageRestrictionsLPr( 17740 mSettings.mPreferredActivities.keyAt(i)); 17741 } 17742 } 17743 17744 for (int userId : UserManagerService.getInstance().getUserIds()) { 17745 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17746 grantPermissionsUserIds = ArrayUtils.appendInt( 17747 grantPermissionsUserIds, userId); 17748 } 17749 } 17750 } 17751 sUserManager.systemReady(); 17752 17753 // If we upgraded grant all default permissions before kicking off. 17754 for (int userId : grantPermissionsUserIds) { 17755 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17756 } 17757 17758 // Kick off any messages waiting for system ready 17759 if (mPostSystemReadyMessages != null) { 17760 for (Message msg : mPostSystemReadyMessages) { 17761 msg.sendToTarget(); 17762 } 17763 mPostSystemReadyMessages = null; 17764 } 17765 17766 // Watch for external volumes that come and go over time 17767 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17768 storage.registerListener(mStorageListener); 17769 17770 mInstallerService.systemReady(); 17771 mPackageDexOptimizer.systemReady(); 17772 17773 MountServiceInternal mountServiceInternal = LocalServices.getService( 17774 MountServiceInternal.class); 17775 mountServiceInternal.addExternalStoragePolicy( 17776 new MountServiceInternal.ExternalStorageMountPolicy() { 17777 @Override 17778 public int getMountMode(int uid, String packageName) { 17779 if (Process.isIsolated(uid)) { 17780 return Zygote.MOUNT_EXTERNAL_NONE; 17781 } 17782 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17783 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17784 } 17785 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17786 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17787 } 17788 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17789 return Zygote.MOUNT_EXTERNAL_READ; 17790 } 17791 return Zygote.MOUNT_EXTERNAL_WRITE; 17792 } 17793 17794 @Override 17795 public boolean hasExternalStorage(int uid, String packageName) { 17796 return true; 17797 } 17798 }); 17799 17800 // Now that we're mostly running, clean up stale users and apps 17801 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17802 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17803 } 17804 17805 @Override 17806 public boolean isSafeMode() { 17807 return mSafeMode; 17808 } 17809 17810 @Override 17811 public boolean hasSystemUidErrors() { 17812 return mHasSystemUidErrors; 17813 } 17814 17815 static String arrayToString(int[] array) { 17816 StringBuffer buf = new StringBuffer(128); 17817 buf.append('['); 17818 if (array != null) { 17819 for (int i=0; i<array.length; i++) { 17820 if (i > 0) buf.append(", "); 17821 buf.append(array[i]); 17822 } 17823 } 17824 buf.append(']'); 17825 return buf.toString(); 17826 } 17827 17828 static class DumpState { 17829 public static final int DUMP_LIBS = 1 << 0; 17830 public static final int DUMP_FEATURES = 1 << 1; 17831 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17832 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17833 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17834 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17835 public static final int DUMP_PERMISSIONS = 1 << 6; 17836 public static final int DUMP_PACKAGES = 1 << 7; 17837 public static final int DUMP_SHARED_USERS = 1 << 8; 17838 public static final int DUMP_MESSAGES = 1 << 9; 17839 public static final int DUMP_PROVIDERS = 1 << 10; 17840 public static final int DUMP_VERIFIERS = 1 << 11; 17841 public static final int DUMP_PREFERRED = 1 << 12; 17842 public static final int DUMP_PREFERRED_XML = 1 << 13; 17843 public static final int DUMP_KEYSETS = 1 << 14; 17844 public static final int DUMP_VERSION = 1 << 15; 17845 public static final int DUMP_INSTALLS = 1 << 16; 17846 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17847 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17848 public static final int DUMP_FROZEN = 1 << 19; 17849 public static final int DUMP_DEXOPT = 1 << 20; 17850 17851 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17852 17853 private int mTypes; 17854 17855 private int mOptions; 17856 17857 private boolean mTitlePrinted; 17858 17859 private SharedUserSetting mSharedUser; 17860 17861 public boolean isDumping(int type) { 17862 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17863 return true; 17864 } 17865 17866 return (mTypes & type) != 0; 17867 } 17868 17869 public void setDump(int type) { 17870 mTypes |= type; 17871 } 17872 17873 public boolean isOptionEnabled(int option) { 17874 return (mOptions & option) != 0; 17875 } 17876 17877 public void setOptionEnabled(int option) { 17878 mOptions |= option; 17879 } 17880 17881 public boolean onTitlePrinted() { 17882 final boolean printed = mTitlePrinted; 17883 mTitlePrinted = true; 17884 return printed; 17885 } 17886 17887 public boolean getTitlePrinted() { 17888 return mTitlePrinted; 17889 } 17890 17891 public void setTitlePrinted(boolean enabled) { 17892 mTitlePrinted = enabled; 17893 } 17894 17895 public SharedUserSetting getSharedUser() { 17896 return mSharedUser; 17897 } 17898 17899 public void setSharedUser(SharedUserSetting user) { 17900 mSharedUser = user; 17901 } 17902 } 17903 17904 @Override 17905 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17906 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17907 (new PackageManagerShellCommand(this)).exec( 17908 this, in, out, err, args, resultReceiver); 17909 } 17910 17911 @Override 17912 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17913 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17914 != PackageManager.PERMISSION_GRANTED) { 17915 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17916 + Binder.getCallingPid() 17917 + ", uid=" + Binder.getCallingUid() 17918 + " without permission " 17919 + android.Manifest.permission.DUMP); 17920 return; 17921 } 17922 17923 DumpState dumpState = new DumpState(); 17924 boolean fullPreferred = false; 17925 boolean checkin = false; 17926 17927 String packageName = null; 17928 ArraySet<String> permissionNames = null; 17929 17930 int opti = 0; 17931 while (opti < args.length) { 17932 String opt = args[opti]; 17933 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17934 break; 17935 } 17936 opti++; 17937 17938 if ("-a".equals(opt)) { 17939 // Right now we only know how to print all. 17940 } else if ("-h".equals(opt)) { 17941 pw.println("Package manager dump options:"); 17942 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17943 pw.println(" --checkin: dump for a checkin"); 17944 pw.println(" -f: print details of intent filters"); 17945 pw.println(" -h: print this help"); 17946 pw.println(" cmd may be one of:"); 17947 pw.println(" l[ibraries]: list known shared libraries"); 17948 pw.println(" f[eatures]: list device features"); 17949 pw.println(" k[eysets]: print known keysets"); 17950 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17951 pw.println(" perm[issions]: dump permissions"); 17952 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17953 pw.println(" pref[erred]: print preferred package settings"); 17954 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17955 pw.println(" prov[iders]: dump content providers"); 17956 pw.println(" p[ackages]: dump installed packages"); 17957 pw.println(" s[hared-users]: dump shared user IDs"); 17958 pw.println(" m[essages]: print collected runtime messages"); 17959 pw.println(" v[erifiers]: print package verifier info"); 17960 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17961 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17962 pw.println(" version: print database version info"); 17963 pw.println(" write: write current settings now"); 17964 pw.println(" installs: details about install sessions"); 17965 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17966 pw.println(" dexopt: dump dexopt state"); 17967 pw.println(" <package.name>: info about given package"); 17968 return; 17969 } else if ("--checkin".equals(opt)) { 17970 checkin = true; 17971 } else if ("-f".equals(opt)) { 17972 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17973 } else { 17974 pw.println("Unknown argument: " + opt + "; use -h for help"); 17975 } 17976 } 17977 17978 // Is the caller requesting to dump a particular piece of data? 17979 if (opti < args.length) { 17980 String cmd = args[opti]; 17981 opti++; 17982 // Is this a package name? 17983 if ("android".equals(cmd) || cmd.contains(".")) { 17984 packageName = cmd; 17985 // When dumping a single package, we always dump all of its 17986 // filter information since the amount of data will be reasonable. 17987 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17988 } else if ("check-permission".equals(cmd)) { 17989 if (opti >= args.length) { 17990 pw.println("Error: check-permission missing permission argument"); 17991 return; 17992 } 17993 String perm = args[opti]; 17994 opti++; 17995 if (opti >= args.length) { 17996 pw.println("Error: check-permission missing package argument"); 17997 return; 17998 } 17999 String pkg = args[opti]; 18000 opti++; 18001 int user = UserHandle.getUserId(Binder.getCallingUid()); 18002 if (opti < args.length) { 18003 try { 18004 user = Integer.parseInt(args[opti]); 18005 } catch (NumberFormatException e) { 18006 pw.println("Error: check-permission user argument is not a number: " 18007 + args[opti]); 18008 return; 18009 } 18010 } 18011 pw.println(checkPermission(perm, pkg, user)); 18012 return; 18013 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18014 dumpState.setDump(DumpState.DUMP_LIBS); 18015 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18016 dumpState.setDump(DumpState.DUMP_FEATURES); 18017 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18018 if (opti >= args.length) { 18019 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18020 | DumpState.DUMP_SERVICE_RESOLVERS 18021 | DumpState.DUMP_RECEIVER_RESOLVERS 18022 | DumpState.DUMP_CONTENT_RESOLVERS); 18023 } else { 18024 while (opti < args.length) { 18025 String name = args[opti]; 18026 if ("a".equals(name) || "activity".equals(name)) { 18027 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18028 } else if ("s".equals(name) || "service".equals(name)) { 18029 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18030 } else if ("r".equals(name) || "receiver".equals(name)) { 18031 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18032 } else if ("c".equals(name) || "content".equals(name)) { 18033 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18034 } else { 18035 pw.println("Error: unknown resolver table type: " + name); 18036 return; 18037 } 18038 opti++; 18039 } 18040 } 18041 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18042 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18043 } else if ("permission".equals(cmd)) { 18044 if (opti >= args.length) { 18045 pw.println("Error: permission requires permission name"); 18046 return; 18047 } 18048 permissionNames = new ArraySet<>(); 18049 while (opti < args.length) { 18050 permissionNames.add(args[opti]); 18051 opti++; 18052 } 18053 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18054 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18055 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18056 dumpState.setDump(DumpState.DUMP_PREFERRED); 18057 } else if ("preferred-xml".equals(cmd)) { 18058 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18059 if (opti < args.length && "--full".equals(args[opti])) { 18060 fullPreferred = true; 18061 opti++; 18062 } 18063 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18064 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18065 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18066 dumpState.setDump(DumpState.DUMP_PACKAGES); 18067 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18068 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18069 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18070 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18071 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18072 dumpState.setDump(DumpState.DUMP_MESSAGES); 18073 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18074 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18075 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18076 || "intent-filter-verifiers".equals(cmd)) { 18077 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18078 } else if ("version".equals(cmd)) { 18079 dumpState.setDump(DumpState.DUMP_VERSION); 18080 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18081 dumpState.setDump(DumpState.DUMP_KEYSETS); 18082 } else if ("installs".equals(cmd)) { 18083 dumpState.setDump(DumpState.DUMP_INSTALLS); 18084 } else if ("frozen".equals(cmd)) { 18085 dumpState.setDump(DumpState.DUMP_FROZEN); 18086 } else if ("dexopt".equals(cmd)) { 18087 dumpState.setDump(DumpState.DUMP_DEXOPT); 18088 } else if ("write".equals(cmd)) { 18089 synchronized (mPackages) { 18090 mSettings.writeLPr(); 18091 pw.println("Settings written."); 18092 return; 18093 } 18094 } 18095 } 18096 18097 if (checkin) { 18098 pw.println("vers,1"); 18099 } 18100 18101 // reader 18102 synchronized (mPackages) { 18103 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18104 if (!checkin) { 18105 if (dumpState.onTitlePrinted()) 18106 pw.println(); 18107 pw.println("Database versions:"); 18108 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18109 } 18110 } 18111 18112 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18113 if (!checkin) { 18114 if (dumpState.onTitlePrinted()) 18115 pw.println(); 18116 pw.println("Verifiers:"); 18117 pw.print(" Required: "); 18118 pw.print(mRequiredVerifierPackage); 18119 pw.print(" (uid="); 18120 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18121 UserHandle.USER_SYSTEM)); 18122 pw.println(")"); 18123 } else if (mRequiredVerifierPackage != null) { 18124 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18125 pw.print(","); 18126 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18127 UserHandle.USER_SYSTEM)); 18128 } 18129 } 18130 18131 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18132 packageName == null) { 18133 if (mIntentFilterVerifierComponent != null) { 18134 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18135 if (!checkin) { 18136 if (dumpState.onTitlePrinted()) 18137 pw.println(); 18138 pw.println("Intent Filter Verifier:"); 18139 pw.print(" Using: "); 18140 pw.print(verifierPackageName); 18141 pw.print(" (uid="); 18142 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18143 UserHandle.USER_SYSTEM)); 18144 pw.println(")"); 18145 } else if (verifierPackageName != null) { 18146 pw.print("ifv,"); pw.print(verifierPackageName); 18147 pw.print(","); 18148 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18149 UserHandle.USER_SYSTEM)); 18150 } 18151 } else { 18152 pw.println(); 18153 pw.println("No Intent Filter Verifier available!"); 18154 } 18155 } 18156 18157 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18158 boolean printedHeader = false; 18159 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18160 while (it.hasNext()) { 18161 String name = it.next(); 18162 SharedLibraryEntry ent = mSharedLibraries.get(name); 18163 if (!checkin) { 18164 if (!printedHeader) { 18165 if (dumpState.onTitlePrinted()) 18166 pw.println(); 18167 pw.println("Libraries:"); 18168 printedHeader = true; 18169 } 18170 pw.print(" "); 18171 } else { 18172 pw.print("lib,"); 18173 } 18174 pw.print(name); 18175 if (!checkin) { 18176 pw.print(" -> "); 18177 } 18178 if (ent.path != null) { 18179 if (!checkin) { 18180 pw.print("(jar) "); 18181 pw.print(ent.path); 18182 } else { 18183 pw.print(",jar,"); 18184 pw.print(ent.path); 18185 } 18186 } else { 18187 if (!checkin) { 18188 pw.print("(apk) "); 18189 pw.print(ent.apk); 18190 } else { 18191 pw.print(",apk,"); 18192 pw.print(ent.apk); 18193 } 18194 } 18195 pw.println(); 18196 } 18197 } 18198 18199 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18200 if (dumpState.onTitlePrinted()) 18201 pw.println(); 18202 if (!checkin) { 18203 pw.println("Features:"); 18204 } 18205 18206 for (FeatureInfo feat : mAvailableFeatures.values()) { 18207 if (checkin) { 18208 pw.print("feat,"); 18209 pw.print(feat.name); 18210 pw.print(","); 18211 pw.println(feat.version); 18212 } else { 18213 pw.print(" "); 18214 pw.print(feat.name); 18215 if (feat.version > 0) { 18216 pw.print(" version="); 18217 pw.print(feat.version); 18218 } 18219 pw.println(); 18220 } 18221 } 18222 } 18223 18224 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18225 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18226 : "Activity Resolver Table:", " ", packageName, 18227 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18228 dumpState.setTitlePrinted(true); 18229 } 18230 } 18231 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18232 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18233 : "Receiver Resolver Table:", " ", packageName, 18234 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18235 dumpState.setTitlePrinted(true); 18236 } 18237 } 18238 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18239 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18240 : "Service Resolver Table:", " ", packageName, 18241 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18242 dumpState.setTitlePrinted(true); 18243 } 18244 } 18245 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18246 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18247 : "Provider Resolver Table:", " ", packageName, 18248 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18249 dumpState.setTitlePrinted(true); 18250 } 18251 } 18252 18253 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18254 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18255 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18256 int user = mSettings.mPreferredActivities.keyAt(i); 18257 if (pir.dump(pw, 18258 dumpState.getTitlePrinted() 18259 ? "\nPreferred Activities User " + user + ":" 18260 : "Preferred Activities User " + user + ":", " ", 18261 packageName, true, false)) { 18262 dumpState.setTitlePrinted(true); 18263 } 18264 } 18265 } 18266 18267 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18268 pw.flush(); 18269 FileOutputStream fout = new FileOutputStream(fd); 18270 BufferedOutputStream str = new BufferedOutputStream(fout); 18271 XmlSerializer serializer = new FastXmlSerializer(); 18272 try { 18273 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18274 serializer.startDocument(null, true); 18275 serializer.setFeature( 18276 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18277 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18278 serializer.endDocument(); 18279 serializer.flush(); 18280 } catch (IllegalArgumentException e) { 18281 pw.println("Failed writing: " + e); 18282 } catch (IllegalStateException e) { 18283 pw.println("Failed writing: " + e); 18284 } catch (IOException e) { 18285 pw.println("Failed writing: " + e); 18286 } 18287 } 18288 18289 if (!checkin 18290 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18291 && packageName == null) { 18292 pw.println(); 18293 int count = mSettings.mPackages.size(); 18294 if (count == 0) { 18295 pw.println("No applications!"); 18296 pw.println(); 18297 } else { 18298 final String prefix = " "; 18299 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18300 if (allPackageSettings.size() == 0) { 18301 pw.println("No domain preferred apps!"); 18302 pw.println(); 18303 } else { 18304 pw.println("App verification status:"); 18305 pw.println(); 18306 count = 0; 18307 for (PackageSetting ps : allPackageSettings) { 18308 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18309 if (ivi == null || ivi.getPackageName() == null) continue; 18310 pw.println(prefix + "Package: " + ivi.getPackageName()); 18311 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18312 pw.println(prefix + "Status: " + ivi.getStatusString()); 18313 pw.println(); 18314 count++; 18315 } 18316 if (count == 0) { 18317 pw.println(prefix + "No app verification established."); 18318 pw.println(); 18319 } 18320 for (int userId : sUserManager.getUserIds()) { 18321 pw.println("App linkages for user " + userId + ":"); 18322 pw.println(); 18323 count = 0; 18324 for (PackageSetting ps : allPackageSettings) { 18325 final long status = ps.getDomainVerificationStatusForUser(userId); 18326 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18327 continue; 18328 } 18329 pw.println(prefix + "Package: " + ps.name); 18330 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18331 String statusStr = IntentFilterVerificationInfo. 18332 getStatusStringFromValue(status); 18333 pw.println(prefix + "Status: " + statusStr); 18334 pw.println(); 18335 count++; 18336 } 18337 if (count == 0) { 18338 pw.println(prefix + "No configured app linkages."); 18339 pw.println(); 18340 } 18341 } 18342 } 18343 } 18344 } 18345 18346 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18347 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18348 if (packageName == null && permissionNames == null) { 18349 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18350 if (iperm == 0) { 18351 if (dumpState.onTitlePrinted()) 18352 pw.println(); 18353 pw.println("AppOp Permissions:"); 18354 } 18355 pw.print(" AppOp Permission "); 18356 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18357 pw.println(":"); 18358 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18359 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18360 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18361 } 18362 } 18363 } 18364 } 18365 18366 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18367 boolean printedSomething = false; 18368 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18369 if (packageName != null && !packageName.equals(p.info.packageName)) { 18370 continue; 18371 } 18372 if (!printedSomething) { 18373 if (dumpState.onTitlePrinted()) 18374 pw.println(); 18375 pw.println("Registered ContentProviders:"); 18376 printedSomething = true; 18377 } 18378 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18379 pw.print(" "); pw.println(p.toString()); 18380 } 18381 printedSomething = false; 18382 for (Map.Entry<String, PackageParser.Provider> entry : 18383 mProvidersByAuthority.entrySet()) { 18384 PackageParser.Provider p = entry.getValue(); 18385 if (packageName != null && !packageName.equals(p.info.packageName)) { 18386 continue; 18387 } 18388 if (!printedSomething) { 18389 if (dumpState.onTitlePrinted()) 18390 pw.println(); 18391 pw.println("ContentProvider Authorities:"); 18392 printedSomething = true; 18393 } 18394 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18395 pw.print(" "); pw.println(p.toString()); 18396 if (p.info != null && p.info.applicationInfo != null) { 18397 final String appInfo = p.info.applicationInfo.toString(); 18398 pw.print(" applicationInfo="); pw.println(appInfo); 18399 } 18400 } 18401 } 18402 18403 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18404 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18405 } 18406 18407 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18408 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18409 } 18410 18411 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18412 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18413 } 18414 18415 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18416 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18417 } 18418 18419 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18420 // XXX should handle packageName != null by dumping only install data that 18421 // the given package is involved with. 18422 if (dumpState.onTitlePrinted()) pw.println(); 18423 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18424 } 18425 18426 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18427 // XXX should handle packageName != null by dumping only install data that 18428 // the given package is involved with. 18429 if (dumpState.onTitlePrinted()) pw.println(); 18430 18431 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18432 ipw.println(); 18433 ipw.println("Frozen packages:"); 18434 ipw.increaseIndent(); 18435 if (mFrozenPackages.size() == 0) { 18436 ipw.println("(none)"); 18437 } else { 18438 for (int i = 0; i < mFrozenPackages.size(); i++) { 18439 ipw.println(mFrozenPackages.valueAt(i)); 18440 } 18441 } 18442 ipw.decreaseIndent(); 18443 } 18444 18445 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18446 if (dumpState.onTitlePrinted()) pw.println(); 18447 dumpDexoptStateLPr(pw, packageName); 18448 } 18449 18450 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18451 if (dumpState.onTitlePrinted()) pw.println(); 18452 mSettings.dumpReadMessagesLPr(pw, dumpState); 18453 18454 pw.println(); 18455 pw.println("Package warning messages:"); 18456 BufferedReader in = null; 18457 String line = null; 18458 try { 18459 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18460 while ((line = in.readLine()) != null) { 18461 if (line.contains("ignored: updated version")) continue; 18462 pw.println(line); 18463 } 18464 } catch (IOException ignored) { 18465 } finally { 18466 IoUtils.closeQuietly(in); 18467 } 18468 } 18469 18470 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18471 BufferedReader in = null; 18472 String line = null; 18473 try { 18474 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18475 while ((line = in.readLine()) != null) { 18476 if (line.contains("ignored: updated version")) continue; 18477 pw.print("msg,"); 18478 pw.println(line); 18479 } 18480 } catch (IOException ignored) { 18481 } finally { 18482 IoUtils.closeQuietly(in); 18483 } 18484 } 18485 } 18486 } 18487 18488 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18489 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18490 ipw.println(); 18491 ipw.println("Dexopt state:"); 18492 ipw.increaseIndent(); 18493 Collection<PackageParser.Package> packages = null; 18494 if (packageName != null) { 18495 PackageParser.Package targetPackage = mPackages.get(packageName); 18496 if (targetPackage != null) { 18497 packages = Collections.singletonList(targetPackage); 18498 } else { 18499 ipw.println("Unable to find package: " + packageName); 18500 return; 18501 } 18502 } else { 18503 packages = mPackages.values(); 18504 } 18505 18506 for (PackageParser.Package pkg : packages) { 18507 ipw.println("[" + pkg.packageName + "]"); 18508 ipw.increaseIndent(); 18509 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18510 ipw.decreaseIndent(); 18511 } 18512 } 18513 18514 private String dumpDomainString(String packageName) { 18515 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18516 .getList(); 18517 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18518 18519 ArraySet<String> result = new ArraySet<>(); 18520 if (iviList.size() > 0) { 18521 for (IntentFilterVerificationInfo ivi : iviList) { 18522 for (String host : ivi.getDomains()) { 18523 result.add(host); 18524 } 18525 } 18526 } 18527 if (filters != null && filters.size() > 0) { 18528 for (IntentFilter filter : filters) { 18529 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18530 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18531 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18532 result.addAll(filter.getHostsList()); 18533 } 18534 } 18535 } 18536 18537 StringBuilder sb = new StringBuilder(result.size() * 16); 18538 for (String domain : result) { 18539 if (sb.length() > 0) sb.append(" "); 18540 sb.append(domain); 18541 } 18542 return sb.toString(); 18543 } 18544 18545 // ------- apps on sdcard specific code ------- 18546 static final boolean DEBUG_SD_INSTALL = false; 18547 18548 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18549 18550 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18551 18552 private boolean mMediaMounted = false; 18553 18554 static String getEncryptKey() { 18555 try { 18556 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18557 SD_ENCRYPTION_KEYSTORE_NAME); 18558 if (sdEncKey == null) { 18559 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18560 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18561 if (sdEncKey == null) { 18562 Slog.e(TAG, "Failed to create encryption keys"); 18563 return null; 18564 } 18565 } 18566 return sdEncKey; 18567 } catch (NoSuchAlgorithmException nsae) { 18568 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18569 return null; 18570 } catch (IOException ioe) { 18571 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18572 return null; 18573 } 18574 } 18575 18576 /* 18577 * Update media status on PackageManager. 18578 */ 18579 @Override 18580 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18581 int callingUid = Binder.getCallingUid(); 18582 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18583 throw new SecurityException("Media status can only be updated by the system"); 18584 } 18585 // reader; this apparently protects mMediaMounted, but should probably 18586 // be a different lock in that case. 18587 synchronized (mPackages) { 18588 Log.i(TAG, "Updating external media status from " 18589 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18590 + (mediaStatus ? "mounted" : "unmounted")); 18591 if (DEBUG_SD_INSTALL) 18592 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18593 + ", mMediaMounted=" + mMediaMounted); 18594 if (mediaStatus == mMediaMounted) { 18595 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18596 : 0, -1); 18597 mHandler.sendMessage(msg); 18598 return; 18599 } 18600 mMediaMounted = mediaStatus; 18601 } 18602 // Queue up an async operation since the package installation may take a 18603 // little while. 18604 mHandler.post(new Runnable() { 18605 public void run() { 18606 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18607 } 18608 }); 18609 } 18610 18611 /** 18612 * Called by MountService when the initial ASECs to scan are available. 18613 * Should block until all the ASEC containers are finished being scanned. 18614 */ 18615 public void scanAvailableAsecs() { 18616 updateExternalMediaStatusInner(true, false, false); 18617 } 18618 18619 /* 18620 * Collect information of applications on external media, map them against 18621 * existing containers and update information based on current mount status. 18622 * Please note that we always have to report status if reportStatus has been 18623 * set to true especially when unloading packages. 18624 */ 18625 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18626 boolean externalStorage) { 18627 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18628 int[] uidArr = EmptyArray.INT; 18629 18630 final String[] list = PackageHelper.getSecureContainerList(); 18631 if (ArrayUtils.isEmpty(list)) { 18632 Log.i(TAG, "No secure containers found"); 18633 } else { 18634 // Process list of secure containers and categorize them 18635 // as active or stale based on their package internal state. 18636 18637 // reader 18638 synchronized (mPackages) { 18639 for (String cid : list) { 18640 // Leave stages untouched for now; installer service owns them 18641 if (PackageInstallerService.isStageName(cid)) continue; 18642 18643 if (DEBUG_SD_INSTALL) 18644 Log.i(TAG, "Processing container " + cid); 18645 String pkgName = getAsecPackageName(cid); 18646 if (pkgName == null) { 18647 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18648 continue; 18649 } 18650 if (DEBUG_SD_INSTALL) 18651 Log.i(TAG, "Looking for pkg : " + pkgName); 18652 18653 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18654 if (ps == null) { 18655 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18656 continue; 18657 } 18658 18659 /* 18660 * Skip packages that are not external if we're unmounting 18661 * external storage. 18662 */ 18663 if (externalStorage && !isMounted && !isExternal(ps)) { 18664 continue; 18665 } 18666 18667 final AsecInstallArgs args = new AsecInstallArgs(cid, 18668 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18669 // The package status is changed only if the code path 18670 // matches between settings and the container id. 18671 if (ps.codePathString != null 18672 && ps.codePathString.startsWith(args.getCodePath())) { 18673 if (DEBUG_SD_INSTALL) { 18674 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18675 + " at code path: " + ps.codePathString); 18676 } 18677 18678 // We do have a valid package installed on sdcard 18679 processCids.put(args, ps.codePathString); 18680 final int uid = ps.appId; 18681 if (uid != -1) { 18682 uidArr = ArrayUtils.appendInt(uidArr, uid); 18683 } 18684 } else { 18685 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18686 + ps.codePathString); 18687 } 18688 } 18689 } 18690 18691 Arrays.sort(uidArr); 18692 } 18693 18694 // Process packages with valid entries. 18695 if (isMounted) { 18696 if (DEBUG_SD_INSTALL) 18697 Log.i(TAG, "Loading packages"); 18698 loadMediaPackages(processCids, uidArr, externalStorage); 18699 startCleaningPackages(); 18700 mInstallerService.onSecureContainersAvailable(); 18701 } else { 18702 if (DEBUG_SD_INSTALL) 18703 Log.i(TAG, "Unloading packages"); 18704 unloadMediaPackages(processCids, uidArr, reportStatus); 18705 } 18706 } 18707 18708 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18709 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18710 final int size = infos.size(); 18711 final String[] packageNames = new String[size]; 18712 final int[] packageUids = new int[size]; 18713 for (int i = 0; i < size; i++) { 18714 final ApplicationInfo info = infos.get(i); 18715 packageNames[i] = info.packageName; 18716 packageUids[i] = info.uid; 18717 } 18718 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18719 finishedReceiver); 18720 } 18721 18722 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18723 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18724 sendResourcesChangedBroadcast(mediaStatus, replacing, 18725 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18726 } 18727 18728 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18729 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18730 int size = pkgList.length; 18731 if (size > 0) { 18732 // Send broadcasts here 18733 Bundle extras = new Bundle(); 18734 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18735 if (uidArr != null) { 18736 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18737 } 18738 if (replacing) { 18739 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18740 } 18741 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18742 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18743 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18744 } 18745 } 18746 18747 /* 18748 * Look at potentially valid container ids from processCids If package 18749 * information doesn't match the one on record or package scanning fails, 18750 * the cid is added to list of removeCids. We currently don't delete stale 18751 * containers. 18752 */ 18753 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18754 boolean externalStorage) { 18755 ArrayList<String> pkgList = new ArrayList<String>(); 18756 Set<AsecInstallArgs> keys = processCids.keySet(); 18757 18758 for (AsecInstallArgs args : keys) { 18759 String codePath = processCids.get(args); 18760 if (DEBUG_SD_INSTALL) 18761 Log.i(TAG, "Loading container : " + args.cid); 18762 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18763 try { 18764 // Make sure there are no container errors first. 18765 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18766 Slog.e(TAG, "Failed to mount cid : " + args.cid 18767 + " when installing from sdcard"); 18768 continue; 18769 } 18770 // Check code path here. 18771 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18772 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18773 + " does not match one in settings " + codePath); 18774 continue; 18775 } 18776 // Parse package 18777 int parseFlags = mDefParseFlags; 18778 if (args.isExternalAsec()) { 18779 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18780 } 18781 if (args.isFwdLocked()) { 18782 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18783 } 18784 18785 synchronized (mInstallLock) { 18786 PackageParser.Package pkg = null; 18787 try { 18788 // Sadly we don't know the package name yet to freeze it 18789 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18790 SCAN_IGNORE_FROZEN, 0, null); 18791 } catch (PackageManagerException e) { 18792 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18793 } 18794 // Scan the package 18795 if (pkg != null) { 18796 /* 18797 * TODO why is the lock being held? doPostInstall is 18798 * called in other places without the lock. This needs 18799 * to be straightened out. 18800 */ 18801 // writer 18802 synchronized (mPackages) { 18803 retCode = PackageManager.INSTALL_SUCCEEDED; 18804 pkgList.add(pkg.packageName); 18805 // Post process args 18806 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18807 pkg.applicationInfo.uid); 18808 } 18809 } else { 18810 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18811 } 18812 } 18813 18814 } finally { 18815 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18816 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18817 } 18818 } 18819 } 18820 // writer 18821 synchronized (mPackages) { 18822 // If the platform SDK has changed since the last time we booted, 18823 // we need to re-grant app permission to catch any new ones that 18824 // appear. This is really a hack, and means that apps can in some 18825 // cases get permissions that the user didn't initially explicitly 18826 // allow... it would be nice to have some better way to handle 18827 // this situation. 18828 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18829 : mSettings.getInternalVersion(); 18830 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18831 : StorageManager.UUID_PRIVATE_INTERNAL; 18832 18833 int updateFlags = UPDATE_PERMISSIONS_ALL; 18834 if (ver.sdkVersion != mSdkVersion) { 18835 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18836 + mSdkVersion + "; regranting permissions for external"); 18837 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18838 } 18839 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18840 18841 // Yay, everything is now upgraded 18842 ver.forceCurrent(); 18843 18844 // can downgrade to reader 18845 // Persist settings 18846 mSettings.writeLPr(); 18847 } 18848 // Send a broadcast to let everyone know we are done processing 18849 if (pkgList.size() > 0) { 18850 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18851 } 18852 } 18853 18854 /* 18855 * Utility method to unload a list of specified containers 18856 */ 18857 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18858 // Just unmount all valid containers. 18859 for (AsecInstallArgs arg : cidArgs) { 18860 synchronized (mInstallLock) { 18861 arg.doPostDeleteLI(false); 18862 } 18863 } 18864 } 18865 18866 /* 18867 * Unload packages mounted on external media. This involves deleting package 18868 * data from internal structures, sending broadcasts about disabled packages, 18869 * gc'ing to free up references, unmounting all secure containers 18870 * corresponding to packages on external media, and posting a 18871 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18872 * that we always have to post this message if status has been requested no 18873 * matter what. 18874 */ 18875 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18876 final boolean reportStatus) { 18877 if (DEBUG_SD_INSTALL) 18878 Log.i(TAG, "unloading media packages"); 18879 ArrayList<String> pkgList = new ArrayList<String>(); 18880 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18881 final Set<AsecInstallArgs> keys = processCids.keySet(); 18882 for (AsecInstallArgs args : keys) { 18883 String pkgName = args.getPackageName(); 18884 if (DEBUG_SD_INSTALL) 18885 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18886 // Delete package internally 18887 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18888 synchronized (mInstallLock) { 18889 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18890 final boolean res; 18891 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18892 "unloadMediaPackages")) { 18893 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18894 null); 18895 } 18896 if (res) { 18897 pkgList.add(pkgName); 18898 } else { 18899 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18900 failedList.add(args); 18901 } 18902 } 18903 } 18904 18905 // reader 18906 synchronized (mPackages) { 18907 // We didn't update the settings after removing each package; 18908 // write them now for all packages. 18909 mSettings.writeLPr(); 18910 } 18911 18912 // We have to absolutely send UPDATED_MEDIA_STATUS only 18913 // after confirming that all the receivers processed the ordered 18914 // broadcast when packages get disabled, force a gc to clean things up. 18915 // and unload all the containers. 18916 if (pkgList.size() > 0) { 18917 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18918 new IIntentReceiver.Stub() { 18919 public void performReceive(Intent intent, int resultCode, String data, 18920 Bundle extras, boolean ordered, boolean sticky, 18921 int sendingUser) throws RemoteException { 18922 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18923 reportStatus ? 1 : 0, 1, keys); 18924 mHandler.sendMessage(msg); 18925 } 18926 }); 18927 } else { 18928 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18929 keys); 18930 mHandler.sendMessage(msg); 18931 } 18932 } 18933 18934 private void loadPrivatePackages(final VolumeInfo vol) { 18935 mHandler.post(new Runnable() { 18936 @Override 18937 public void run() { 18938 loadPrivatePackagesInner(vol); 18939 } 18940 }); 18941 } 18942 18943 private void loadPrivatePackagesInner(VolumeInfo vol) { 18944 final String volumeUuid = vol.fsUuid; 18945 if (TextUtils.isEmpty(volumeUuid)) { 18946 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18947 return; 18948 } 18949 18950 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18951 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18952 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18953 18954 final VersionInfo ver; 18955 final List<PackageSetting> packages; 18956 synchronized (mPackages) { 18957 ver = mSettings.findOrCreateVersion(volumeUuid); 18958 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18959 } 18960 18961 for (PackageSetting ps : packages) { 18962 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18963 synchronized (mInstallLock) { 18964 final PackageParser.Package pkg; 18965 try { 18966 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18967 loaded.add(pkg.applicationInfo); 18968 18969 } catch (PackageManagerException e) { 18970 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18971 } 18972 18973 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18974 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18975 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18976 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18977 } 18978 } 18979 } 18980 18981 // Reconcile app data for all started/unlocked users 18982 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18983 final UserManager um = mContext.getSystemService(UserManager.class); 18984 for (UserInfo user : um.getUsers()) { 18985 final int flags; 18986 if (um.isUserUnlockingOrUnlocked(user.id)) { 18987 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18988 } else if (um.isUserRunning(user.id)) { 18989 flags = StorageManager.FLAG_STORAGE_DE; 18990 } else { 18991 continue; 18992 } 18993 18994 try { 18995 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18996 synchronized (mInstallLock) { 18997 reconcileAppsDataLI(volumeUuid, user.id, flags); 18998 } 18999 } catch (IllegalStateException e) { 19000 // Device was probably ejected, and we'll process that event momentarily 19001 Slog.w(TAG, "Failed to prepare storage: " + e); 19002 } 19003 } 19004 19005 synchronized (mPackages) { 19006 int updateFlags = UPDATE_PERMISSIONS_ALL; 19007 if (ver.sdkVersion != mSdkVersion) { 19008 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19009 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19010 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19011 } 19012 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19013 19014 // Yay, everything is now upgraded 19015 ver.forceCurrent(); 19016 19017 mSettings.writeLPr(); 19018 } 19019 19020 for (PackageFreezer freezer : freezers) { 19021 freezer.close(); 19022 } 19023 19024 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19025 sendResourcesChangedBroadcast(true, false, loaded, null); 19026 } 19027 19028 private void unloadPrivatePackages(final VolumeInfo vol) { 19029 mHandler.post(new Runnable() { 19030 @Override 19031 public void run() { 19032 unloadPrivatePackagesInner(vol); 19033 } 19034 }); 19035 } 19036 19037 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19038 final String volumeUuid = vol.fsUuid; 19039 if (TextUtils.isEmpty(volumeUuid)) { 19040 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19041 return; 19042 } 19043 19044 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19045 synchronized (mInstallLock) { 19046 synchronized (mPackages) { 19047 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19048 for (PackageSetting ps : packages) { 19049 if (ps.pkg == null) continue; 19050 19051 final ApplicationInfo info = ps.pkg.applicationInfo; 19052 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19053 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19054 19055 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19056 "unloadPrivatePackagesInner")) { 19057 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19058 false, null)) { 19059 unloaded.add(info); 19060 } else { 19061 Slog.w(TAG, "Failed to unload " + ps.codePath); 19062 } 19063 } 19064 } 19065 19066 mSettings.writeLPr(); 19067 } 19068 } 19069 19070 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19071 sendResourcesChangedBroadcast(false, false, unloaded, null); 19072 } 19073 19074 /** 19075 * Prepare storage areas for given user on all mounted devices. 19076 */ 19077 void prepareUserData(int userId, int userSerial, int flags) { 19078 synchronized (mInstallLock) { 19079 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19080 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19081 final String volumeUuid = vol.getFsUuid(); 19082 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19083 } 19084 } 19085 } 19086 19087 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19088 boolean allowRecover) { 19089 // Prepare storage and verify that serial numbers are consistent; if 19090 // there's a mismatch we need to destroy to avoid leaking data 19091 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19092 try { 19093 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19094 19095 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19096 UserManagerService.enforceSerialNumber( 19097 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19098 } 19099 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19100 UserManagerService.enforceSerialNumber( 19101 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19102 } 19103 19104 synchronized (mInstallLock) { 19105 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19106 } 19107 } catch (Exception e) { 19108 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19109 + " because we failed to prepare: " + e); 19110 destroyUserDataLI(volumeUuid, userId, 19111 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19112 19113 if (allowRecover) { 19114 // Try one last time; if we fail again we're really in trouble 19115 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19116 } 19117 } 19118 } 19119 19120 /** 19121 * Destroy storage areas for given user on all mounted devices. 19122 */ 19123 void destroyUserData(int userId, int flags) { 19124 synchronized (mInstallLock) { 19125 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19126 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19127 final String volumeUuid = vol.getFsUuid(); 19128 destroyUserDataLI(volumeUuid, userId, flags); 19129 } 19130 } 19131 } 19132 19133 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19134 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19135 try { 19136 // Clean up app data, profile data, and media data 19137 mInstaller.destroyUserData(volumeUuid, userId, flags); 19138 19139 // Clean up system data 19140 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19141 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19142 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19143 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19144 } 19145 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19146 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19147 } 19148 } 19149 19150 // Data with special labels is now gone, so finish the job 19151 storage.destroyUserStorage(volumeUuid, userId, flags); 19152 19153 } catch (Exception e) { 19154 logCriticalInfo(Log.WARN, 19155 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19156 } 19157 } 19158 19159 /** 19160 * Examine all users present on given mounted volume, and destroy data 19161 * belonging to users that are no longer valid, or whose user ID has been 19162 * recycled. 19163 */ 19164 private void reconcileUsers(String volumeUuid) { 19165 final List<File> files = new ArrayList<>(); 19166 Collections.addAll(files, FileUtils 19167 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19168 Collections.addAll(files, FileUtils 19169 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19170 for (File file : files) { 19171 if (!file.isDirectory()) continue; 19172 19173 final int userId; 19174 final UserInfo info; 19175 try { 19176 userId = Integer.parseInt(file.getName()); 19177 info = sUserManager.getUserInfo(userId); 19178 } catch (NumberFormatException e) { 19179 Slog.w(TAG, "Invalid user directory " + file); 19180 continue; 19181 } 19182 19183 boolean destroyUser = false; 19184 if (info == null) { 19185 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19186 + " because no matching user was found"); 19187 destroyUser = true; 19188 } else if (!mOnlyCore) { 19189 try { 19190 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19191 } catch (IOException e) { 19192 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19193 + " because we failed to enforce serial number: " + e); 19194 destroyUser = true; 19195 } 19196 } 19197 19198 if (destroyUser) { 19199 synchronized (mInstallLock) { 19200 destroyUserDataLI(volumeUuid, userId, 19201 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19202 } 19203 } 19204 } 19205 } 19206 19207 private void assertPackageKnown(String volumeUuid, String packageName) 19208 throws PackageManagerException { 19209 synchronized (mPackages) { 19210 final PackageSetting ps = mSettings.mPackages.get(packageName); 19211 if (ps == null) { 19212 throw new PackageManagerException("Package " + packageName + " is unknown"); 19213 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19214 throw new PackageManagerException( 19215 "Package " + packageName + " found on unknown volume " + volumeUuid 19216 + "; expected volume " + ps.volumeUuid); 19217 } 19218 } 19219 } 19220 19221 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19222 throws PackageManagerException { 19223 synchronized (mPackages) { 19224 final PackageSetting ps = mSettings.mPackages.get(packageName); 19225 if (ps == null) { 19226 throw new PackageManagerException("Package " + packageName + " is unknown"); 19227 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19228 throw new PackageManagerException( 19229 "Package " + packageName + " found on unknown volume " + volumeUuid 19230 + "; expected volume " + ps.volumeUuid); 19231 } else if (!ps.getInstalled(userId)) { 19232 throw new PackageManagerException( 19233 "Package " + packageName + " not installed for user " + userId); 19234 } 19235 } 19236 } 19237 19238 /** 19239 * Examine all apps present on given mounted volume, and destroy apps that 19240 * aren't expected, either due to uninstallation or reinstallation on 19241 * another volume. 19242 */ 19243 private void reconcileApps(String volumeUuid) { 19244 final File[] files = FileUtils 19245 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19246 for (File file : files) { 19247 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19248 && !PackageInstallerService.isStageName(file.getName()); 19249 if (!isPackage) { 19250 // Ignore entries which are not packages 19251 continue; 19252 } 19253 19254 try { 19255 final PackageLite pkg = PackageParser.parsePackageLite(file, 19256 PackageParser.PARSE_MUST_BE_APK); 19257 assertPackageKnown(volumeUuid, pkg.packageName); 19258 19259 } catch (PackageParserException | PackageManagerException e) { 19260 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19261 synchronized (mInstallLock) { 19262 removeCodePathLI(file); 19263 } 19264 } 19265 } 19266 } 19267 19268 /** 19269 * Reconcile all app data for the given user. 19270 * <p> 19271 * Verifies that directories exist and that ownership and labeling is 19272 * correct for all installed apps on all mounted volumes. 19273 */ 19274 void reconcileAppsData(int userId, int flags) { 19275 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19276 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19277 final String volumeUuid = vol.getFsUuid(); 19278 synchronized (mInstallLock) { 19279 reconcileAppsDataLI(volumeUuid, userId, flags); 19280 } 19281 } 19282 } 19283 19284 /** 19285 * Reconcile all app data on given mounted volume. 19286 * <p> 19287 * Destroys app data that isn't expected, either due to uninstallation or 19288 * reinstallation on another volume. 19289 * <p> 19290 * Verifies that directories exist and that ownership and labeling is 19291 * correct for all installed apps. 19292 */ 19293 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19294 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19295 + Integer.toHexString(flags)); 19296 19297 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19298 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19299 19300 boolean restoreconNeeded = false; 19301 19302 // First look for stale data that doesn't belong, and check if things 19303 // have changed since we did our last restorecon 19304 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19305 if (StorageManager.isFileEncryptedNativeOrEmulated() 19306 && !StorageManager.isUserKeyUnlocked(userId)) { 19307 throw new RuntimeException( 19308 "Yikes, someone asked us to reconcile CE storage while " + userId 19309 + " was still locked; this would have caused massive data loss!"); 19310 } 19311 19312 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19313 19314 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19315 for (File file : files) { 19316 final String packageName = file.getName(); 19317 try { 19318 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19319 } catch (PackageManagerException e) { 19320 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19321 try { 19322 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19323 StorageManager.FLAG_STORAGE_CE, 0); 19324 } catch (InstallerException e2) { 19325 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19326 } 19327 } 19328 } 19329 } 19330 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19331 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19332 19333 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19334 for (File file : files) { 19335 final String packageName = file.getName(); 19336 try { 19337 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19338 } catch (PackageManagerException e) { 19339 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19340 try { 19341 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19342 StorageManager.FLAG_STORAGE_DE, 0); 19343 } catch (InstallerException e2) { 19344 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19345 } 19346 } 19347 } 19348 } 19349 19350 // Ensure that data directories are ready to roll for all packages 19351 // installed for this volume and user 19352 final List<PackageSetting> packages; 19353 synchronized (mPackages) { 19354 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19355 } 19356 int preparedCount = 0; 19357 for (PackageSetting ps : packages) { 19358 final String packageName = ps.name; 19359 if (ps.pkg == null) { 19360 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19361 // TODO: might be due to legacy ASEC apps; we should circle back 19362 // and reconcile again once they're scanned 19363 continue; 19364 } 19365 19366 if (ps.getInstalled(userId)) { 19367 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19368 19369 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19370 // We may have just shuffled around app data directories, so 19371 // prepare them one more time 19372 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19373 } 19374 19375 preparedCount++; 19376 } 19377 } 19378 19379 if (restoreconNeeded) { 19380 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19381 SELinuxMMAC.setRestoreconDone(ceDir); 19382 } 19383 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19384 SELinuxMMAC.setRestoreconDone(deDir); 19385 } 19386 } 19387 19388 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19389 + " packages; restoreconNeeded was " + restoreconNeeded); 19390 } 19391 19392 /** 19393 * Prepare app data for the given app just after it was installed or 19394 * upgraded. This method carefully only touches users that it's installed 19395 * for, and it forces a restorecon to handle any seinfo changes. 19396 * <p> 19397 * Verifies that directories exist and that ownership and labeling is 19398 * correct for all installed apps. If there is an ownership mismatch, it 19399 * will try recovering system apps by wiping data; third-party app data is 19400 * left intact. 19401 * <p> 19402 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19403 */ 19404 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19405 final PackageSetting ps; 19406 synchronized (mPackages) { 19407 ps = mSettings.mPackages.get(pkg.packageName); 19408 mSettings.writeKernelMappingLPr(ps); 19409 } 19410 19411 final UserManager um = mContext.getSystemService(UserManager.class); 19412 for (UserInfo user : um.getUsers()) { 19413 final int flags; 19414 if (um.isUserUnlockingOrUnlocked(user.id)) { 19415 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19416 } else if (um.isUserRunning(user.id)) { 19417 flags = StorageManager.FLAG_STORAGE_DE; 19418 } else { 19419 continue; 19420 } 19421 19422 if (ps.getInstalled(user.id)) { 19423 // Whenever an app changes, force a restorecon of its data 19424 // TODO: when user data is locked, mark that we're still dirty 19425 prepareAppDataLIF(pkg, user.id, flags, true); 19426 } 19427 } 19428 } 19429 19430 /** 19431 * Prepare app data for the given app. 19432 * <p> 19433 * Verifies that directories exist and that ownership and labeling is 19434 * correct for all installed apps. If there is an ownership mismatch, this 19435 * will try recovering system apps by wiping data; third-party app data is 19436 * left intact. 19437 */ 19438 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19439 boolean restoreconNeeded) { 19440 if (pkg == null) { 19441 Slog.wtf(TAG, "Package was null!", new Throwable()); 19442 return; 19443 } 19444 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19445 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19446 for (int i = 0; i < childCount; i++) { 19447 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19448 } 19449 } 19450 19451 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19452 boolean restoreconNeeded) { 19453 if (DEBUG_APP_DATA) { 19454 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19455 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19456 } 19457 19458 final String volumeUuid = pkg.volumeUuid; 19459 final String packageName = pkg.packageName; 19460 final ApplicationInfo app = pkg.applicationInfo; 19461 final int appId = UserHandle.getAppId(app.uid); 19462 19463 Preconditions.checkNotNull(app.seinfo); 19464 19465 try { 19466 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19467 appId, app.seinfo, app.targetSdkVersion); 19468 } catch (InstallerException e) { 19469 if (app.isSystemApp()) { 19470 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19471 + ", but trying to recover: " + e); 19472 destroyAppDataLeafLIF(pkg, userId, flags); 19473 try { 19474 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19475 appId, app.seinfo, app.targetSdkVersion); 19476 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19477 } catch (InstallerException e2) { 19478 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19479 } 19480 } else { 19481 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19482 } 19483 } 19484 19485 if (restoreconNeeded) { 19486 try { 19487 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19488 app.seinfo); 19489 } catch (InstallerException e) { 19490 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19491 } 19492 } 19493 19494 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19495 try { 19496 // CE storage is unlocked right now, so read out the inode and 19497 // remember for use later when it's locked 19498 // TODO: mark this structure as dirty so we persist it! 19499 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19500 StorageManager.FLAG_STORAGE_CE); 19501 synchronized (mPackages) { 19502 final PackageSetting ps = mSettings.mPackages.get(packageName); 19503 if (ps != null) { 19504 ps.setCeDataInode(ceDataInode, userId); 19505 } 19506 } 19507 } catch (InstallerException e) { 19508 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19509 } 19510 } 19511 19512 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19513 } 19514 19515 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19516 if (pkg == null) { 19517 Slog.wtf(TAG, "Package was null!", new Throwable()); 19518 return; 19519 } 19520 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19521 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19522 for (int i = 0; i < childCount; i++) { 19523 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19524 } 19525 } 19526 19527 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19528 final String volumeUuid = pkg.volumeUuid; 19529 final String packageName = pkg.packageName; 19530 final ApplicationInfo app = pkg.applicationInfo; 19531 19532 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19533 // Create a native library symlink only if we have native libraries 19534 // and if the native libraries are 32 bit libraries. We do not provide 19535 // this symlink for 64 bit libraries. 19536 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19537 final String nativeLibPath = app.nativeLibraryDir; 19538 try { 19539 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19540 nativeLibPath, userId); 19541 } catch (InstallerException e) { 19542 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19543 } 19544 } 19545 } 19546 } 19547 19548 /** 19549 * For system apps on non-FBE devices, this method migrates any existing 19550 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19551 * requested by the app. 19552 */ 19553 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19554 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19555 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19556 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19557 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19558 try { 19559 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19560 storageTarget); 19561 } catch (InstallerException e) { 19562 logCriticalInfo(Log.WARN, 19563 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19564 } 19565 return true; 19566 } else { 19567 return false; 19568 } 19569 } 19570 19571 public PackageFreezer freezePackage(String packageName, String killReason) { 19572 return new PackageFreezer(packageName, killReason); 19573 } 19574 19575 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19576 String killReason) { 19577 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19578 return new PackageFreezer(); 19579 } else { 19580 return freezePackage(packageName, killReason); 19581 } 19582 } 19583 19584 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19585 String killReason) { 19586 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19587 return new PackageFreezer(); 19588 } else { 19589 return freezePackage(packageName, killReason); 19590 } 19591 } 19592 19593 /** 19594 * Class that freezes and kills the given package upon creation, and 19595 * unfreezes it upon closing. This is typically used when doing surgery on 19596 * app code/data to prevent the app from running while you're working. 19597 */ 19598 private class PackageFreezer implements AutoCloseable { 19599 private final String mPackageName; 19600 private final PackageFreezer[] mChildren; 19601 19602 private final boolean mWeFroze; 19603 19604 private final AtomicBoolean mClosed = new AtomicBoolean(); 19605 private final CloseGuard mCloseGuard = CloseGuard.get(); 19606 19607 /** 19608 * Create and return a stub freezer that doesn't actually do anything, 19609 * typically used when someone requested 19610 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19611 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19612 */ 19613 public PackageFreezer() { 19614 mPackageName = null; 19615 mChildren = null; 19616 mWeFroze = false; 19617 mCloseGuard.open("close"); 19618 } 19619 19620 public PackageFreezer(String packageName, String killReason) { 19621 synchronized (mPackages) { 19622 mPackageName = packageName; 19623 mWeFroze = mFrozenPackages.add(mPackageName); 19624 19625 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19626 if (ps != null) { 19627 killApplication(ps.name, ps.appId, killReason); 19628 } 19629 19630 final PackageParser.Package p = mPackages.get(packageName); 19631 if (p != null && p.childPackages != null) { 19632 final int N = p.childPackages.size(); 19633 mChildren = new PackageFreezer[N]; 19634 for (int i = 0; i < N; i++) { 19635 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19636 killReason); 19637 } 19638 } else { 19639 mChildren = null; 19640 } 19641 } 19642 mCloseGuard.open("close"); 19643 } 19644 19645 @Override 19646 protected void finalize() throws Throwable { 19647 try { 19648 mCloseGuard.warnIfOpen(); 19649 close(); 19650 } finally { 19651 super.finalize(); 19652 } 19653 } 19654 19655 @Override 19656 public void close() { 19657 mCloseGuard.close(); 19658 if (mClosed.compareAndSet(false, true)) { 19659 synchronized (mPackages) { 19660 if (mWeFroze) { 19661 mFrozenPackages.remove(mPackageName); 19662 } 19663 19664 if (mChildren != null) { 19665 for (PackageFreezer freezer : mChildren) { 19666 freezer.close(); 19667 } 19668 } 19669 } 19670 } 19671 } 19672 } 19673 19674 /** 19675 * Verify that given package is currently frozen. 19676 */ 19677 private void checkPackageFrozen(String packageName) { 19678 synchronized (mPackages) { 19679 if (!mFrozenPackages.contains(packageName)) { 19680 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19681 } 19682 } 19683 } 19684 19685 @Override 19686 public int movePackage(final String packageName, final String volumeUuid) { 19687 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19688 19689 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19690 final int moveId = mNextMoveId.getAndIncrement(); 19691 mHandler.post(new Runnable() { 19692 @Override 19693 public void run() { 19694 try { 19695 movePackageInternal(packageName, volumeUuid, moveId, user); 19696 } catch (PackageManagerException e) { 19697 Slog.w(TAG, "Failed to move " + packageName, e); 19698 mMoveCallbacks.notifyStatusChanged(moveId, 19699 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19700 } 19701 } 19702 }); 19703 return moveId; 19704 } 19705 19706 private void movePackageInternal(final String packageName, final String volumeUuid, 19707 final int moveId, UserHandle user) throws PackageManagerException { 19708 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19709 final PackageManager pm = mContext.getPackageManager(); 19710 19711 final boolean currentAsec; 19712 final String currentVolumeUuid; 19713 final File codeFile; 19714 final String installerPackageName; 19715 final String packageAbiOverride; 19716 final int appId; 19717 final String seinfo; 19718 final String label; 19719 final int targetSdkVersion; 19720 final PackageFreezer freezer; 19721 final int[] installedUserIds; 19722 19723 // reader 19724 synchronized (mPackages) { 19725 final PackageParser.Package pkg = mPackages.get(packageName); 19726 final PackageSetting ps = mSettings.mPackages.get(packageName); 19727 if (pkg == null || ps == null) { 19728 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19729 } 19730 19731 if (pkg.applicationInfo.isSystemApp()) { 19732 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19733 "Cannot move system application"); 19734 } 19735 19736 if (pkg.applicationInfo.isExternalAsec()) { 19737 currentAsec = true; 19738 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19739 } else if (pkg.applicationInfo.isForwardLocked()) { 19740 currentAsec = true; 19741 currentVolumeUuid = "forward_locked"; 19742 } else { 19743 currentAsec = false; 19744 currentVolumeUuid = ps.volumeUuid; 19745 19746 final File probe = new File(pkg.codePath); 19747 final File probeOat = new File(probe, "oat"); 19748 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19749 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19750 "Move only supported for modern cluster style installs"); 19751 } 19752 } 19753 19754 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19755 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19756 "Package already moved to " + volumeUuid); 19757 } 19758 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19759 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19760 "Device admin cannot be moved"); 19761 } 19762 19763 if (mFrozenPackages.contains(packageName)) { 19764 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19765 "Failed to move already frozen package"); 19766 } 19767 19768 codeFile = new File(pkg.codePath); 19769 installerPackageName = ps.installerPackageName; 19770 packageAbiOverride = ps.cpuAbiOverrideString; 19771 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19772 seinfo = pkg.applicationInfo.seinfo; 19773 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19774 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19775 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19776 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19777 } 19778 19779 final Bundle extras = new Bundle(); 19780 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19781 extras.putString(Intent.EXTRA_TITLE, label); 19782 mMoveCallbacks.notifyCreated(moveId, extras); 19783 19784 int installFlags; 19785 final boolean moveCompleteApp; 19786 final File measurePath; 19787 19788 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19789 installFlags = INSTALL_INTERNAL; 19790 moveCompleteApp = !currentAsec; 19791 measurePath = Environment.getDataAppDirectory(volumeUuid); 19792 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19793 installFlags = INSTALL_EXTERNAL; 19794 moveCompleteApp = false; 19795 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19796 } else { 19797 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19798 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19799 || !volume.isMountedWritable()) { 19800 freezer.close(); 19801 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19802 "Move location not mounted private volume"); 19803 } 19804 19805 Preconditions.checkState(!currentAsec); 19806 19807 installFlags = INSTALL_INTERNAL; 19808 moveCompleteApp = true; 19809 measurePath = Environment.getDataAppDirectory(volumeUuid); 19810 } 19811 19812 final PackageStats stats = new PackageStats(null, -1); 19813 synchronized (mInstaller) { 19814 for (int userId : installedUserIds) { 19815 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19816 freezer.close(); 19817 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19818 "Failed to measure package size"); 19819 } 19820 } 19821 } 19822 19823 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19824 + stats.dataSize); 19825 19826 final long startFreeBytes = measurePath.getFreeSpace(); 19827 final long sizeBytes; 19828 if (moveCompleteApp) { 19829 sizeBytes = stats.codeSize + stats.dataSize; 19830 } else { 19831 sizeBytes = stats.codeSize; 19832 } 19833 19834 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19835 freezer.close(); 19836 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19837 "Not enough free space to move"); 19838 } 19839 19840 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19841 19842 final CountDownLatch installedLatch = new CountDownLatch(1); 19843 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19844 @Override 19845 public void onUserActionRequired(Intent intent) throws RemoteException { 19846 throw new IllegalStateException(); 19847 } 19848 19849 @Override 19850 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19851 Bundle extras) throws RemoteException { 19852 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19853 + PackageManager.installStatusToString(returnCode, msg)); 19854 19855 installedLatch.countDown(); 19856 freezer.close(); 19857 19858 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19859 switch (status) { 19860 case PackageInstaller.STATUS_SUCCESS: 19861 mMoveCallbacks.notifyStatusChanged(moveId, 19862 PackageManager.MOVE_SUCCEEDED); 19863 break; 19864 case PackageInstaller.STATUS_FAILURE_STORAGE: 19865 mMoveCallbacks.notifyStatusChanged(moveId, 19866 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19867 break; 19868 default: 19869 mMoveCallbacks.notifyStatusChanged(moveId, 19870 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19871 break; 19872 } 19873 } 19874 }; 19875 19876 final MoveInfo move; 19877 if (moveCompleteApp) { 19878 // Kick off a thread to report progress estimates 19879 new Thread() { 19880 @Override 19881 public void run() { 19882 while (true) { 19883 try { 19884 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19885 break; 19886 } 19887 } catch (InterruptedException ignored) { 19888 } 19889 19890 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19891 final int progress = 10 + (int) MathUtils.constrain( 19892 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19893 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19894 } 19895 } 19896 }.start(); 19897 19898 final String dataAppName = codeFile.getName(); 19899 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19900 dataAppName, appId, seinfo, targetSdkVersion); 19901 } else { 19902 move = null; 19903 } 19904 19905 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19906 19907 final Message msg = mHandler.obtainMessage(INIT_COPY); 19908 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19909 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19910 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19911 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19912 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19913 msg.obj = params; 19914 19915 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19916 System.identityHashCode(msg.obj)); 19917 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19918 System.identityHashCode(msg.obj)); 19919 19920 mHandler.sendMessage(msg); 19921 } 19922 19923 @Override 19924 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19926 19927 final int realMoveId = mNextMoveId.getAndIncrement(); 19928 final Bundle extras = new Bundle(); 19929 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19930 mMoveCallbacks.notifyCreated(realMoveId, extras); 19931 19932 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19933 @Override 19934 public void onCreated(int moveId, Bundle extras) { 19935 // Ignored 19936 } 19937 19938 @Override 19939 public void onStatusChanged(int moveId, int status, long estMillis) { 19940 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19941 } 19942 }; 19943 19944 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19945 storage.setPrimaryStorageUuid(volumeUuid, callback); 19946 return realMoveId; 19947 } 19948 19949 @Override 19950 public int getMoveStatus(int moveId) { 19951 mContext.enforceCallingOrSelfPermission( 19952 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19953 return mMoveCallbacks.mLastStatus.get(moveId); 19954 } 19955 19956 @Override 19957 public void registerMoveCallback(IPackageMoveObserver callback) { 19958 mContext.enforceCallingOrSelfPermission( 19959 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19960 mMoveCallbacks.register(callback); 19961 } 19962 19963 @Override 19964 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19965 mContext.enforceCallingOrSelfPermission( 19966 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19967 mMoveCallbacks.unregister(callback); 19968 } 19969 19970 @Override 19971 public boolean setInstallLocation(int loc) { 19972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19973 null); 19974 if (getInstallLocation() == loc) { 19975 return true; 19976 } 19977 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19978 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19979 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19980 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19981 return true; 19982 } 19983 return false; 19984 } 19985 19986 @Override 19987 public int getInstallLocation() { 19988 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19989 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19990 PackageHelper.APP_INSTALL_AUTO); 19991 } 19992 19993 /** Called by UserManagerService */ 19994 void cleanUpUser(UserManagerService userManager, int userHandle) { 19995 synchronized (mPackages) { 19996 mDirtyUsers.remove(userHandle); 19997 mUserNeedsBadging.delete(userHandle); 19998 mSettings.removeUserLPw(userHandle); 19999 mPendingBroadcasts.remove(userHandle); 20000 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20001 removeUnusedPackagesLPw(userManager, userHandle); 20002 } 20003 } 20004 20005 /** 20006 * We're removing userHandle and would like to remove any downloaded packages 20007 * that are no longer in use by any other user. 20008 * @param userHandle the user being removed 20009 */ 20010 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20011 final boolean DEBUG_CLEAN_APKS = false; 20012 int [] users = userManager.getUserIds(); 20013 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20014 while (psit.hasNext()) { 20015 PackageSetting ps = psit.next(); 20016 if (ps.pkg == null) { 20017 continue; 20018 } 20019 final String packageName = ps.pkg.packageName; 20020 // Skip over if system app 20021 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20022 continue; 20023 } 20024 if (DEBUG_CLEAN_APKS) { 20025 Slog.i(TAG, "Checking package " + packageName); 20026 } 20027 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20028 if (keep) { 20029 if (DEBUG_CLEAN_APKS) { 20030 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20031 } 20032 } else { 20033 for (int i = 0; i < users.length; i++) { 20034 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20035 keep = true; 20036 if (DEBUG_CLEAN_APKS) { 20037 Slog.i(TAG, " Keeping package " + packageName + " for user " 20038 + users[i]); 20039 } 20040 break; 20041 } 20042 } 20043 } 20044 if (!keep) { 20045 if (DEBUG_CLEAN_APKS) { 20046 Slog.i(TAG, " Removing package " + packageName); 20047 } 20048 mHandler.post(new Runnable() { 20049 public void run() { 20050 deletePackageX(packageName, userHandle, 0); 20051 } //end run 20052 }); 20053 } 20054 } 20055 } 20056 20057 /** Called by UserManagerService */ 20058 void createNewUser(int userId) { 20059 synchronized (mInstallLock) { 20060 mSettings.createNewUserLI(this, mInstaller, userId); 20061 } 20062 synchronized (mPackages) { 20063 scheduleWritePackageRestrictionsLocked(userId); 20064 scheduleWritePackageListLocked(userId); 20065 applyFactoryDefaultBrowserLPw(userId); 20066 primeDomainVerificationsLPw(userId); 20067 } 20068 } 20069 20070 void newUserCreated(final int userHandle) { 20071 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20072 // If permission review for legacy apps is required, we represent 20073 // dagerous permissions for such apps as always granted runtime 20074 // permissions to keep per user flag state whether review is needed. 20075 // Hence, if a new user is added we have to propagate dangerous 20076 // permission grants for these legacy apps. 20077 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20078 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20079 | UPDATE_PERMISSIONS_REPLACE_ALL); 20080 } 20081 } 20082 20083 @Override 20084 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20085 mContext.enforceCallingOrSelfPermission( 20086 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20087 "Only package verification agents can read the verifier device identity"); 20088 20089 synchronized (mPackages) { 20090 return mSettings.getVerifierDeviceIdentityLPw(); 20091 } 20092 } 20093 20094 @Override 20095 public void setPermissionEnforced(String permission, boolean enforced) { 20096 // TODO: Now that we no longer change GID for storage, this should to away. 20097 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20098 "setPermissionEnforced"); 20099 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20100 synchronized (mPackages) { 20101 if (mSettings.mReadExternalStorageEnforced == null 20102 || mSettings.mReadExternalStorageEnforced != enforced) { 20103 mSettings.mReadExternalStorageEnforced = enforced; 20104 mSettings.writeLPr(); 20105 } 20106 } 20107 // kill any non-foreground processes so we restart them and 20108 // grant/revoke the GID. 20109 final IActivityManager am = ActivityManagerNative.getDefault(); 20110 if (am != null) { 20111 final long token = Binder.clearCallingIdentity(); 20112 try { 20113 am.killProcessesBelowForeground("setPermissionEnforcement"); 20114 } catch (RemoteException e) { 20115 } finally { 20116 Binder.restoreCallingIdentity(token); 20117 } 20118 } 20119 } else { 20120 throw new IllegalArgumentException("No selective enforcement for " + permission); 20121 } 20122 } 20123 20124 @Override 20125 @Deprecated 20126 public boolean isPermissionEnforced(String permission) { 20127 return true; 20128 } 20129 20130 @Override 20131 public boolean isStorageLow() { 20132 final long token = Binder.clearCallingIdentity(); 20133 try { 20134 final DeviceStorageMonitorInternal 20135 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20136 if (dsm != null) { 20137 return dsm.isMemoryLow(); 20138 } else { 20139 return false; 20140 } 20141 } finally { 20142 Binder.restoreCallingIdentity(token); 20143 } 20144 } 20145 20146 @Override 20147 public IPackageInstaller getPackageInstaller() { 20148 return mInstallerService; 20149 } 20150 20151 private boolean userNeedsBadging(int userId) { 20152 int index = mUserNeedsBadging.indexOfKey(userId); 20153 if (index < 0) { 20154 final UserInfo userInfo; 20155 final long token = Binder.clearCallingIdentity(); 20156 try { 20157 userInfo = sUserManager.getUserInfo(userId); 20158 } finally { 20159 Binder.restoreCallingIdentity(token); 20160 } 20161 final boolean b; 20162 if (userInfo != null && userInfo.isManagedProfile()) { 20163 b = true; 20164 } else { 20165 b = false; 20166 } 20167 mUserNeedsBadging.put(userId, b); 20168 return b; 20169 } 20170 return mUserNeedsBadging.valueAt(index); 20171 } 20172 20173 @Override 20174 public KeySet getKeySetByAlias(String packageName, String alias) { 20175 if (packageName == null || alias == null) { 20176 return null; 20177 } 20178 synchronized(mPackages) { 20179 final PackageParser.Package pkg = mPackages.get(packageName); 20180 if (pkg == null) { 20181 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20182 throw new IllegalArgumentException("Unknown package: " + packageName); 20183 } 20184 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20185 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20186 } 20187 } 20188 20189 @Override 20190 public KeySet getSigningKeySet(String packageName) { 20191 if (packageName == null) { 20192 return null; 20193 } 20194 synchronized(mPackages) { 20195 final PackageParser.Package pkg = mPackages.get(packageName); 20196 if (pkg == null) { 20197 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20198 throw new IllegalArgumentException("Unknown package: " + packageName); 20199 } 20200 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20201 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20202 throw new SecurityException("May not access signing KeySet of other apps."); 20203 } 20204 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20205 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20206 } 20207 } 20208 20209 @Override 20210 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20211 if (packageName == null || ks == null) { 20212 return false; 20213 } 20214 synchronized(mPackages) { 20215 final PackageParser.Package pkg = mPackages.get(packageName); 20216 if (pkg == null) { 20217 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20218 throw new IllegalArgumentException("Unknown package: " + packageName); 20219 } 20220 IBinder ksh = ks.getToken(); 20221 if (ksh instanceof KeySetHandle) { 20222 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20223 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20224 } 20225 return false; 20226 } 20227 } 20228 20229 @Override 20230 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20231 if (packageName == null || ks == null) { 20232 return false; 20233 } 20234 synchronized(mPackages) { 20235 final PackageParser.Package pkg = mPackages.get(packageName); 20236 if (pkg == null) { 20237 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20238 throw new IllegalArgumentException("Unknown package: " + packageName); 20239 } 20240 IBinder ksh = ks.getToken(); 20241 if (ksh instanceof KeySetHandle) { 20242 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20243 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20244 } 20245 return false; 20246 } 20247 } 20248 20249 private void deletePackageIfUnusedLPr(final String packageName) { 20250 PackageSetting ps = mSettings.mPackages.get(packageName); 20251 if (ps == null) { 20252 return; 20253 } 20254 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20255 // TODO Implement atomic delete if package is unused 20256 // It is currently possible that the package will be deleted even if it is installed 20257 // after this method returns. 20258 mHandler.post(new Runnable() { 20259 public void run() { 20260 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20261 } 20262 }); 20263 } 20264 } 20265 20266 /** 20267 * Check and throw if the given before/after packages would be considered a 20268 * downgrade. 20269 */ 20270 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20271 throws PackageManagerException { 20272 if (after.versionCode < before.mVersionCode) { 20273 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20274 "Update version code " + after.versionCode + " is older than current " 20275 + before.mVersionCode); 20276 } else if (after.versionCode == before.mVersionCode) { 20277 if (after.baseRevisionCode < before.baseRevisionCode) { 20278 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20279 "Update base revision code " + after.baseRevisionCode 20280 + " is older than current " + before.baseRevisionCode); 20281 } 20282 20283 if (!ArrayUtils.isEmpty(after.splitNames)) { 20284 for (int i = 0; i < after.splitNames.length; i++) { 20285 final String splitName = after.splitNames[i]; 20286 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20287 if (j != -1) { 20288 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20289 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20290 "Update split " + splitName + " revision code " 20291 + after.splitRevisionCodes[i] + " is older than current " 20292 + before.splitRevisionCodes[j]); 20293 } 20294 } 20295 } 20296 } 20297 } 20298 } 20299 20300 private static class MoveCallbacks extends Handler { 20301 private static final int MSG_CREATED = 1; 20302 private static final int MSG_STATUS_CHANGED = 2; 20303 20304 private final RemoteCallbackList<IPackageMoveObserver> 20305 mCallbacks = new RemoteCallbackList<>(); 20306 20307 private final SparseIntArray mLastStatus = new SparseIntArray(); 20308 20309 public MoveCallbacks(Looper looper) { 20310 super(looper); 20311 } 20312 20313 public void register(IPackageMoveObserver callback) { 20314 mCallbacks.register(callback); 20315 } 20316 20317 public void unregister(IPackageMoveObserver callback) { 20318 mCallbacks.unregister(callback); 20319 } 20320 20321 @Override 20322 public void handleMessage(Message msg) { 20323 final SomeArgs args = (SomeArgs) msg.obj; 20324 final int n = mCallbacks.beginBroadcast(); 20325 for (int i = 0; i < n; i++) { 20326 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20327 try { 20328 invokeCallback(callback, msg.what, args); 20329 } catch (RemoteException ignored) { 20330 } 20331 } 20332 mCallbacks.finishBroadcast(); 20333 args.recycle(); 20334 } 20335 20336 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20337 throws RemoteException { 20338 switch (what) { 20339 case MSG_CREATED: { 20340 callback.onCreated(args.argi1, (Bundle) args.arg2); 20341 break; 20342 } 20343 case MSG_STATUS_CHANGED: { 20344 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20345 break; 20346 } 20347 } 20348 } 20349 20350 private void notifyCreated(int moveId, Bundle extras) { 20351 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20352 20353 final SomeArgs args = SomeArgs.obtain(); 20354 args.argi1 = moveId; 20355 args.arg2 = extras; 20356 obtainMessage(MSG_CREATED, args).sendToTarget(); 20357 } 20358 20359 private void notifyStatusChanged(int moveId, int status) { 20360 notifyStatusChanged(moveId, status, -1); 20361 } 20362 20363 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20364 Slog.v(TAG, "Move " + moveId + " status " + status); 20365 20366 final SomeArgs args = SomeArgs.obtain(); 20367 args.argi1 = moveId; 20368 args.argi2 = status; 20369 args.arg3 = estMillis; 20370 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20371 20372 synchronized (mLastStatus) { 20373 mLastStatus.put(moveId, status); 20374 } 20375 } 20376 } 20377 20378 private final static class OnPermissionChangeListeners extends Handler { 20379 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20380 20381 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20382 new RemoteCallbackList<>(); 20383 20384 public OnPermissionChangeListeners(Looper looper) { 20385 super(looper); 20386 } 20387 20388 @Override 20389 public void handleMessage(Message msg) { 20390 switch (msg.what) { 20391 case MSG_ON_PERMISSIONS_CHANGED: { 20392 final int uid = msg.arg1; 20393 handleOnPermissionsChanged(uid); 20394 } break; 20395 } 20396 } 20397 20398 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20399 mPermissionListeners.register(listener); 20400 20401 } 20402 20403 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20404 mPermissionListeners.unregister(listener); 20405 } 20406 20407 public void onPermissionsChanged(int uid) { 20408 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20409 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20410 } 20411 } 20412 20413 private void handleOnPermissionsChanged(int uid) { 20414 final int count = mPermissionListeners.beginBroadcast(); 20415 try { 20416 for (int i = 0; i < count; i++) { 20417 IOnPermissionsChangeListener callback = mPermissionListeners 20418 .getBroadcastItem(i); 20419 try { 20420 callback.onPermissionsChanged(uid); 20421 } catch (RemoteException e) { 20422 Log.e(TAG, "Permission listener is dead", e); 20423 } 20424 } 20425 } finally { 20426 mPermissionListeners.finishBroadcast(); 20427 } 20428 } 20429 } 20430 20431 private class PackageManagerInternalImpl extends PackageManagerInternal { 20432 @Override 20433 public void setLocationPackagesProvider(PackagesProvider provider) { 20434 synchronized (mPackages) { 20435 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20436 } 20437 } 20438 20439 @Override 20440 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20441 synchronized (mPackages) { 20442 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20443 } 20444 } 20445 20446 @Override 20447 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20448 synchronized (mPackages) { 20449 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20450 } 20451 } 20452 20453 @Override 20454 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20455 synchronized (mPackages) { 20456 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20457 } 20458 } 20459 20460 @Override 20461 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20462 synchronized (mPackages) { 20463 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20464 } 20465 } 20466 20467 @Override 20468 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20469 synchronized (mPackages) { 20470 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20471 } 20472 } 20473 20474 @Override 20475 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20476 synchronized (mPackages) { 20477 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20478 packageName, userId); 20479 } 20480 } 20481 20482 @Override 20483 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20484 synchronized (mPackages) { 20485 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20486 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20487 packageName, userId); 20488 } 20489 } 20490 20491 @Override 20492 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20493 synchronized (mPackages) { 20494 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20495 packageName, userId); 20496 } 20497 } 20498 20499 @Override 20500 public void setKeepUninstalledPackages(final List<String> packageList) { 20501 Preconditions.checkNotNull(packageList); 20502 List<String> removedFromList = null; 20503 synchronized (mPackages) { 20504 if (mKeepUninstalledPackages != null) { 20505 final int packagesCount = mKeepUninstalledPackages.size(); 20506 for (int i = 0; i < packagesCount; i++) { 20507 String oldPackage = mKeepUninstalledPackages.get(i); 20508 if (packageList != null && packageList.contains(oldPackage)) { 20509 continue; 20510 } 20511 if (removedFromList == null) { 20512 removedFromList = new ArrayList<>(); 20513 } 20514 removedFromList.add(oldPackage); 20515 } 20516 } 20517 mKeepUninstalledPackages = new ArrayList<>(packageList); 20518 if (removedFromList != null) { 20519 final int removedCount = removedFromList.size(); 20520 for (int i = 0; i < removedCount; i++) { 20521 deletePackageIfUnusedLPr(removedFromList.get(i)); 20522 } 20523 } 20524 } 20525 } 20526 20527 @Override 20528 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20529 synchronized (mPackages) { 20530 // If we do not support permission review, done. 20531 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20532 return false; 20533 } 20534 20535 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20536 if (packageSetting == null) { 20537 return false; 20538 } 20539 20540 // Permission review applies only to apps not supporting the new permission model. 20541 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20542 return false; 20543 } 20544 20545 // Legacy apps have the permission and get user consent on launch. 20546 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20547 return permissionsState.isPermissionReviewRequired(userId); 20548 } 20549 } 20550 20551 @Override 20552 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20553 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20554 } 20555 20556 @Override 20557 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20558 int userId) { 20559 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20560 } 20561 } 20562 20563 @Override 20564 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20565 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20566 synchronized (mPackages) { 20567 final long identity = Binder.clearCallingIdentity(); 20568 try { 20569 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20570 packageNames, userId); 20571 } finally { 20572 Binder.restoreCallingIdentity(identity); 20573 } 20574 } 20575 } 20576 20577 private static void enforceSystemOrPhoneCaller(String tag) { 20578 int callingUid = Binder.getCallingUid(); 20579 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20580 throw new SecurityException( 20581 "Cannot call " + tag + " from UID " + callingUid); 20582 } 20583 } 20584 20585 boolean isHistoricalPackageUsageAvailable() { 20586 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20587 } 20588 20589 /** 20590 * Return a <b>copy</b> of the collection of packages known to the package manager. 20591 * @return A copy of the values of mPackages. 20592 */ 20593 Collection<PackageParser.Package> getPackages() { 20594 synchronized (mPackages) { 20595 return new ArrayList<>(mPackages.values()); 20596 } 20597 } 20598 20599 /** 20600 * Logs process start information (including base APK hash) to the security log. 20601 * @hide 20602 */ 20603 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20604 String apkFile, int pid) { 20605 if (!SecurityLog.isLoggingEnabled()) { 20606 return; 20607 } 20608 Bundle data = new Bundle(); 20609 data.putLong("startTimestamp", System.currentTimeMillis()); 20610 data.putString("processName", processName); 20611 data.putInt("uid", uid); 20612 data.putString("seinfo", seinfo); 20613 data.putString("apkFile", apkFile); 20614 data.putInt("pid", pid); 20615 Message msg = mProcessLoggingHandler.obtainMessage( 20616 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20617 msg.setData(data); 20618 mProcessLoggingHandler.sendMessage(msg); 20619 } 20620} 20621