PackageManagerService.java revision b633f9d01f484d1a17ebfcd5aa4d6000dff53773
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_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.IActivityManager; 105import android.app.ResourcesManager; 106import android.app.admin.IDevicePolicyManager; 107import android.app.admin.SecurityLog; 108import android.app.backup.IBackupManager; 109import android.content.BroadcastReceiver; 110import android.content.ComponentName; 111import android.content.ContentResolver; 112import android.content.Context; 113import android.content.IIntentReceiver; 114import android.content.Intent; 115import android.content.IntentFilter; 116import android.content.IntentSender; 117import android.content.IntentSender.SendIntentException; 118import android.content.ServiceConnection; 119import android.content.pm.ActivityInfo; 120import android.content.pm.ApplicationInfo; 121import android.content.pm.AppsQueryHelper; 122import android.content.pm.ComponentInfo; 123import android.content.pm.EphemeralApplicationInfo; 124import android.content.pm.EphemeralIntentFilter; 125import android.content.pm.EphemeralResolveInfo; 126import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 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.PatternMatcher; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.ShellCallback; 189import android.os.SystemClock; 190import android.os.SystemProperties; 191import android.os.Trace; 192import android.os.UserHandle; 193import android.os.UserManager; 194import android.os.UserManagerInternal; 195import android.os.storage.IStorageManager; 196import android.os.storage.StorageManagerInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.provider.Settings.Global; 202import android.provider.Settings.Secure; 203import android.security.KeyStore; 204import android.security.SystemKeyStore; 205import android.system.ErrnoException; 206import android.system.Os; 207import android.text.TextUtils; 208import android.text.format.DateUtils; 209import android.util.ArrayMap; 210import android.util.ArraySet; 211import android.util.DisplayMetrics; 212import android.util.EventLog; 213import android.util.ExceptionUtils; 214import android.util.Log; 215import android.util.LogPrinter; 216import android.util.MathUtils; 217import android.util.Pair; 218import android.util.PrintStreamPrinter; 219import android.util.Slog; 220import android.util.SparseArray; 221import android.util.SparseBooleanArray; 222import android.util.SparseIntArray; 223import android.util.Xml; 224import android.util.jar.StrictJarFile; 225import android.view.Display; 226 227import com.android.internal.R; 228import com.android.internal.annotations.GuardedBy; 229import com.android.internal.app.IMediaContainerService; 230import com.android.internal.app.ResolverActivity; 231import com.android.internal.content.NativeLibraryHelper; 232import com.android.internal.content.PackageHelper; 233import com.android.internal.logging.MetricsLogger; 234import com.android.internal.os.IParcelFileDescriptorFactory; 235import com.android.internal.os.InstallerConnection.InstallerException; 236import com.android.internal.os.RoSystemProperties; 237import com.android.internal.os.SomeArgs; 238import com.android.internal.os.Zygote; 239import com.android.internal.telephony.CarrierAppUtils; 240import com.android.internal.util.ArrayUtils; 241import com.android.internal.util.FastPrintWriter; 242import com.android.internal.util.FastXmlSerializer; 243import com.android.internal.util.IndentingPrintWriter; 244import com.android.internal.util.Preconditions; 245import com.android.internal.util.XmlUtils; 246import com.android.server.AttributeCache; 247import com.android.server.EventLogTags; 248import com.android.server.FgThread; 249import com.android.server.IntentResolver; 250import com.android.server.LocalServices; 251import com.android.server.ServiceThread; 252import com.android.server.SystemConfig; 253import com.android.server.Watchdog; 254import com.android.server.net.NetworkPolicyManagerInternal; 255import com.android.server.pm.PermissionsState.PermissionState; 256import com.android.server.pm.Settings.DatabaseVersion; 257import com.android.server.pm.Settings.VersionInfo; 258import com.android.server.storage.DeviceStorageMonitorInternal; 259 260import dalvik.system.CloseGuard; 261import dalvik.system.DexFile; 262import dalvik.system.VMRuntime; 263 264import libcore.io.IoUtils; 265import libcore.util.EmptyArray; 266 267import org.xmlpull.v1.XmlPullParser; 268import org.xmlpull.v1.XmlPullParserException; 269import org.xmlpull.v1.XmlSerializer; 270 271import java.io.BufferedOutputStream; 272import java.io.BufferedReader; 273import java.io.ByteArrayInputStream; 274import java.io.ByteArrayOutputStream; 275import java.io.File; 276import java.io.FileDescriptor; 277import java.io.FileInputStream; 278import java.io.FileNotFoundException; 279import java.io.FileOutputStream; 280import java.io.FileReader; 281import java.io.FilenameFilter; 282import java.io.IOException; 283import java.io.PrintWriter; 284import java.nio.charset.StandardCharsets; 285import java.security.DigestInputStream; 286import java.security.MessageDigest; 287import java.security.NoSuchAlgorithmException; 288import java.security.PublicKey; 289import java.security.cert.Certificate; 290import java.security.cert.CertificateEncodingException; 291import java.security.cert.CertificateException; 292import java.text.SimpleDateFormat; 293import java.util.ArrayList; 294import java.util.Arrays; 295import java.util.Collection; 296import java.util.Collections; 297import java.util.Comparator; 298import java.util.Date; 299import java.util.HashSet; 300import java.util.Iterator; 301import java.util.List; 302import java.util.Map; 303import java.util.Objects; 304import java.util.Set; 305import java.util.concurrent.CountDownLatch; 306import java.util.concurrent.TimeUnit; 307import java.util.concurrent.atomic.AtomicBoolean; 308import java.util.concurrent.atomic.AtomicInteger; 309 310/** 311 * Keep track of all those APKs everywhere. 312 * <p> 313 * Internally there are two important locks: 314 * <ul> 315 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 316 * and other related state. It is a fine-grained lock that should only be held 317 * momentarily, as it's one of the most contended locks in the system. 318 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 319 * operations typically involve heavy lifting of application data on disk. Since 320 * {@code installd} is single-threaded, and it's operations can often be slow, 321 * this lock should never be acquired while already holding {@link #mPackages}. 322 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 323 * holding {@link #mInstallLock}. 324 * </ul> 325 * Many internal methods rely on the caller to hold the appropriate locks, and 326 * this contract is expressed through method name suffixes: 327 * <ul> 328 * <li>fooLI(): the caller must hold {@link #mInstallLock} 329 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 330 * being modified must be frozen 331 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 332 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 333 * </ul> 334 * <p> 335 * Because this class is very central to the platform's security; please run all 336 * CTS and unit tests whenever making modifications: 337 * 338 * <pre> 339 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 340 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 341 * </pre> 342 */ 343public class PackageManagerService extends IPackageManager.Stub { 344 static final String TAG = "PackageManager"; 345 static final boolean DEBUG_SETTINGS = false; 346 static final boolean DEBUG_PREFERRED = false; 347 static final boolean DEBUG_UPGRADE = false; 348 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 349 private static final boolean DEBUG_BACKUP = false; 350 private static final boolean DEBUG_INSTALL = false; 351 private static final boolean DEBUG_REMOVE = false; 352 private static final boolean DEBUG_BROADCASTS = false; 353 private static final boolean DEBUG_SHOW_INFO = false; 354 private static final boolean DEBUG_PACKAGE_INFO = false; 355 private static final boolean DEBUG_INTENT_MATCHING = false; 356 private static final boolean DEBUG_PACKAGE_SCANNING = false; 357 private static final boolean DEBUG_VERIFY = false; 358 private static final boolean DEBUG_FILTERS = false; 359 360 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 361 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 362 // user, but by default initialize to this. 363 static final boolean DEBUG_DEXOPT = false; 364 365 private static final boolean DEBUG_ABI_SELECTION = false; 366 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 367 private static final boolean DEBUG_TRIAGED_MISSING = false; 368 private static final boolean DEBUG_APP_DATA = false; 369 370 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 371 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 372 373 private static final boolean DISABLE_EPHEMERAL_APPS = false; 374 private static final boolean HIDE_EPHEMERAL_APIS = true; 375 376 private static final int RADIO_UID = Process.PHONE_UID; 377 private static final int LOG_UID = Process.LOG_UID; 378 private static final int NFC_UID = Process.NFC_UID; 379 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 380 private static final int SHELL_UID = Process.SHELL_UID; 381 382 // Cap the size of permission trees that 3rd party apps can define 383 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 384 385 // Suffix used during package installation when copying/moving 386 // package apks to install directory. 387 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 388 389 static final int SCAN_NO_DEX = 1<<1; 390 static final int SCAN_FORCE_DEX = 1<<2; 391 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 392 static final int SCAN_NEW_INSTALL = 1<<4; 393 static final int SCAN_NO_PATHS = 1<<5; 394 static final int SCAN_UPDATE_TIME = 1<<6; 395 static final int SCAN_DEFER_DEX = 1<<7; 396 static final int SCAN_BOOTING = 1<<8; 397 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 398 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 399 static final int SCAN_REPLACING = 1<<11; 400 static final int SCAN_REQUIRE_KNOWN = 1<<12; 401 static final int SCAN_MOVE = 1<<13; 402 static final int SCAN_INITIAL = 1<<14; 403 static final int SCAN_CHECK_ONLY = 1<<15; 404 static final int SCAN_DONT_KILL_APP = 1<<17; 405 static final int SCAN_IGNORE_FROZEN = 1<<18; 406 407 static final int REMOVE_CHATTY = 1<<16; 408 409 private static final int[] EMPTY_INT_ARRAY = new int[0]; 410 411 /** 412 * Timeout (in milliseconds) after which the watchdog should declare that 413 * our handler thread is wedged. The usual default for such things is one 414 * minute but we sometimes do very lengthy I/O operations on this thread, 415 * such as installing multi-gigabyte applications, so ours needs to be longer. 416 */ 417 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 418 419 /** 420 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 421 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 422 * settings entry if available, otherwise we use the hardcoded default. If it's been 423 * more than this long since the last fstrim, we force one during the boot sequence. 424 * 425 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 426 * one gets run at the next available charging+idle time. This final mandatory 427 * no-fstrim check kicks in only of the other scheduling criteria is never met. 428 */ 429 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 430 431 /** 432 * Whether verification is enabled by default. 433 */ 434 private static final boolean DEFAULT_VERIFY_ENABLE = true; 435 436 /** 437 * The default maximum time to wait for the verification agent to return in 438 * milliseconds. 439 */ 440 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 441 442 /** 443 * The default response for package verification timeout. 444 * 445 * This can be either PackageManager.VERIFICATION_ALLOW or 446 * PackageManager.VERIFICATION_REJECT. 447 */ 448 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 449 450 static final String PLATFORM_PACKAGE_NAME = "android"; 451 452 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 453 454 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 455 DEFAULT_CONTAINER_PACKAGE, 456 "com.android.defcontainer.DefaultContainerService"); 457 458 private static final String KILL_APP_REASON_GIDS_CHANGED = 459 "permission grant or revoke changed gids"; 460 461 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 462 "permissions revoked"; 463 464 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 465 466 private static final String PACKAGE_SCHEME = "package"; 467 468 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 469 /** 470 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 471 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 472 * VENDOR_OVERLAY_DIR. 473 */ 474 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 475 /** 476 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 477 * is in VENDOR_OVERLAY_THEME_PROPERTY. 478 */ 479 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 480 = "persist.vendor.overlay.theme"; 481 482 /** Permission grant: not grant the permission. */ 483 private static final int GRANT_DENIED = 1; 484 485 /** Permission grant: grant the permission as an install permission. */ 486 private static final int GRANT_INSTALL = 2; 487 488 /** Permission grant: grant the permission as a runtime one. */ 489 private static final int GRANT_RUNTIME = 3; 490 491 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 492 private static final int GRANT_UPGRADE = 4; 493 494 /** Canonical intent used to identify what counts as a "web browser" app */ 495 private static final Intent sBrowserIntent; 496 static { 497 sBrowserIntent = new Intent(); 498 sBrowserIntent.setAction(Intent.ACTION_VIEW); 499 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 500 sBrowserIntent.setData(Uri.parse("http:")); 501 } 502 503 /** 504 * The set of all protected actions [i.e. those actions for which a high priority 505 * intent filter is disallowed]. 506 */ 507 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 508 static { 509 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 510 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 511 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 512 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 513 } 514 515 // Compilation reasons. 516 public static final int REASON_FIRST_BOOT = 0; 517 public static final int REASON_BOOT = 1; 518 public static final int REASON_INSTALL = 2; 519 public static final int REASON_BACKGROUND_DEXOPT = 3; 520 public static final int REASON_AB_OTA = 4; 521 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 522 public static final int REASON_SHARED_APK = 6; 523 public static final int REASON_FORCED_DEXOPT = 7; 524 public static final int REASON_CORE_APP = 8; 525 526 public static final int REASON_LAST = REASON_CORE_APP; 527 528 /** Special library name that skips shared libraries check during compilation. */ 529 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 530 531 final ServiceThread mHandlerThread; 532 533 final PackageHandler mHandler; 534 535 private final ProcessLoggingHandler mProcessLoggingHandler; 536 537 /** 538 * Messages for {@link #mHandler} that need to wait for system ready before 539 * being dispatched. 540 */ 541 private ArrayList<Message> mPostSystemReadyMessages; 542 543 final int mSdkVersion = Build.VERSION.SDK_INT; 544 545 final Context mContext; 546 final boolean mFactoryTest; 547 final boolean mOnlyCore; 548 final DisplayMetrics mMetrics; 549 final int mDefParseFlags; 550 final String[] mSeparateProcesses; 551 final boolean mIsUpgrade; 552 final boolean mIsPreNUpgrade; 553 final boolean mIsPreNMR1Upgrade; 554 555 @GuardedBy("mPackages") 556 private boolean mDexOptDialogShown; 557 558 /** The location for ASEC container files on internal storage. */ 559 final String mAsecInternalPath; 560 561 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 562 // LOCK HELD. Can be called with mInstallLock held. 563 @GuardedBy("mInstallLock") 564 final Installer mInstaller; 565 566 /** Directory where installed third-party apps stored */ 567 final File mAppInstallDir; 568 final File mEphemeralInstallDir; 569 570 /** 571 * Directory to which applications installed internally have their 572 * 32 bit native libraries copied. 573 */ 574 private File mAppLib32InstallDir; 575 576 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 577 // apps. 578 final File mDrmAppPrivateInstallDir; 579 580 // ---------------------------------------------------------------- 581 582 // Lock for state used when installing and doing other long running 583 // operations. Methods that must be called with this lock held have 584 // the suffix "LI". 585 final Object mInstallLock = new Object(); 586 587 // ---------------------------------------------------------------- 588 589 // Keys are String (package name), values are Package. This also serves 590 // as the lock for the global state. Methods that must be called with 591 // this lock held have the prefix "LP". 592 @GuardedBy("mPackages") 593 final ArrayMap<String, PackageParser.Package> mPackages = 594 new ArrayMap<String, PackageParser.Package>(); 595 596 final ArrayMap<String, Set<String>> mKnownCodebase = 597 new ArrayMap<String, Set<String>>(); 598 599 // Tracks available target package names -> overlay package paths. 600 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 601 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 602 603 /** 604 * Tracks new system packages [received in an OTA] that we expect to 605 * find updated user-installed versions. Keys are package name, values 606 * are package location. 607 */ 608 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 609 /** 610 * Tracks high priority intent filters for protected actions. During boot, certain 611 * filter actions are protected and should never be allowed to have a high priority 612 * intent filter for them. However, there is one, and only one exception -- the 613 * setup wizard. It must be able to define a high priority intent filter for these 614 * actions to ensure there are no escapes from the wizard. We need to delay processing 615 * of these during boot as we need to look at all of the system packages in order 616 * to know which component is the setup wizard. 617 */ 618 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 619 /** 620 * Whether or not processing protected filters should be deferred. 621 */ 622 private boolean mDeferProtectedFilters = true; 623 624 /** 625 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 626 */ 627 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 628 /** 629 * Whether or not system app permissions should be promoted from install to runtime. 630 */ 631 boolean mPromoteSystemApps; 632 633 @GuardedBy("mPackages") 634 final Settings mSettings; 635 636 /** 637 * Set of package names that are currently "frozen", which means active 638 * surgery is being done on the code/data for that package. The platform 639 * will refuse to launch frozen packages to avoid race conditions. 640 * 641 * @see PackageFreezer 642 */ 643 @GuardedBy("mPackages") 644 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 645 646 final ProtectedPackages mProtectedPackages; 647 648 boolean mFirstBoot; 649 650 // System configuration read by SystemConfig. 651 final int[] mGlobalGids; 652 final SparseArray<ArraySet<String>> mSystemPermissions; 653 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 654 655 // If mac_permissions.xml was found for seinfo labeling. 656 boolean mFoundPolicyFile; 657 658 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 659 660 public static final class SharedLibraryEntry { 661 public final String path; 662 public final String apk; 663 664 SharedLibraryEntry(String _path, String _apk) { 665 path = _path; 666 apk = _apk; 667 } 668 } 669 670 // Currently known shared libraries. 671 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 672 new ArrayMap<String, SharedLibraryEntry>(); 673 674 // All available activities, for your resolving pleasure. 675 final ActivityIntentResolver mActivities = 676 new ActivityIntentResolver(); 677 678 // All available receivers, for your resolving pleasure. 679 final ActivityIntentResolver mReceivers = 680 new ActivityIntentResolver(); 681 682 // All available services, for your resolving pleasure. 683 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 684 685 // All available providers, for your resolving pleasure. 686 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 687 688 // Mapping from provider base names (first directory in content URI codePath) 689 // to the provider information. 690 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 691 new ArrayMap<String, PackageParser.Provider>(); 692 693 // Mapping from instrumentation class names to info about them. 694 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 695 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 696 697 // Mapping from permission names to info about them. 698 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 699 new ArrayMap<String, PackageParser.PermissionGroup>(); 700 701 // Packages whose data we have transfered into another package, thus 702 // should no longer exist. 703 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 704 705 // Broadcast actions that are only available to the system. 706 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 707 708 /** List of packages waiting for verification. */ 709 final SparseArray<PackageVerificationState> mPendingVerification 710 = new SparseArray<PackageVerificationState>(); 711 712 /** Set of packages associated with each app op permission. */ 713 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 714 715 final PackageInstallerService mInstallerService; 716 717 private final PackageDexOptimizer mPackageDexOptimizer; 718 719 private AtomicInteger mNextMoveId = new AtomicInteger(); 720 private final MoveCallbacks mMoveCallbacks; 721 722 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 723 724 // Cache of users who need badging. 725 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 726 727 /** Token for keys in mPendingVerification. */ 728 private int mPendingVerificationToken = 0; 729 730 volatile boolean mSystemReady; 731 volatile boolean mSafeMode; 732 volatile boolean mHasSystemUidErrors; 733 734 ApplicationInfo mAndroidApplication; 735 final ActivityInfo mResolveActivity = new ActivityInfo(); 736 final ResolveInfo mResolveInfo = new ResolveInfo(); 737 ComponentName mResolveComponentName; 738 PackageParser.Package mPlatformPackage; 739 ComponentName mCustomResolverComponentName; 740 741 boolean mResolverReplaced = false; 742 743 private final @Nullable ComponentName mIntentFilterVerifierComponent; 744 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 745 746 private int mIntentFilterVerificationToken = 0; 747 748 /** Component that knows whether or not an ephemeral application exists */ 749 final ComponentName mEphemeralResolverComponent; 750 /** The service connection to the ephemeral resolver */ 751 final EphemeralResolverConnection mEphemeralResolverConnection; 752 753 /** Component used to install ephemeral applications */ 754 final ComponentName mEphemeralInstallerComponent; 755 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 756 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 757 758 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 759 = new SparseArray<IntentFilterVerificationState>(); 760 761 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 762 763 // List of packages names to keep cached, even if they are uninstalled for all users 764 private List<String> mKeepUninstalledPackages; 765 766 private UserManagerInternal mUserManagerInternal; 767 768 private static class IFVerificationParams { 769 PackageParser.Package pkg; 770 boolean replacing; 771 int userId; 772 int verifierUid; 773 774 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 775 int _userId, int _verifierUid) { 776 pkg = _pkg; 777 replacing = _replacing; 778 userId = _userId; 779 replacing = _replacing; 780 verifierUid = _verifierUid; 781 } 782 } 783 784 private interface IntentFilterVerifier<T extends IntentFilter> { 785 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 786 T filter, String packageName); 787 void startVerifications(int userId); 788 void receiveVerificationResponse(int verificationId); 789 } 790 791 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 792 private Context mContext; 793 private ComponentName mIntentFilterVerifierComponent; 794 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 795 796 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 797 mContext = context; 798 mIntentFilterVerifierComponent = verifierComponent; 799 } 800 801 private String getDefaultScheme() { 802 return IntentFilter.SCHEME_HTTPS; 803 } 804 805 @Override 806 public void startVerifications(int userId) { 807 // Launch verifications requests 808 int count = mCurrentIntentFilterVerifications.size(); 809 for (int n=0; n<count; n++) { 810 int verificationId = mCurrentIntentFilterVerifications.get(n); 811 final IntentFilterVerificationState ivs = 812 mIntentFilterVerificationStates.get(verificationId); 813 814 String packageName = ivs.getPackageName(); 815 816 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 817 final int filterCount = filters.size(); 818 ArraySet<String> domainsSet = new ArraySet<>(); 819 for (int m=0; m<filterCount; m++) { 820 PackageParser.ActivityIntentInfo filter = filters.get(m); 821 domainsSet.addAll(filter.getHostsList()); 822 } 823 synchronized (mPackages) { 824 if (mSettings.createIntentFilterVerificationIfNeededLPw( 825 packageName, domainsSet) != null) { 826 scheduleWriteSettingsLocked(); 827 } 828 } 829 sendVerificationRequest(userId, verificationId, ivs); 830 } 831 mCurrentIntentFilterVerifications.clear(); 832 } 833 834 private void sendVerificationRequest(int userId, int verificationId, 835 IntentFilterVerificationState ivs) { 836 837 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 838 verificationIntent.putExtra( 839 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 840 verificationId); 841 verificationIntent.putExtra( 842 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 843 getDefaultScheme()); 844 verificationIntent.putExtra( 845 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 846 ivs.getHostsString()); 847 verificationIntent.putExtra( 848 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 849 ivs.getPackageName()); 850 verificationIntent.setComponent(mIntentFilterVerifierComponent); 851 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 852 853 UserHandle user = new UserHandle(userId); 854 mContext.sendBroadcastAsUser(verificationIntent, user); 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 856 "Sending IntentFilter verification broadcast"); 857 } 858 859 public void receiveVerificationResponse(int verificationId) { 860 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 861 862 final boolean verified = ivs.isVerified(); 863 864 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 865 final int count = filters.size(); 866 if (DEBUG_DOMAIN_VERIFICATION) { 867 Slog.i(TAG, "Received verification response " + verificationId 868 + " for " + count + " filters, verified=" + verified); 869 } 870 for (int n=0; n<count; n++) { 871 PackageParser.ActivityIntentInfo filter = filters.get(n); 872 filter.setVerified(verified); 873 874 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 875 + " verified with result:" + verified + " and hosts:" 876 + ivs.getHostsString()); 877 } 878 879 mIntentFilterVerificationStates.remove(verificationId); 880 881 final String packageName = ivs.getPackageName(); 882 IntentFilterVerificationInfo ivi = null; 883 884 synchronized (mPackages) { 885 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 886 } 887 if (ivi == null) { 888 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 889 + verificationId + " packageName:" + packageName); 890 return; 891 } 892 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 893 "Updating IntentFilterVerificationInfo for package " + packageName 894 +" verificationId:" + verificationId); 895 896 synchronized (mPackages) { 897 if (verified) { 898 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 899 } else { 900 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 901 } 902 scheduleWriteSettingsLocked(); 903 904 final int userId = ivs.getUserId(); 905 if (userId != UserHandle.USER_ALL) { 906 final int userStatus = 907 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 908 909 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 910 boolean needUpdate = false; 911 912 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 913 // already been set by the User thru the Disambiguation dialog 914 switch (userStatus) { 915 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 916 if (verified) { 917 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 918 } else { 919 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 920 } 921 needUpdate = true; 922 break; 923 924 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 925 if (verified) { 926 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 927 needUpdate = true; 928 } 929 break; 930 931 default: 932 // Nothing to do 933 } 934 935 if (needUpdate) { 936 mSettings.updateIntentFilterVerificationStatusLPw( 937 packageName, updatedStatus, userId); 938 scheduleWritePackageRestrictionsLocked(userId); 939 } 940 } 941 } 942 } 943 944 @Override 945 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 946 ActivityIntentInfo filter, String packageName) { 947 if (!hasValidDomains(filter)) { 948 return false; 949 } 950 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 951 if (ivs == null) { 952 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 953 packageName); 954 } 955 if (DEBUG_DOMAIN_VERIFICATION) { 956 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 957 } 958 ivs.addFilter(filter); 959 return true; 960 } 961 962 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 963 int userId, int verificationId, String packageName) { 964 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 965 verifierUid, userId, packageName); 966 ivs.setPendingState(); 967 synchronized (mPackages) { 968 mIntentFilterVerificationStates.append(verificationId, ivs); 969 mCurrentIntentFilterVerifications.add(verificationId); 970 } 971 return ivs; 972 } 973 } 974 975 private static boolean hasValidDomains(ActivityIntentInfo filter) { 976 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 977 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 978 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 979 } 980 981 // Set of pending broadcasts for aggregating enable/disable of components. 982 static class PendingPackageBroadcasts { 983 // for each user id, a map of <package name -> components within that package> 984 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 985 986 public PendingPackageBroadcasts() { 987 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 988 } 989 990 public ArrayList<String> get(int userId, String packageName) { 991 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 992 return packages.get(packageName); 993 } 994 995 public void put(int userId, String packageName, ArrayList<String> components) { 996 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 997 packages.put(packageName, components); 998 } 999 1000 public void remove(int userId, String packageName) { 1001 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1002 if (packages != null) { 1003 packages.remove(packageName); 1004 } 1005 } 1006 1007 public void remove(int userId) { 1008 mUidMap.remove(userId); 1009 } 1010 1011 public int userIdCount() { 1012 return mUidMap.size(); 1013 } 1014 1015 public int userIdAt(int n) { 1016 return mUidMap.keyAt(n); 1017 } 1018 1019 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1020 return mUidMap.get(userId); 1021 } 1022 1023 public int size() { 1024 // total number of pending broadcast entries across all userIds 1025 int num = 0; 1026 for (int i = 0; i< mUidMap.size(); i++) { 1027 num += mUidMap.valueAt(i).size(); 1028 } 1029 return num; 1030 } 1031 1032 public void clear() { 1033 mUidMap.clear(); 1034 } 1035 1036 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1037 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1038 if (map == null) { 1039 map = new ArrayMap<String, ArrayList<String>>(); 1040 mUidMap.put(userId, map); 1041 } 1042 return map; 1043 } 1044 } 1045 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1046 1047 // Service Connection to remote media container service to copy 1048 // package uri's from external media onto secure containers 1049 // or internal storage. 1050 private IMediaContainerService mContainerService = null; 1051 1052 static final int SEND_PENDING_BROADCAST = 1; 1053 static final int MCS_BOUND = 3; 1054 static final int END_COPY = 4; 1055 static final int INIT_COPY = 5; 1056 static final int MCS_UNBIND = 6; 1057 static final int START_CLEANING_PACKAGE = 7; 1058 static final int FIND_INSTALL_LOC = 8; 1059 static final int POST_INSTALL = 9; 1060 static final int MCS_RECONNECT = 10; 1061 static final int MCS_GIVE_UP = 11; 1062 static final int UPDATED_MEDIA_STATUS = 12; 1063 static final int WRITE_SETTINGS = 13; 1064 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1065 static final int PACKAGE_VERIFIED = 15; 1066 static final int CHECK_PENDING_VERIFICATION = 16; 1067 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1068 static final int INTENT_FILTER_VERIFIED = 18; 1069 static final int WRITE_PACKAGE_LIST = 19; 1070 1071 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1072 1073 // Delay time in millisecs 1074 static final int BROADCAST_DELAY = 10 * 1000; 1075 1076 static UserManagerService sUserManager; 1077 1078 // Stores a list of users whose package restrictions file needs to be updated 1079 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1080 1081 final private DefaultContainerConnection mDefContainerConn = 1082 new DefaultContainerConnection(); 1083 class DefaultContainerConnection implements ServiceConnection { 1084 public void onServiceConnected(ComponentName name, IBinder service) { 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1086 final IMediaContainerService imcs = IMediaContainerService.Stub 1087 .asInterface(Binder.allowBlocking(service)); 1088 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1089 } 1090 1091 public void onServiceDisconnected(ComponentName name) { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1093 } 1094 } 1095 1096 // Recordkeeping of restore-after-install operations that are currently in flight 1097 // between the Package Manager and the Backup Manager 1098 static class PostInstallData { 1099 public InstallArgs args; 1100 public PackageInstalledInfo res; 1101 1102 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1103 args = _a; 1104 res = _r; 1105 } 1106 } 1107 1108 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1109 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1110 1111 // XML tags for backup/restore of various bits of state 1112 private static final String TAG_PREFERRED_BACKUP = "pa"; 1113 private static final String TAG_DEFAULT_APPS = "da"; 1114 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1115 1116 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1117 private static final String TAG_ALL_GRANTS = "rt-grants"; 1118 private static final String TAG_GRANT = "grant"; 1119 private static final String ATTR_PACKAGE_NAME = "pkg"; 1120 1121 private static final String TAG_PERMISSION = "perm"; 1122 private static final String ATTR_PERMISSION_NAME = "name"; 1123 private static final String ATTR_IS_GRANTED = "g"; 1124 private static final String ATTR_USER_SET = "set"; 1125 private static final String ATTR_USER_FIXED = "fixed"; 1126 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1127 1128 // System/policy permission grants are not backed up 1129 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1130 FLAG_PERMISSION_POLICY_FIXED 1131 | FLAG_PERMISSION_SYSTEM_FIXED 1132 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1133 1134 // And we back up these user-adjusted states 1135 private static final int USER_RUNTIME_GRANT_MASK = 1136 FLAG_PERMISSION_USER_SET 1137 | FLAG_PERMISSION_USER_FIXED 1138 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1139 1140 final @Nullable String mRequiredVerifierPackage; 1141 final @NonNull String mRequiredInstallerPackage; 1142 final @NonNull String mRequiredUninstallerPackage; 1143 final @Nullable String mSetupWizardPackage; 1144 final @Nullable String mStorageManagerPackage; 1145 final @NonNull String mServicesSystemSharedLibraryPackageName; 1146 final @NonNull String mSharedSystemSharedLibraryPackageName; 1147 1148 final boolean mPermissionReviewRequired; 1149 1150 private final PackageUsage mPackageUsage = new PackageUsage(); 1151 private final CompilerStats mCompilerStats = new CompilerStats(); 1152 1153 class PackageHandler extends Handler { 1154 private boolean mBound = false; 1155 final ArrayList<HandlerParams> mPendingInstalls = 1156 new ArrayList<HandlerParams>(); 1157 1158 private boolean connectToService() { 1159 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1160 " DefaultContainerService"); 1161 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1163 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1164 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1166 mBound = true; 1167 return true; 1168 } 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1170 return false; 1171 } 1172 1173 private void disconnectService() { 1174 mContainerService = null; 1175 mBound = false; 1176 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1177 mContext.unbindService(mDefContainerConn); 1178 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1179 } 1180 1181 PackageHandler(Looper looper) { 1182 super(looper); 1183 } 1184 1185 public void handleMessage(Message msg) { 1186 try { 1187 doHandleMessage(msg); 1188 } finally { 1189 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1190 } 1191 } 1192 1193 void doHandleMessage(Message msg) { 1194 switch (msg.what) { 1195 case INIT_COPY: { 1196 HandlerParams params = (HandlerParams) msg.obj; 1197 int idx = mPendingInstalls.size(); 1198 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1199 // If a bind was already initiated we dont really 1200 // need to do anything. The pending install 1201 // will be processed later on. 1202 if (!mBound) { 1203 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1204 System.identityHashCode(mHandler)); 1205 // If this is the only one pending we might 1206 // have to bind to the service again. 1207 if (!connectToService()) { 1208 Slog.e(TAG, "Failed to bind to media container service"); 1209 params.serviceError(); 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1211 System.identityHashCode(mHandler)); 1212 if (params.traceMethod != null) { 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1214 params.traceCookie); 1215 } 1216 return; 1217 } else { 1218 // Once we bind to the service, the first 1219 // pending request will be processed. 1220 mPendingInstalls.add(idx, params); 1221 } 1222 } else { 1223 mPendingInstalls.add(idx, params); 1224 // Already bound to the service. Just make 1225 // sure we trigger off processing the first request. 1226 if (idx == 0) { 1227 mHandler.sendEmptyMessage(MCS_BOUND); 1228 } 1229 } 1230 break; 1231 } 1232 case MCS_BOUND: { 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1234 if (msg.obj != null) { 1235 mContainerService = (IMediaContainerService) msg.obj; 1236 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1237 System.identityHashCode(mHandler)); 1238 } 1239 if (mContainerService == null) { 1240 if (!mBound) { 1241 // Something seriously wrong since we are not bound and we are not 1242 // waiting for connection. Bail out. 1243 Slog.e(TAG, "Cannot bind to media container service"); 1244 for (HandlerParams params : mPendingInstalls) { 1245 // Indicate service bind error 1246 params.serviceError(); 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1248 System.identityHashCode(params)); 1249 if (params.traceMethod != null) { 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1251 params.traceMethod, params.traceCookie); 1252 } 1253 return; 1254 } 1255 mPendingInstalls.clear(); 1256 } else { 1257 Slog.w(TAG, "Waiting to connect to media container service"); 1258 } 1259 } else if (mPendingInstalls.size() > 0) { 1260 HandlerParams params = mPendingInstalls.get(0); 1261 if (params != null) { 1262 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1263 System.identityHashCode(params)); 1264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1265 if (params.startCopy()) { 1266 // We are done... look for more work or to 1267 // go idle. 1268 if (DEBUG_SD_INSTALL) Log.i(TAG, 1269 "Checking for more work or unbind..."); 1270 // Delete pending install 1271 if (mPendingInstalls.size() > 0) { 1272 mPendingInstalls.remove(0); 1273 } 1274 if (mPendingInstalls.size() == 0) { 1275 if (mBound) { 1276 if (DEBUG_SD_INSTALL) Log.i(TAG, 1277 "Posting delayed MCS_UNBIND"); 1278 removeMessages(MCS_UNBIND); 1279 Message ubmsg = obtainMessage(MCS_UNBIND); 1280 // Unbind after a little delay, to avoid 1281 // continual thrashing. 1282 sendMessageDelayed(ubmsg, 10000); 1283 } 1284 } else { 1285 // There are more pending requests in queue. 1286 // Just post MCS_BOUND message to trigger processing 1287 // of next pending install. 1288 if (DEBUG_SD_INSTALL) Log.i(TAG, 1289 "Posting MCS_BOUND for next work"); 1290 mHandler.sendEmptyMessage(MCS_BOUND); 1291 } 1292 } 1293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1294 } 1295 } else { 1296 // Should never happen ideally. 1297 Slog.w(TAG, "Empty queue"); 1298 } 1299 break; 1300 } 1301 case MCS_RECONNECT: { 1302 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1303 if (mPendingInstalls.size() > 0) { 1304 if (mBound) { 1305 disconnectService(); 1306 } 1307 if (!connectToService()) { 1308 Slog.e(TAG, "Failed to bind to media container service"); 1309 for (HandlerParams params : mPendingInstalls) { 1310 // Indicate service bind error 1311 params.serviceError(); 1312 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1313 System.identityHashCode(params)); 1314 } 1315 mPendingInstalls.clear(); 1316 } 1317 } 1318 break; 1319 } 1320 case MCS_UNBIND: { 1321 // If there is no actual work left, then time to unbind. 1322 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1323 1324 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1325 if (mBound) { 1326 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1327 1328 disconnectService(); 1329 } 1330 } else if (mPendingInstalls.size() > 0) { 1331 // There are more pending requests in queue. 1332 // Just post MCS_BOUND message to trigger processing 1333 // of next pending install. 1334 mHandler.sendEmptyMessage(MCS_BOUND); 1335 } 1336 1337 break; 1338 } 1339 case MCS_GIVE_UP: { 1340 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1341 HandlerParams params = mPendingInstalls.remove(0); 1342 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1343 System.identityHashCode(params)); 1344 break; 1345 } 1346 case SEND_PENDING_BROADCAST: { 1347 String packages[]; 1348 ArrayList<String> components[]; 1349 int size = 0; 1350 int uids[]; 1351 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1352 synchronized (mPackages) { 1353 if (mPendingBroadcasts == null) { 1354 return; 1355 } 1356 size = mPendingBroadcasts.size(); 1357 if (size <= 0) { 1358 // Nothing to be done. Just return 1359 return; 1360 } 1361 packages = new String[size]; 1362 components = new ArrayList[size]; 1363 uids = new int[size]; 1364 int i = 0; // filling out the above arrays 1365 1366 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1367 int packageUserId = mPendingBroadcasts.userIdAt(n); 1368 Iterator<Map.Entry<String, ArrayList<String>>> it 1369 = mPendingBroadcasts.packagesForUserId(packageUserId) 1370 .entrySet().iterator(); 1371 while (it.hasNext() && i < size) { 1372 Map.Entry<String, ArrayList<String>> ent = it.next(); 1373 packages[i] = ent.getKey(); 1374 components[i] = ent.getValue(); 1375 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1376 uids[i] = (ps != null) 1377 ? UserHandle.getUid(packageUserId, ps.appId) 1378 : -1; 1379 i++; 1380 } 1381 } 1382 size = i; 1383 mPendingBroadcasts.clear(); 1384 } 1385 // Send broadcasts 1386 for (int i = 0; i < size; i++) { 1387 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1388 } 1389 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1390 break; 1391 } 1392 case START_CLEANING_PACKAGE: { 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1394 final String packageName = (String)msg.obj; 1395 final int userId = msg.arg1; 1396 final boolean andCode = msg.arg2 != 0; 1397 synchronized (mPackages) { 1398 if (userId == UserHandle.USER_ALL) { 1399 int[] users = sUserManager.getUserIds(); 1400 for (int user : users) { 1401 mSettings.addPackageToCleanLPw( 1402 new PackageCleanItem(user, packageName, andCode)); 1403 } 1404 } else { 1405 mSettings.addPackageToCleanLPw( 1406 new PackageCleanItem(userId, packageName, andCode)); 1407 } 1408 } 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1410 startCleaningPackages(); 1411 } break; 1412 case POST_INSTALL: { 1413 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1414 1415 PostInstallData data = mRunningInstalls.get(msg.arg1); 1416 final boolean didRestore = (msg.arg2 != 0); 1417 mRunningInstalls.delete(msg.arg1); 1418 1419 if (data != null) { 1420 InstallArgs args = data.args; 1421 PackageInstalledInfo parentRes = data.res; 1422 1423 final boolean grantPermissions = (args.installFlags 1424 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1425 final boolean killApp = (args.installFlags 1426 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1427 final String[] grantedPermissions = args.installGrantPermissions; 1428 1429 // Handle the parent package 1430 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1431 grantedPermissions, didRestore, args.installerPackageName, 1432 args.observer); 1433 1434 // Handle the child packages 1435 final int childCount = (parentRes.addedChildPackages != null) 1436 ? parentRes.addedChildPackages.size() : 0; 1437 for (int i = 0; i < childCount; i++) { 1438 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1439 handlePackagePostInstall(childRes, grantPermissions, killApp, 1440 grantedPermissions, false, args.installerPackageName, 1441 args.observer); 1442 } 1443 1444 // Log tracing if needed 1445 if (args.traceMethod != null) { 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1447 args.traceCookie); 1448 } 1449 } else { 1450 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1451 } 1452 1453 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1454 } break; 1455 case UPDATED_MEDIA_STATUS: { 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1457 boolean reportStatus = msg.arg1 == 1; 1458 boolean doGc = msg.arg2 == 1; 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1460 if (doGc) { 1461 // Force a gc to clear up stale containers. 1462 Runtime.getRuntime().gc(); 1463 } 1464 if (msg.obj != null) { 1465 @SuppressWarnings("unchecked") 1466 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1468 // Unload containers 1469 unloadAllContainers(args); 1470 } 1471 if (reportStatus) { 1472 try { 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, 1474 "Invoking StorageManagerService call back"); 1475 PackageHelper.getStorageManager().finishMediaUpdate(); 1476 } catch (RemoteException e) { 1477 Log.e(TAG, "StorageManagerService not running?"); 1478 } 1479 } 1480 } break; 1481 case WRITE_SETTINGS: { 1482 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1483 synchronized (mPackages) { 1484 removeMessages(WRITE_SETTINGS); 1485 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1486 mSettings.writeLPr(); 1487 mDirtyUsers.clear(); 1488 } 1489 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1490 } break; 1491 case WRITE_PACKAGE_RESTRICTIONS: { 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1493 synchronized (mPackages) { 1494 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1495 for (int userId : mDirtyUsers) { 1496 mSettings.writePackageRestrictionsLPr(userId); 1497 } 1498 mDirtyUsers.clear(); 1499 } 1500 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1501 } break; 1502 case WRITE_PACKAGE_LIST: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_PACKAGE_LIST); 1506 mSettings.writePackageListLPr(msg.arg1); 1507 } 1508 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1509 } break; 1510 case CHECK_PENDING_VERIFICATION: { 1511 final int verificationId = msg.arg1; 1512 final PackageVerificationState state = mPendingVerification.get(verificationId); 1513 1514 if ((state != null) && !state.timeoutExtended()) { 1515 final InstallArgs args = state.getInstallArgs(); 1516 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1517 1518 Slog.i(TAG, "Verification timed out for " + originUri); 1519 mPendingVerification.remove(verificationId); 1520 1521 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1522 1523 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1524 Slog.i(TAG, "Continuing with installation of " + originUri); 1525 state.setVerifierResponse(Binder.getCallingUid(), 1526 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1527 broadcastPackageVerified(verificationId, originUri, 1528 PackageManager.VERIFICATION_ALLOW, 1529 state.getInstallArgs().getUser()); 1530 try { 1531 ret = args.copyApk(mContainerService, true); 1532 } catch (RemoteException e) { 1533 Slog.e(TAG, "Could not contact the ContainerService"); 1534 } 1535 } else { 1536 broadcastPackageVerified(verificationId, originUri, 1537 PackageManager.VERIFICATION_REJECT, 1538 state.getInstallArgs().getUser()); 1539 } 1540 1541 Trace.asyncTraceEnd( 1542 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1543 1544 processPendingInstall(args, ret); 1545 mHandler.sendEmptyMessage(MCS_UNBIND); 1546 } 1547 break; 1548 } 1549 case PACKAGE_VERIFIED: { 1550 final int verificationId = msg.arg1; 1551 1552 final PackageVerificationState state = mPendingVerification.get(verificationId); 1553 if (state == null) { 1554 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1555 break; 1556 } 1557 1558 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1559 1560 state.setVerifierResponse(response.callerUid, response.code); 1561 1562 if (state.isVerificationComplete()) { 1563 mPendingVerification.remove(verificationId); 1564 1565 final InstallArgs args = state.getInstallArgs(); 1566 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1567 1568 int ret; 1569 if (state.isInstallAllowed()) { 1570 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1571 broadcastPackageVerified(verificationId, originUri, 1572 response.code, state.getInstallArgs().getUser()); 1573 try { 1574 ret = args.copyApk(mContainerService, true); 1575 } catch (RemoteException e) { 1576 Slog.e(TAG, "Could not contact the ContainerService"); 1577 } 1578 } else { 1579 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1580 } 1581 1582 Trace.asyncTraceEnd( 1583 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1584 1585 processPendingInstall(args, ret); 1586 mHandler.sendEmptyMessage(MCS_UNBIND); 1587 } 1588 1589 break; 1590 } 1591 case START_INTENT_FILTER_VERIFICATIONS: { 1592 IFVerificationParams params = (IFVerificationParams) msg.obj; 1593 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1594 params.replacing, params.pkg); 1595 break; 1596 } 1597 case INTENT_FILTER_VERIFIED: { 1598 final int verificationId = msg.arg1; 1599 1600 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1601 verificationId); 1602 if (state == null) { 1603 Slog.w(TAG, "Invalid IntentFilter verification token " 1604 + verificationId + " received"); 1605 break; 1606 } 1607 1608 final int userId = state.getUserId(); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "Processing IntentFilter verification with token:" 1612 + verificationId + " and userId:" + userId); 1613 1614 final IntentFilterVerificationResponse response = 1615 (IntentFilterVerificationResponse) msg.obj; 1616 1617 state.setVerifierResponse(response.callerUid, response.code); 1618 1619 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1620 "IntentFilter verification with token:" + verificationId 1621 + " and userId:" + userId 1622 + " is settings verifier response with response code:" 1623 + response.code); 1624 1625 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1626 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1627 + response.getFailedDomainsString()); 1628 } 1629 1630 if (state.isVerificationComplete()) { 1631 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1632 } else { 1633 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1634 "IntentFilter verification with token:" + verificationId 1635 + " was not said to be complete"); 1636 } 1637 1638 break; 1639 } 1640 } 1641 } 1642 } 1643 1644 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1645 boolean killApp, String[] grantedPermissions, 1646 boolean launchedForRestore, String installerPackage, 1647 IPackageInstallObserver2 installObserver) { 1648 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1649 // Send the removed broadcasts 1650 if (res.removedInfo != null) { 1651 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1652 } 1653 1654 // Now that we successfully installed the package, grant runtime 1655 // permissions if requested before broadcasting the install. 1656 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1657 >= Build.VERSION_CODES.M) { 1658 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1659 } 1660 1661 final boolean update = res.removedInfo != null 1662 && res.removedInfo.removedPackage != null; 1663 1664 // If this is the first time we have child packages for a disabled privileged 1665 // app that had no children, we grant requested runtime permissions to the new 1666 // children if the parent on the system image had them already granted. 1667 if (res.pkg.parentPackage != null) { 1668 synchronized (mPackages) { 1669 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1670 } 1671 } 1672 1673 synchronized (mPackages) { 1674 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1675 } 1676 1677 final String packageName = res.pkg.applicationInfo.packageName; 1678 1679 // Determine the set of users who are adding this package for 1680 // the first time vs. those who are seeing an update. 1681 int[] firstUsers = EMPTY_INT_ARRAY; 1682 int[] updateUsers = EMPTY_INT_ARRAY; 1683 if (res.origUsers == null || res.origUsers.length == 0) { 1684 firstUsers = res.newUsers; 1685 } else { 1686 for (int newUser : res.newUsers) { 1687 boolean isNew = true; 1688 for (int origUser : res.origUsers) { 1689 if (origUser == newUser) { 1690 isNew = false; 1691 break; 1692 } 1693 } 1694 if (isNew) { 1695 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1696 } else { 1697 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1698 } 1699 } 1700 } 1701 1702 // Send installed broadcasts if the install/update is not ephemeral 1703 if (!isEphemeral(res.pkg)) { 1704 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1705 1706 // Send added for users that see the package for the first time 1707 // sendPackageAddedForNewUsers also deals with system apps 1708 int appId = UserHandle.getAppId(res.uid); 1709 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1710 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1711 1712 // Send added for users that don't see the package for the first time 1713 Bundle extras = new Bundle(1); 1714 extras.putInt(Intent.EXTRA_UID, res.uid); 1715 if (update) { 1716 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1717 } 1718 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1719 extras, 0 /*flags*/, null /*targetPackage*/, 1720 null /*finishedReceiver*/, updateUsers); 1721 1722 // Send replaced for users that don't see the package for the first time 1723 if (update) { 1724 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1725 packageName, extras, 0 /*flags*/, 1726 null /*targetPackage*/, null /*finishedReceiver*/, 1727 updateUsers); 1728 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1729 null /*package*/, null /*extras*/, 0 /*flags*/, 1730 packageName /*targetPackage*/, 1731 null /*finishedReceiver*/, updateUsers); 1732 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1733 // First-install and we did a restore, so we're responsible for the 1734 // first-launch broadcast. 1735 if (DEBUG_BACKUP) { 1736 Slog.i(TAG, "Post-restore of " + packageName 1737 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1738 } 1739 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1740 } 1741 1742 // Send broadcast package appeared if forward locked/external for all users 1743 // treat asec-hosted packages like removable media on upgrade 1744 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1745 if (DEBUG_INSTALL) { 1746 Slog.i(TAG, "upgrading pkg " + res.pkg 1747 + " is ASEC-hosted -> AVAILABLE"); 1748 } 1749 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1750 ArrayList<String> pkgList = new ArrayList<>(1); 1751 pkgList.add(packageName); 1752 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1753 } 1754 } 1755 1756 // Work that needs to happen on first install within each user 1757 if (firstUsers != null && firstUsers.length > 0) { 1758 synchronized (mPackages) { 1759 for (int userId : firstUsers) { 1760 // If this app is a browser and it's newly-installed for some 1761 // users, clear any default-browser state in those users. The 1762 // app's nature doesn't depend on the user, so we can just check 1763 // its browser nature in any user and generalize. 1764 if (packageIsBrowser(packageName, userId)) { 1765 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1766 } 1767 1768 // We may also need to apply pending (restored) runtime 1769 // permission grants within these users. 1770 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1771 } 1772 } 1773 } 1774 1775 // Log current value of "unknown sources" setting 1776 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1777 getUnknownSourcesSettings()); 1778 1779 // Force a gc to clear up things 1780 Runtime.getRuntime().gc(); 1781 1782 // Remove the replaced package's older resources safely now 1783 // We delete after a gc for applications on sdcard. 1784 if (res.removedInfo != null && res.removedInfo.args != null) { 1785 synchronized (mInstallLock) { 1786 res.removedInfo.args.doPostDeleteLI(true); 1787 } 1788 } 1789 } 1790 1791 // If someone is watching installs - notify them 1792 if (installObserver != null) { 1793 try { 1794 Bundle extras = extrasForInstallResult(res); 1795 installObserver.onPackageInstalled(res.name, res.returnCode, 1796 res.returnMsg, extras); 1797 } catch (RemoteException e) { 1798 Slog.i(TAG, "Observer no longer exists."); 1799 } 1800 } 1801 } 1802 1803 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1804 PackageParser.Package pkg) { 1805 if (pkg.parentPackage == null) { 1806 return; 1807 } 1808 if (pkg.requestedPermissions == null) { 1809 return; 1810 } 1811 final PackageSetting disabledSysParentPs = mSettings 1812 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1813 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1814 || !disabledSysParentPs.isPrivileged() 1815 || (disabledSysParentPs.childPackageNames != null 1816 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1817 return; 1818 } 1819 final int[] allUserIds = sUserManager.getUserIds(); 1820 final int permCount = pkg.requestedPermissions.size(); 1821 for (int i = 0; i < permCount; i++) { 1822 String permission = pkg.requestedPermissions.get(i); 1823 BasePermission bp = mSettings.mPermissions.get(permission); 1824 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1825 continue; 1826 } 1827 for (int userId : allUserIds) { 1828 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1829 permission, userId)) { 1830 grantRuntimePermission(pkg.packageName, permission, userId); 1831 } 1832 } 1833 } 1834 } 1835 1836 private StorageEventListener mStorageListener = new StorageEventListener() { 1837 @Override 1838 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1839 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1840 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1841 final String volumeUuid = vol.getFsUuid(); 1842 1843 // Clean up any users or apps that were removed or recreated 1844 // while this volume was missing 1845 reconcileUsers(volumeUuid); 1846 reconcileApps(volumeUuid); 1847 1848 // Clean up any install sessions that expired or were 1849 // cancelled while this volume was missing 1850 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1851 1852 loadPrivatePackages(vol); 1853 1854 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1855 unloadPrivatePackages(vol); 1856 } 1857 } 1858 1859 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1860 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1861 updateExternalMediaStatus(true, false); 1862 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1863 updateExternalMediaStatus(false, false); 1864 } 1865 } 1866 } 1867 1868 @Override 1869 public void onVolumeForgotten(String fsUuid) { 1870 if (TextUtils.isEmpty(fsUuid)) { 1871 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1872 return; 1873 } 1874 1875 // Remove any apps installed on the forgotten volume 1876 synchronized (mPackages) { 1877 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1878 for (PackageSetting ps : packages) { 1879 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1880 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1881 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1882 } 1883 1884 mSettings.onVolumeForgotten(fsUuid); 1885 mSettings.writeLPr(); 1886 } 1887 } 1888 }; 1889 1890 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1891 String[] grantedPermissions) { 1892 for (int userId : userIds) { 1893 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1894 } 1895 1896 // We could have touched GID membership, so flush out packages.list 1897 synchronized (mPackages) { 1898 mSettings.writePackageListLPr(); 1899 } 1900 } 1901 1902 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1903 String[] grantedPermissions) { 1904 SettingBase sb = (SettingBase) pkg.mExtras; 1905 if (sb == null) { 1906 return; 1907 } 1908 1909 PermissionsState permissionsState = sb.getPermissionsState(); 1910 1911 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1912 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1913 1914 for (String permission : pkg.requestedPermissions) { 1915 final BasePermission bp; 1916 synchronized (mPackages) { 1917 bp = mSettings.mPermissions.get(permission); 1918 } 1919 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1920 && (grantedPermissions == null 1921 || ArrayUtils.contains(grantedPermissions, permission))) { 1922 final int flags = permissionsState.getPermissionFlags(permission, userId); 1923 // Installer cannot change immutable permissions. 1924 if ((flags & immutableFlags) == 0) { 1925 grantRuntimePermission(pkg.packageName, permission, userId); 1926 } 1927 } 1928 } 1929 } 1930 1931 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1932 Bundle extras = null; 1933 switch (res.returnCode) { 1934 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1935 extras = new Bundle(); 1936 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1937 res.origPermission); 1938 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1939 res.origPackage); 1940 break; 1941 } 1942 case PackageManager.INSTALL_SUCCEEDED: { 1943 extras = new Bundle(); 1944 extras.putBoolean(Intent.EXTRA_REPLACING, 1945 res.removedInfo != null && res.removedInfo.removedPackage != null); 1946 break; 1947 } 1948 } 1949 return extras; 1950 } 1951 1952 void scheduleWriteSettingsLocked() { 1953 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1954 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1955 } 1956 } 1957 1958 void scheduleWritePackageListLocked(int userId) { 1959 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1960 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1961 msg.arg1 = userId; 1962 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1963 } 1964 } 1965 1966 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1967 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1968 scheduleWritePackageRestrictionsLocked(userId); 1969 } 1970 1971 void scheduleWritePackageRestrictionsLocked(int userId) { 1972 final int[] userIds = (userId == UserHandle.USER_ALL) 1973 ? sUserManager.getUserIds() : new int[]{userId}; 1974 for (int nextUserId : userIds) { 1975 if (!sUserManager.exists(nextUserId)) return; 1976 mDirtyUsers.add(nextUserId); 1977 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1978 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1979 } 1980 } 1981 } 1982 1983 public static PackageManagerService main(Context context, Installer installer, 1984 boolean factoryTest, boolean onlyCore) { 1985 // Self-check for initial settings. 1986 PackageManagerServiceCompilerMapping.checkProperties(); 1987 1988 PackageManagerService m = new PackageManagerService(context, installer, 1989 factoryTest, onlyCore); 1990 m.enableSystemUserPackages(); 1991 ServiceManager.addService("package", m); 1992 return m; 1993 } 1994 1995 private void enableSystemUserPackages() { 1996 if (!UserManager.isSplitSystemUser()) { 1997 return; 1998 } 1999 // For system user, enable apps based on the following conditions: 2000 // - app is whitelisted or belong to one of these groups: 2001 // -- system app which has no launcher icons 2002 // -- system app which has INTERACT_ACROSS_USERS permission 2003 // -- system IME app 2004 // - app is not in the blacklist 2005 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2006 Set<String> enableApps = new ArraySet<>(); 2007 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2008 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2009 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2010 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2011 enableApps.addAll(wlApps); 2012 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2013 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2014 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2015 enableApps.removeAll(blApps); 2016 Log.i(TAG, "Applications installed for system user: " + enableApps); 2017 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2018 UserHandle.SYSTEM); 2019 final int allAppsSize = allAps.size(); 2020 synchronized (mPackages) { 2021 for (int i = 0; i < allAppsSize; i++) { 2022 String pName = allAps.get(i); 2023 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2024 // Should not happen, but we shouldn't be failing if it does 2025 if (pkgSetting == null) { 2026 continue; 2027 } 2028 boolean install = enableApps.contains(pName); 2029 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2030 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2031 + " for system user"); 2032 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2033 } 2034 } 2035 } 2036 } 2037 2038 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2039 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2040 Context.DISPLAY_SERVICE); 2041 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2042 } 2043 2044 /** 2045 * Requests that files preopted on a secondary system partition be copied to the data partition 2046 * if possible. Note that the actual copying of the files is accomplished by init for security 2047 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2048 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2049 */ 2050 private static void requestCopyPreoptedFiles() { 2051 final int WAIT_TIME_MS = 100; 2052 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2053 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2054 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2055 // We will wait for up to 100 seconds. 2056 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2057 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2058 try { 2059 Thread.sleep(WAIT_TIME_MS); 2060 } catch (InterruptedException e) { 2061 // Do nothing 2062 } 2063 if (SystemClock.uptimeMillis() > timeEnd) { 2064 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2065 Slog.wtf(TAG, "cppreopt did not finish!"); 2066 break; 2067 } 2068 } 2069 } 2070 } 2071 2072 public PackageManagerService(Context context, Installer installer, 2073 boolean factoryTest, boolean onlyCore) { 2074 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2075 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2076 SystemClock.uptimeMillis()); 2077 2078 if (mSdkVersion <= 0) { 2079 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2080 } 2081 2082 mContext = context; 2083 2084 mPermissionReviewRequired = context.getResources().getBoolean( 2085 R.bool.config_permissionReviewRequired); 2086 2087 mFactoryTest = factoryTest; 2088 mOnlyCore = onlyCore; 2089 mMetrics = new DisplayMetrics(); 2090 mSettings = new Settings(mPackages); 2091 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2092 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2093 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2094 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2095 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2096 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2097 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2098 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2099 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2100 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2101 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2102 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2103 2104 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2105 if (separateProcesses != null && separateProcesses.length() > 0) { 2106 if ("*".equals(separateProcesses)) { 2107 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2108 mSeparateProcesses = null; 2109 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2110 } else { 2111 mDefParseFlags = 0; 2112 mSeparateProcesses = separateProcesses.split(","); 2113 Slog.w(TAG, "Running with debug.separate_processes: " 2114 + separateProcesses); 2115 } 2116 } else { 2117 mDefParseFlags = 0; 2118 mSeparateProcesses = null; 2119 } 2120 2121 mInstaller = installer; 2122 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2123 "*dexopt*"); 2124 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2125 2126 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2127 FgThread.get().getLooper()); 2128 2129 getDefaultDisplayMetrics(context, mMetrics); 2130 2131 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2132 SystemConfig systemConfig = SystemConfig.getInstance(); 2133 mGlobalGids = systemConfig.getGlobalGids(); 2134 mSystemPermissions = systemConfig.getSystemPermissions(); 2135 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2136 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2137 2138 mProtectedPackages = new ProtectedPackages(mContext); 2139 2140 synchronized (mInstallLock) { 2141 // writer 2142 synchronized (mPackages) { 2143 mHandlerThread = new ServiceThread(TAG, 2144 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2145 mHandlerThread.start(); 2146 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2147 mProcessLoggingHandler = new ProcessLoggingHandler(); 2148 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2149 2150 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2151 2152 File dataDir = Environment.getDataDirectory(); 2153 mAppInstallDir = new File(dataDir, "app"); 2154 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2155 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2156 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2157 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2158 2159 sUserManager = new UserManagerService(context, this, mPackages); 2160 2161 // Propagate permission configuration in to package manager. 2162 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2163 = systemConfig.getPermissions(); 2164 for (int i=0; i<permConfig.size(); i++) { 2165 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2166 BasePermission bp = mSettings.mPermissions.get(perm.name); 2167 if (bp == null) { 2168 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2169 mSettings.mPermissions.put(perm.name, bp); 2170 } 2171 if (perm.gids != null) { 2172 bp.setGids(perm.gids, perm.perUser); 2173 } 2174 } 2175 2176 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2177 for (int i=0; i<libConfig.size(); i++) { 2178 mSharedLibraries.put(libConfig.keyAt(i), 2179 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2180 } 2181 2182 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2183 2184 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2185 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2186 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2187 2188 if (mFirstBoot) { 2189 requestCopyPreoptedFiles(); 2190 } 2191 2192 String customResolverActivity = Resources.getSystem().getString( 2193 R.string.config_customResolverActivity); 2194 if (TextUtils.isEmpty(customResolverActivity)) { 2195 customResolverActivity = null; 2196 } else { 2197 mCustomResolverComponentName = ComponentName.unflattenFromString( 2198 customResolverActivity); 2199 } 2200 2201 long startTime = SystemClock.uptimeMillis(); 2202 2203 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2204 startTime); 2205 2206 // Set flag to monitor and not change apk file paths when 2207 // scanning install directories. 2208 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2209 2210 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2211 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2212 2213 if (bootClassPath == null) { 2214 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2215 } 2216 2217 if (systemServerClassPath == null) { 2218 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2219 } 2220 2221 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2222 final String[] dexCodeInstructionSets = 2223 getDexCodeInstructionSets( 2224 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2225 2226 /** 2227 * Ensure all external libraries have had dexopt run on them. 2228 */ 2229 if (mSharedLibraries.size() > 0) { 2230 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2231 // NOTE: For now, we're compiling these system "shared libraries" 2232 // (and framework jars) into all available architectures. It's possible 2233 // to compile them only when we come across an app that uses them (there's 2234 // already logic for that in scanPackageLI) but that adds some complexity. 2235 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2236 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2237 final String lib = libEntry.path; 2238 if (lib == null) { 2239 continue; 2240 } 2241 2242 try { 2243 // Shared libraries do not have profiles so we perform a full 2244 // AOT compilation (if needed). 2245 int dexoptNeeded = DexFile.getDexOptNeeded( 2246 lib, dexCodeInstructionSet, 2247 getCompilerFilterForReason(REASON_SHARED_APK), 2248 false /* newProfile */); 2249 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2250 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2251 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2252 getCompilerFilterForReason(REASON_SHARED_APK), 2253 StorageManager.UUID_PRIVATE_INTERNAL, 2254 SKIP_SHARED_LIBRARY_CHECK); 2255 } 2256 } catch (FileNotFoundException e) { 2257 Slog.w(TAG, "Library not found: " + lib); 2258 } catch (IOException | InstallerException e) { 2259 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2260 + e.getMessage()); 2261 } 2262 } 2263 } 2264 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2265 } 2266 2267 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2268 2269 final VersionInfo ver = mSettings.getInternalVersion(); 2270 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2271 2272 // when upgrading from pre-M, promote system app permissions from install to runtime 2273 mPromoteSystemApps = 2274 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2275 2276 // When upgrading from pre-N, we need to handle package extraction like first boot, 2277 // as there is no profiling data available. 2278 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2279 2280 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2281 2282 // save off the names of pre-existing system packages prior to scanning; we don't 2283 // want to automatically grant runtime permissions for new system apps 2284 if (mPromoteSystemApps) { 2285 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2286 while (pkgSettingIter.hasNext()) { 2287 PackageSetting ps = pkgSettingIter.next(); 2288 if (isSystemApp(ps)) { 2289 mExistingSystemPackages.add(ps.name); 2290 } 2291 } 2292 } 2293 2294 // Collect vendor overlay packages. (Do this before scanning any apps.) 2295 // For security and version matching reason, only consider 2296 // overlay packages if they reside in the right directory. 2297 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2298 if (overlayThemeDir.isEmpty()) { 2299 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2300 } 2301 if (!overlayThemeDir.isEmpty()) { 2302 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2303 | PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR 2305 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2306 } 2307 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2308 | PackageParser.PARSE_IS_SYSTEM 2309 | PackageParser.PARSE_IS_SYSTEM_DIR 2310 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2311 2312 // Find base frameworks (resource packages without code). 2313 scanDirTracedLI(frameworkDir, mDefParseFlags 2314 | PackageParser.PARSE_IS_SYSTEM 2315 | PackageParser.PARSE_IS_SYSTEM_DIR 2316 | PackageParser.PARSE_IS_PRIVILEGED, 2317 scanFlags | SCAN_NO_DEX, 0); 2318 2319 // Collected privileged system packages. 2320 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2321 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2322 | PackageParser.PARSE_IS_SYSTEM 2323 | PackageParser.PARSE_IS_SYSTEM_DIR 2324 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2325 2326 // Collect ordinary system packages. 2327 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2328 scanDirTracedLI(systemAppDir, mDefParseFlags 2329 | PackageParser.PARSE_IS_SYSTEM 2330 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2331 2332 // Collect all vendor packages. 2333 File vendorAppDir = new File("/vendor/app"); 2334 try { 2335 vendorAppDir = vendorAppDir.getCanonicalFile(); 2336 } catch (IOException e) { 2337 // failed to look up canonical path, continue with original one 2338 } 2339 scanDirTracedLI(vendorAppDir, mDefParseFlags 2340 | PackageParser.PARSE_IS_SYSTEM 2341 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2342 2343 // Collect all OEM packages. 2344 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2345 scanDirTracedLI(oemAppDir, mDefParseFlags 2346 | PackageParser.PARSE_IS_SYSTEM 2347 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2348 2349 // Prune any system packages that no longer exist. 2350 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2351 if (!mOnlyCore) { 2352 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2353 while (psit.hasNext()) { 2354 PackageSetting ps = psit.next(); 2355 2356 /* 2357 * If this is not a system app, it can't be a 2358 * disable system app. 2359 */ 2360 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2361 continue; 2362 } 2363 2364 /* 2365 * If the package is scanned, it's not erased. 2366 */ 2367 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2368 if (scannedPkg != null) { 2369 /* 2370 * If the system app is both scanned and in the 2371 * disabled packages list, then it must have been 2372 * added via OTA. Remove it from the currently 2373 * scanned package so the previously user-installed 2374 * application can be scanned. 2375 */ 2376 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2377 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2378 + ps.name + "; removing system app. Last known codePath=" 2379 + ps.codePathString + ", installStatus=" + ps.installStatus 2380 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2381 + scannedPkg.mVersionCode); 2382 removePackageLI(scannedPkg, true); 2383 mExpectingBetter.put(ps.name, ps.codePath); 2384 } 2385 2386 continue; 2387 } 2388 2389 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2390 psit.remove(); 2391 logCriticalInfo(Log.WARN, "System package " + ps.name 2392 + " no longer exists; it's data will be wiped"); 2393 // Actual deletion of code and data will be handled by later 2394 // reconciliation step 2395 } else { 2396 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2397 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2398 possiblyDeletedUpdatedSystemApps.add(ps.name); 2399 } 2400 } 2401 } 2402 } 2403 2404 //look for any incomplete package installations 2405 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2406 for (int i = 0; i < deletePkgsList.size(); i++) { 2407 // Actual deletion of code and data will be handled by later 2408 // reconciliation step 2409 final String packageName = deletePkgsList.get(i).name; 2410 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2411 synchronized (mPackages) { 2412 mSettings.removePackageLPw(packageName); 2413 } 2414 } 2415 2416 //delete tmp files 2417 deleteTempPackageFiles(); 2418 2419 // Remove any shared userIDs that have no associated packages 2420 mSettings.pruneSharedUsersLPw(); 2421 2422 if (!mOnlyCore) { 2423 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2424 SystemClock.uptimeMillis()); 2425 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2426 2427 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2428 | PackageParser.PARSE_FORWARD_LOCK, 2429 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2430 2431 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2432 | PackageParser.PARSE_IS_EPHEMERAL, 2433 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2434 2435 /** 2436 * Remove disable package settings for any updated system 2437 * apps that were removed via an OTA. If they're not a 2438 * previously-updated app, remove them completely. 2439 * Otherwise, just revoke their system-level permissions. 2440 */ 2441 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2442 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2443 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2444 2445 String msg; 2446 if (deletedPkg == null) { 2447 msg = "Updated system package " + deletedAppName 2448 + " no longer exists; it's data will be wiped"; 2449 // Actual deletion of code and data will be handled by later 2450 // reconciliation step 2451 } else { 2452 msg = "Updated system app + " + deletedAppName 2453 + " no longer present; removing system privileges for " 2454 + deletedAppName; 2455 2456 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2457 2458 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2459 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2460 } 2461 logCriticalInfo(Log.WARN, msg); 2462 } 2463 2464 /** 2465 * Make sure all system apps that we expected to appear on 2466 * the userdata partition actually showed up. If they never 2467 * appeared, crawl back and revive the system version. 2468 */ 2469 for (int i = 0; i < mExpectingBetter.size(); i++) { 2470 final String packageName = mExpectingBetter.keyAt(i); 2471 if (!mPackages.containsKey(packageName)) { 2472 final File scanFile = mExpectingBetter.valueAt(i); 2473 2474 logCriticalInfo(Log.WARN, "Expected better " + packageName 2475 + " but never showed up; reverting to system"); 2476 2477 int reparseFlags = mDefParseFlags; 2478 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2479 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2480 | PackageParser.PARSE_IS_SYSTEM_DIR 2481 | PackageParser.PARSE_IS_PRIVILEGED; 2482 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2483 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2484 | PackageParser.PARSE_IS_SYSTEM_DIR; 2485 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2486 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2487 | PackageParser.PARSE_IS_SYSTEM_DIR; 2488 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2489 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR; 2491 } else { 2492 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2493 continue; 2494 } 2495 2496 mSettings.enableSystemPackageLPw(packageName); 2497 2498 try { 2499 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2500 } catch (PackageManagerException e) { 2501 Slog.e(TAG, "Failed to parse original system package: " 2502 + e.getMessage()); 2503 } 2504 } 2505 } 2506 } 2507 mExpectingBetter.clear(); 2508 2509 // Resolve the storage manager. 2510 mStorageManagerPackage = getStorageManagerPackageName(); 2511 2512 // Resolve protected action filters. Only the setup wizard is allowed to 2513 // have a high priority filter for these actions. 2514 mSetupWizardPackage = getSetupWizardPackageName(); 2515 if (mProtectedFilters.size() > 0) { 2516 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2517 Slog.i(TAG, "No setup wizard;" 2518 + " All protected intents capped to priority 0"); 2519 } 2520 for (ActivityIntentInfo filter : mProtectedFilters) { 2521 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2522 if (DEBUG_FILTERS) { 2523 Slog.i(TAG, "Found setup wizard;" 2524 + " allow priority " + filter.getPriority() + ";" 2525 + " package: " + filter.activity.info.packageName 2526 + " activity: " + filter.activity.className 2527 + " priority: " + filter.getPriority()); 2528 } 2529 // skip setup wizard; allow it to keep the high priority filter 2530 continue; 2531 } 2532 Slog.w(TAG, "Protected action; cap priority to 0;" 2533 + " package: " + filter.activity.info.packageName 2534 + " activity: " + filter.activity.className 2535 + " origPrio: " + filter.getPriority()); 2536 filter.setPriority(0); 2537 } 2538 } 2539 mDeferProtectedFilters = false; 2540 mProtectedFilters.clear(); 2541 2542 // Now that we know all of the shared libraries, update all clients to have 2543 // the correct library paths. 2544 updateAllSharedLibrariesLPw(); 2545 2546 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2547 // NOTE: We ignore potential failures here during a system scan (like 2548 // the rest of the commands above) because there's precious little we 2549 // can do about it. A settings error is reported, though. 2550 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2551 } 2552 2553 // Now that we know all the packages we are keeping, 2554 // read and update their last usage times. 2555 mPackageUsage.read(mPackages); 2556 mCompilerStats.read(); 2557 2558 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2559 SystemClock.uptimeMillis()); 2560 Slog.i(TAG, "Time to scan packages: " 2561 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2562 + " seconds"); 2563 2564 // If the platform SDK has changed since the last time we booted, 2565 // we need to re-grant app permission to catch any new ones that 2566 // appear. This is really a hack, and means that apps can in some 2567 // cases get permissions that the user didn't initially explicitly 2568 // allow... it would be nice to have some better way to handle 2569 // this situation. 2570 int updateFlags = UPDATE_PERMISSIONS_ALL; 2571 if (ver.sdkVersion != mSdkVersion) { 2572 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2573 + mSdkVersion + "; regranting permissions for internal storage"); 2574 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2575 } 2576 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2577 ver.sdkVersion = mSdkVersion; 2578 2579 // If this is the first boot or an update from pre-M, and it is a normal 2580 // boot, then we need to initialize the default preferred apps across 2581 // all defined users. 2582 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2583 for (UserInfo user : sUserManager.getUsers(true)) { 2584 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2585 applyFactoryDefaultBrowserLPw(user.id); 2586 primeDomainVerificationsLPw(user.id); 2587 } 2588 } 2589 2590 // Prepare storage for system user really early during boot, 2591 // since core system apps like SettingsProvider and SystemUI 2592 // can't wait for user to start 2593 final int storageFlags; 2594 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2595 storageFlags = StorageManager.FLAG_STORAGE_DE; 2596 } else { 2597 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2598 } 2599 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2600 storageFlags, true /* migrateAppData */); 2601 2602 // If this is first boot after an OTA, and a normal boot, then 2603 // we need to clear code cache directories. 2604 // Note that we do *not* clear the application profiles. These remain valid 2605 // across OTAs and are used to drive profile verification (post OTA) and 2606 // profile compilation (without waiting to collect a fresh set of profiles). 2607 if (mIsUpgrade && !onlyCore) { 2608 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2609 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2610 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2611 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2612 // No apps are running this early, so no need to freeze 2613 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2614 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2615 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2616 } 2617 } 2618 ver.fingerprint = Build.FINGERPRINT; 2619 } 2620 2621 checkDefaultBrowser(); 2622 2623 // clear only after permissions and other defaults have been updated 2624 mExistingSystemPackages.clear(); 2625 mPromoteSystemApps = false; 2626 2627 // All the changes are done during package scanning. 2628 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2629 2630 // can downgrade to reader 2631 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2632 mSettings.writeLPr(); 2633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2634 2635 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2636 // early on (before the package manager declares itself as early) because other 2637 // components in the system server might ask for package contexts for these apps. 2638 // 2639 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2640 // (i.e, that the data partition is unavailable). 2641 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2642 long start = System.nanoTime(); 2643 List<PackageParser.Package> coreApps = new ArrayList<>(); 2644 for (PackageParser.Package pkg : mPackages.values()) { 2645 if (pkg.coreApp) { 2646 coreApps.add(pkg); 2647 } 2648 } 2649 2650 int[] stats = performDexOptUpgrade(coreApps, false, 2651 getCompilerFilterForReason(REASON_CORE_APP)); 2652 2653 final int elapsedTimeSeconds = 2654 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2655 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2656 2657 if (DEBUG_DEXOPT) { 2658 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2659 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2660 } 2661 2662 2663 // TODO: Should we log these stats to tron too ? 2664 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2665 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2666 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2667 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2668 } 2669 2670 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2671 SystemClock.uptimeMillis()); 2672 2673 if (!mOnlyCore) { 2674 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2675 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2676 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2677 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2678 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2679 mIntentFilterVerifierComponent); 2680 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2681 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2682 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2683 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2684 } else { 2685 mRequiredVerifierPackage = null; 2686 mRequiredInstallerPackage = null; 2687 mRequiredUninstallerPackage = null; 2688 mIntentFilterVerifierComponent = null; 2689 mIntentFilterVerifier = null; 2690 mServicesSystemSharedLibraryPackageName = null; 2691 mSharedSystemSharedLibraryPackageName = null; 2692 } 2693 2694 mInstallerService = new PackageInstallerService(context, this); 2695 2696 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2697 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2698 // both the installer and resolver must be present to enable ephemeral 2699 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2700 if (DEBUG_EPHEMERAL) { 2701 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2702 + " installer:" + ephemeralInstallerComponent); 2703 } 2704 mEphemeralResolverComponent = ephemeralResolverComponent; 2705 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2706 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2707 mEphemeralResolverConnection = 2708 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2709 } else { 2710 if (DEBUG_EPHEMERAL) { 2711 final String missingComponent = 2712 (ephemeralResolverComponent == null) 2713 ? (ephemeralInstallerComponent == null) 2714 ? "resolver and installer" 2715 : "resolver" 2716 : "installer"; 2717 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2718 } 2719 mEphemeralResolverComponent = null; 2720 mEphemeralInstallerComponent = null; 2721 mEphemeralResolverConnection = null; 2722 } 2723 2724 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2725 } // synchronized (mPackages) 2726 } // synchronized (mInstallLock) 2727 2728 // Now after opening every single application zip, make sure they 2729 // are all flushed. Not really needed, but keeps things nice and 2730 // tidy. 2731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2732 Runtime.getRuntime().gc(); 2733 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2734 2735 // The initial scanning above does many calls into installd while 2736 // holding the mPackages lock, but we're mostly interested in yelling 2737 // once we have a booted system. 2738 mInstaller.setWarnIfHeld(mPackages); 2739 2740 // Expose private service for system components to use. 2741 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2743 } 2744 2745 @Override 2746 public boolean isFirstBoot() { 2747 return mFirstBoot; 2748 } 2749 2750 @Override 2751 public boolean isOnlyCoreApps() { 2752 return mOnlyCore; 2753 } 2754 2755 @Override 2756 public boolean isUpgrade() { 2757 return mIsUpgrade; 2758 } 2759 2760 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2761 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2762 2763 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2764 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2765 UserHandle.USER_SYSTEM); 2766 if (matches.size() == 1) { 2767 return matches.get(0).getComponentInfo().packageName; 2768 } else if (matches.size() == 0) { 2769 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2770 return null; 2771 } 2772 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2773 } 2774 2775 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2776 synchronized (mPackages) { 2777 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2778 if (libraryEntry == null) { 2779 throw new IllegalStateException("Missing required shared library:" + libraryName); 2780 } 2781 return libraryEntry.apk; 2782 } 2783 } 2784 2785 private @NonNull String getRequiredInstallerLPr() { 2786 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2787 intent.addCategory(Intent.CATEGORY_DEFAULT); 2788 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2789 2790 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2791 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2792 UserHandle.USER_SYSTEM); 2793 if (matches.size() == 1) { 2794 ResolveInfo resolveInfo = matches.get(0); 2795 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2796 throw new RuntimeException("The installer must be a privileged app"); 2797 } 2798 return matches.get(0).getComponentInfo().packageName; 2799 } else { 2800 throw new RuntimeException("There must be exactly one installer; found " + matches); 2801 } 2802 } 2803 2804 private @NonNull String getRequiredUninstallerLPr() { 2805 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2806 intent.addCategory(Intent.CATEGORY_DEFAULT); 2807 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2808 2809 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2810 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2811 UserHandle.USER_SYSTEM); 2812 if (resolveInfo == null || 2813 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2814 throw new RuntimeException("There must be exactly one uninstaller; found " 2815 + resolveInfo); 2816 } 2817 return resolveInfo.getComponentInfo().packageName; 2818 } 2819 2820 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2821 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2822 2823 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2824 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2825 UserHandle.USER_SYSTEM); 2826 ResolveInfo best = null; 2827 final int N = matches.size(); 2828 for (int i = 0; i < N; i++) { 2829 final ResolveInfo cur = matches.get(i); 2830 final String packageName = cur.getComponentInfo().packageName; 2831 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2832 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2833 continue; 2834 } 2835 2836 if (best == null || cur.priority > best.priority) { 2837 best = cur; 2838 } 2839 } 2840 2841 if (best != null) { 2842 return best.getComponentInfo().getComponentName(); 2843 } else { 2844 throw new RuntimeException("There must be at least one intent filter verifier"); 2845 } 2846 } 2847 2848 private @Nullable ComponentName getEphemeralResolverLPr() { 2849 final String[] packageArray = 2850 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2851 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2852 if (DEBUG_EPHEMERAL) { 2853 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2854 } 2855 return null; 2856 } 2857 2858 final int resolveFlags = 2859 MATCH_DIRECT_BOOT_AWARE 2860 | MATCH_DIRECT_BOOT_UNAWARE 2861 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2862 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2863 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2864 resolveFlags, UserHandle.USER_SYSTEM); 2865 2866 final int N = resolvers.size(); 2867 if (N == 0) { 2868 if (DEBUG_EPHEMERAL) { 2869 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2870 } 2871 return null; 2872 } 2873 2874 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2875 for (int i = 0; i < N; i++) { 2876 final ResolveInfo info = resolvers.get(i); 2877 2878 if (info.serviceInfo == null) { 2879 continue; 2880 } 2881 2882 final String packageName = info.serviceInfo.packageName; 2883 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2884 if (DEBUG_EPHEMERAL) { 2885 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2886 + " pkg: " + packageName + ", info:" + info); 2887 } 2888 continue; 2889 } 2890 2891 if (DEBUG_EPHEMERAL) { 2892 Slog.v(TAG, "Ephemeral resolver found;" 2893 + " pkg: " + packageName + ", info:" + info); 2894 } 2895 return new ComponentName(packageName, info.serviceInfo.name); 2896 } 2897 if (DEBUG_EPHEMERAL) { 2898 Slog.v(TAG, "Ephemeral resolver NOT found"); 2899 } 2900 return null; 2901 } 2902 2903 private @Nullable ComponentName getEphemeralInstallerLPr() { 2904 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2905 intent.addCategory(Intent.CATEGORY_DEFAULT); 2906 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2907 2908 final int resolveFlags = 2909 MATCH_DIRECT_BOOT_AWARE 2910 | MATCH_DIRECT_BOOT_UNAWARE 2911 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2912 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2913 resolveFlags, UserHandle.USER_SYSTEM); 2914 if (matches.size() == 0) { 2915 return null; 2916 } else if (matches.size() == 1) { 2917 return matches.get(0).getComponentInfo().getComponentName(); 2918 } else { 2919 throw new RuntimeException( 2920 "There must be at most one ephemeral installer; found " + matches); 2921 } 2922 } 2923 2924 private void primeDomainVerificationsLPw(int userId) { 2925 if (DEBUG_DOMAIN_VERIFICATION) { 2926 Slog.d(TAG, "Priming domain verifications in user " + userId); 2927 } 2928 2929 SystemConfig systemConfig = SystemConfig.getInstance(); 2930 ArraySet<String> packages = systemConfig.getLinkedApps(); 2931 2932 for (String packageName : packages) { 2933 PackageParser.Package pkg = mPackages.get(packageName); 2934 if (pkg != null) { 2935 if (!pkg.isSystemApp()) { 2936 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2937 continue; 2938 } 2939 2940 ArraySet<String> domains = null; 2941 for (PackageParser.Activity a : pkg.activities) { 2942 for (ActivityIntentInfo filter : a.intents) { 2943 if (hasValidDomains(filter)) { 2944 if (domains == null) { 2945 domains = new ArraySet<String>(); 2946 } 2947 domains.addAll(filter.getHostsList()); 2948 } 2949 } 2950 } 2951 2952 if (domains != null && domains.size() > 0) { 2953 if (DEBUG_DOMAIN_VERIFICATION) { 2954 Slog.v(TAG, " + " + packageName); 2955 } 2956 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2957 // state w.r.t. the formal app-linkage "no verification attempted" state; 2958 // and then 'always' in the per-user state actually used for intent resolution. 2959 final IntentFilterVerificationInfo ivi; 2960 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 2961 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2962 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2963 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2964 } else { 2965 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2966 + "' does not handle web links"); 2967 } 2968 } else { 2969 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2970 } 2971 } 2972 2973 scheduleWritePackageRestrictionsLocked(userId); 2974 scheduleWriteSettingsLocked(); 2975 } 2976 2977 private void applyFactoryDefaultBrowserLPw(int userId) { 2978 // The default browser app's package name is stored in a string resource, 2979 // with a product-specific overlay used for vendor customization. 2980 String browserPkg = mContext.getResources().getString( 2981 com.android.internal.R.string.default_browser); 2982 if (!TextUtils.isEmpty(browserPkg)) { 2983 // non-empty string => required to be a known package 2984 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2985 if (ps == null) { 2986 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2987 browserPkg = null; 2988 } else { 2989 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2990 } 2991 } 2992 2993 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2994 // default. If there's more than one, just leave everything alone. 2995 if (browserPkg == null) { 2996 calculateDefaultBrowserLPw(userId); 2997 } 2998 } 2999 3000 private void calculateDefaultBrowserLPw(int userId) { 3001 List<String> allBrowsers = resolveAllBrowserApps(userId); 3002 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3003 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3004 } 3005 3006 private List<String> resolveAllBrowserApps(int userId) { 3007 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3008 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3009 PackageManager.MATCH_ALL, userId); 3010 3011 final int count = list.size(); 3012 List<String> result = new ArrayList<String>(count); 3013 for (int i=0; i<count; i++) { 3014 ResolveInfo info = list.get(i); 3015 if (info.activityInfo == null 3016 || !info.handleAllWebDataURI 3017 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3018 || result.contains(info.activityInfo.packageName)) { 3019 continue; 3020 } 3021 result.add(info.activityInfo.packageName); 3022 } 3023 3024 return result; 3025 } 3026 3027 private boolean packageIsBrowser(String packageName, int userId) { 3028 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3029 PackageManager.MATCH_ALL, userId); 3030 final int N = list.size(); 3031 for (int i = 0; i < N; i++) { 3032 ResolveInfo info = list.get(i); 3033 if (packageName.equals(info.activityInfo.packageName)) { 3034 return true; 3035 } 3036 } 3037 return false; 3038 } 3039 3040 private void checkDefaultBrowser() { 3041 final int myUserId = UserHandle.myUserId(); 3042 final String packageName = getDefaultBrowserPackageName(myUserId); 3043 if (packageName != null) { 3044 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3045 if (info == null) { 3046 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3047 synchronized (mPackages) { 3048 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3049 } 3050 } 3051 } 3052 } 3053 3054 @Override 3055 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3056 throws RemoteException { 3057 try { 3058 return super.onTransact(code, data, reply, flags); 3059 } catch (RuntimeException e) { 3060 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3061 Slog.wtf(TAG, "Package Manager Crash", e); 3062 } 3063 throw e; 3064 } 3065 } 3066 3067 static int[] appendInts(int[] cur, int[] add) { 3068 if (add == null) return cur; 3069 if (cur == null) return add; 3070 final int N = add.length; 3071 for (int i=0; i<N; i++) { 3072 cur = appendInt(cur, add[i]); 3073 } 3074 return cur; 3075 } 3076 3077 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3078 if (!sUserManager.exists(userId)) return null; 3079 if (ps == null) { 3080 return null; 3081 } 3082 final PackageParser.Package p = ps.pkg; 3083 if (p == null) { 3084 return null; 3085 } 3086 3087 final PermissionsState permissionsState = ps.getPermissionsState(); 3088 3089 // Compute GIDs only if requested 3090 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3091 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3092 // Compute granted permissions only if package has requested permissions 3093 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3094 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3095 final PackageUserState state = ps.readUserState(userId); 3096 3097 return PackageParser.generatePackageInfo(p, gids, flags, 3098 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3099 } 3100 3101 @Override 3102 public void checkPackageStartable(String packageName, int userId) { 3103 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3104 3105 synchronized (mPackages) { 3106 final PackageSetting ps = mSettings.mPackages.get(packageName); 3107 if (ps == null) { 3108 throw new SecurityException("Package " + packageName + " was not found!"); 3109 } 3110 3111 if (!ps.getInstalled(userId)) { 3112 throw new SecurityException( 3113 "Package " + packageName + " was not installed for user " + userId + "!"); 3114 } 3115 3116 if (mSafeMode && !ps.isSystem()) { 3117 throw new SecurityException("Package " + packageName + " not a system app!"); 3118 } 3119 3120 if (mFrozenPackages.contains(packageName)) { 3121 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3122 } 3123 3124 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3125 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3126 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3127 } 3128 } 3129 } 3130 3131 @Override 3132 public boolean isPackageAvailable(String packageName, int userId) { 3133 if (!sUserManager.exists(userId)) return false; 3134 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3135 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3136 synchronized (mPackages) { 3137 PackageParser.Package p = mPackages.get(packageName); 3138 if (p != null) { 3139 final PackageSetting ps = (PackageSetting) p.mExtras; 3140 if (ps != null) { 3141 final PackageUserState state = ps.readUserState(userId); 3142 if (state != null) { 3143 return PackageParser.isAvailable(state); 3144 } 3145 } 3146 } 3147 } 3148 return false; 3149 } 3150 3151 @Override 3152 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3153 if (!sUserManager.exists(userId)) return null; 3154 flags = updateFlagsForPackage(flags, userId, packageName); 3155 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3156 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3157 // reader 3158 synchronized (mPackages) { 3159 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3160 PackageParser.Package p = null; 3161 if (matchFactoryOnly) { 3162 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3163 if (ps != null) { 3164 return generatePackageInfo(ps, flags, userId); 3165 } 3166 } 3167 if (p == null) { 3168 p = mPackages.get(packageName); 3169 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3170 return null; 3171 } 3172 } 3173 if (DEBUG_PACKAGE_INFO) 3174 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3175 if (p != null) { 3176 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3177 } 3178 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3179 final PackageSetting ps = mSettings.mPackages.get(packageName); 3180 return generatePackageInfo(ps, flags, userId); 3181 } 3182 } 3183 return null; 3184 } 3185 3186 @Override 3187 public String[] currentToCanonicalPackageNames(String[] names) { 3188 String[] out = new String[names.length]; 3189 // reader 3190 synchronized (mPackages) { 3191 for (int i=names.length-1; i>=0; i--) { 3192 PackageSetting ps = mSettings.mPackages.get(names[i]); 3193 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3194 } 3195 } 3196 return out; 3197 } 3198 3199 @Override 3200 public String[] canonicalToCurrentPackageNames(String[] names) { 3201 String[] out = new String[names.length]; 3202 // reader 3203 synchronized (mPackages) { 3204 for (int i=names.length-1; i>=0; i--) { 3205 String cur = mSettings.getRenamedPackageLPr(names[i]); 3206 out[i] = cur != null ? cur : names[i]; 3207 } 3208 } 3209 return out; 3210 } 3211 3212 @Override 3213 public int getPackageUid(String packageName, int flags, int userId) { 3214 if (!sUserManager.exists(userId)) return -1; 3215 flags = updateFlagsForPackage(flags, userId, packageName); 3216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3217 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3218 3219 // reader 3220 synchronized (mPackages) { 3221 final PackageParser.Package p = mPackages.get(packageName); 3222 if (p != null && p.isMatch(flags)) { 3223 return UserHandle.getUid(userId, p.applicationInfo.uid); 3224 } 3225 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3226 final PackageSetting ps = mSettings.mPackages.get(packageName); 3227 if (ps != null && ps.isMatch(flags)) { 3228 return UserHandle.getUid(userId, ps.appId); 3229 } 3230 } 3231 } 3232 3233 return -1; 3234 } 3235 3236 @Override 3237 public int[] getPackageGids(String packageName, int flags, int userId) { 3238 if (!sUserManager.exists(userId)) return null; 3239 flags = updateFlagsForPackage(flags, userId, packageName); 3240 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3241 false /* requireFullPermission */, false /* checkShell */, 3242 "getPackageGids"); 3243 3244 // reader 3245 synchronized (mPackages) { 3246 final PackageParser.Package p = mPackages.get(packageName); 3247 if (p != null && p.isMatch(flags)) { 3248 PackageSetting ps = (PackageSetting) p.mExtras; 3249 return ps.getPermissionsState().computeGids(userId); 3250 } 3251 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3252 final PackageSetting ps = mSettings.mPackages.get(packageName); 3253 if (ps != null && ps.isMatch(flags)) { 3254 return ps.getPermissionsState().computeGids(userId); 3255 } 3256 } 3257 } 3258 3259 return null; 3260 } 3261 3262 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3263 if (bp.perm != null) { 3264 return PackageParser.generatePermissionInfo(bp.perm, flags); 3265 } 3266 PermissionInfo pi = new PermissionInfo(); 3267 pi.name = bp.name; 3268 pi.packageName = bp.sourcePackage; 3269 pi.nonLocalizedLabel = bp.name; 3270 pi.protectionLevel = bp.protectionLevel; 3271 return pi; 3272 } 3273 3274 @Override 3275 public PermissionInfo getPermissionInfo(String name, int flags) { 3276 // reader 3277 synchronized (mPackages) { 3278 final BasePermission p = mSettings.mPermissions.get(name); 3279 if (p != null) { 3280 return generatePermissionInfo(p, flags); 3281 } 3282 return null; 3283 } 3284 } 3285 3286 @Override 3287 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3288 int flags) { 3289 // reader 3290 synchronized (mPackages) { 3291 if (group != null && !mPermissionGroups.containsKey(group)) { 3292 // This is thrown as NameNotFoundException 3293 return null; 3294 } 3295 3296 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3297 for (BasePermission p : mSettings.mPermissions.values()) { 3298 if (group == null) { 3299 if (p.perm == null || p.perm.info.group == null) { 3300 out.add(generatePermissionInfo(p, flags)); 3301 } 3302 } else { 3303 if (p.perm != null && group.equals(p.perm.info.group)) { 3304 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3305 } 3306 } 3307 } 3308 return new ParceledListSlice<>(out); 3309 } 3310 } 3311 3312 @Override 3313 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3314 // reader 3315 synchronized (mPackages) { 3316 return PackageParser.generatePermissionGroupInfo( 3317 mPermissionGroups.get(name), flags); 3318 } 3319 } 3320 3321 @Override 3322 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3323 // reader 3324 synchronized (mPackages) { 3325 final int N = mPermissionGroups.size(); 3326 ArrayList<PermissionGroupInfo> out 3327 = new ArrayList<PermissionGroupInfo>(N); 3328 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3329 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3330 } 3331 return new ParceledListSlice<>(out); 3332 } 3333 } 3334 3335 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3336 int userId) { 3337 if (!sUserManager.exists(userId)) return null; 3338 PackageSetting ps = mSettings.mPackages.get(packageName); 3339 if (ps != null) { 3340 if (ps.pkg == null) { 3341 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3342 if (pInfo != null) { 3343 return pInfo.applicationInfo; 3344 } 3345 return null; 3346 } 3347 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3348 ps.readUserState(userId), userId); 3349 } 3350 return null; 3351 } 3352 3353 @Override 3354 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3355 if (!sUserManager.exists(userId)) return null; 3356 flags = updateFlagsForApplication(flags, userId, packageName); 3357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3358 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3359 // writer 3360 synchronized (mPackages) { 3361 PackageParser.Package p = mPackages.get(packageName); 3362 if (DEBUG_PACKAGE_INFO) Log.v( 3363 TAG, "getApplicationInfo " + packageName 3364 + ": " + p); 3365 if (p != null) { 3366 PackageSetting ps = mSettings.mPackages.get(packageName); 3367 if (ps == null) return null; 3368 // Note: isEnabledLP() does not apply here - always return info 3369 return PackageParser.generateApplicationInfo( 3370 p, flags, ps.readUserState(userId), userId); 3371 } 3372 if ("android".equals(packageName)||"system".equals(packageName)) { 3373 return mAndroidApplication; 3374 } 3375 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3376 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3377 } 3378 } 3379 return null; 3380 } 3381 3382 @Override 3383 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3384 final IPackageDataObserver observer) { 3385 mContext.enforceCallingOrSelfPermission( 3386 android.Manifest.permission.CLEAR_APP_CACHE, null); 3387 // Queue up an async operation since clearing cache may take a little while. 3388 mHandler.post(new Runnable() { 3389 public void run() { 3390 mHandler.removeCallbacks(this); 3391 boolean success = true; 3392 synchronized (mInstallLock) { 3393 try { 3394 mInstaller.freeCache(volumeUuid, freeStorageSize); 3395 } catch (InstallerException e) { 3396 Slog.w(TAG, "Couldn't clear application caches: " + e); 3397 success = false; 3398 } 3399 } 3400 if (observer != null) { 3401 try { 3402 observer.onRemoveCompleted(null, success); 3403 } catch (RemoteException e) { 3404 Slog.w(TAG, "RemoveException when invoking call back"); 3405 } 3406 } 3407 } 3408 }); 3409 } 3410 3411 @Override 3412 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3413 final IntentSender pi) { 3414 mContext.enforceCallingOrSelfPermission( 3415 android.Manifest.permission.CLEAR_APP_CACHE, null); 3416 // Queue up an async operation since clearing cache may take a little while. 3417 mHandler.post(new Runnable() { 3418 public void run() { 3419 mHandler.removeCallbacks(this); 3420 boolean success = true; 3421 synchronized (mInstallLock) { 3422 try { 3423 mInstaller.freeCache(volumeUuid, freeStorageSize); 3424 } catch (InstallerException e) { 3425 Slog.w(TAG, "Couldn't clear application caches: " + e); 3426 success = false; 3427 } 3428 } 3429 if(pi != null) { 3430 try { 3431 // Callback via pending intent 3432 int code = success ? 1 : 0; 3433 pi.sendIntent(null, code, null, 3434 null, null); 3435 } catch (SendIntentException e1) { 3436 Slog.i(TAG, "Failed to send pending intent"); 3437 } 3438 } 3439 } 3440 }); 3441 } 3442 3443 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3444 synchronized (mInstallLock) { 3445 try { 3446 mInstaller.freeCache(volumeUuid, freeStorageSize); 3447 } catch (InstallerException e) { 3448 throw new IOException("Failed to free enough space", e); 3449 } 3450 } 3451 } 3452 3453 /** 3454 * Update given flags based on encryption status of current user. 3455 */ 3456 private int updateFlags(int flags, int userId) { 3457 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3458 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3459 // Caller expressed an explicit opinion about what encryption 3460 // aware/unaware components they want to see, so fall through and 3461 // give them what they want 3462 } else { 3463 // Caller expressed no opinion, so match based on user state 3464 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3465 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3466 } else { 3467 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3468 } 3469 } 3470 return flags; 3471 } 3472 3473 private UserManagerInternal getUserManagerInternal() { 3474 if (mUserManagerInternal == null) { 3475 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3476 } 3477 return mUserManagerInternal; 3478 } 3479 3480 /** 3481 * Update given flags when being used to request {@link PackageInfo}. 3482 */ 3483 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3484 boolean triaged = true; 3485 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3486 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3487 // Caller is asking for component details, so they'd better be 3488 // asking for specific encryption matching behavior, or be triaged 3489 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3490 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3491 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3492 triaged = false; 3493 } 3494 } 3495 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3496 | PackageManager.MATCH_SYSTEM_ONLY 3497 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3498 triaged = false; 3499 } 3500 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3501 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3502 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3503 } 3504 return updateFlags(flags, userId); 3505 } 3506 3507 /** 3508 * Update given flags when being used to request {@link ApplicationInfo}. 3509 */ 3510 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3511 return updateFlagsForPackage(flags, userId, cookie); 3512 } 3513 3514 /** 3515 * Update given flags when being used to request {@link ComponentInfo}. 3516 */ 3517 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3518 if (cookie instanceof Intent) { 3519 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3520 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3521 } 3522 } 3523 3524 boolean triaged = true; 3525 // Caller is asking for component details, so they'd better be 3526 // asking for specific encryption matching behavior, or be triaged 3527 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3528 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3529 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3530 triaged = false; 3531 } 3532 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3533 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3534 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3535 } 3536 3537 return updateFlags(flags, userId); 3538 } 3539 3540 /** 3541 * Update given flags when being used to request {@link ResolveInfo}. 3542 */ 3543 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3544 // Safe mode means we shouldn't match any third-party components 3545 if (mSafeMode) { 3546 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3547 } 3548 3549 return updateFlagsForComponent(flags, userId, cookie); 3550 } 3551 3552 @Override 3553 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3554 if (!sUserManager.exists(userId)) return null; 3555 flags = updateFlagsForComponent(flags, userId, component); 3556 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3557 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3558 synchronized (mPackages) { 3559 PackageParser.Activity a = mActivities.mActivities.get(component); 3560 3561 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3562 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3563 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3564 if (ps == null) return null; 3565 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3566 userId); 3567 } 3568 if (mResolveComponentName.equals(component)) { 3569 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3570 new PackageUserState(), userId); 3571 } 3572 } 3573 return null; 3574 } 3575 3576 @Override 3577 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3578 String resolvedType) { 3579 synchronized (mPackages) { 3580 if (component.equals(mResolveComponentName)) { 3581 // The resolver supports EVERYTHING! 3582 return true; 3583 } 3584 PackageParser.Activity a = mActivities.mActivities.get(component); 3585 if (a == null) { 3586 return false; 3587 } 3588 for (int i=0; i<a.intents.size(); i++) { 3589 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3590 intent.getData(), intent.getCategories(), TAG) >= 0) { 3591 return true; 3592 } 3593 } 3594 return false; 3595 } 3596 } 3597 3598 @Override 3599 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3600 if (!sUserManager.exists(userId)) return null; 3601 flags = updateFlagsForComponent(flags, userId, component); 3602 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3603 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3604 synchronized (mPackages) { 3605 PackageParser.Activity a = mReceivers.mActivities.get(component); 3606 if (DEBUG_PACKAGE_INFO) Log.v( 3607 TAG, "getReceiverInfo " + component + ": " + a); 3608 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3609 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3610 if (ps == null) return null; 3611 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3612 userId); 3613 } 3614 } 3615 return null; 3616 } 3617 3618 @Override 3619 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3620 if (!sUserManager.exists(userId)) return null; 3621 flags = updateFlagsForComponent(flags, userId, component); 3622 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3623 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3624 synchronized (mPackages) { 3625 PackageParser.Service s = mServices.mServices.get(component); 3626 if (DEBUG_PACKAGE_INFO) Log.v( 3627 TAG, "getServiceInfo " + component + ": " + s); 3628 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3629 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3630 if (ps == null) return null; 3631 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3632 userId); 3633 } 3634 } 3635 return null; 3636 } 3637 3638 @Override 3639 public ProviderInfo getProviderInfo(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 provider info"); 3644 synchronized (mPackages) { 3645 PackageParser.Provider p = mProviders.mProviders.get(component); 3646 if (DEBUG_PACKAGE_INFO) Log.v( 3647 TAG, "getProviderInfo " + component + ": " + p); 3648 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3649 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3650 if (ps == null) return null; 3651 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3652 userId); 3653 } 3654 } 3655 return null; 3656 } 3657 3658 @Override 3659 public String[] getSystemSharedLibraryNames() { 3660 Set<String> libSet; 3661 synchronized (mPackages) { 3662 libSet = mSharedLibraries.keySet(); 3663 int size = libSet.size(); 3664 if (size > 0) { 3665 String[] libs = new String[size]; 3666 libSet.toArray(libs); 3667 return libs; 3668 } 3669 } 3670 return null; 3671 } 3672 3673 @Override 3674 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3675 synchronized (mPackages) { 3676 return mServicesSystemSharedLibraryPackageName; 3677 } 3678 } 3679 3680 @Override 3681 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3682 synchronized (mPackages) { 3683 return mSharedSystemSharedLibraryPackageName; 3684 } 3685 } 3686 3687 @Override 3688 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3689 synchronized (mPackages) { 3690 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3691 3692 final FeatureInfo fi = new FeatureInfo(); 3693 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3694 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3695 res.add(fi); 3696 3697 return new ParceledListSlice<>(res); 3698 } 3699 } 3700 3701 @Override 3702 public boolean hasSystemFeature(String name, int version) { 3703 synchronized (mPackages) { 3704 final FeatureInfo feat = mAvailableFeatures.get(name); 3705 if (feat == null) { 3706 return false; 3707 } else { 3708 return feat.version >= version; 3709 } 3710 } 3711 } 3712 3713 @Override 3714 public int checkPermission(String permName, String pkgName, int userId) { 3715 if (!sUserManager.exists(userId)) { 3716 return PackageManager.PERMISSION_DENIED; 3717 } 3718 3719 synchronized (mPackages) { 3720 final PackageParser.Package p = mPackages.get(pkgName); 3721 if (p != null && p.mExtras != null) { 3722 final PackageSetting ps = (PackageSetting) p.mExtras; 3723 final PermissionsState permissionsState = ps.getPermissionsState(); 3724 if (permissionsState.hasPermission(permName, userId)) { 3725 return PackageManager.PERMISSION_GRANTED; 3726 } 3727 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3728 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3729 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3730 return PackageManager.PERMISSION_GRANTED; 3731 } 3732 } 3733 } 3734 3735 return PackageManager.PERMISSION_DENIED; 3736 } 3737 3738 @Override 3739 public int checkUidPermission(String permName, int uid) { 3740 final int userId = UserHandle.getUserId(uid); 3741 3742 if (!sUserManager.exists(userId)) { 3743 return PackageManager.PERMISSION_DENIED; 3744 } 3745 3746 synchronized (mPackages) { 3747 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3748 if (obj != null) { 3749 final SettingBase ps = (SettingBase) obj; 3750 final PermissionsState permissionsState = ps.getPermissionsState(); 3751 if (permissionsState.hasPermission(permName, userId)) { 3752 return PackageManager.PERMISSION_GRANTED; 3753 } 3754 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3755 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3756 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3757 return PackageManager.PERMISSION_GRANTED; 3758 } 3759 } else { 3760 ArraySet<String> perms = mSystemPermissions.get(uid); 3761 if (perms != null) { 3762 if (perms.contains(permName)) { 3763 return PackageManager.PERMISSION_GRANTED; 3764 } 3765 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3766 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3767 return PackageManager.PERMISSION_GRANTED; 3768 } 3769 } 3770 } 3771 } 3772 3773 return PackageManager.PERMISSION_DENIED; 3774 } 3775 3776 @Override 3777 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3778 if (UserHandle.getCallingUserId() != userId) { 3779 mContext.enforceCallingPermission( 3780 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3781 "isPermissionRevokedByPolicy for user " + userId); 3782 } 3783 3784 if (checkPermission(permission, packageName, userId) 3785 == PackageManager.PERMISSION_GRANTED) { 3786 return false; 3787 } 3788 3789 final long identity = Binder.clearCallingIdentity(); 3790 try { 3791 final int flags = getPermissionFlags(permission, packageName, userId); 3792 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3793 } finally { 3794 Binder.restoreCallingIdentity(identity); 3795 } 3796 } 3797 3798 @Override 3799 public String getPermissionControllerPackageName() { 3800 synchronized (mPackages) { 3801 return mRequiredInstallerPackage; 3802 } 3803 } 3804 3805 /** 3806 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3807 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3808 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3809 * @param message the message to log on security exception 3810 */ 3811 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3812 boolean checkShell, String message) { 3813 if (userId < 0) { 3814 throw new IllegalArgumentException("Invalid userId " + userId); 3815 } 3816 if (checkShell) { 3817 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3818 } 3819 if (userId == UserHandle.getUserId(callingUid)) return; 3820 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3821 if (requireFullPermission) { 3822 mContext.enforceCallingOrSelfPermission( 3823 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3824 } else { 3825 try { 3826 mContext.enforceCallingOrSelfPermission( 3827 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3828 } catch (SecurityException se) { 3829 mContext.enforceCallingOrSelfPermission( 3830 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3831 } 3832 } 3833 } 3834 } 3835 3836 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3837 if (callingUid == Process.SHELL_UID) { 3838 if (userHandle >= 0 3839 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3840 throw new SecurityException("Shell does not have permission to access user " 3841 + userHandle); 3842 } else if (userHandle < 0) { 3843 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3844 + Debug.getCallers(3)); 3845 } 3846 } 3847 } 3848 3849 private BasePermission findPermissionTreeLP(String permName) { 3850 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3851 if (permName.startsWith(bp.name) && 3852 permName.length() > bp.name.length() && 3853 permName.charAt(bp.name.length()) == '.') { 3854 return bp; 3855 } 3856 } 3857 return null; 3858 } 3859 3860 private BasePermission checkPermissionTreeLP(String permName) { 3861 if (permName != null) { 3862 BasePermission bp = findPermissionTreeLP(permName); 3863 if (bp != null) { 3864 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3865 return bp; 3866 } 3867 throw new SecurityException("Calling uid " 3868 + Binder.getCallingUid() 3869 + " is not allowed to add to permission tree " 3870 + bp.name + " owned by uid " + bp.uid); 3871 } 3872 } 3873 throw new SecurityException("No permission tree found for " + permName); 3874 } 3875 3876 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3877 if (s1 == null) { 3878 return s2 == null; 3879 } 3880 if (s2 == null) { 3881 return false; 3882 } 3883 if (s1.getClass() != s2.getClass()) { 3884 return false; 3885 } 3886 return s1.equals(s2); 3887 } 3888 3889 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3890 if (pi1.icon != pi2.icon) return false; 3891 if (pi1.logo != pi2.logo) return false; 3892 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3893 if (!compareStrings(pi1.name, pi2.name)) return false; 3894 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3895 // We'll take care of setting this one. 3896 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3897 // These are not currently stored in settings. 3898 //if (!compareStrings(pi1.group, pi2.group)) return false; 3899 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3900 //if (pi1.labelRes != pi2.labelRes) return false; 3901 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3902 return true; 3903 } 3904 3905 int permissionInfoFootprint(PermissionInfo info) { 3906 int size = info.name.length(); 3907 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3908 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3909 return size; 3910 } 3911 3912 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3913 int size = 0; 3914 for (BasePermission perm : mSettings.mPermissions.values()) { 3915 if (perm.uid == tree.uid) { 3916 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3917 } 3918 } 3919 return size; 3920 } 3921 3922 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3923 // We calculate the max size of permissions defined by this uid and throw 3924 // if that plus the size of 'info' would exceed our stated maximum. 3925 if (tree.uid != Process.SYSTEM_UID) { 3926 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3927 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3928 throw new SecurityException("Permission tree size cap exceeded"); 3929 } 3930 } 3931 } 3932 3933 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3934 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3935 throw new SecurityException("Label must be specified in permission"); 3936 } 3937 BasePermission tree = checkPermissionTreeLP(info.name); 3938 BasePermission bp = mSettings.mPermissions.get(info.name); 3939 boolean added = bp == null; 3940 boolean changed = true; 3941 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3942 if (added) { 3943 enforcePermissionCapLocked(info, tree); 3944 bp = new BasePermission(info.name, tree.sourcePackage, 3945 BasePermission.TYPE_DYNAMIC); 3946 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3947 throw new SecurityException( 3948 "Not allowed to modify non-dynamic permission " 3949 + info.name); 3950 } else { 3951 if (bp.protectionLevel == fixedLevel 3952 && bp.perm.owner.equals(tree.perm.owner) 3953 && bp.uid == tree.uid 3954 && comparePermissionInfos(bp.perm.info, info)) { 3955 changed = false; 3956 } 3957 } 3958 bp.protectionLevel = fixedLevel; 3959 info = new PermissionInfo(info); 3960 info.protectionLevel = fixedLevel; 3961 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3962 bp.perm.info.packageName = tree.perm.info.packageName; 3963 bp.uid = tree.uid; 3964 if (added) { 3965 mSettings.mPermissions.put(info.name, bp); 3966 } 3967 if (changed) { 3968 if (!async) { 3969 mSettings.writeLPr(); 3970 } else { 3971 scheduleWriteSettingsLocked(); 3972 } 3973 } 3974 return added; 3975 } 3976 3977 @Override 3978 public boolean addPermission(PermissionInfo info) { 3979 synchronized (mPackages) { 3980 return addPermissionLocked(info, false); 3981 } 3982 } 3983 3984 @Override 3985 public boolean addPermissionAsync(PermissionInfo info) { 3986 synchronized (mPackages) { 3987 return addPermissionLocked(info, true); 3988 } 3989 } 3990 3991 @Override 3992 public void removePermission(String name) { 3993 synchronized (mPackages) { 3994 checkPermissionTreeLP(name); 3995 BasePermission bp = mSettings.mPermissions.get(name); 3996 if (bp != null) { 3997 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3998 throw new SecurityException( 3999 "Not allowed to modify non-dynamic permission " 4000 + name); 4001 } 4002 mSettings.mPermissions.remove(name); 4003 mSettings.writeLPr(); 4004 } 4005 } 4006 } 4007 4008 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4009 BasePermission bp) { 4010 int index = pkg.requestedPermissions.indexOf(bp.name); 4011 if (index == -1) { 4012 throw new SecurityException("Package " + pkg.packageName 4013 + " has not requested permission " + bp.name); 4014 } 4015 if (!bp.isRuntime() && !bp.isDevelopment()) { 4016 throw new SecurityException("Permission " + bp.name 4017 + " is not a changeable permission type"); 4018 } 4019 } 4020 4021 @Override 4022 public void grantRuntimePermission(String packageName, String name, final int userId) { 4023 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4024 } 4025 4026 private void grantRuntimePermission(String packageName, String name, final int userId, 4027 boolean overridePolicy) { 4028 if (!sUserManager.exists(userId)) { 4029 Log.e(TAG, "No such user:" + userId); 4030 return; 4031 } 4032 4033 mContext.enforceCallingOrSelfPermission( 4034 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4035 "grantRuntimePermission"); 4036 4037 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4038 true /* requireFullPermission */, true /* checkShell */, 4039 "grantRuntimePermission"); 4040 4041 final int uid; 4042 final SettingBase sb; 4043 4044 synchronized (mPackages) { 4045 final PackageParser.Package pkg = mPackages.get(packageName); 4046 if (pkg == null) { 4047 throw new IllegalArgumentException("Unknown package: " + packageName); 4048 } 4049 4050 final BasePermission bp = mSettings.mPermissions.get(name); 4051 if (bp == null) { 4052 throw new IllegalArgumentException("Unknown permission: " + name); 4053 } 4054 4055 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4056 4057 // If a permission review is required for legacy apps we represent 4058 // their permissions as always granted runtime ones since we need 4059 // to keep the review required permission flag per user while an 4060 // install permission's state is shared across all users. 4061 if (mPermissionReviewRequired 4062 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4063 && bp.isRuntime()) { 4064 return; 4065 } 4066 4067 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4068 sb = (SettingBase) pkg.mExtras; 4069 if (sb == null) { 4070 throw new IllegalArgumentException("Unknown package: " + packageName); 4071 } 4072 4073 final PermissionsState permissionsState = sb.getPermissionsState(); 4074 4075 final int flags = permissionsState.getPermissionFlags(name, userId); 4076 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4077 throw new SecurityException("Cannot grant system fixed permission " 4078 + name + " for package " + packageName); 4079 } 4080 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4081 throw new SecurityException("Cannot grant policy fixed permission " 4082 + name + " for package " + packageName); 4083 } 4084 4085 if (bp.isDevelopment()) { 4086 // Development permissions must be handled specially, since they are not 4087 // normal runtime permissions. For now they apply to all users. 4088 if (permissionsState.grantInstallPermission(bp) != 4089 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4090 scheduleWriteSettingsLocked(); 4091 } 4092 return; 4093 } 4094 4095 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4096 throw new SecurityException("Cannot grant non-ephemeral permission" 4097 + name + " for package " + packageName); 4098 } 4099 4100 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4101 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4102 return; 4103 } 4104 4105 final int result = permissionsState.grantRuntimePermission(bp, userId); 4106 switch (result) { 4107 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4108 return; 4109 } 4110 4111 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4112 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4113 mHandler.post(new Runnable() { 4114 @Override 4115 public void run() { 4116 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4117 } 4118 }); 4119 } 4120 break; 4121 } 4122 4123 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4124 4125 // Not critical if that is lost - app has to request again. 4126 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4127 } 4128 4129 // Only need to do this if user is initialized. Otherwise it's a new user 4130 // and there are no processes running as the user yet and there's no need 4131 // to make an expensive call to remount processes for the changed permissions. 4132 if (READ_EXTERNAL_STORAGE.equals(name) 4133 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4134 final long token = Binder.clearCallingIdentity(); 4135 try { 4136 if (sUserManager.isInitialized(userId)) { 4137 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4138 StorageManagerInternal.class); 4139 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4140 } 4141 } finally { 4142 Binder.restoreCallingIdentity(token); 4143 } 4144 } 4145 } 4146 4147 @Override 4148 public void revokeRuntimePermission(String packageName, String name, int userId) { 4149 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4150 } 4151 4152 private void revokeRuntimePermission(String packageName, String name, int userId, 4153 boolean overridePolicy) { 4154 if (!sUserManager.exists(userId)) { 4155 Log.e(TAG, "No such user:" + userId); 4156 return; 4157 } 4158 4159 mContext.enforceCallingOrSelfPermission( 4160 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4161 "revokeRuntimePermission"); 4162 4163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4164 true /* requireFullPermission */, true /* checkShell */, 4165 "revokeRuntimePermission"); 4166 4167 final int appId; 4168 4169 synchronized (mPackages) { 4170 final PackageParser.Package pkg = mPackages.get(packageName); 4171 if (pkg == null) { 4172 throw new IllegalArgumentException("Unknown package: " + packageName); 4173 } 4174 4175 final BasePermission bp = mSettings.mPermissions.get(name); 4176 if (bp == null) { 4177 throw new IllegalArgumentException("Unknown permission: " + name); 4178 } 4179 4180 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4181 4182 // If a permission review is required for legacy apps we represent 4183 // their permissions as always granted runtime ones since we need 4184 // to keep the review required permission flag per user while an 4185 // install permission's state is shared across all users. 4186 if (mPermissionReviewRequired 4187 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4188 && bp.isRuntime()) { 4189 return; 4190 } 4191 4192 SettingBase sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 final int flags = permissionsState.getPermissionFlags(name, userId); 4200 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4201 throw new SecurityException("Cannot revoke system fixed permission " 4202 + name + " for package " + packageName); 4203 } 4204 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4205 throw new SecurityException("Cannot revoke policy fixed permission " 4206 + name + " for package " + packageName); 4207 } 4208 4209 if (bp.isDevelopment()) { 4210 // Development permissions must be handled specially, since they are not 4211 // normal runtime permissions. For now they apply to all users. 4212 if (permissionsState.revokeInstallPermission(bp) != 4213 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4214 scheduleWriteSettingsLocked(); 4215 } 4216 return; 4217 } 4218 4219 if (permissionsState.revokeRuntimePermission(bp, userId) == 4220 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4221 return; 4222 } 4223 4224 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4225 4226 // Critical, after this call app should never have the permission. 4227 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4228 4229 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4230 } 4231 4232 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4233 } 4234 4235 @Override 4236 public void resetRuntimePermissions() { 4237 mContext.enforceCallingOrSelfPermission( 4238 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4239 "revokeRuntimePermission"); 4240 4241 int callingUid = Binder.getCallingUid(); 4242 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4243 mContext.enforceCallingOrSelfPermission( 4244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4245 "resetRuntimePermissions"); 4246 } 4247 4248 synchronized (mPackages) { 4249 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4250 for (int userId : UserManagerService.getInstance().getUserIds()) { 4251 final int packageCount = mPackages.size(); 4252 for (int i = 0; i < packageCount; i++) { 4253 PackageParser.Package pkg = mPackages.valueAt(i); 4254 if (!(pkg.mExtras instanceof PackageSetting)) { 4255 continue; 4256 } 4257 PackageSetting ps = (PackageSetting) pkg.mExtras; 4258 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4259 } 4260 } 4261 } 4262 } 4263 4264 @Override 4265 public int getPermissionFlags(String name, String packageName, int userId) { 4266 if (!sUserManager.exists(userId)) { 4267 return 0; 4268 } 4269 4270 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4271 4272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4273 true /* requireFullPermission */, false /* checkShell */, 4274 "getPermissionFlags"); 4275 4276 synchronized (mPackages) { 4277 final PackageParser.Package pkg = mPackages.get(packageName); 4278 if (pkg == null) { 4279 return 0; 4280 } 4281 4282 final BasePermission bp = mSettings.mPermissions.get(name); 4283 if (bp == null) { 4284 return 0; 4285 } 4286 4287 SettingBase sb = (SettingBase) pkg.mExtras; 4288 if (sb == null) { 4289 return 0; 4290 } 4291 4292 PermissionsState permissionsState = sb.getPermissionsState(); 4293 return permissionsState.getPermissionFlags(name, userId); 4294 } 4295 } 4296 4297 @Override 4298 public void updatePermissionFlags(String name, String packageName, int flagMask, 4299 int flagValues, int userId) { 4300 if (!sUserManager.exists(userId)) { 4301 return; 4302 } 4303 4304 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4305 4306 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4307 true /* requireFullPermission */, true /* checkShell */, 4308 "updatePermissionFlags"); 4309 4310 // Only the system can change these flags and nothing else. 4311 if (getCallingUid() != Process.SYSTEM_UID) { 4312 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4313 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4314 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4315 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4316 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4317 } 4318 4319 synchronized (mPackages) { 4320 final PackageParser.Package pkg = mPackages.get(packageName); 4321 if (pkg == null) { 4322 throw new IllegalArgumentException("Unknown package: " + packageName); 4323 } 4324 4325 final BasePermission bp = mSettings.mPermissions.get(name); 4326 if (bp == null) { 4327 throw new IllegalArgumentException("Unknown permission: " + name); 4328 } 4329 4330 SettingBase sb = (SettingBase) pkg.mExtras; 4331 if (sb == null) { 4332 throw new IllegalArgumentException("Unknown package: " + packageName); 4333 } 4334 4335 PermissionsState permissionsState = sb.getPermissionsState(); 4336 4337 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4338 4339 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4340 // Install and runtime permissions are stored in different places, 4341 // so figure out what permission changed and persist the change. 4342 if (permissionsState.getInstallPermissionState(name) != null) { 4343 scheduleWriteSettingsLocked(); 4344 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4345 || hadState) { 4346 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4347 } 4348 } 4349 } 4350 } 4351 4352 /** 4353 * Update the permission flags for all packages and runtime permissions of a user in order 4354 * to allow device or profile owner to remove POLICY_FIXED. 4355 */ 4356 @Override 4357 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4358 if (!sUserManager.exists(userId)) { 4359 return; 4360 } 4361 4362 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4363 4364 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4365 true /* requireFullPermission */, true /* checkShell */, 4366 "updatePermissionFlagsForAllApps"); 4367 4368 // Only the system can change system fixed flags. 4369 if (getCallingUid() != Process.SYSTEM_UID) { 4370 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4371 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4372 } 4373 4374 synchronized (mPackages) { 4375 boolean changed = false; 4376 final int packageCount = mPackages.size(); 4377 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4378 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4379 SettingBase sb = (SettingBase) pkg.mExtras; 4380 if (sb == null) { 4381 continue; 4382 } 4383 PermissionsState permissionsState = sb.getPermissionsState(); 4384 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4385 userId, flagMask, flagValues); 4386 } 4387 if (changed) { 4388 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4389 } 4390 } 4391 } 4392 4393 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4394 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4395 != PackageManager.PERMISSION_GRANTED 4396 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4397 != PackageManager.PERMISSION_GRANTED) { 4398 throw new SecurityException(message + " requires " 4399 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4400 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4401 } 4402 } 4403 4404 @Override 4405 public boolean shouldShowRequestPermissionRationale(String permissionName, 4406 String packageName, int userId) { 4407 if (UserHandle.getCallingUserId() != userId) { 4408 mContext.enforceCallingPermission( 4409 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4410 "canShowRequestPermissionRationale for user " + userId); 4411 } 4412 4413 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4414 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4415 return false; 4416 } 4417 4418 if (checkPermission(permissionName, packageName, userId) 4419 == PackageManager.PERMISSION_GRANTED) { 4420 return false; 4421 } 4422 4423 final int flags; 4424 4425 final long identity = Binder.clearCallingIdentity(); 4426 try { 4427 flags = getPermissionFlags(permissionName, 4428 packageName, userId); 4429 } finally { 4430 Binder.restoreCallingIdentity(identity); 4431 } 4432 4433 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4434 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4435 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4436 4437 if ((flags & fixedFlags) != 0) { 4438 return false; 4439 } 4440 4441 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4442 } 4443 4444 @Override 4445 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4446 mContext.enforceCallingOrSelfPermission( 4447 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4448 "addOnPermissionsChangeListener"); 4449 4450 synchronized (mPackages) { 4451 mOnPermissionChangeListeners.addListenerLocked(listener); 4452 } 4453 } 4454 4455 @Override 4456 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4457 synchronized (mPackages) { 4458 mOnPermissionChangeListeners.removeListenerLocked(listener); 4459 } 4460 } 4461 4462 @Override 4463 public boolean isProtectedBroadcast(String actionName) { 4464 synchronized (mPackages) { 4465 if (mProtectedBroadcasts.contains(actionName)) { 4466 return true; 4467 } else if (actionName != null) { 4468 // TODO: remove these terrible hacks 4469 if (actionName.startsWith("android.net.netmon.lingerExpired") 4470 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4471 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4472 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4473 return true; 4474 } 4475 } 4476 } 4477 return false; 4478 } 4479 4480 @Override 4481 public int checkSignatures(String pkg1, String pkg2) { 4482 synchronized (mPackages) { 4483 final PackageParser.Package p1 = mPackages.get(pkg1); 4484 final PackageParser.Package p2 = mPackages.get(pkg2); 4485 if (p1 == null || p1.mExtras == null 4486 || p2 == null || p2.mExtras == null) { 4487 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4488 } 4489 return compareSignatures(p1.mSignatures, p2.mSignatures); 4490 } 4491 } 4492 4493 @Override 4494 public int checkUidSignatures(int uid1, int uid2) { 4495 // Map to base uids. 4496 uid1 = UserHandle.getAppId(uid1); 4497 uid2 = UserHandle.getAppId(uid2); 4498 // reader 4499 synchronized (mPackages) { 4500 Signature[] s1; 4501 Signature[] s2; 4502 Object obj = mSettings.getUserIdLPr(uid1); 4503 if (obj != null) { 4504 if (obj instanceof SharedUserSetting) { 4505 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4506 } else if (obj instanceof PackageSetting) { 4507 s1 = ((PackageSetting)obj).signatures.mSignatures; 4508 } else { 4509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4510 } 4511 } else { 4512 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4513 } 4514 obj = mSettings.getUserIdLPr(uid2); 4515 if (obj != null) { 4516 if (obj instanceof SharedUserSetting) { 4517 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4518 } else if (obj instanceof PackageSetting) { 4519 s2 = ((PackageSetting)obj).signatures.mSignatures; 4520 } else { 4521 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4522 } 4523 } else { 4524 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4525 } 4526 return compareSignatures(s1, s2); 4527 } 4528 } 4529 4530 /** 4531 * This method should typically only be used when granting or revoking 4532 * permissions, since the app may immediately restart after this call. 4533 * <p> 4534 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4535 * guard your work against the app being relaunched. 4536 */ 4537 private void killUid(int appId, int userId, String reason) { 4538 final long identity = Binder.clearCallingIdentity(); 4539 try { 4540 IActivityManager am = ActivityManager.getService(); 4541 if (am != null) { 4542 try { 4543 am.killUid(appId, userId, reason); 4544 } catch (RemoteException e) { 4545 /* ignore - same process */ 4546 } 4547 } 4548 } finally { 4549 Binder.restoreCallingIdentity(identity); 4550 } 4551 } 4552 4553 /** 4554 * Compares two sets of signatures. Returns: 4555 * <br /> 4556 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4557 * <br /> 4558 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4559 * <br /> 4560 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4561 * <br /> 4562 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4563 * <br /> 4564 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4565 */ 4566 static int compareSignatures(Signature[] s1, Signature[] s2) { 4567 if (s1 == null) { 4568 return s2 == null 4569 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4570 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4571 } 4572 4573 if (s2 == null) { 4574 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4575 } 4576 4577 if (s1.length != s2.length) { 4578 return PackageManager.SIGNATURE_NO_MATCH; 4579 } 4580 4581 // Since both signature sets are of size 1, we can compare without HashSets. 4582 if (s1.length == 1) { 4583 return s1[0].equals(s2[0]) ? 4584 PackageManager.SIGNATURE_MATCH : 4585 PackageManager.SIGNATURE_NO_MATCH; 4586 } 4587 4588 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4589 for (Signature sig : s1) { 4590 set1.add(sig); 4591 } 4592 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4593 for (Signature sig : s2) { 4594 set2.add(sig); 4595 } 4596 // Make sure s2 contains all signatures in s1. 4597 if (set1.equals(set2)) { 4598 return PackageManager.SIGNATURE_MATCH; 4599 } 4600 return PackageManager.SIGNATURE_NO_MATCH; 4601 } 4602 4603 /** 4604 * If the database version for this type of package (internal storage or 4605 * external storage) is less than the version where package signatures 4606 * were updated, return true. 4607 */ 4608 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4609 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4610 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4611 } 4612 4613 /** 4614 * Used for backward compatibility to make sure any packages with 4615 * certificate chains get upgraded to the new style. {@code existingSigs} 4616 * will be in the old format (since they were stored on disk from before the 4617 * system upgrade) and {@code scannedSigs} will be in the newer format. 4618 */ 4619 private int compareSignaturesCompat(PackageSignatures existingSigs, 4620 PackageParser.Package scannedPkg) { 4621 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4622 return PackageManager.SIGNATURE_NO_MATCH; 4623 } 4624 4625 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4626 for (Signature sig : existingSigs.mSignatures) { 4627 existingSet.add(sig); 4628 } 4629 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4630 for (Signature sig : scannedPkg.mSignatures) { 4631 try { 4632 Signature[] chainSignatures = sig.getChainSignatures(); 4633 for (Signature chainSig : chainSignatures) { 4634 scannedCompatSet.add(chainSig); 4635 } 4636 } catch (CertificateEncodingException e) { 4637 scannedCompatSet.add(sig); 4638 } 4639 } 4640 /* 4641 * Make sure the expanded scanned set contains all signatures in the 4642 * existing one. 4643 */ 4644 if (scannedCompatSet.equals(existingSet)) { 4645 // Migrate the old signatures to the new scheme. 4646 existingSigs.assignSignatures(scannedPkg.mSignatures); 4647 // The new KeySets will be re-added later in the scanning process. 4648 synchronized (mPackages) { 4649 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4650 } 4651 return PackageManager.SIGNATURE_MATCH; 4652 } 4653 return PackageManager.SIGNATURE_NO_MATCH; 4654 } 4655 4656 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4657 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4658 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4659 } 4660 4661 private int compareSignaturesRecover(PackageSignatures existingSigs, 4662 PackageParser.Package scannedPkg) { 4663 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4664 return PackageManager.SIGNATURE_NO_MATCH; 4665 } 4666 4667 String msg = null; 4668 try { 4669 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4670 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4671 + scannedPkg.packageName); 4672 return PackageManager.SIGNATURE_MATCH; 4673 } 4674 } catch (CertificateException e) { 4675 msg = e.getMessage(); 4676 } 4677 4678 logCriticalInfo(Log.INFO, 4679 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4680 return PackageManager.SIGNATURE_NO_MATCH; 4681 } 4682 4683 @Override 4684 public List<String> getAllPackages() { 4685 synchronized (mPackages) { 4686 return new ArrayList<String>(mPackages.keySet()); 4687 } 4688 } 4689 4690 @Override 4691 public String[] getPackagesForUid(int uid) { 4692 final int userId = UserHandle.getUserId(uid); 4693 uid = UserHandle.getAppId(uid); 4694 // reader 4695 synchronized (mPackages) { 4696 Object obj = mSettings.getUserIdLPr(uid); 4697 if (obj instanceof SharedUserSetting) { 4698 final SharedUserSetting sus = (SharedUserSetting) obj; 4699 final int N = sus.packages.size(); 4700 String[] res = new String[N]; 4701 final Iterator<PackageSetting> it = sus.packages.iterator(); 4702 int i = 0; 4703 while (it.hasNext()) { 4704 PackageSetting ps = it.next(); 4705 if (ps.getInstalled(userId)) { 4706 res[i++] = ps.name; 4707 } else { 4708 res = ArrayUtils.removeElement(String.class, res, res[i]); 4709 } 4710 } 4711 return res; 4712 } else if (obj instanceof PackageSetting) { 4713 final PackageSetting ps = (PackageSetting) obj; 4714 return new String[] { ps.name }; 4715 } 4716 } 4717 return null; 4718 } 4719 4720 @Override 4721 public String getNameForUid(int uid) { 4722 // reader 4723 synchronized (mPackages) { 4724 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4725 if (obj instanceof SharedUserSetting) { 4726 final SharedUserSetting sus = (SharedUserSetting) obj; 4727 return sus.name + ":" + sus.userId; 4728 } else if (obj instanceof PackageSetting) { 4729 final PackageSetting ps = (PackageSetting) obj; 4730 return ps.name; 4731 } 4732 } 4733 return null; 4734 } 4735 4736 @Override 4737 public int getUidForSharedUser(String sharedUserName) { 4738 if(sharedUserName == null) { 4739 return -1; 4740 } 4741 // reader 4742 synchronized (mPackages) { 4743 SharedUserSetting suid; 4744 try { 4745 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4746 if (suid != null) { 4747 return suid.userId; 4748 } 4749 } catch (PackageManagerException ignore) { 4750 // can't happen, but, still need to catch it 4751 } 4752 return -1; 4753 } 4754 } 4755 4756 @Override 4757 public int getFlagsForUid(int uid) { 4758 synchronized (mPackages) { 4759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4760 if (obj instanceof SharedUserSetting) { 4761 final SharedUserSetting sus = (SharedUserSetting) obj; 4762 return sus.pkgFlags; 4763 } else if (obj instanceof PackageSetting) { 4764 final PackageSetting ps = (PackageSetting) obj; 4765 return ps.pkgFlags; 4766 } 4767 } 4768 return 0; 4769 } 4770 4771 @Override 4772 public int getPrivateFlagsForUid(int uid) { 4773 synchronized (mPackages) { 4774 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4775 if (obj instanceof SharedUserSetting) { 4776 final SharedUserSetting sus = (SharedUserSetting) obj; 4777 return sus.pkgPrivateFlags; 4778 } else if (obj instanceof PackageSetting) { 4779 final PackageSetting ps = (PackageSetting) obj; 4780 return ps.pkgPrivateFlags; 4781 } 4782 } 4783 return 0; 4784 } 4785 4786 @Override 4787 public boolean isUidPrivileged(int uid) { 4788 uid = UserHandle.getAppId(uid); 4789 // reader 4790 synchronized (mPackages) { 4791 Object obj = mSettings.getUserIdLPr(uid); 4792 if (obj instanceof SharedUserSetting) { 4793 final SharedUserSetting sus = (SharedUserSetting) obj; 4794 final Iterator<PackageSetting> it = sus.packages.iterator(); 4795 while (it.hasNext()) { 4796 if (it.next().isPrivileged()) { 4797 return true; 4798 } 4799 } 4800 } else if (obj instanceof PackageSetting) { 4801 final PackageSetting ps = (PackageSetting) obj; 4802 return ps.isPrivileged(); 4803 } 4804 } 4805 return false; 4806 } 4807 4808 @Override 4809 public String[] getAppOpPermissionPackages(String permissionName) { 4810 synchronized (mPackages) { 4811 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4812 if (pkgs == null) { 4813 return null; 4814 } 4815 return pkgs.toArray(new String[pkgs.size()]); 4816 } 4817 } 4818 4819 @Override 4820 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4821 int flags, int userId) { 4822 try { 4823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4824 4825 if (!sUserManager.exists(userId)) return null; 4826 flags = updateFlagsForResolve(flags, userId, intent); 4827 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4828 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4829 4830 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4831 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4832 flags, userId); 4833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4834 4835 final ResolveInfo bestChoice = 4836 chooseBestActivity(intent, resolvedType, flags, query, userId); 4837 return bestChoice; 4838 } finally { 4839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4840 } 4841 } 4842 4843 @Override 4844 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4845 IntentFilter filter, int match, ComponentName activity) { 4846 final int userId = UserHandle.getCallingUserId(); 4847 if (DEBUG_PREFERRED) { 4848 Log.v(TAG, "setLastChosenActivity intent=" + intent 4849 + " resolvedType=" + resolvedType 4850 + " flags=" + flags 4851 + " filter=" + filter 4852 + " match=" + match 4853 + " activity=" + activity); 4854 filter.dump(new PrintStreamPrinter(System.out), " "); 4855 } 4856 intent.setComponent(null); 4857 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4858 userId); 4859 // Find any earlier preferred or last chosen entries and nuke them 4860 findPreferredActivity(intent, resolvedType, 4861 flags, query, 0, false, true, false, userId); 4862 // Add the new activity as the last chosen for this filter 4863 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4864 "Setting last chosen"); 4865 } 4866 4867 @Override 4868 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4869 final int userId = UserHandle.getCallingUserId(); 4870 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4871 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4872 userId); 4873 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4874 false, false, false, userId); 4875 } 4876 4877 private boolean isEphemeralDisabled() { 4878 // ephemeral apps have been disabled across the board 4879 if (DISABLE_EPHEMERAL_APPS) { 4880 return true; 4881 } 4882 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4883 if (!mSystemReady) { 4884 return true; 4885 } 4886 // we can't get a content resolver until the system is ready; these checks must happen last 4887 final ContentResolver resolver = mContext.getContentResolver(); 4888 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4889 return true; 4890 } 4891 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4892 } 4893 4894 private boolean isEphemeralAllowed( 4895 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4896 boolean skipPackageCheck) { 4897 // Short circuit and return early if possible. 4898 if (isEphemeralDisabled()) { 4899 return false; 4900 } 4901 final int callingUser = UserHandle.getCallingUserId(); 4902 if (callingUser != UserHandle.USER_SYSTEM) { 4903 return false; 4904 } 4905 if (mEphemeralResolverConnection == null) { 4906 return false; 4907 } 4908 if (intent.getComponent() != null) { 4909 return false; 4910 } 4911 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4912 return false; 4913 } 4914 if (!skipPackageCheck && intent.getPackage() != null) { 4915 return false; 4916 } 4917 final boolean isWebUri = hasWebURI(intent); 4918 if (!isWebUri || intent.getData().getHost() == null) { 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 = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4924 for (int n = 0; n < count; n++) { 4925 ResolveInfo info = resolvedActivities.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 static EphemeralResolveIntentInfo getEphemeralIntentInfo( 4948 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4949 String resolvedType, int userId, String packageName) { 4950 final EphemeralDigest digest = 4951 new EphemeralDigest(intent.getData().getHost(), 5 /*maxDigests*/); 4952 final int[] shaPrefix = digest.getDigestPrefix(); 4953 final byte[][] digestBytes = digest.getDigestBytes(); 4954 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4955 resolverConnection.getEphemeralResolveInfoList(shaPrefix); 4956 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4957 // No hash prefix match; there are no ephemeral apps for this domain. 4958 return null; 4959 } 4960 4961 // Go in reverse order so we match the narrowest scope first. 4962 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4963 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4964 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4965 continue; 4966 } 4967 final List<EphemeralIntentFilter> ephemeralFilters = 4968 ephemeralApplication.getIntentFilters(); 4969 // No filters; this should never happen. 4970 if (ephemeralFilters.isEmpty()) { 4971 continue; 4972 } 4973 if (packageName != null 4974 && !packageName.equals(ephemeralApplication.getPackageName())) { 4975 continue; 4976 } 4977 // We have a domain match; resolve the filters to see if anything matches. 4978 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4979 for (int j = ephemeralFilters.size() - 1; j >= 0; --j) { 4980 final EphemeralIntentFilter ephemeralFilter = ephemeralFilters.get(j); 4981 final List<IntentFilter> splitFilters = ephemeralFilter.getFilters(); 4982 if (splitFilters == null || splitFilters.isEmpty()) { 4983 continue; 4984 } 4985 for (int k = splitFilters.size() - 1; k >= 0; --k) { 4986 final EphemeralResolveIntentInfo intentInfo = 4987 new EphemeralResolveIntentInfo(splitFilters.get(k), 4988 ephemeralApplication, ephemeralFilter.getSplitName()); 4989 ephemeralResolver.addFilter(intentInfo); 4990 } 4991 } 4992 List<EphemeralResolveIntentInfo> matchedResolveInfoList = ephemeralResolver 4993 .queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 4994 if (!matchedResolveInfoList.isEmpty()) { 4995 return matchedResolveInfoList.get(0); 4996 } 4997 } 4998 } 4999 // Hash or filter mis-match; no ephemeral apps for this domain. 5000 return null; 5001 } 5002 5003 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5004 int flags, List<ResolveInfo> query, int userId) { 5005 if (query != null) { 5006 final int N = query.size(); 5007 if (N == 1) { 5008 return query.get(0); 5009 } else if (N > 1) { 5010 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5011 // If there is more than one activity with the same priority, 5012 // then let the user decide between them. 5013 ResolveInfo r0 = query.get(0); 5014 ResolveInfo r1 = query.get(1); 5015 if (DEBUG_INTENT_MATCHING || debug) { 5016 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5017 + r1.activityInfo.name + "=" + r1.priority); 5018 } 5019 // If the first activity has a higher priority, or a different 5020 // default, then it is always desirable to pick it. 5021 if (r0.priority != r1.priority 5022 || r0.preferredOrder != r1.preferredOrder 5023 || r0.isDefault != r1.isDefault) { 5024 return query.get(0); 5025 } 5026 // If we have saved a preference for a preferred activity for 5027 // this Intent, use that. 5028 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5029 flags, query, r0.priority, true, false, debug, userId); 5030 if (ri != null) { 5031 return ri; 5032 } 5033 ri = new ResolveInfo(mResolveInfo); 5034 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5035 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5036 // If all of the options come from the same package, show the application's 5037 // label and icon instead of the generic resolver's. 5038 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5039 // and then throw away the ResolveInfo itself, meaning that the caller loses 5040 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5041 // a fallback for this case; we only set the target package's resources on 5042 // the ResolveInfo, not the ActivityInfo. 5043 final String intentPackage = intent.getPackage(); 5044 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5045 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5046 ri.resolvePackageName = intentPackage; 5047 if (userNeedsBadging(userId)) { 5048 ri.noResourceId = true; 5049 } else { 5050 ri.icon = appi.icon; 5051 } 5052 ri.iconResourceId = appi.icon; 5053 ri.labelRes = appi.labelRes; 5054 } 5055 ri.activityInfo.applicationInfo = new ApplicationInfo( 5056 ri.activityInfo.applicationInfo); 5057 if (userId != 0) { 5058 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5059 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5060 } 5061 // Make sure that the resolver is displayable in car mode 5062 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5063 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5064 return ri; 5065 } 5066 } 5067 return null; 5068 } 5069 5070 /** 5071 * Return true if the given list is not empty and all of its contents have 5072 * an activityInfo with the given package name. 5073 */ 5074 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5075 if (ArrayUtils.isEmpty(list)) { 5076 return false; 5077 } 5078 for (int i = 0, N = list.size(); i < N; i++) { 5079 final ResolveInfo ri = list.get(i); 5080 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5081 if (ai == null || !packageName.equals(ai.packageName)) { 5082 return false; 5083 } 5084 } 5085 return true; 5086 } 5087 5088 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5089 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5090 final int N = query.size(); 5091 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5092 .get(userId); 5093 // Get the list of persistent preferred activities that handle the intent 5094 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5095 List<PersistentPreferredActivity> pprefs = ppir != null 5096 ? ppir.queryIntent(intent, resolvedType, 5097 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5098 : null; 5099 if (pprefs != null && pprefs.size() > 0) { 5100 final int M = pprefs.size(); 5101 for (int i=0; i<M; i++) { 5102 final PersistentPreferredActivity ppa = pprefs.get(i); 5103 if (DEBUG_PREFERRED || debug) { 5104 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5105 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5106 + "\n component=" + ppa.mComponent); 5107 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5108 } 5109 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5110 flags | MATCH_DISABLED_COMPONENTS, userId); 5111 if (DEBUG_PREFERRED || debug) { 5112 Slog.v(TAG, "Found persistent preferred activity:"); 5113 if (ai != null) { 5114 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5115 } else { 5116 Slog.v(TAG, " null"); 5117 } 5118 } 5119 if (ai == null) { 5120 // This previously registered persistent preferred activity 5121 // component is no longer known. Ignore it and do NOT remove it. 5122 continue; 5123 } 5124 for (int j=0; j<N; j++) { 5125 final ResolveInfo ri = query.get(j); 5126 if (!ri.activityInfo.applicationInfo.packageName 5127 .equals(ai.applicationInfo.packageName)) { 5128 continue; 5129 } 5130 if (!ri.activityInfo.name.equals(ai.name)) { 5131 continue; 5132 } 5133 // Found a persistent preference that can handle the intent. 5134 if (DEBUG_PREFERRED || debug) { 5135 Slog.v(TAG, "Returning persistent preferred activity: " + 5136 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5137 } 5138 return ri; 5139 } 5140 } 5141 } 5142 return null; 5143 } 5144 5145 // TODO: handle preferred activities missing while user has amnesia 5146 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5147 List<ResolveInfo> query, int priority, boolean always, 5148 boolean removeMatches, boolean debug, int userId) { 5149 if (!sUserManager.exists(userId)) return null; 5150 flags = updateFlagsForResolve(flags, userId, intent); 5151 // writer 5152 synchronized (mPackages) { 5153 if (intent.getSelector() != null) { 5154 intent = intent.getSelector(); 5155 } 5156 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5157 5158 // Try to find a matching persistent preferred activity. 5159 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5160 debug, userId); 5161 5162 // If a persistent preferred activity matched, use it. 5163 if (pri != null) { 5164 return pri; 5165 } 5166 5167 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5168 // Get the list of preferred activities that handle the intent 5169 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5170 List<PreferredActivity> prefs = pir != null 5171 ? pir.queryIntent(intent, resolvedType, 5172 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5173 : null; 5174 if (prefs != null && prefs.size() > 0) { 5175 boolean changed = false; 5176 try { 5177 // First figure out how good the original match set is. 5178 // We will only allow preferred activities that came 5179 // from the same match quality. 5180 int match = 0; 5181 5182 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5183 5184 final int N = query.size(); 5185 for (int j=0; j<N; j++) { 5186 final ResolveInfo ri = query.get(j); 5187 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5188 + ": 0x" + Integer.toHexString(match)); 5189 if (ri.match > match) { 5190 match = ri.match; 5191 } 5192 } 5193 5194 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5195 + Integer.toHexString(match)); 5196 5197 match &= IntentFilter.MATCH_CATEGORY_MASK; 5198 final int M = prefs.size(); 5199 for (int i=0; i<M; i++) { 5200 final PreferredActivity pa = prefs.get(i); 5201 if (DEBUG_PREFERRED || debug) { 5202 Slog.v(TAG, "Checking PreferredActivity ds=" 5203 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5204 + "\n component=" + pa.mPref.mComponent); 5205 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5206 } 5207 if (pa.mPref.mMatch != match) { 5208 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5209 + Integer.toHexString(pa.mPref.mMatch)); 5210 continue; 5211 } 5212 // If it's not an "always" type preferred activity and that's what we're 5213 // looking for, skip it. 5214 if (always && !pa.mPref.mAlways) { 5215 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5216 continue; 5217 } 5218 final ActivityInfo ai = getActivityInfo( 5219 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5220 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5221 userId); 5222 if (DEBUG_PREFERRED || debug) { 5223 Slog.v(TAG, "Found preferred activity:"); 5224 if (ai != null) { 5225 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5226 } else { 5227 Slog.v(TAG, " null"); 5228 } 5229 } 5230 if (ai == null) { 5231 // This previously registered preferred activity 5232 // component is no longer known. Most likely an update 5233 // to the app was installed and in the new version this 5234 // component no longer exists. Clean it up by removing 5235 // it from the preferred activities list, and skip it. 5236 Slog.w(TAG, "Removing dangling preferred activity: " 5237 + pa.mPref.mComponent); 5238 pir.removeFilter(pa); 5239 changed = true; 5240 continue; 5241 } 5242 for (int j=0; j<N; j++) { 5243 final ResolveInfo ri = query.get(j); 5244 if (!ri.activityInfo.applicationInfo.packageName 5245 .equals(ai.applicationInfo.packageName)) { 5246 continue; 5247 } 5248 if (!ri.activityInfo.name.equals(ai.name)) { 5249 continue; 5250 } 5251 5252 if (removeMatches) { 5253 pir.removeFilter(pa); 5254 changed = true; 5255 if (DEBUG_PREFERRED) { 5256 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5257 } 5258 break; 5259 } 5260 5261 // Okay we found a previously set preferred or last chosen app. 5262 // If the result set is different from when this 5263 // was created, we need to clear it and re-ask the 5264 // user their preference, if we're looking for an "always" type entry. 5265 if (always && !pa.mPref.sameSet(query)) { 5266 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5267 + intent + " type " + resolvedType); 5268 if (DEBUG_PREFERRED) { 5269 Slog.v(TAG, "Removing preferred activity since set changed " 5270 + pa.mPref.mComponent); 5271 } 5272 pir.removeFilter(pa); 5273 // Re-add the filter as a "last chosen" entry (!always) 5274 PreferredActivity lastChosen = new PreferredActivity( 5275 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5276 pir.addFilter(lastChosen); 5277 changed = true; 5278 return null; 5279 } 5280 5281 // Yay! Either the set matched or we're looking for the last chosen 5282 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5283 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5284 return ri; 5285 } 5286 } 5287 } finally { 5288 if (changed) { 5289 if (DEBUG_PREFERRED) { 5290 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5291 } 5292 scheduleWritePackageRestrictionsLocked(userId); 5293 } 5294 } 5295 } 5296 } 5297 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5298 return null; 5299 } 5300 5301 /* 5302 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5303 */ 5304 @Override 5305 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5306 int targetUserId) { 5307 mContext.enforceCallingOrSelfPermission( 5308 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5309 List<CrossProfileIntentFilter> matches = 5310 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5311 if (matches != null) { 5312 int size = matches.size(); 5313 for (int i = 0; i < size; i++) { 5314 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5315 } 5316 } 5317 if (hasWebURI(intent)) { 5318 // cross-profile app linking works only towards the parent. 5319 final UserInfo parent = getProfileParent(sourceUserId); 5320 synchronized(mPackages) { 5321 int flags = updateFlagsForResolve(0, parent.id, intent); 5322 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5323 intent, resolvedType, flags, sourceUserId, parent.id); 5324 return xpDomainInfo != null; 5325 } 5326 } 5327 return false; 5328 } 5329 5330 private UserInfo getProfileParent(int userId) { 5331 final long identity = Binder.clearCallingIdentity(); 5332 try { 5333 return sUserManager.getProfileParent(userId); 5334 } finally { 5335 Binder.restoreCallingIdentity(identity); 5336 } 5337 } 5338 5339 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5340 String resolvedType, int userId) { 5341 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5342 if (resolver != null) { 5343 return resolver.queryIntent(intent, resolvedType, false, userId); 5344 } 5345 return null; 5346 } 5347 5348 @Override 5349 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5350 String resolvedType, int flags, int userId) { 5351 try { 5352 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5353 5354 return new ParceledListSlice<>( 5355 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5356 } finally { 5357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5358 } 5359 } 5360 5361 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5362 String resolvedType, int flags, int userId) { 5363 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5364 flags = updateFlagsForResolve(flags, userId, intent); 5365 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5366 false /* requireFullPermission */, false /* checkShell */, 5367 "query intent activities"); 5368 ComponentName comp = intent.getComponent(); 5369 if (comp == null) { 5370 if (intent.getSelector() != null) { 5371 intent = intent.getSelector(); 5372 comp = intent.getComponent(); 5373 } 5374 } 5375 5376 if (comp != null) { 5377 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5378 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5379 if (ai != null) { 5380 final ResolveInfo ri = new ResolveInfo(); 5381 ri.activityInfo = ai; 5382 list.add(ri); 5383 } 5384 return list; 5385 } 5386 5387 // reader 5388 boolean sortResult = false; 5389 boolean addEphemeral = false; 5390 boolean matchEphemeralPackage = false; 5391 List<ResolveInfo> result; 5392 final String pkgName = intent.getPackage(); 5393 synchronized (mPackages) { 5394 if (pkgName == null) { 5395 List<CrossProfileIntentFilter> matchingFilters = 5396 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5397 // Check for results that need to skip the current profile. 5398 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5399 resolvedType, flags, userId); 5400 if (xpResolveInfo != null) { 5401 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5402 xpResult.add(xpResolveInfo); 5403 return filterIfNotSystemUser(xpResult, userId); 5404 } 5405 5406 // Check for results in the current profile. 5407 result = filterIfNotSystemUser(mActivities.queryIntent( 5408 intent, resolvedType, flags, userId), userId); 5409 addEphemeral = 5410 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5411 5412 // Check for cross profile results. 5413 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5414 xpResolveInfo = queryCrossProfileIntents( 5415 matchingFilters, intent, resolvedType, flags, userId, 5416 hasNonNegativePriorityResult); 5417 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5418 boolean isVisibleToUser = filterIfNotSystemUser( 5419 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5420 if (isVisibleToUser) { 5421 result.add(xpResolveInfo); 5422 sortResult = true; 5423 } 5424 } 5425 if (hasWebURI(intent)) { 5426 CrossProfileDomainInfo xpDomainInfo = null; 5427 final UserInfo parent = getProfileParent(userId); 5428 if (parent != null) { 5429 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5430 flags, userId, parent.id); 5431 } 5432 if (xpDomainInfo != null) { 5433 if (xpResolveInfo != null) { 5434 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5435 // in the result. 5436 result.remove(xpResolveInfo); 5437 } 5438 if (result.size() == 0 && !addEphemeral) { 5439 // No result in current profile, but found candidate in parent user. 5440 // And we are not going to add emphemeral app, so we can return the 5441 // result straight away. 5442 result.add(xpDomainInfo.resolveInfo); 5443 return result; 5444 } 5445 } else if (result.size() <= 1 && !addEphemeral) { 5446 // No result in parent user and <= 1 result in current profile, and we 5447 // are not going to add emphemeral app, so we can return the result without 5448 // further processing. 5449 return result; 5450 } 5451 // We have more than one candidate (combining results from current and parent 5452 // profile), so we need filtering and sorting. 5453 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5454 intent, flags, result, xpDomainInfo, userId); 5455 sortResult = true; 5456 } 5457 } else { 5458 final PackageParser.Package pkg = mPackages.get(pkgName); 5459 if (pkg != null) { 5460 result = filterIfNotSystemUser( 5461 mActivities.queryIntentForPackage( 5462 intent, resolvedType, flags, pkg.activities, userId), 5463 userId); 5464 } else { 5465 // the caller wants to resolve for a particular package; however, there 5466 // were no installed results, so, try to find an ephemeral result 5467 addEphemeral = isEphemeralAllowed( 5468 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5469 matchEphemeralPackage = true; 5470 result = new ArrayList<ResolveInfo>(); 5471 } 5472 } 5473 } 5474 if (addEphemeral) { 5475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5476 final EphemeralResolveIntentInfo intentInfo = getEphemeralIntentInfo( 5477 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5478 matchEphemeralPackage ? pkgName : null); 5479 if (intentInfo != null) { 5480 if (DEBUG_EPHEMERAL) { 5481 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5482 } 5483 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5484 ephemeralInstaller.ephemeralIntentInfo = intentInfo; 5485 // make sure this resolver is the default 5486 ephemeralInstaller.isDefault = true; 5487 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5488 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5489 // add a non-generic filter 5490 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5491 ephemeralInstaller.filter.addDataPath( 5492 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5493 result.add(ephemeralInstaller); 5494 } 5495 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5496 } 5497 if (sortResult) { 5498 Collections.sort(result, mResolvePrioritySorter); 5499 } 5500 return result; 5501 } 5502 5503 private static class CrossProfileDomainInfo { 5504 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5505 ResolveInfo resolveInfo; 5506 /* Best domain verification status of the activities found in the other profile */ 5507 int bestDomainVerificationStatus; 5508 } 5509 5510 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5511 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5512 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5513 sourceUserId)) { 5514 return null; 5515 } 5516 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5517 resolvedType, flags, parentUserId); 5518 5519 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5520 return null; 5521 } 5522 CrossProfileDomainInfo result = null; 5523 int size = resultTargetUser.size(); 5524 for (int i = 0; i < size; i++) { 5525 ResolveInfo riTargetUser = resultTargetUser.get(i); 5526 // Intent filter verification is only for filters that specify a host. So don't return 5527 // those that handle all web uris. 5528 if (riTargetUser.handleAllWebDataURI) { 5529 continue; 5530 } 5531 String packageName = riTargetUser.activityInfo.packageName; 5532 PackageSetting ps = mSettings.mPackages.get(packageName); 5533 if (ps == null) { 5534 continue; 5535 } 5536 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5537 int status = (int)(verificationState >> 32); 5538 if (result == null) { 5539 result = new CrossProfileDomainInfo(); 5540 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5541 sourceUserId, parentUserId); 5542 result.bestDomainVerificationStatus = status; 5543 } else { 5544 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5545 result.bestDomainVerificationStatus); 5546 } 5547 } 5548 // Don't consider matches with status NEVER across profiles. 5549 if (result != null && result.bestDomainVerificationStatus 5550 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5551 return null; 5552 } 5553 return result; 5554 } 5555 5556 /** 5557 * Verification statuses are ordered from the worse to the best, except for 5558 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5559 */ 5560 private int bestDomainVerificationStatus(int status1, int status2) { 5561 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5562 return status2; 5563 } 5564 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5565 return status1; 5566 } 5567 return (int) MathUtils.max(status1, status2); 5568 } 5569 5570 private boolean isUserEnabled(int userId) { 5571 long callingId = Binder.clearCallingIdentity(); 5572 try { 5573 UserInfo userInfo = sUserManager.getUserInfo(userId); 5574 return userInfo != null && userInfo.isEnabled(); 5575 } finally { 5576 Binder.restoreCallingIdentity(callingId); 5577 } 5578 } 5579 5580 /** 5581 * Filter out activities with systemUserOnly flag set, when current user is not System. 5582 * 5583 * @return filtered list 5584 */ 5585 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5586 if (userId == UserHandle.USER_SYSTEM) { 5587 return resolveInfos; 5588 } 5589 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5590 ResolveInfo info = resolveInfos.get(i); 5591 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5592 resolveInfos.remove(i); 5593 } 5594 } 5595 return resolveInfos; 5596 } 5597 5598 /** 5599 * @param resolveInfos list of resolve infos in descending priority order 5600 * @return if the list contains a resolve info with non-negative priority 5601 */ 5602 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5603 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5604 } 5605 5606 private static boolean hasWebURI(Intent intent) { 5607 if (intent.getData() == null) { 5608 return false; 5609 } 5610 final String scheme = intent.getScheme(); 5611 if (TextUtils.isEmpty(scheme)) { 5612 return false; 5613 } 5614 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5615 } 5616 5617 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5618 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5619 int userId) { 5620 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5621 5622 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5623 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5624 candidates.size()); 5625 } 5626 5627 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5628 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5629 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5630 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5631 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5632 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5633 5634 synchronized (mPackages) { 5635 final int count = candidates.size(); 5636 // First, try to use linked apps. Partition the candidates into four lists: 5637 // one for the final results, one for the "do not use ever", one for "undefined status" 5638 // and finally one for "browser app type". 5639 for (int n=0; n<count; n++) { 5640 ResolveInfo info = candidates.get(n); 5641 String packageName = info.activityInfo.packageName; 5642 PackageSetting ps = mSettings.mPackages.get(packageName); 5643 if (ps != null) { 5644 // Add to the special match all list (Browser use case) 5645 if (info.handleAllWebDataURI) { 5646 matchAllList.add(info); 5647 continue; 5648 } 5649 // Try to get the status from User settings first 5650 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5651 int status = (int)(packedStatus >> 32); 5652 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5653 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5654 if (DEBUG_DOMAIN_VERIFICATION) { 5655 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5656 + " : linkgen=" + linkGeneration); 5657 } 5658 // Use link-enabled generation as preferredOrder, i.e. 5659 // prefer newly-enabled over earlier-enabled. 5660 info.preferredOrder = linkGeneration; 5661 alwaysList.add(info); 5662 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5663 if (DEBUG_DOMAIN_VERIFICATION) { 5664 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5665 } 5666 neverList.add(info); 5667 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5668 if (DEBUG_DOMAIN_VERIFICATION) { 5669 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5670 } 5671 alwaysAskList.add(info); 5672 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5673 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5674 if (DEBUG_DOMAIN_VERIFICATION) { 5675 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5676 } 5677 undefinedList.add(info); 5678 } 5679 } 5680 } 5681 5682 // We'll want to include browser possibilities in a few cases 5683 boolean includeBrowser = false; 5684 5685 // First try to add the "always" resolution(s) for the current user, if any 5686 if (alwaysList.size() > 0) { 5687 result.addAll(alwaysList); 5688 } else { 5689 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5690 result.addAll(undefinedList); 5691 // Maybe add one for the other profile. 5692 if (xpDomainInfo != null && ( 5693 xpDomainInfo.bestDomainVerificationStatus 5694 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5695 result.add(xpDomainInfo.resolveInfo); 5696 } 5697 includeBrowser = true; 5698 } 5699 5700 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5701 // If there were 'always' entries their preferred order has been set, so we also 5702 // back that off to make the alternatives equivalent 5703 if (alwaysAskList.size() > 0) { 5704 for (ResolveInfo i : result) { 5705 i.preferredOrder = 0; 5706 } 5707 result.addAll(alwaysAskList); 5708 includeBrowser = true; 5709 } 5710 5711 if (includeBrowser) { 5712 // Also add browsers (all of them or only the default one) 5713 if (DEBUG_DOMAIN_VERIFICATION) { 5714 Slog.v(TAG, " ...including browsers in candidate set"); 5715 } 5716 if ((matchFlags & MATCH_ALL) != 0) { 5717 result.addAll(matchAllList); 5718 } else { 5719 // Browser/generic handling case. If there's a default browser, go straight 5720 // to that (but only if there is no other higher-priority match). 5721 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5722 int maxMatchPrio = 0; 5723 ResolveInfo defaultBrowserMatch = null; 5724 final int numCandidates = matchAllList.size(); 5725 for (int n = 0; n < numCandidates; n++) { 5726 ResolveInfo info = matchAllList.get(n); 5727 // track the highest overall match priority... 5728 if (info.priority > maxMatchPrio) { 5729 maxMatchPrio = info.priority; 5730 } 5731 // ...and the highest-priority default browser match 5732 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5733 if (defaultBrowserMatch == null 5734 || (defaultBrowserMatch.priority < info.priority)) { 5735 if (debug) { 5736 Slog.v(TAG, "Considering default browser match " + info); 5737 } 5738 defaultBrowserMatch = info; 5739 } 5740 } 5741 } 5742 if (defaultBrowserMatch != null 5743 && defaultBrowserMatch.priority >= maxMatchPrio 5744 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5745 { 5746 if (debug) { 5747 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5748 } 5749 result.add(defaultBrowserMatch); 5750 } else { 5751 result.addAll(matchAllList); 5752 } 5753 } 5754 5755 // If there is nothing selected, add all candidates and remove the ones that the user 5756 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5757 if (result.size() == 0) { 5758 result.addAll(candidates); 5759 result.removeAll(neverList); 5760 } 5761 } 5762 } 5763 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5764 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5765 result.size()); 5766 for (ResolveInfo info : result) { 5767 Slog.v(TAG, " + " + info.activityInfo); 5768 } 5769 } 5770 return result; 5771 } 5772 5773 // Returns a packed value as a long: 5774 // 5775 // high 'int'-sized word: link status: undefined/ask/never/always. 5776 // low 'int'-sized word: relative priority among 'always' results. 5777 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5778 long result = ps.getDomainVerificationStatusForUser(userId); 5779 // if none available, get the master status 5780 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5781 if (ps.getIntentFilterVerificationInfo() != null) { 5782 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5783 } 5784 } 5785 return result; 5786 } 5787 5788 private ResolveInfo querySkipCurrentProfileIntents( 5789 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5790 int flags, int sourceUserId) { 5791 if (matchingFilters != null) { 5792 int size = matchingFilters.size(); 5793 for (int i = 0; i < size; i ++) { 5794 CrossProfileIntentFilter filter = matchingFilters.get(i); 5795 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5796 // Checking if there are activities in the target user that can handle the 5797 // intent. 5798 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5799 resolvedType, flags, sourceUserId); 5800 if (resolveInfo != null) { 5801 return resolveInfo; 5802 } 5803 } 5804 } 5805 } 5806 return null; 5807 } 5808 5809 // Return matching ResolveInfo in target user if any. 5810 private ResolveInfo queryCrossProfileIntents( 5811 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5812 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5813 if (matchingFilters != null) { 5814 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5815 // match the same intent. For performance reasons, it is better not to 5816 // run queryIntent twice for the same userId 5817 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5818 int size = matchingFilters.size(); 5819 for (int i = 0; i < size; i++) { 5820 CrossProfileIntentFilter filter = matchingFilters.get(i); 5821 int targetUserId = filter.getTargetUserId(); 5822 boolean skipCurrentProfile = 5823 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5824 boolean skipCurrentProfileIfNoMatchFound = 5825 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5826 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5827 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5828 // Checking if there are activities in the target user that can handle the 5829 // intent. 5830 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5831 resolvedType, flags, sourceUserId); 5832 if (resolveInfo != null) return resolveInfo; 5833 alreadyTriedUserIds.put(targetUserId, true); 5834 } 5835 } 5836 } 5837 return null; 5838 } 5839 5840 /** 5841 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5842 * will forward the intent to the filter's target user. 5843 * Otherwise, returns null. 5844 */ 5845 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5846 String resolvedType, int flags, int sourceUserId) { 5847 int targetUserId = filter.getTargetUserId(); 5848 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5849 resolvedType, flags, targetUserId); 5850 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5851 // If all the matches in the target profile are suspended, return null. 5852 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5853 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5854 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5855 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5856 targetUserId); 5857 } 5858 } 5859 } 5860 return null; 5861 } 5862 5863 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5864 int sourceUserId, int targetUserId) { 5865 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5866 long ident = Binder.clearCallingIdentity(); 5867 boolean targetIsProfile; 5868 try { 5869 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5870 } finally { 5871 Binder.restoreCallingIdentity(ident); 5872 } 5873 String className; 5874 if (targetIsProfile) { 5875 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5876 } else { 5877 className = FORWARD_INTENT_TO_PARENT; 5878 } 5879 ComponentName forwardingActivityComponentName = new ComponentName( 5880 mAndroidApplication.packageName, className); 5881 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5882 sourceUserId); 5883 if (!targetIsProfile) { 5884 forwardingActivityInfo.showUserIcon = targetUserId; 5885 forwardingResolveInfo.noResourceId = true; 5886 } 5887 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5888 forwardingResolveInfo.priority = 0; 5889 forwardingResolveInfo.preferredOrder = 0; 5890 forwardingResolveInfo.match = 0; 5891 forwardingResolveInfo.isDefault = true; 5892 forwardingResolveInfo.filter = filter; 5893 forwardingResolveInfo.targetUserId = targetUserId; 5894 return forwardingResolveInfo; 5895 } 5896 5897 @Override 5898 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5899 Intent[] specifics, String[] specificTypes, Intent intent, 5900 String resolvedType, int flags, int userId) { 5901 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5902 specificTypes, intent, resolvedType, flags, userId)); 5903 } 5904 5905 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5906 Intent[] specifics, String[] specificTypes, Intent intent, 5907 String resolvedType, int flags, int userId) { 5908 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5909 flags = updateFlagsForResolve(flags, userId, intent); 5910 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5911 false /* requireFullPermission */, false /* checkShell */, 5912 "query intent activity options"); 5913 final String resultsAction = intent.getAction(); 5914 5915 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5916 | PackageManager.GET_RESOLVED_FILTER, userId); 5917 5918 if (DEBUG_INTENT_MATCHING) { 5919 Log.v(TAG, "Query " + intent + ": " + results); 5920 } 5921 5922 int specificsPos = 0; 5923 int N; 5924 5925 // todo: note that the algorithm used here is O(N^2). This 5926 // isn't a problem in our current environment, but if we start running 5927 // into situations where we have more than 5 or 10 matches then this 5928 // should probably be changed to something smarter... 5929 5930 // First we go through and resolve each of the specific items 5931 // that were supplied, taking care of removing any corresponding 5932 // duplicate items in the generic resolve list. 5933 if (specifics != null) { 5934 for (int i=0; i<specifics.length; i++) { 5935 final Intent sintent = specifics[i]; 5936 if (sintent == null) { 5937 continue; 5938 } 5939 5940 if (DEBUG_INTENT_MATCHING) { 5941 Log.v(TAG, "Specific #" + i + ": " + sintent); 5942 } 5943 5944 String action = sintent.getAction(); 5945 if (resultsAction != null && resultsAction.equals(action)) { 5946 // If this action was explicitly requested, then don't 5947 // remove things that have it. 5948 action = null; 5949 } 5950 5951 ResolveInfo ri = null; 5952 ActivityInfo ai = null; 5953 5954 ComponentName comp = sintent.getComponent(); 5955 if (comp == null) { 5956 ri = resolveIntent( 5957 sintent, 5958 specificTypes != null ? specificTypes[i] : null, 5959 flags, userId); 5960 if (ri == null) { 5961 continue; 5962 } 5963 if (ri == mResolveInfo) { 5964 // ACK! Must do something better with this. 5965 } 5966 ai = ri.activityInfo; 5967 comp = new ComponentName(ai.applicationInfo.packageName, 5968 ai.name); 5969 } else { 5970 ai = getActivityInfo(comp, flags, userId); 5971 if (ai == null) { 5972 continue; 5973 } 5974 } 5975 5976 // Look for any generic query activities that are duplicates 5977 // of this specific one, and remove them from the results. 5978 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5979 N = results.size(); 5980 int j; 5981 for (j=specificsPos; j<N; j++) { 5982 ResolveInfo sri = results.get(j); 5983 if ((sri.activityInfo.name.equals(comp.getClassName()) 5984 && sri.activityInfo.applicationInfo.packageName.equals( 5985 comp.getPackageName())) 5986 || (action != null && sri.filter.matchAction(action))) { 5987 results.remove(j); 5988 if (DEBUG_INTENT_MATCHING) Log.v( 5989 TAG, "Removing duplicate item from " + j 5990 + " due to specific " + specificsPos); 5991 if (ri == null) { 5992 ri = sri; 5993 } 5994 j--; 5995 N--; 5996 } 5997 } 5998 5999 // Add this specific item to its proper place. 6000 if (ri == null) { 6001 ri = new ResolveInfo(); 6002 ri.activityInfo = ai; 6003 } 6004 results.add(specificsPos, ri); 6005 ri.specificIndex = i; 6006 specificsPos++; 6007 } 6008 } 6009 6010 // Now we go through the remaining generic results and remove any 6011 // duplicate actions that are found here. 6012 N = results.size(); 6013 for (int i=specificsPos; i<N-1; i++) { 6014 final ResolveInfo rii = results.get(i); 6015 if (rii.filter == null) { 6016 continue; 6017 } 6018 6019 // Iterate over all of the actions of this result's intent 6020 // filter... typically this should be just one. 6021 final Iterator<String> it = rii.filter.actionsIterator(); 6022 if (it == null) { 6023 continue; 6024 } 6025 while (it.hasNext()) { 6026 final String action = it.next(); 6027 if (resultsAction != null && resultsAction.equals(action)) { 6028 // If this action was explicitly requested, then don't 6029 // remove things that have it. 6030 continue; 6031 } 6032 for (int j=i+1; j<N; j++) { 6033 final ResolveInfo rij = results.get(j); 6034 if (rij.filter != null && rij.filter.hasAction(action)) { 6035 results.remove(j); 6036 if (DEBUG_INTENT_MATCHING) Log.v( 6037 TAG, "Removing duplicate item from " + j 6038 + " due to action " + action + " at " + i); 6039 j--; 6040 N--; 6041 } 6042 } 6043 } 6044 6045 // If the caller didn't request filter information, drop it now 6046 // so we don't have to marshall/unmarshall it. 6047 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6048 rii.filter = null; 6049 } 6050 } 6051 6052 // Filter out the caller activity if so requested. 6053 if (caller != null) { 6054 N = results.size(); 6055 for (int i=0; i<N; i++) { 6056 ActivityInfo ainfo = results.get(i).activityInfo; 6057 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6058 && caller.getClassName().equals(ainfo.name)) { 6059 results.remove(i); 6060 break; 6061 } 6062 } 6063 } 6064 6065 // If the caller didn't request filter information, 6066 // drop them now so we don't have to 6067 // marshall/unmarshall it. 6068 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6069 N = results.size(); 6070 for (int i=0; i<N; i++) { 6071 results.get(i).filter = null; 6072 } 6073 } 6074 6075 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6076 return results; 6077 } 6078 6079 @Override 6080 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6081 String resolvedType, int flags, int userId) { 6082 return new ParceledListSlice<>( 6083 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6084 } 6085 6086 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6087 String resolvedType, int flags, int userId) { 6088 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6089 flags = updateFlagsForResolve(flags, userId, intent); 6090 ComponentName comp = intent.getComponent(); 6091 if (comp == null) { 6092 if (intent.getSelector() != null) { 6093 intent = intent.getSelector(); 6094 comp = intent.getComponent(); 6095 } 6096 } 6097 if (comp != null) { 6098 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6099 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6100 if (ai != null) { 6101 ResolveInfo ri = new ResolveInfo(); 6102 ri.activityInfo = ai; 6103 list.add(ri); 6104 } 6105 return list; 6106 } 6107 6108 // reader 6109 synchronized (mPackages) { 6110 String pkgName = intent.getPackage(); 6111 if (pkgName == null) { 6112 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6113 } 6114 final PackageParser.Package pkg = mPackages.get(pkgName); 6115 if (pkg != null) { 6116 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6117 userId); 6118 } 6119 return Collections.emptyList(); 6120 } 6121 } 6122 6123 @Override 6124 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6125 if (!sUserManager.exists(userId)) return null; 6126 flags = updateFlagsForResolve(flags, userId, intent); 6127 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6128 if (query != null) { 6129 if (query.size() >= 1) { 6130 // If there is more than one service with the same priority, 6131 // just arbitrarily pick the first one. 6132 return query.get(0); 6133 } 6134 } 6135 return null; 6136 } 6137 6138 @Override 6139 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6140 String resolvedType, int flags, int userId) { 6141 return new ParceledListSlice<>( 6142 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6143 } 6144 6145 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6146 String resolvedType, int flags, int userId) { 6147 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6148 flags = updateFlagsForResolve(flags, userId, intent); 6149 ComponentName comp = intent.getComponent(); 6150 if (comp == null) { 6151 if (intent.getSelector() != null) { 6152 intent = intent.getSelector(); 6153 comp = intent.getComponent(); 6154 } 6155 } 6156 if (comp != null) { 6157 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6158 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6159 if (si != null) { 6160 final ResolveInfo ri = new ResolveInfo(); 6161 ri.serviceInfo = si; 6162 list.add(ri); 6163 } 6164 return list; 6165 } 6166 6167 // reader 6168 synchronized (mPackages) { 6169 String pkgName = intent.getPackage(); 6170 if (pkgName == null) { 6171 return mServices.queryIntent(intent, resolvedType, flags, userId); 6172 } 6173 final PackageParser.Package pkg = mPackages.get(pkgName); 6174 if (pkg != null) { 6175 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6176 userId); 6177 } 6178 return Collections.emptyList(); 6179 } 6180 } 6181 6182 @Override 6183 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6184 String resolvedType, int flags, int userId) { 6185 return new ParceledListSlice<>( 6186 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6187 } 6188 6189 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6190 Intent intent, String resolvedType, int flags, int userId) { 6191 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6192 flags = updateFlagsForResolve(flags, userId, intent); 6193 ComponentName comp = intent.getComponent(); 6194 if (comp == null) { 6195 if (intent.getSelector() != null) { 6196 intent = intent.getSelector(); 6197 comp = intent.getComponent(); 6198 } 6199 } 6200 if (comp != null) { 6201 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6202 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6203 if (pi != null) { 6204 final ResolveInfo ri = new ResolveInfo(); 6205 ri.providerInfo = pi; 6206 list.add(ri); 6207 } 6208 return list; 6209 } 6210 6211 // reader 6212 synchronized (mPackages) { 6213 String pkgName = intent.getPackage(); 6214 if (pkgName == null) { 6215 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6216 } 6217 final PackageParser.Package pkg = mPackages.get(pkgName); 6218 if (pkg != null) { 6219 return mProviders.queryIntentForPackage( 6220 intent, resolvedType, flags, pkg.providers, userId); 6221 } 6222 return Collections.emptyList(); 6223 } 6224 } 6225 6226 @Override 6227 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6228 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6229 flags = updateFlagsForPackage(flags, userId, null); 6230 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6231 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6232 true /* requireFullPermission */, false /* checkShell */, 6233 "get installed packages"); 6234 6235 // writer 6236 synchronized (mPackages) { 6237 ArrayList<PackageInfo> list; 6238 if (listUninstalled) { 6239 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6240 for (PackageSetting ps : mSettings.mPackages.values()) { 6241 final PackageInfo pi; 6242 if (ps.pkg != null) { 6243 pi = generatePackageInfo(ps, flags, userId); 6244 } else { 6245 pi = generatePackageInfo(ps, flags, userId); 6246 } 6247 if (pi != null) { 6248 list.add(pi); 6249 } 6250 } 6251 } else { 6252 list = new ArrayList<PackageInfo>(mPackages.size()); 6253 for (PackageParser.Package p : mPackages.values()) { 6254 final PackageInfo pi = 6255 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6256 if (pi != null) { 6257 list.add(pi); 6258 } 6259 } 6260 } 6261 6262 return new ParceledListSlice<PackageInfo>(list); 6263 } 6264 } 6265 6266 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6267 String[] permissions, boolean[] tmp, int flags, int userId) { 6268 int numMatch = 0; 6269 final PermissionsState permissionsState = ps.getPermissionsState(); 6270 for (int i=0; i<permissions.length; i++) { 6271 final String permission = permissions[i]; 6272 if (permissionsState.hasPermission(permission, userId)) { 6273 tmp[i] = true; 6274 numMatch++; 6275 } else { 6276 tmp[i] = false; 6277 } 6278 } 6279 if (numMatch == 0) { 6280 return; 6281 } 6282 final PackageInfo pi; 6283 if (ps.pkg != null) { 6284 pi = generatePackageInfo(ps, flags, userId); 6285 } else { 6286 pi = generatePackageInfo(ps, flags, userId); 6287 } 6288 // The above might return null in cases of uninstalled apps or install-state 6289 // skew across users/profiles. 6290 if (pi != null) { 6291 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6292 if (numMatch == permissions.length) { 6293 pi.requestedPermissions = permissions; 6294 } else { 6295 pi.requestedPermissions = new String[numMatch]; 6296 numMatch = 0; 6297 for (int i=0; i<permissions.length; i++) { 6298 if (tmp[i]) { 6299 pi.requestedPermissions[numMatch] = permissions[i]; 6300 numMatch++; 6301 } 6302 } 6303 } 6304 } 6305 list.add(pi); 6306 } 6307 } 6308 6309 @Override 6310 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6311 String[] permissions, int flags, int userId) { 6312 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6313 flags = updateFlagsForPackage(flags, userId, permissions); 6314 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6315 6316 // writer 6317 synchronized (mPackages) { 6318 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6319 boolean[] tmpBools = new boolean[permissions.length]; 6320 if (listUninstalled) { 6321 for (PackageSetting ps : mSettings.mPackages.values()) { 6322 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6323 } 6324 } else { 6325 for (PackageParser.Package pkg : mPackages.values()) { 6326 PackageSetting ps = (PackageSetting)pkg.mExtras; 6327 if (ps != null) { 6328 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6329 userId); 6330 } 6331 } 6332 } 6333 6334 return new ParceledListSlice<PackageInfo>(list); 6335 } 6336 } 6337 6338 @Override 6339 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6340 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6341 flags = updateFlagsForApplication(flags, userId, null); 6342 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6343 6344 // writer 6345 synchronized (mPackages) { 6346 ArrayList<ApplicationInfo> list; 6347 if (listUninstalled) { 6348 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6349 for (PackageSetting ps : mSettings.mPackages.values()) { 6350 ApplicationInfo ai; 6351 if (ps.pkg != null) { 6352 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6353 ps.readUserState(userId), userId); 6354 } else { 6355 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6356 } 6357 if (ai != null) { 6358 list.add(ai); 6359 } 6360 } 6361 } else { 6362 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6363 for (PackageParser.Package p : mPackages.values()) { 6364 if (p.mExtras != null) { 6365 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6366 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6367 if (ai != null) { 6368 list.add(ai); 6369 } 6370 } 6371 } 6372 } 6373 6374 return new ParceledListSlice<ApplicationInfo>(list); 6375 } 6376 } 6377 6378 @Override 6379 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6380 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6381 return null; 6382 } 6383 6384 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6385 "getEphemeralApplications"); 6386 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6387 true /* requireFullPermission */, false /* checkShell */, 6388 "getEphemeralApplications"); 6389 synchronized (mPackages) { 6390 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6391 .getEphemeralApplicationsLPw(userId); 6392 if (ephemeralApps != null) { 6393 return new ParceledListSlice<>(ephemeralApps); 6394 } 6395 } 6396 return null; 6397 } 6398 6399 @Override 6400 public boolean isEphemeralApplication(String packageName, int userId) { 6401 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6402 true /* requireFullPermission */, false /* checkShell */, 6403 "isEphemeral"); 6404 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6405 return false; 6406 } 6407 6408 if (!isCallerSameApp(packageName)) { 6409 return false; 6410 } 6411 synchronized (mPackages) { 6412 PackageParser.Package pkg = mPackages.get(packageName); 6413 if (pkg != null) { 6414 return pkg.applicationInfo.isEphemeralApp(); 6415 } 6416 } 6417 return false; 6418 } 6419 6420 @Override 6421 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6422 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6423 return null; 6424 } 6425 6426 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6427 true /* requireFullPermission */, false /* checkShell */, 6428 "getCookie"); 6429 if (!isCallerSameApp(packageName)) { 6430 return null; 6431 } 6432 synchronized (mPackages) { 6433 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6434 packageName, userId); 6435 } 6436 } 6437 6438 @Override 6439 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6440 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6441 return true; 6442 } 6443 6444 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6445 true /* requireFullPermission */, true /* checkShell */, 6446 "setCookie"); 6447 if (!isCallerSameApp(packageName)) { 6448 return false; 6449 } 6450 synchronized (mPackages) { 6451 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6452 packageName, cookie, userId); 6453 } 6454 } 6455 6456 @Override 6457 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6458 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6459 return null; 6460 } 6461 6462 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6463 "getEphemeralApplicationIcon"); 6464 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6465 true /* requireFullPermission */, false /* checkShell */, 6466 "getEphemeralApplicationIcon"); 6467 synchronized (mPackages) { 6468 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6469 packageName, userId); 6470 } 6471 } 6472 6473 private boolean isCallerSameApp(String packageName) { 6474 PackageParser.Package pkg = mPackages.get(packageName); 6475 return pkg != null 6476 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6477 } 6478 6479 @Override 6480 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6481 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6482 } 6483 6484 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6485 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6486 6487 // reader 6488 synchronized (mPackages) { 6489 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6490 final int userId = UserHandle.getCallingUserId(); 6491 while (i.hasNext()) { 6492 final PackageParser.Package p = i.next(); 6493 if (p.applicationInfo == null) continue; 6494 6495 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6496 && !p.applicationInfo.isDirectBootAware(); 6497 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6498 && p.applicationInfo.isDirectBootAware(); 6499 6500 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6501 && (!mSafeMode || isSystemApp(p)) 6502 && (matchesUnaware || matchesAware)) { 6503 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6504 if (ps != null) { 6505 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6506 ps.readUserState(userId), userId); 6507 if (ai != null) { 6508 finalList.add(ai); 6509 } 6510 } 6511 } 6512 } 6513 } 6514 6515 return finalList; 6516 } 6517 6518 @Override 6519 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6520 if (!sUserManager.exists(userId)) return null; 6521 flags = updateFlagsForComponent(flags, userId, name); 6522 // reader 6523 synchronized (mPackages) { 6524 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6525 PackageSetting ps = provider != null 6526 ? mSettings.mPackages.get(provider.owner.packageName) 6527 : null; 6528 return ps != null 6529 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6530 ? PackageParser.generateProviderInfo(provider, flags, 6531 ps.readUserState(userId), userId) 6532 : null; 6533 } 6534 } 6535 6536 /** 6537 * @deprecated 6538 */ 6539 @Deprecated 6540 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6541 // reader 6542 synchronized (mPackages) { 6543 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6544 .entrySet().iterator(); 6545 final int userId = UserHandle.getCallingUserId(); 6546 while (i.hasNext()) { 6547 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6548 PackageParser.Provider p = entry.getValue(); 6549 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6550 6551 if (ps != null && p.syncable 6552 && (!mSafeMode || (p.info.applicationInfo.flags 6553 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6554 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6555 ps.readUserState(userId), userId); 6556 if (info != null) { 6557 outNames.add(entry.getKey()); 6558 outInfo.add(info); 6559 } 6560 } 6561 } 6562 } 6563 } 6564 6565 @Override 6566 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6567 int uid, int flags) { 6568 final int userId = processName != null ? UserHandle.getUserId(uid) 6569 : UserHandle.getCallingUserId(); 6570 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6571 flags = updateFlagsForComponent(flags, userId, processName); 6572 6573 ArrayList<ProviderInfo> finalList = null; 6574 // reader 6575 synchronized (mPackages) { 6576 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6577 while (i.hasNext()) { 6578 final PackageParser.Provider p = i.next(); 6579 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6580 if (ps != null && p.info.authority != null 6581 && (processName == null 6582 || (p.info.processName.equals(processName) 6583 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6584 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6585 if (finalList == null) { 6586 finalList = new ArrayList<ProviderInfo>(3); 6587 } 6588 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6589 ps.readUserState(userId), userId); 6590 if (info != null) { 6591 finalList.add(info); 6592 } 6593 } 6594 } 6595 } 6596 6597 if (finalList != null) { 6598 Collections.sort(finalList, mProviderInitOrderSorter); 6599 return new ParceledListSlice<ProviderInfo>(finalList); 6600 } 6601 6602 return ParceledListSlice.emptyList(); 6603 } 6604 6605 @Override 6606 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6607 // reader 6608 synchronized (mPackages) { 6609 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6610 return PackageParser.generateInstrumentationInfo(i, flags); 6611 } 6612 } 6613 6614 @Override 6615 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6616 String targetPackage, int flags) { 6617 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6618 } 6619 6620 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6621 int flags) { 6622 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6623 6624 // reader 6625 synchronized (mPackages) { 6626 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6627 while (i.hasNext()) { 6628 final PackageParser.Instrumentation p = i.next(); 6629 if (targetPackage == null 6630 || targetPackage.equals(p.info.targetPackage)) { 6631 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6632 flags); 6633 if (ii != null) { 6634 finalList.add(ii); 6635 } 6636 } 6637 } 6638 } 6639 6640 return finalList; 6641 } 6642 6643 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6644 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6645 if (overlays == null) { 6646 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6647 return; 6648 } 6649 for (PackageParser.Package opkg : overlays.values()) { 6650 // Not much to do if idmap fails: we already logged the error 6651 // and we certainly don't want to abort installation of pkg simply 6652 // because an overlay didn't fit properly. For these reasons, 6653 // ignore the return value of createIdmapForPackagePairLI. 6654 createIdmapForPackagePairLI(pkg, opkg); 6655 } 6656 } 6657 6658 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6659 PackageParser.Package opkg) { 6660 if (!opkg.mTrustedOverlay) { 6661 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6662 opkg.baseCodePath + ": overlay not trusted"); 6663 return false; 6664 } 6665 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6666 if (overlaySet == null) { 6667 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6668 opkg.baseCodePath + " but target package has no known overlays"); 6669 return false; 6670 } 6671 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6672 // TODO: generate idmap for split APKs 6673 try { 6674 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6675 } catch (InstallerException e) { 6676 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6677 + opkg.baseCodePath); 6678 return false; 6679 } 6680 PackageParser.Package[] overlayArray = 6681 overlaySet.values().toArray(new PackageParser.Package[0]); 6682 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6683 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6684 return p1.mOverlayPriority - p2.mOverlayPriority; 6685 } 6686 }; 6687 Arrays.sort(overlayArray, cmp); 6688 6689 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6690 int i = 0; 6691 for (PackageParser.Package p : overlayArray) { 6692 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6693 } 6694 return true; 6695 } 6696 6697 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6698 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6699 try { 6700 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6701 } finally { 6702 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6703 } 6704 } 6705 6706 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6707 final File[] files = dir.listFiles(); 6708 if (ArrayUtils.isEmpty(files)) { 6709 Log.d(TAG, "No files in app dir " + dir); 6710 return; 6711 } 6712 6713 if (DEBUG_PACKAGE_SCANNING) { 6714 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6715 + " flags=0x" + Integer.toHexString(parseFlags)); 6716 } 6717 6718 for (File file : files) { 6719 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6720 && !PackageInstallerService.isStageName(file.getName()); 6721 if (!isPackage) { 6722 // Ignore entries which are not packages 6723 continue; 6724 } 6725 try { 6726 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6727 scanFlags, currentTime, null); 6728 } catch (PackageManagerException e) { 6729 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6730 6731 // Delete invalid userdata apps 6732 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6733 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6734 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6735 removeCodePathLI(file); 6736 } 6737 } 6738 } 6739 } 6740 6741 private static File getSettingsProblemFile() { 6742 File dataDir = Environment.getDataDirectory(); 6743 File systemDir = new File(dataDir, "system"); 6744 File fname = new File(systemDir, "uiderrors.txt"); 6745 return fname; 6746 } 6747 6748 static void reportSettingsProblem(int priority, String msg) { 6749 logCriticalInfo(priority, msg); 6750 } 6751 6752 static void logCriticalInfo(int priority, String msg) { 6753 Slog.println(priority, TAG, msg); 6754 EventLogTags.writePmCriticalInfo(msg); 6755 try { 6756 File fname = getSettingsProblemFile(); 6757 FileOutputStream out = new FileOutputStream(fname, true); 6758 PrintWriter pw = new FastPrintWriter(out); 6759 SimpleDateFormat formatter = new SimpleDateFormat(); 6760 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6761 pw.println(dateString + ": " + msg); 6762 pw.close(); 6763 FileUtils.setPermissions( 6764 fname.toString(), 6765 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6766 -1, -1); 6767 } catch (java.io.IOException e) { 6768 } 6769 } 6770 6771 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6772 if (srcFile.isDirectory()) { 6773 final File baseFile = new File(pkg.baseCodePath); 6774 long maxModifiedTime = baseFile.lastModified(); 6775 if (pkg.splitCodePaths != null) { 6776 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6777 final File splitFile = new File(pkg.splitCodePaths[i]); 6778 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6779 } 6780 } 6781 return maxModifiedTime; 6782 } 6783 return srcFile.lastModified(); 6784 } 6785 6786 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6787 final int policyFlags) throws PackageManagerException { 6788 // When upgrading from pre-N MR1, verify the package time stamp using the package 6789 // directory and not the APK file. 6790 final long lastModifiedTime = mIsPreNMR1Upgrade 6791 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6792 if (ps != null 6793 && ps.codePath.equals(srcFile) 6794 && ps.timeStamp == lastModifiedTime 6795 && !isCompatSignatureUpdateNeeded(pkg) 6796 && !isRecoverSignatureUpdateNeeded(pkg)) { 6797 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6798 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6799 ArraySet<PublicKey> signingKs; 6800 synchronized (mPackages) { 6801 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6802 } 6803 if (ps.signatures.mSignatures != null 6804 && ps.signatures.mSignatures.length != 0 6805 && signingKs != null) { 6806 // Optimization: reuse the existing cached certificates 6807 // if the package appears to be unchanged. 6808 pkg.mSignatures = ps.signatures.mSignatures; 6809 pkg.mSigningKeys = signingKs; 6810 return; 6811 } 6812 6813 Slog.w(TAG, "PackageSetting for " + ps.name 6814 + " is missing signatures. Collecting certs again to recover them."); 6815 } else { 6816 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6817 } 6818 6819 try { 6820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 6821 PackageParser.collectCertificates(pkg, policyFlags); 6822 } catch (PackageParserException e) { 6823 throw PackageManagerException.from(e); 6824 } finally { 6825 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6826 } 6827 } 6828 6829 /** 6830 * Traces a package scan. 6831 * @see #scanPackageLI(File, int, int, long, UserHandle) 6832 */ 6833 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6834 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6835 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 6836 try { 6837 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6838 } finally { 6839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6840 } 6841 } 6842 6843 /** 6844 * Scans a package and returns the newly parsed package. 6845 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6846 */ 6847 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6848 long currentTime, UserHandle user) throws PackageManagerException { 6849 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6850 PackageParser pp = new PackageParser(); 6851 pp.setSeparateProcesses(mSeparateProcesses); 6852 pp.setOnlyCoreApps(mOnlyCore); 6853 pp.setDisplayMetrics(mMetrics); 6854 6855 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6856 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6857 } 6858 6859 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6860 final PackageParser.Package pkg; 6861 try { 6862 pkg = pp.parsePackage(scanFile, parseFlags); 6863 } catch (PackageParserException e) { 6864 throw PackageManagerException.from(e); 6865 } finally { 6866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6867 } 6868 6869 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6870 } 6871 6872 /** 6873 * Scans a package and returns the newly parsed package. 6874 * @throws PackageManagerException on a parse error. 6875 */ 6876 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6877 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6878 throws PackageManagerException { 6879 // If the package has children and this is the first dive in the function 6880 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6881 // packages (parent and children) would be successfully scanned before the 6882 // actual scan since scanning mutates internal state and we want to atomically 6883 // install the package and its children. 6884 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6885 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6886 scanFlags |= SCAN_CHECK_ONLY; 6887 } 6888 } else { 6889 scanFlags &= ~SCAN_CHECK_ONLY; 6890 } 6891 6892 // Scan the parent 6893 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6894 scanFlags, currentTime, user); 6895 6896 // Scan the children 6897 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6898 for (int i = 0; i < childCount; i++) { 6899 PackageParser.Package childPackage = pkg.childPackages.get(i); 6900 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6901 currentTime, user); 6902 } 6903 6904 6905 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6906 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6907 } 6908 6909 return scannedPkg; 6910 } 6911 6912 /** 6913 * Scans a package and returns the newly parsed package. 6914 * @throws PackageManagerException on a parse error. 6915 */ 6916 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6917 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6918 throws PackageManagerException { 6919 PackageSetting ps = null; 6920 PackageSetting updatedPkg; 6921 // reader 6922 synchronized (mPackages) { 6923 // Look to see if we already know about this package. 6924 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 6925 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6926 // This package has been renamed to its original name. Let's 6927 // use that. 6928 ps = mSettings.getPackageLPr(oldName); 6929 } 6930 // If there was no original package, see one for the real package name. 6931 if (ps == null) { 6932 ps = mSettings.getPackageLPr(pkg.packageName); 6933 } 6934 // Check to see if this package could be hiding/updating a system 6935 // package. Must look for it either under the original or real 6936 // package name depending on our state. 6937 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6938 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6939 6940 // If this is a package we don't know about on the system partition, we 6941 // may need to remove disabled child packages on the system partition 6942 // or may need to not add child packages if the parent apk is updated 6943 // on the data partition and no longer defines this child package. 6944 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6945 // If this is a parent package for an updated system app and this system 6946 // app got an OTA update which no longer defines some of the child packages 6947 // we have to prune them from the disabled system packages. 6948 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6949 if (disabledPs != null) { 6950 final int scannedChildCount = (pkg.childPackages != null) 6951 ? pkg.childPackages.size() : 0; 6952 final int disabledChildCount = disabledPs.childPackageNames != null 6953 ? disabledPs.childPackageNames.size() : 0; 6954 for (int i = 0; i < disabledChildCount; i++) { 6955 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6956 boolean disabledPackageAvailable = false; 6957 for (int j = 0; j < scannedChildCount; j++) { 6958 PackageParser.Package childPkg = pkg.childPackages.get(j); 6959 if (childPkg.packageName.equals(disabledChildPackageName)) { 6960 disabledPackageAvailable = true; 6961 break; 6962 } 6963 } 6964 if (!disabledPackageAvailable) { 6965 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6966 } 6967 } 6968 } 6969 } 6970 } 6971 6972 boolean updatedPkgBetter = false; 6973 // First check if this is a system package that may involve an update 6974 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6975 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6976 // it needs to drop FLAG_PRIVILEGED. 6977 if (locationIsPrivileged(scanFile)) { 6978 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6979 } else { 6980 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6981 } 6982 6983 if (ps != null && !ps.codePath.equals(scanFile)) { 6984 // The path has changed from what was last scanned... check the 6985 // version of the new path against what we have stored to determine 6986 // what to do. 6987 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6988 if (pkg.mVersionCode <= ps.versionCode) { 6989 // The system package has been updated and the code path does not match 6990 // Ignore entry. Skip it. 6991 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6992 + " ignored: updated version " + ps.versionCode 6993 + " better than this " + pkg.mVersionCode); 6994 if (!updatedPkg.codePath.equals(scanFile)) { 6995 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6996 + ps.name + " changing from " + updatedPkg.codePathString 6997 + " to " + scanFile); 6998 updatedPkg.codePath = scanFile; 6999 updatedPkg.codePathString = scanFile.toString(); 7000 updatedPkg.resourcePath = scanFile; 7001 updatedPkg.resourcePathString = scanFile.toString(); 7002 } 7003 updatedPkg.pkg = pkg; 7004 updatedPkg.versionCode = pkg.mVersionCode; 7005 7006 // Update the disabled system child packages to point to the package too. 7007 final int childCount = updatedPkg.childPackageNames != null 7008 ? updatedPkg.childPackageNames.size() : 0; 7009 for (int i = 0; i < childCount; i++) { 7010 String childPackageName = updatedPkg.childPackageNames.get(i); 7011 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7012 childPackageName); 7013 if (updatedChildPkg != null) { 7014 updatedChildPkg.pkg = pkg; 7015 updatedChildPkg.versionCode = pkg.mVersionCode; 7016 } 7017 } 7018 7019 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7020 + scanFile + " ignored: updated version " + ps.versionCode 7021 + " better than this " + pkg.mVersionCode); 7022 } else { 7023 // The current app on the system partition is better than 7024 // what we have updated to on the data partition; switch 7025 // back to the system partition version. 7026 // At this point, its safely assumed that package installation for 7027 // apps in system partition will go through. If not there won't be a working 7028 // version of the app 7029 // writer 7030 synchronized (mPackages) { 7031 // Just remove the loaded entries from package lists. 7032 mPackages.remove(ps.name); 7033 } 7034 7035 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7036 + " reverting from " + ps.codePathString 7037 + ": new version " + pkg.mVersionCode 7038 + " better than installed " + ps.versionCode); 7039 7040 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7041 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7042 synchronized (mInstallLock) { 7043 args.cleanUpResourcesLI(); 7044 } 7045 synchronized (mPackages) { 7046 mSettings.enableSystemPackageLPw(ps.name); 7047 } 7048 updatedPkgBetter = true; 7049 } 7050 } 7051 } 7052 7053 if (updatedPkg != null) { 7054 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7055 // initially 7056 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7057 7058 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7059 // flag set initially 7060 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7061 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7062 } 7063 } 7064 7065 // Verify certificates against what was last scanned 7066 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7067 7068 /* 7069 * A new system app appeared, but we already had a non-system one of the 7070 * same name installed earlier. 7071 */ 7072 boolean shouldHideSystemApp = false; 7073 if (updatedPkg == null && ps != null 7074 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7075 /* 7076 * Check to make sure the signatures match first. If they don't, 7077 * wipe the installed application and its data. 7078 */ 7079 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7080 != PackageManager.SIGNATURE_MATCH) { 7081 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7082 + " signatures don't match existing userdata copy; removing"); 7083 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7084 "scanPackageInternalLI")) { 7085 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7086 } 7087 ps = null; 7088 } else { 7089 /* 7090 * If the newly-added system app is an older version than the 7091 * already installed version, hide it. It will be scanned later 7092 * and re-added like an update. 7093 */ 7094 if (pkg.mVersionCode <= ps.versionCode) { 7095 shouldHideSystemApp = true; 7096 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7097 + " but new version " + pkg.mVersionCode + " better than installed " 7098 + ps.versionCode + "; hiding system"); 7099 } else { 7100 /* 7101 * The newly found system app is a newer version that the 7102 * one previously installed. Simply remove the 7103 * already-installed application and replace it with our own 7104 * while keeping the application data. 7105 */ 7106 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7107 + " reverting from " + ps.codePathString + ": new version " 7108 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7109 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7110 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7111 synchronized (mInstallLock) { 7112 args.cleanUpResourcesLI(); 7113 } 7114 } 7115 } 7116 } 7117 7118 // The apk is forward locked (not public) if its code and resources 7119 // are kept in different files. (except for app in either system or 7120 // vendor path). 7121 // TODO grab this value from PackageSettings 7122 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7123 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7124 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7125 } 7126 } 7127 7128 // TODO: extend to support forward-locked splits 7129 String resourcePath = null; 7130 String baseResourcePath = null; 7131 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7132 if (ps != null && ps.resourcePathString != null) { 7133 resourcePath = ps.resourcePathString; 7134 baseResourcePath = ps.resourcePathString; 7135 } else { 7136 // Should not happen at all. Just log an error. 7137 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7138 } 7139 } else { 7140 resourcePath = pkg.codePath; 7141 baseResourcePath = pkg.baseCodePath; 7142 } 7143 7144 // Set application objects path explicitly. 7145 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7146 pkg.setApplicationInfoCodePath(pkg.codePath); 7147 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7148 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7149 pkg.setApplicationInfoResourcePath(resourcePath); 7150 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7151 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7152 7153 // Note that we invoke the following method only if we are about to unpack an application 7154 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7155 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7156 7157 /* 7158 * If the system app should be overridden by a previously installed 7159 * data, hide the system app now and let the /data/app scan pick it up 7160 * again. 7161 */ 7162 if (shouldHideSystemApp) { 7163 synchronized (mPackages) { 7164 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7165 } 7166 } 7167 7168 return scannedPkg; 7169 } 7170 7171 private static String fixProcessName(String defProcessName, 7172 String processName) { 7173 if (processName == null) { 7174 return defProcessName; 7175 } 7176 return processName; 7177 } 7178 7179 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7180 throws PackageManagerException { 7181 if (pkgSetting.signatures.mSignatures != null) { 7182 // Already existing package. Make sure signatures match 7183 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7184 == PackageManager.SIGNATURE_MATCH; 7185 if (!match) { 7186 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7187 == PackageManager.SIGNATURE_MATCH; 7188 } 7189 if (!match) { 7190 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7191 == PackageManager.SIGNATURE_MATCH; 7192 } 7193 if (!match) { 7194 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7195 + pkg.packageName + " signatures do not match the " 7196 + "previously installed version; ignoring!"); 7197 } 7198 } 7199 7200 // Check for shared user signatures 7201 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7202 // Already existing package. Make sure signatures match 7203 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7204 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7205 if (!match) { 7206 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7207 == PackageManager.SIGNATURE_MATCH; 7208 } 7209 if (!match) { 7210 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7211 == PackageManager.SIGNATURE_MATCH; 7212 } 7213 if (!match) { 7214 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7215 "Package " + pkg.packageName 7216 + " has no signatures that match those in shared user " 7217 + pkgSetting.sharedUser.name + "; ignoring!"); 7218 } 7219 } 7220 } 7221 7222 /** 7223 * Enforces that only the system UID or root's UID can call a method exposed 7224 * via Binder. 7225 * 7226 * @param message used as message if SecurityException is thrown 7227 * @throws SecurityException if the caller is not system or root 7228 */ 7229 private static final void enforceSystemOrRoot(String message) { 7230 final int uid = Binder.getCallingUid(); 7231 if (uid != Process.SYSTEM_UID && uid != 0) { 7232 throw new SecurityException(message); 7233 } 7234 } 7235 7236 @Override 7237 public void performFstrimIfNeeded() { 7238 enforceSystemOrRoot("Only the system can request fstrim"); 7239 7240 // Before everything else, see whether we need to fstrim. 7241 try { 7242 IStorageManager sm = PackageHelper.getStorageManager(); 7243 if (sm != null) { 7244 boolean doTrim = false; 7245 final long interval = android.provider.Settings.Global.getLong( 7246 mContext.getContentResolver(), 7247 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7248 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7249 if (interval > 0) { 7250 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7251 if (timeSinceLast > interval) { 7252 doTrim = true; 7253 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7254 + "; running immediately"); 7255 } 7256 } 7257 if (doTrim) { 7258 final boolean dexOptDialogShown; 7259 synchronized (mPackages) { 7260 dexOptDialogShown = mDexOptDialogShown; 7261 } 7262 if (!isFirstBoot() && dexOptDialogShown) { 7263 try { 7264 ActivityManager.getService().showBootMessage( 7265 mContext.getResources().getString( 7266 R.string.android_upgrading_fstrim), true); 7267 } catch (RemoteException e) { 7268 } 7269 } 7270 sm.runMaintenance(); 7271 } 7272 } else { 7273 Slog.e(TAG, "storageManager service unavailable!"); 7274 } 7275 } catch (RemoteException e) { 7276 // Can't happen; StorageManagerService is local 7277 } 7278 } 7279 7280 @Override 7281 public void updatePackagesIfNeeded() { 7282 enforceSystemOrRoot("Only the system can request package update"); 7283 7284 // We need to re-extract after an OTA. 7285 boolean causeUpgrade = isUpgrade(); 7286 7287 // First boot or factory reset. 7288 // Note: we also handle devices that are upgrading to N right now as if it is their 7289 // first boot, as they do not have profile data. 7290 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7291 7292 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7293 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7294 7295 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7296 return; 7297 } 7298 7299 List<PackageParser.Package> pkgs; 7300 synchronized (mPackages) { 7301 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7302 } 7303 7304 final long startTime = System.nanoTime(); 7305 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7306 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7307 7308 final int elapsedTimeSeconds = 7309 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7310 7311 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7312 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7313 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7314 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7315 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7316 } 7317 7318 /** 7319 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7320 * containing statistics about the invocation. The array consists of three elements, 7321 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7322 * and {@code numberOfPackagesFailed}. 7323 */ 7324 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7325 String compilerFilter) { 7326 7327 int numberOfPackagesVisited = 0; 7328 int numberOfPackagesOptimized = 0; 7329 int numberOfPackagesSkipped = 0; 7330 int numberOfPackagesFailed = 0; 7331 final int numberOfPackagesToDexopt = pkgs.size(); 7332 7333 for (PackageParser.Package pkg : pkgs) { 7334 numberOfPackagesVisited++; 7335 7336 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7337 if (DEBUG_DEXOPT) { 7338 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7339 } 7340 numberOfPackagesSkipped++; 7341 continue; 7342 } 7343 7344 if (DEBUG_DEXOPT) { 7345 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7346 numberOfPackagesToDexopt + ": " + pkg.packageName); 7347 } 7348 7349 if (showDialog) { 7350 try { 7351 ActivityManager.getService().showBootMessage( 7352 mContext.getResources().getString(R.string.android_upgrading_apk, 7353 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7354 } catch (RemoteException e) { 7355 } 7356 synchronized (mPackages) { 7357 mDexOptDialogShown = true; 7358 } 7359 } 7360 7361 // If the OTA updates a system app which was previously preopted to a non-preopted state 7362 // the app might end up being verified at runtime. That's because by default the apps 7363 // are verify-profile but for preopted apps there's no profile. 7364 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7365 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7366 // filter (by default interpret-only). 7367 // Note that at this stage unused apps are already filtered. 7368 if (isSystemApp(pkg) && 7369 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7370 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7371 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7372 } 7373 7374 // If the OTA updates a system app which was previously preopted to a non-preopted state 7375 // the app might end up being verified at runtime. That's because by default the apps 7376 // are verify-profile but for preopted apps there's no profile. 7377 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7378 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7379 // filter (by default interpret-only). 7380 // Note that at this stage unused apps are already filtered. 7381 if (isSystemApp(pkg) && 7382 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7383 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7384 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7385 } 7386 7387 // checkProfiles is false to avoid merging profiles during boot which 7388 // might interfere with background compilation (b/28612421). 7389 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7390 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7391 // trade-off worth doing to save boot time work. 7392 int dexOptStatus = performDexOptTraced(pkg.packageName, 7393 false /* checkProfiles */, 7394 compilerFilter, 7395 false /* force */); 7396 switch (dexOptStatus) { 7397 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7398 numberOfPackagesOptimized++; 7399 break; 7400 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7401 numberOfPackagesSkipped++; 7402 break; 7403 case PackageDexOptimizer.DEX_OPT_FAILED: 7404 numberOfPackagesFailed++; 7405 break; 7406 default: 7407 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7408 break; 7409 } 7410 } 7411 7412 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7413 numberOfPackagesFailed }; 7414 } 7415 7416 @Override 7417 public void notifyPackageUse(String packageName, int reason) { 7418 synchronized (mPackages) { 7419 PackageParser.Package p = mPackages.get(packageName); 7420 if (p == null) { 7421 return; 7422 } 7423 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7424 } 7425 } 7426 7427 // TODO: this is not used nor needed. Delete it. 7428 @Override 7429 public boolean performDexOptIfNeeded(String packageName) { 7430 int dexOptStatus = performDexOptTraced(packageName, 7431 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7432 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7433 } 7434 7435 @Override 7436 public boolean performDexOpt(String packageName, 7437 boolean checkProfiles, int compileReason, boolean force) { 7438 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7439 getCompilerFilterForReason(compileReason), force); 7440 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7441 } 7442 7443 @Override 7444 public boolean performDexOptMode(String packageName, 7445 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7446 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7447 targetCompilerFilter, force); 7448 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7449 } 7450 7451 private int performDexOptTraced(String packageName, 7452 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7453 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7454 try { 7455 return performDexOptInternal(packageName, checkProfiles, 7456 targetCompilerFilter, force); 7457 } finally { 7458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7459 } 7460 } 7461 7462 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7463 // if the package can now be considered up to date for the given filter. 7464 private int performDexOptInternal(String packageName, 7465 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7466 PackageParser.Package p; 7467 synchronized (mPackages) { 7468 p = mPackages.get(packageName); 7469 if (p == null) { 7470 // Package could not be found. Report failure. 7471 return PackageDexOptimizer.DEX_OPT_FAILED; 7472 } 7473 mPackageUsage.maybeWriteAsync(mPackages); 7474 mCompilerStats.maybeWriteAsync(); 7475 } 7476 long callingId = Binder.clearCallingIdentity(); 7477 try { 7478 synchronized (mInstallLock) { 7479 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7480 targetCompilerFilter, force); 7481 } 7482 } finally { 7483 Binder.restoreCallingIdentity(callingId); 7484 } 7485 } 7486 7487 public ArraySet<String> getOptimizablePackages() { 7488 ArraySet<String> pkgs = new ArraySet<String>(); 7489 synchronized (mPackages) { 7490 for (PackageParser.Package p : mPackages.values()) { 7491 if (PackageDexOptimizer.canOptimizePackage(p)) { 7492 pkgs.add(p.packageName); 7493 } 7494 } 7495 } 7496 return pkgs; 7497 } 7498 7499 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7500 boolean checkProfiles, String targetCompilerFilter, 7501 boolean force) { 7502 // Select the dex optimizer based on the force parameter. 7503 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7504 // allocate an object here. 7505 PackageDexOptimizer pdo = force 7506 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7507 : mPackageDexOptimizer; 7508 7509 // Optimize all dependencies first. Note: we ignore the return value and march on 7510 // on errors. 7511 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7512 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7513 if (!deps.isEmpty()) { 7514 for (PackageParser.Package depPackage : deps) { 7515 // TODO: Analyze and investigate if we (should) profile libraries. 7516 // Currently this will do a full compilation of the library by default. 7517 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7518 false /* checkProfiles */, 7519 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7520 getOrCreateCompilerPackageStats(depPackage)); 7521 } 7522 } 7523 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7524 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7525 } 7526 7527 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7528 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7529 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7530 Set<String> collectedNames = new HashSet<>(); 7531 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7532 7533 retValue.remove(p); 7534 7535 return retValue; 7536 } else { 7537 return Collections.emptyList(); 7538 } 7539 } 7540 7541 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7542 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7543 if (!collectedNames.contains(p.packageName)) { 7544 collectedNames.add(p.packageName); 7545 collected.add(p); 7546 7547 if (p.usesLibraries != null) { 7548 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7549 } 7550 if (p.usesOptionalLibraries != null) { 7551 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7552 collectedNames); 7553 } 7554 } 7555 } 7556 7557 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7558 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7559 for (String libName : libs) { 7560 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7561 if (libPkg != null) { 7562 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7563 } 7564 } 7565 } 7566 7567 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7568 synchronized (mPackages) { 7569 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7570 if (lib != null && lib.apk != null) { 7571 return mPackages.get(lib.apk); 7572 } 7573 } 7574 return null; 7575 } 7576 7577 public void shutdown() { 7578 mPackageUsage.writeNow(mPackages); 7579 mCompilerStats.writeNow(); 7580 } 7581 7582 @Override 7583 public void dumpProfiles(String packageName) { 7584 PackageParser.Package pkg; 7585 synchronized (mPackages) { 7586 pkg = mPackages.get(packageName); 7587 if (pkg == null) { 7588 throw new IllegalArgumentException("Unknown package: " + packageName); 7589 } 7590 } 7591 /* Only the shell, root, or the app user should be able to dump profiles. */ 7592 int callingUid = Binder.getCallingUid(); 7593 if (callingUid != Process.SHELL_UID && 7594 callingUid != Process.ROOT_UID && 7595 callingUid != pkg.applicationInfo.uid) { 7596 throw new SecurityException("dumpProfiles"); 7597 } 7598 7599 synchronized (mInstallLock) { 7600 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7601 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7602 try { 7603 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7604 String gid = Integer.toString(sharedGid); 7605 String codePaths = TextUtils.join(";", allCodePaths); 7606 mInstaller.dumpProfiles(gid, packageName, codePaths); 7607 } catch (InstallerException e) { 7608 Slog.w(TAG, "Failed to dump profiles", e); 7609 } 7610 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7611 } 7612 } 7613 7614 @Override 7615 public void forceDexOpt(String packageName) { 7616 enforceSystemOrRoot("forceDexOpt"); 7617 7618 PackageParser.Package pkg; 7619 synchronized (mPackages) { 7620 pkg = mPackages.get(packageName); 7621 if (pkg == null) { 7622 throw new IllegalArgumentException("Unknown package: " + packageName); 7623 } 7624 } 7625 7626 synchronized (mInstallLock) { 7627 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7628 7629 // Whoever is calling forceDexOpt wants a fully compiled package. 7630 // Don't use profiles since that may cause compilation to be skipped. 7631 final int res = performDexOptInternalWithDependenciesLI(pkg, 7632 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7633 true /* force */); 7634 7635 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7636 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7637 throw new IllegalStateException("Failed to dexopt: " + res); 7638 } 7639 } 7640 } 7641 7642 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7643 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7644 Slog.w(TAG, "Unable to update from " + oldPkg.name 7645 + " to " + newPkg.packageName 7646 + ": old package not in system partition"); 7647 return false; 7648 } else if (mPackages.get(oldPkg.name) != null) { 7649 Slog.w(TAG, "Unable to update from " + oldPkg.name 7650 + " to " + newPkg.packageName 7651 + ": old package still exists"); 7652 return false; 7653 } 7654 return true; 7655 } 7656 7657 void removeCodePathLI(File codePath) { 7658 if (codePath.isDirectory()) { 7659 try { 7660 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7661 } catch (InstallerException e) { 7662 Slog.w(TAG, "Failed to remove code path", e); 7663 } 7664 } else { 7665 codePath.delete(); 7666 } 7667 } 7668 7669 private int[] resolveUserIds(int userId) { 7670 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7671 } 7672 7673 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7674 if (pkg == null) { 7675 Slog.wtf(TAG, "Package was null!", new Throwable()); 7676 return; 7677 } 7678 clearAppDataLeafLIF(pkg, userId, flags); 7679 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7680 for (int i = 0; i < childCount; i++) { 7681 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7682 } 7683 } 7684 7685 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7686 final PackageSetting ps; 7687 synchronized (mPackages) { 7688 ps = mSettings.mPackages.get(pkg.packageName); 7689 } 7690 for (int realUserId : resolveUserIds(userId)) { 7691 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7692 try { 7693 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7694 ceDataInode); 7695 } catch (InstallerException e) { 7696 Slog.w(TAG, String.valueOf(e)); 7697 } 7698 } 7699 } 7700 7701 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7702 if (pkg == null) { 7703 Slog.wtf(TAG, "Package was null!", new Throwable()); 7704 return; 7705 } 7706 destroyAppDataLeafLIF(pkg, userId, flags); 7707 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7708 for (int i = 0; i < childCount; i++) { 7709 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7710 } 7711 } 7712 7713 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7714 final PackageSetting ps; 7715 synchronized (mPackages) { 7716 ps = mSettings.mPackages.get(pkg.packageName); 7717 } 7718 for (int realUserId : resolveUserIds(userId)) { 7719 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7720 try { 7721 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7722 ceDataInode); 7723 } catch (InstallerException e) { 7724 Slog.w(TAG, String.valueOf(e)); 7725 } 7726 } 7727 } 7728 7729 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7730 if (pkg == null) { 7731 Slog.wtf(TAG, "Package was null!", new Throwable()); 7732 return; 7733 } 7734 destroyAppProfilesLeafLIF(pkg); 7735 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7736 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7737 for (int i = 0; i < childCount; i++) { 7738 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7739 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7740 true /* removeBaseMarker */); 7741 } 7742 } 7743 7744 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7745 boolean removeBaseMarker) { 7746 if (pkg.isForwardLocked()) { 7747 return; 7748 } 7749 7750 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7751 try { 7752 path = PackageManagerServiceUtils.realpath(new File(path)); 7753 } catch (IOException e) { 7754 // TODO: Should we return early here ? 7755 Slog.w(TAG, "Failed to get canonical path", e); 7756 continue; 7757 } 7758 7759 final String useMarker = path.replace('/', '@'); 7760 for (int realUserId : resolveUserIds(userId)) { 7761 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7762 if (removeBaseMarker) { 7763 File foreignUseMark = new File(profileDir, useMarker); 7764 if (foreignUseMark.exists()) { 7765 if (!foreignUseMark.delete()) { 7766 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7767 + pkg.packageName); 7768 } 7769 } 7770 } 7771 7772 File[] markers = profileDir.listFiles(); 7773 if (markers != null) { 7774 final String searchString = "@" + pkg.packageName + "@"; 7775 // We also delete all markers that contain the package name we're 7776 // uninstalling. These are associated with secondary dex-files belonging 7777 // to the package. Reconstructing the path of these dex files is messy 7778 // in general. 7779 for (File marker : markers) { 7780 if (marker.getName().indexOf(searchString) > 0) { 7781 if (!marker.delete()) { 7782 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7783 + pkg.packageName); 7784 } 7785 } 7786 } 7787 } 7788 } 7789 } 7790 } 7791 7792 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7793 try { 7794 mInstaller.destroyAppProfiles(pkg.packageName); 7795 } catch (InstallerException e) { 7796 Slog.w(TAG, String.valueOf(e)); 7797 } 7798 } 7799 7800 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7801 if (pkg == null) { 7802 Slog.wtf(TAG, "Package was null!", new Throwable()); 7803 return; 7804 } 7805 clearAppProfilesLeafLIF(pkg); 7806 // We don't remove the base foreign use marker when clearing profiles because 7807 // we will rename it when the app is updated. Unlike the actual profile contents, 7808 // the foreign use marker is good across installs. 7809 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7810 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7811 for (int i = 0; i < childCount; i++) { 7812 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7813 } 7814 } 7815 7816 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7817 try { 7818 mInstaller.clearAppProfiles(pkg.packageName); 7819 } catch (InstallerException e) { 7820 Slog.w(TAG, String.valueOf(e)); 7821 } 7822 } 7823 7824 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7825 long lastUpdateTime) { 7826 // Set parent install/update time 7827 PackageSetting ps = (PackageSetting) pkg.mExtras; 7828 if (ps != null) { 7829 ps.firstInstallTime = firstInstallTime; 7830 ps.lastUpdateTime = lastUpdateTime; 7831 } 7832 // Set children install/update time 7833 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7834 for (int i = 0; i < childCount; i++) { 7835 PackageParser.Package childPkg = pkg.childPackages.get(i); 7836 ps = (PackageSetting) childPkg.mExtras; 7837 if (ps != null) { 7838 ps.firstInstallTime = firstInstallTime; 7839 ps.lastUpdateTime = lastUpdateTime; 7840 } 7841 } 7842 } 7843 7844 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7845 PackageParser.Package changingLib) { 7846 if (file.path != null) { 7847 usesLibraryFiles.add(file.path); 7848 return; 7849 } 7850 PackageParser.Package p = mPackages.get(file.apk); 7851 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7852 // If we are doing this while in the middle of updating a library apk, 7853 // then we need to make sure to use that new apk for determining the 7854 // dependencies here. (We haven't yet finished committing the new apk 7855 // to the package manager state.) 7856 if (p == null || p.packageName.equals(changingLib.packageName)) { 7857 p = changingLib; 7858 } 7859 } 7860 if (p != null) { 7861 usesLibraryFiles.addAll(p.getAllCodePaths()); 7862 } 7863 } 7864 7865 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 7866 PackageParser.Package changingLib) throws PackageManagerException { 7867 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7868 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7869 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7870 for (int i=0; i<N; i++) { 7871 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7872 if (file == null) { 7873 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7874 "Package " + pkg.packageName + " requires unavailable shared library " 7875 + pkg.usesLibraries.get(i) + "; failing!"); 7876 } 7877 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7878 } 7879 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7880 for (int i=0; i<N; i++) { 7881 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7882 if (file == null) { 7883 Slog.w(TAG, "Package " + pkg.packageName 7884 + " desires unavailable shared library " 7885 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7886 } else { 7887 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7888 } 7889 } 7890 N = usesLibraryFiles.size(); 7891 if (N > 0) { 7892 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7893 } else { 7894 pkg.usesLibraryFiles = null; 7895 } 7896 } 7897 } 7898 7899 private static boolean hasString(List<String> list, List<String> which) { 7900 if (list == null) { 7901 return false; 7902 } 7903 for (int i=list.size()-1; i>=0; i--) { 7904 for (int j=which.size()-1; j>=0; j--) { 7905 if (which.get(j).equals(list.get(i))) { 7906 return true; 7907 } 7908 } 7909 } 7910 return false; 7911 } 7912 7913 private void updateAllSharedLibrariesLPw() { 7914 for (PackageParser.Package pkg : mPackages.values()) { 7915 try { 7916 updateSharedLibrariesLPr(pkg, null); 7917 } catch (PackageManagerException e) { 7918 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7919 } 7920 } 7921 } 7922 7923 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7924 PackageParser.Package changingPkg) { 7925 ArrayList<PackageParser.Package> res = null; 7926 for (PackageParser.Package pkg : mPackages.values()) { 7927 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7928 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7929 if (res == null) { 7930 res = new ArrayList<PackageParser.Package>(); 7931 } 7932 res.add(pkg); 7933 try { 7934 updateSharedLibrariesLPr(pkg, changingPkg); 7935 } catch (PackageManagerException e) { 7936 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7937 } 7938 } 7939 } 7940 return res; 7941 } 7942 7943 /** 7944 * Derive the value of the {@code cpuAbiOverride} based on the provided 7945 * value and an optional stored value from the package settings. 7946 */ 7947 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7948 String cpuAbiOverride = null; 7949 7950 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7951 cpuAbiOverride = null; 7952 } else if (abiOverride != null) { 7953 cpuAbiOverride = abiOverride; 7954 } else if (settings != null) { 7955 cpuAbiOverride = settings.cpuAbiOverrideString; 7956 } 7957 7958 return cpuAbiOverride; 7959 } 7960 7961 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7962 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7963 throws PackageManagerException { 7964 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7965 // If the package has children and this is the first dive in the function 7966 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7967 // whether all packages (parent and children) would be successfully scanned 7968 // before the actual scan since scanning mutates internal state and we want 7969 // to atomically install the package and its children. 7970 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7971 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7972 scanFlags |= SCAN_CHECK_ONLY; 7973 } 7974 } else { 7975 scanFlags &= ~SCAN_CHECK_ONLY; 7976 } 7977 7978 final PackageParser.Package scannedPkg; 7979 try { 7980 // Scan the parent 7981 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7982 // Scan the children 7983 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7984 for (int i = 0; i < childCount; i++) { 7985 PackageParser.Package childPkg = pkg.childPackages.get(i); 7986 scanPackageLI(childPkg, policyFlags, 7987 scanFlags, currentTime, user); 7988 } 7989 } finally { 7990 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7991 } 7992 7993 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7994 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7995 } 7996 7997 return scannedPkg; 7998 } 7999 8000 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8001 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8002 boolean success = false; 8003 try { 8004 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8005 currentTime, user); 8006 success = true; 8007 return res; 8008 } finally { 8009 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8010 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8011 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8012 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8013 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8014 } 8015 } 8016 } 8017 8018 /** 8019 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8020 */ 8021 private static boolean apkHasCode(String fileName) { 8022 StrictJarFile jarFile = null; 8023 try { 8024 jarFile = new StrictJarFile(fileName, 8025 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8026 return jarFile.findEntry("classes.dex") != null; 8027 } catch (IOException ignore) { 8028 } finally { 8029 try { 8030 if (jarFile != null) { 8031 jarFile.close(); 8032 } 8033 } catch (IOException ignore) {} 8034 } 8035 return false; 8036 } 8037 8038 /** 8039 * Enforces code policy for the package. This ensures that if an APK has 8040 * declared hasCode="true" in its manifest that the APK actually contains 8041 * code. 8042 * 8043 * @throws PackageManagerException If bytecode could not be found when it should exist 8044 */ 8045 private static void assertCodePolicy(PackageParser.Package pkg) 8046 throws PackageManagerException { 8047 final boolean shouldHaveCode = 8048 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8049 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8050 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8051 "Package " + pkg.baseCodePath + " code is missing"); 8052 } 8053 8054 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8055 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8056 final boolean splitShouldHaveCode = 8057 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8058 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8059 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8060 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8061 } 8062 } 8063 } 8064 } 8065 8066 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8067 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8068 throws PackageManagerException { 8069 if (DEBUG_PACKAGE_SCANNING) { 8070 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8071 Log.d(TAG, "Scanning package " + pkg.packageName); 8072 } 8073 8074 applyPolicy(pkg, policyFlags); 8075 8076 assertPackageIsValid(pkg, policyFlags); 8077 8078 // Initialize package source and resource directories 8079 final File scanFile = new File(pkg.codePath); 8080 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8081 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8082 8083 SharedUserSetting suid = null; 8084 PackageSetting pkgSetting = null; 8085 8086 // Getting the package setting may have a side-effect, so if we 8087 // are only checking if scan would succeed, stash a copy of the 8088 // old setting to restore at the end. 8089 PackageSetting nonMutatedPs = null; 8090 8091 // writer 8092 synchronized (mPackages) { 8093 if (pkg.mSharedUserId != null) { 8094 // SIDE EFFECTS; may potentially allocate a new shared user 8095 suid = mSettings.getSharedUserLPw( 8096 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8097 if (DEBUG_PACKAGE_SCANNING) { 8098 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8099 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8100 + "): packages=" + suid.packages); 8101 } 8102 } 8103 8104 // Check if we are renaming from an original package name. 8105 PackageSetting origPackage = null; 8106 String realName = null; 8107 if (pkg.mOriginalPackages != null) { 8108 // This package may need to be renamed to a previously 8109 // installed name. Let's check on that... 8110 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8111 if (pkg.mOriginalPackages.contains(renamed)) { 8112 // This package had originally been installed as the 8113 // original name, and we have already taken care of 8114 // transitioning to the new one. Just update the new 8115 // one to continue using the old name. 8116 realName = pkg.mRealPackage; 8117 if (!pkg.packageName.equals(renamed)) { 8118 // Callers into this function may have already taken 8119 // care of renaming the package; only do it here if 8120 // it is not already done. 8121 pkg.setPackageName(renamed); 8122 } 8123 } else { 8124 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8125 if ((origPackage = mSettings.getPackageLPr( 8126 pkg.mOriginalPackages.get(i))) != null) { 8127 // We do have the package already installed under its 8128 // original name... should we use it? 8129 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8130 // New package is not compatible with original. 8131 origPackage = null; 8132 continue; 8133 } else if (origPackage.sharedUser != null) { 8134 // Make sure uid is compatible between packages. 8135 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8136 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8137 + " to " + pkg.packageName + ": old uid " 8138 + origPackage.sharedUser.name 8139 + " differs from " + pkg.mSharedUserId); 8140 origPackage = null; 8141 continue; 8142 } 8143 // TODO: Add case when shared user id is added [b/28144775] 8144 } else { 8145 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8146 + pkg.packageName + " to old name " + origPackage.name); 8147 } 8148 break; 8149 } 8150 } 8151 } 8152 } 8153 8154 if (mTransferedPackages.contains(pkg.packageName)) { 8155 Slog.w(TAG, "Package " + pkg.packageName 8156 + " was transferred to another, but its .apk remains"); 8157 } 8158 8159 // See comments in nonMutatedPs declaration 8160 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8161 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8162 if (foundPs != null) { 8163 nonMutatedPs = new PackageSetting(foundPs); 8164 } 8165 } 8166 8167 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8168 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8169 PackageManagerService.reportSettingsProblem(Log.WARN, 8170 "Package " + pkg.packageName + " shared user changed from " 8171 + (pkgSetting.sharedUser != null 8172 ? pkgSetting.sharedUser.name : "<nothing>") 8173 + " to " 8174 + (suid != null ? suid.name : "<nothing>") 8175 + "; replacing with new"); 8176 pkgSetting = null; 8177 } 8178 final PackageSetting oldPkgSetting = 8179 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8180 final PackageSetting disabledPkgSetting = 8181 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8182 if (pkgSetting == null) { 8183 final String parentPackageName = (pkg.parentPackage != null) 8184 ? pkg.parentPackage.packageName : null; 8185 // REMOVE SharedUserSetting from method; update in a separate call 8186 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8187 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8188 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8189 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8190 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8191 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8192 UserManagerService.getInstance()); 8193 // SIDE EFFECTS; updates system state; move elsewhere 8194 if (origPackage != null) { 8195 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8196 } 8197 mSettings.addUserToSettingLPw(pkgSetting); 8198 } else { 8199 // REMOVE SharedUserSetting from method; update in a separate call 8200 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8201 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8202 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8203 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8204 UserManagerService.getInstance()); 8205 } 8206 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8207 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8208 8209 // SIDE EFFECTS; modifies system state; move elsewhere 8210 if (pkgSetting.origPackage != null) { 8211 // If we are first transitioning from an original package, 8212 // fix up the new package's name now. We need to do this after 8213 // looking up the package under its new name, so getPackageLP 8214 // can take care of fiddling things correctly. 8215 pkg.setPackageName(origPackage.name); 8216 8217 // File a report about this. 8218 String msg = "New package " + pkgSetting.realName 8219 + " renamed to replace old package " + pkgSetting.name; 8220 reportSettingsProblem(Log.WARN, msg); 8221 8222 // Make a note of it. 8223 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8224 mTransferedPackages.add(origPackage.name); 8225 } 8226 8227 // No longer need to retain this. 8228 pkgSetting.origPackage = null; 8229 } 8230 8231 // SIDE EFFECTS; modifies system state; move elsewhere 8232 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8233 // Make a note of it. 8234 mTransferedPackages.add(pkg.packageName); 8235 } 8236 8237 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8238 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8239 } 8240 8241 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8242 // Check all shared libraries and map to their actual file path. 8243 // We only do this here for apps not on a system dir, because those 8244 // are the only ones that can fail an install due to this. We 8245 // will take care of the system apps by updating all of their 8246 // library paths after the scan is done. 8247 updateSharedLibrariesLPr(pkg, null); 8248 } 8249 8250 if (mFoundPolicyFile) { 8251 SELinuxMMAC.assignSeinfoValue(pkg); 8252 } 8253 8254 pkg.applicationInfo.uid = pkgSetting.appId; 8255 pkg.mExtras = pkgSetting; 8256 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8257 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8258 // We just determined the app is signed correctly, so bring 8259 // over the latest parsed certs. 8260 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8261 } else { 8262 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8263 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8264 "Package " + pkg.packageName + " upgrade keys do not match the " 8265 + "previously installed version"); 8266 } else { 8267 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8268 String msg = "System package " + pkg.packageName 8269 + " signature changed; retaining data."; 8270 reportSettingsProblem(Log.WARN, msg); 8271 } 8272 } 8273 } else { 8274 try { 8275 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8276 verifySignaturesLP(pkgSetting, pkg); 8277 // We just determined the app is signed correctly, so bring 8278 // over the latest parsed certs. 8279 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8280 } catch (PackageManagerException e) { 8281 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8282 throw e; 8283 } 8284 // The signature has changed, but this package is in the system 8285 // image... let's recover! 8286 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8287 // However... if this package is part of a shared user, but it 8288 // doesn't match the signature of the shared user, let's fail. 8289 // What this means is that you can't change the signatures 8290 // associated with an overall shared user, which doesn't seem all 8291 // that unreasonable. 8292 if (pkgSetting.sharedUser != null) { 8293 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8294 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8295 throw new PackageManagerException( 8296 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8297 "Signature mismatch for shared user: " 8298 + pkgSetting.sharedUser); 8299 } 8300 } 8301 // File a report about this. 8302 String msg = "System package " + pkg.packageName 8303 + " signature changed; retaining data."; 8304 reportSettingsProblem(Log.WARN, msg); 8305 } 8306 } 8307 8308 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8309 // This package wants to adopt ownership of permissions from 8310 // another package. 8311 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8312 final String origName = pkg.mAdoptPermissions.get(i); 8313 final PackageSetting orig = mSettings.getPackageLPr(origName); 8314 if (orig != null) { 8315 if (verifyPackageUpdateLPr(orig, pkg)) { 8316 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8317 + pkg.packageName); 8318 // SIDE EFFECTS; updates permissions system state; move elsewhere 8319 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8320 } 8321 } 8322 } 8323 } 8324 } 8325 8326 pkg.applicationInfo.processName = fixProcessName( 8327 pkg.applicationInfo.packageName, 8328 pkg.applicationInfo.processName); 8329 8330 if (pkg != mPlatformPackage) { 8331 // Get all of our default paths setup 8332 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8333 } 8334 8335 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8336 8337 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8338 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8339 derivePackageAbi( 8340 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8341 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8342 8343 // Some system apps still use directory structure for native libraries 8344 // in which case we might end up not detecting abi solely based on apk 8345 // structure. Try to detect abi based on directory structure. 8346 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8347 pkg.applicationInfo.primaryCpuAbi == null) { 8348 setBundledAppAbisAndRoots(pkg, pkgSetting); 8349 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8350 } 8351 } else { 8352 if ((scanFlags & SCAN_MOVE) != 0) { 8353 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8354 // but we already have this packages package info in the PackageSetting. We just 8355 // use that and derive the native library path based on the new codepath. 8356 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8357 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8358 } 8359 8360 // Set native library paths again. For moves, the path will be updated based on the 8361 // ABIs we've determined above. For non-moves, the path will be updated based on the 8362 // ABIs we determined during compilation, but the path will depend on the final 8363 // package path (after the rename away from the stage path). 8364 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8365 } 8366 8367 // This is a special case for the "system" package, where the ABI is 8368 // dictated by the zygote configuration (and init.rc). We should keep track 8369 // of this ABI so that we can deal with "normal" applications that run under 8370 // the same UID correctly. 8371 if (mPlatformPackage == pkg) { 8372 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8373 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8374 } 8375 8376 // If there's a mismatch between the abi-override in the package setting 8377 // and the abiOverride specified for the install. Warn about this because we 8378 // would've already compiled the app without taking the package setting into 8379 // account. 8380 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8381 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8382 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8383 " for package " + pkg.packageName); 8384 } 8385 } 8386 8387 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8388 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8389 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8390 8391 // Copy the derived override back to the parsed package, so that we can 8392 // update the package settings accordingly. 8393 pkg.cpuAbiOverride = cpuAbiOverride; 8394 8395 if (DEBUG_ABI_SELECTION) { 8396 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8397 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8398 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8399 } 8400 8401 // Push the derived path down into PackageSettings so we know what to 8402 // clean up at uninstall time. 8403 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8404 8405 if (DEBUG_ABI_SELECTION) { 8406 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8407 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8408 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8409 } 8410 8411 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8412 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8413 // We don't do this here during boot because we can do it all 8414 // at once after scanning all existing packages. 8415 // 8416 // We also do this *before* we perform dexopt on this package, so that 8417 // we can avoid redundant dexopts, and also to make sure we've got the 8418 // code and package path correct. 8419 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8420 } 8421 8422 if (mFactoryTest && pkg.requestedPermissions.contains( 8423 android.Manifest.permission.FACTORY_TEST)) { 8424 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8425 } 8426 8427 if (isSystemApp(pkg)) { 8428 pkgSetting.isOrphaned = true; 8429 } 8430 8431 // Take care of first install / last update times. 8432 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8433 if (currentTime != 0) { 8434 if (pkgSetting.firstInstallTime == 0) { 8435 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8436 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8437 pkgSetting.lastUpdateTime = currentTime; 8438 } 8439 } else if (pkgSetting.firstInstallTime == 0) { 8440 // We need *something*. Take time time stamp of the file. 8441 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8442 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8443 if (scanFileTime != pkgSetting.timeStamp) { 8444 // A package on the system image has changed; consider this 8445 // to be an update. 8446 pkgSetting.lastUpdateTime = scanFileTime; 8447 } 8448 } 8449 pkgSetting.setTimeStamp(scanFileTime); 8450 8451 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8452 if (nonMutatedPs != null) { 8453 synchronized (mPackages) { 8454 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8455 } 8456 } 8457 } else { 8458 // Modify state for the given package setting 8459 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8460 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8461 } 8462 return pkg; 8463 } 8464 8465 /** 8466 * Applies policy to the parsed package based upon the given policy flags. 8467 * Ensures the package is in a good state. 8468 * <p> 8469 * Implementation detail: This method must NOT have any side effect. It would 8470 * ideally be static, but, it requires locks to read system state. 8471 */ 8472 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8473 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8474 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8475 if (pkg.applicationInfo.isDirectBootAware()) { 8476 // we're direct boot aware; set for all components 8477 for (PackageParser.Service s : pkg.services) { 8478 s.info.encryptionAware = s.info.directBootAware = true; 8479 } 8480 for (PackageParser.Provider p : pkg.providers) { 8481 p.info.encryptionAware = p.info.directBootAware = true; 8482 } 8483 for (PackageParser.Activity a : pkg.activities) { 8484 a.info.encryptionAware = a.info.directBootAware = true; 8485 } 8486 for (PackageParser.Activity r : pkg.receivers) { 8487 r.info.encryptionAware = r.info.directBootAware = true; 8488 } 8489 } 8490 } else { 8491 // Only allow system apps to be flagged as core apps. 8492 pkg.coreApp = false; 8493 // clear flags not applicable to regular apps 8494 pkg.applicationInfo.privateFlags &= 8495 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8496 pkg.applicationInfo.privateFlags &= 8497 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8498 } 8499 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8500 8501 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8502 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8503 } 8504 8505 if (!isSystemApp(pkg)) { 8506 // Only system apps can use these features. 8507 pkg.mOriginalPackages = null; 8508 pkg.mRealPackage = null; 8509 pkg.mAdoptPermissions = null; 8510 } 8511 } 8512 8513 /** 8514 * Asserts the parsed package is valid according to teh given policy. If the 8515 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8516 * <p> 8517 * Implementation detail: This method must NOT have any side effects. It would 8518 * ideally be static, but, it requires locks to read system state. 8519 * 8520 * @throws PackageManagerException If the package fails any of the validation checks 8521 */ 8522 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags) 8523 throws PackageManagerException { 8524 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8525 assertCodePolicy(pkg); 8526 } 8527 8528 if (pkg.applicationInfo.getCodePath() == null || 8529 pkg.applicationInfo.getResourcePath() == null) { 8530 // Bail out. The resource and code paths haven't been set. 8531 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8532 "Code and resource paths haven't been set correctly"); 8533 } 8534 8535 // Make sure we're not adding any bogus keyset info 8536 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8537 ksms.assertScannedPackageValid(pkg); 8538 8539 synchronized (mPackages) { 8540 // The special "android" package can only be defined once 8541 if (pkg.packageName.equals("android")) { 8542 if (mAndroidApplication != null) { 8543 Slog.w(TAG, "*************************************************"); 8544 Slog.w(TAG, "Core android package being redefined. Skipping."); 8545 Slog.w(TAG, " codePath=" + pkg.codePath); 8546 Slog.w(TAG, "*************************************************"); 8547 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8548 "Core android package being redefined. Skipping."); 8549 } 8550 } 8551 8552 // A package name must be unique; don't allow duplicates 8553 if (mPackages.containsKey(pkg.packageName) 8554 || mSharedLibraries.containsKey(pkg.packageName)) { 8555 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8556 "Application package " + pkg.packageName 8557 + " already installed. Skipping duplicate."); 8558 } 8559 8560 // Only privileged apps and updated privileged apps can add child packages. 8561 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8562 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8563 throw new PackageManagerException("Only privileged apps can add child " 8564 + "packages. Ignoring package " + pkg.packageName); 8565 } 8566 final int childCount = pkg.childPackages.size(); 8567 for (int i = 0; i < childCount; i++) { 8568 PackageParser.Package childPkg = pkg.childPackages.get(i); 8569 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8570 childPkg.packageName)) { 8571 throw new PackageManagerException("Can't override child of " 8572 + "another disabled app. Ignoring package " + pkg.packageName); 8573 } 8574 } 8575 } 8576 8577 // If we're only installing presumed-existing packages, require that the 8578 // scanned APK is both already known and at the path previously established 8579 // for it. Previously unknown packages we pick up normally, but if we have an 8580 // a priori expectation about this package's install presence, enforce it. 8581 // With a singular exception for new system packages. When an OTA contains 8582 // a new system package, we allow the codepath to change from a system location 8583 // to the user-installed location. If we don't allow this change, any newer, 8584 // user-installed version of the application will be ignored. 8585 if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) { 8586 if (mExpectingBetter.containsKey(pkg.packageName)) { 8587 logCriticalInfo(Log.WARN, 8588 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8589 } else { 8590 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8591 if (known != null) { 8592 if (DEBUG_PACKAGE_SCANNING) { 8593 Log.d(TAG, "Examining " + pkg.codePath 8594 + " and requiring known paths " + known.codePathString 8595 + " & " + known.resourcePathString); 8596 } 8597 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8598 || !pkg.applicationInfo.getResourcePath().equals( 8599 known.resourcePathString)) { 8600 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8601 "Application package " + pkg.packageName 8602 + " found at " + pkg.applicationInfo.getCodePath() 8603 + " but expected at " + known.codePathString 8604 + "; ignoring."); 8605 } 8606 } 8607 } 8608 } 8609 8610 // Verify that this new package doesn't have any content providers 8611 // that conflict with existing packages. Only do this if the 8612 // package isn't already installed, since we don't want to break 8613 // things that are installed. 8614 if ((policyFlags & SCAN_NEW_INSTALL) != 0) { 8615 final int N = pkg.providers.size(); 8616 int i; 8617 for (i=0; i<N; i++) { 8618 PackageParser.Provider p = pkg.providers.get(i); 8619 if (p.info.authority != null) { 8620 String names[] = p.info.authority.split(";"); 8621 for (int j = 0; j < names.length; j++) { 8622 if (mProvidersByAuthority.containsKey(names[j])) { 8623 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8624 final String otherPackageName = 8625 ((other != null && other.getComponentName() != null) ? 8626 other.getComponentName().getPackageName() : "?"); 8627 throw new PackageManagerException( 8628 INSTALL_FAILED_CONFLICTING_PROVIDER, 8629 "Can't install because provider name " + names[j] 8630 + " (in package " + pkg.applicationInfo.packageName 8631 + ") is already used by " + otherPackageName); 8632 } 8633 } 8634 } 8635 } 8636 } 8637 } 8638 } 8639 8640 /** 8641 * Adds a scanned package to the system. When this method is finished, the package will 8642 * be available for query, resolution, etc... 8643 */ 8644 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8645 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8646 final String pkgName = pkg.packageName; 8647 if (mCustomResolverComponentName != null && 8648 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8649 setUpCustomResolverActivity(pkg); 8650 } 8651 8652 if (pkg.packageName.equals("android")) { 8653 synchronized (mPackages) { 8654 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8655 // Set up information for our fall-back user intent resolution activity. 8656 mPlatformPackage = pkg; 8657 pkg.mVersionCode = mSdkVersion; 8658 mAndroidApplication = pkg.applicationInfo; 8659 8660 if (!mResolverReplaced) { 8661 mResolveActivity.applicationInfo = mAndroidApplication; 8662 mResolveActivity.name = ResolverActivity.class.getName(); 8663 mResolveActivity.packageName = mAndroidApplication.packageName; 8664 mResolveActivity.processName = "system:ui"; 8665 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8666 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8667 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8668 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8669 mResolveActivity.exported = true; 8670 mResolveActivity.enabled = true; 8671 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8672 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8673 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8674 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8675 | ActivityInfo.CONFIG_ORIENTATION 8676 | ActivityInfo.CONFIG_KEYBOARD 8677 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8678 mResolveInfo.activityInfo = mResolveActivity; 8679 mResolveInfo.priority = 0; 8680 mResolveInfo.preferredOrder = 0; 8681 mResolveInfo.match = 0; 8682 mResolveComponentName = new ComponentName( 8683 mAndroidApplication.packageName, mResolveActivity.name); 8684 } 8685 } 8686 } 8687 } 8688 8689 ArrayList<PackageParser.Package> clientLibPkgs = null; 8690 // writer 8691 synchronized (mPackages) { 8692 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8693 // Only system apps can add new shared libraries. 8694 if (pkg.libraryNames != null) { 8695 for (int i=0; i<pkg.libraryNames.size(); i++) { 8696 String name = pkg.libraryNames.get(i); 8697 boolean allowed = false; 8698 if (pkg.isUpdatedSystemApp()) { 8699 // New library entries can only be added through the 8700 // system image. This is important to get rid of a lot 8701 // of nasty edge cases: for example if we allowed a non- 8702 // system update of the app to add a library, then uninstalling 8703 // the update would make the library go away, and assumptions 8704 // we made such as through app install filtering would now 8705 // have allowed apps on the device which aren't compatible 8706 // with it. Better to just have the restriction here, be 8707 // conservative, and create many fewer cases that can negatively 8708 // impact the user experience. 8709 final PackageSetting sysPs = mSettings 8710 .getDisabledSystemPkgLPr(pkg.packageName); 8711 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8712 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8713 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8714 allowed = true; 8715 break; 8716 } 8717 } 8718 } 8719 } else { 8720 allowed = true; 8721 } 8722 if (allowed) { 8723 if (!mSharedLibraries.containsKey(name)) { 8724 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8725 } else if (!name.equals(pkg.packageName)) { 8726 Slog.w(TAG, "Package " + pkg.packageName + " library " 8727 + name + " already exists; skipping"); 8728 } 8729 } else { 8730 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8731 + name + " that is not declared on system image; skipping"); 8732 } 8733 } 8734 if ((scanFlags & SCAN_BOOTING) == 0) { 8735 // If we are not booting, we need to update any applications 8736 // that are clients of our shared library. If we are booting, 8737 // this will all be done once the scan is complete. 8738 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8739 } 8740 } 8741 } 8742 } 8743 8744 if ((scanFlags & SCAN_BOOTING) != 0) { 8745 // No apps can run during boot scan, so they don't need to be frozen 8746 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8747 // Caller asked to not kill app, so it's probably not frozen 8748 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8749 // Caller asked us to ignore frozen check for some reason; they 8750 // probably didn't know the package name 8751 } else { 8752 // We're doing major surgery on this package, so it better be frozen 8753 // right now to keep it from launching 8754 checkPackageFrozen(pkgName); 8755 } 8756 8757 // Also need to kill any apps that are dependent on the library. 8758 if (clientLibPkgs != null) { 8759 for (int i=0; i<clientLibPkgs.size(); i++) { 8760 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8761 killApplication(clientPkg.applicationInfo.packageName, 8762 clientPkg.applicationInfo.uid, "update lib"); 8763 } 8764 } 8765 8766 // writer 8767 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8768 8769 boolean createIdmapFailed = false; 8770 synchronized (mPackages) { 8771 // We don't expect installation to fail beyond this point 8772 8773 if (pkgSetting.pkg != null) { 8774 // Note that |user| might be null during the initial boot scan. If a codePath 8775 // for an app has changed during a boot scan, it's due to an app update that's 8776 // part of the system partition and marker changes must be applied to all users. 8777 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 8778 final int[] userIds = resolveUserIds(userId); 8779 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 8780 } 8781 8782 // Add the new setting to mSettings 8783 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8784 // Add the new setting to mPackages 8785 mPackages.put(pkg.applicationInfo.packageName, pkg); 8786 // Make sure we don't accidentally delete its data. 8787 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8788 while (iter.hasNext()) { 8789 PackageCleanItem item = iter.next(); 8790 if (pkgName.equals(item.packageName)) { 8791 iter.remove(); 8792 } 8793 } 8794 8795 // Add the package's KeySets to the global KeySetManagerService 8796 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8797 ksms.addScannedPackageLPw(pkg); 8798 8799 int N = pkg.providers.size(); 8800 StringBuilder r = null; 8801 int i; 8802 for (i=0; i<N; i++) { 8803 PackageParser.Provider p = pkg.providers.get(i); 8804 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8805 p.info.processName); 8806 mProviders.addProvider(p); 8807 p.syncable = p.info.isSyncable; 8808 if (p.info.authority != null) { 8809 String names[] = p.info.authority.split(";"); 8810 p.info.authority = null; 8811 for (int j = 0; j < names.length; j++) { 8812 if (j == 1 && p.syncable) { 8813 // We only want the first authority for a provider to possibly be 8814 // syncable, so if we already added this provider using a different 8815 // authority clear the syncable flag. We copy the provider before 8816 // changing it because the mProviders object contains a reference 8817 // to a provider that we don't want to change. 8818 // Only do this for the second authority since the resulting provider 8819 // object can be the same for all future authorities for this provider. 8820 p = new PackageParser.Provider(p); 8821 p.syncable = false; 8822 } 8823 if (!mProvidersByAuthority.containsKey(names[j])) { 8824 mProvidersByAuthority.put(names[j], p); 8825 if (p.info.authority == null) { 8826 p.info.authority = names[j]; 8827 } else { 8828 p.info.authority = p.info.authority + ";" + names[j]; 8829 } 8830 if (DEBUG_PACKAGE_SCANNING) { 8831 if (chatty) 8832 Log.d(TAG, "Registered content provider: " + names[j] 8833 + ", className = " + p.info.name + ", isSyncable = " 8834 + p.info.isSyncable); 8835 } 8836 } else { 8837 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8838 Slog.w(TAG, "Skipping provider name " + names[j] + 8839 " (in package " + pkg.applicationInfo.packageName + 8840 "): name already used by " 8841 + ((other != null && other.getComponentName() != null) 8842 ? other.getComponentName().getPackageName() : "?")); 8843 } 8844 } 8845 } 8846 if (chatty) { 8847 if (r == null) { 8848 r = new StringBuilder(256); 8849 } else { 8850 r.append(' '); 8851 } 8852 r.append(p.info.name); 8853 } 8854 } 8855 if (r != null) { 8856 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8857 } 8858 8859 N = pkg.services.size(); 8860 r = null; 8861 for (i=0; i<N; i++) { 8862 PackageParser.Service s = pkg.services.get(i); 8863 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8864 s.info.processName); 8865 mServices.addService(s); 8866 if (chatty) { 8867 if (r == null) { 8868 r = new StringBuilder(256); 8869 } else { 8870 r.append(' '); 8871 } 8872 r.append(s.info.name); 8873 } 8874 } 8875 if (r != null) { 8876 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8877 } 8878 8879 N = pkg.receivers.size(); 8880 r = null; 8881 for (i=0; i<N; i++) { 8882 PackageParser.Activity a = pkg.receivers.get(i); 8883 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8884 a.info.processName); 8885 mReceivers.addActivity(a, "receiver"); 8886 if (chatty) { 8887 if (r == null) { 8888 r = new StringBuilder(256); 8889 } else { 8890 r.append(' '); 8891 } 8892 r.append(a.info.name); 8893 } 8894 } 8895 if (r != null) { 8896 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8897 } 8898 8899 N = pkg.activities.size(); 8900 r = null; 8901 for (i=0; i<N; i++) { 8902 PackageParser.Activity a = pkg.activities.get(i); 8903 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8904 a.info.processName); 8905 mActivities.addActivity(a, "activity"); 8906 if (chatty) { 8907 if (r == null) { 8908 r = new StringBuilder(256); 8909 } else { 8910 r.append(' '); 8911 } 8912 r.append(a.info.name); 8913 } 8914 } 8915 if (r != null) { 8916 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8917 } 8918 8919 N = pkg.permissionGroups.size(); 8920 r = null; 8921 for (i=0; i<N; i++) { 8922 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8923 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8924 final String curPackageName = cur == null ? null : cur.info.packageName; 8925 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8926 if (cur == null || isPackageUpdate) { 8927 mPermissionGroups.put(pg.info.name, pg); 8928 if (chatty) { 8929 if (r == null) { 8930 r = new StringBuilder(256); 8931 } else { 8932 r.append(' '); 8933 } 8934 if (isPackageUpdate) { 8935 r.append("UPD:"); 8936 } 8937 r.append(pg.info.name); 8938 } 8939 } else { 8940 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8941 + pg.info.packageName + " ignored: original from " 8942 + cur.info.packageName); 8943 if (chatty) { 8944 if (r == null) { 8945 r = new StringBuilder(256); 8946 } else { 8947 r.append(' '); 8948 } 8949 r.append("DUP:"); 8950 r.append(pg.info.name); 8951 } 8952 } 8953 } 8954 if (r != null) { 8955 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8956 } 8957 8958 N = pkg.permissions.size(); 8959 r = null; 8960 for (i=0; i<N; i++) { 8961 PackageParser.Permission p = pkg.permissions.get(i); 8962 8963 // Assume by default that we did not install this permission into the system. 8964 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8965 8966 // Now that permission groups have a special meaning, we ignore permission 8967 // groups for legacy apps to prevent unexpected behavior. In particular, 8968 // permissions for one app being granted to someone just becase they happen 8969 // to be in a group defined by another app (before this had no implications). 8970 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8971 p.group = mPermissionGroups.get(p.info.group); 8972 // Warn for a permission in an unknown group. 8973 if (p.info.group != null && p.group == null) { 8974 Slog.w(TAG, "Permission " + p.info.name + " from package " 8975 + p.info.packageName + " in an unknown group " + p.info.group); 8976 } 8977 } 8978 8979 ArrayMap<String, BasePermission> permissionMap = 8980 p.tree ? mSettings.mPermissionTrees 8981 : mSettings.mPermissions; 8982 BasePermission bp = permissionMap.get(p.info.name); 8983 8984 // Allow system apps to redefine non-system permissions 8985 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8986 final boolean currentOwnerIsSystem = (bp.perm != null 8987 && isSystemApp(bp.perm.owner)); 8988 if (isSystemApp(p.owner)) { 8989 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8990 // It's a built-in permission and no owner, take ownership now 8991 bp.packageSetting = pkgSetting; 8992 bp.perm = p; 8993 bp.uid = pkg.applicationInfo.uid; 8994 bp.sourcePackage = p.info.packageName; 8995 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8996 } else if (!currentOwnerIsSystem) { 8997 String msg = "New decl " + p.owner + " of permission " 8998 + p.info.name + " is system; overriding " + bp.sourcePackage; 8999 reportSettingsProblem(Log.WARN, msg); 9000 bp = null; 9001 } 9002 } 9003 } 9004 9005 if (bp == null) { 9006 bp = new BasePermission(p.info.name, p.info.packageName, 9007 BasePermission.TYPE_NORMAL); 9008 permissionMap.put(p.info.name, bp); 9009 } 9010 9011 if (bp.perm == null) { 9012 if (bp.sourcePackage == null 9013 || bp.sourcePackage.equals(p.info.packageName)) { 9014 BasePermission tree = findPermissionTreeLP(p.info.name); 9015 if (tree == null 9016 || tree.sourcePackage.equals(p.info.packageName)) { 9017 bp.packageSetting = pkgSetting; 9018 bp.perm = p; 9019 bp.uid = pkg.applicationInfo.uid; 9020 bp.sourcePackage = p.info.packageName; 9021 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9022 if (chatty) { 9023 if (r == null) { 9024 r = new StringBuilder(256); 9025 } else { 9026 r.append(' '); 9027 } 9028 r.append(p.info.name); 9029 } 9030 } else { 9031 Slog.w(TAG, "Permission " + p.info.name + " from package " 9032 + p.info.packageName + " ignored: base tree " 9033 + tree.name + " is from package " 9034 + tree.sourcePackage); 9035 } 9036 } else { 9037 Slog.w(TAG, "Permission " + p.info.name + " from package " 9038 + p.info.packageName + " ignored: original from " 9039 + bp.sourcePackage); 9040 } 9041 } else if (chatty) { 9042 if (r == null) { 9043 r = new StringBuilder(256); 9044 } else { 9045 r.append(' '); 9046 } 9047 r.append("DUP:"); 9048 r.append(p.info.name); 9049 } 9050 if (bp.perm == p) { 9051 bp.protectionLevel = p.info.protectionLevel; 9052 } 9053 } 9054 9055 if (r != null) { 9056 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9057 } 9058 9059 N = pkg.instrumentation.size(); 9060 r = null; 9061 for (i=0; i<N; i++) { 9062 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9063 a.info.packageName = pkg.applicationInfo.packageName; 9064 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9065 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9066 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9067 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9068 a.info.dataDir = pkg.applicationInfo.dataDir; 9069 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9070 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9071 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9072 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9073 mInstrumentation.put(a.getComponentName(), a); 9074 if (chatty) { 9075 if (r == null) { 9076 r = new StringBuilder(256); 9077 } else { 9078 r.append(' '); 9079 } 9080 r.append(a.info.name); 9081 } 9082 } 9083 if (r != null) { 9084 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9085 } 9086 9087 if (pkg.protectedBroadcasts != null) { 9088 N = pkg.protectedBroadcasts.size(); 9089 for (i=0; i<N; i++) { 9090 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9091 } 9092 } 9093 9094 // Create idmap files for pairs of (packages, overlay packages). 9095 // Note: "android", ie framework-res.apk, is handled by native layers. 9096 if (pkg.mOverlayTarget != null) { 9097 // This is an overlay package. 9098 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9099 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9100 mOverlays.put(pkg.mOverlayTarget, 9101 new ArrayMap<String, PackageParser.Package>()); 9102 } 9103 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9104 map.put(pkg.packageName, pkg); 9105 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9106 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9107 createIdmapFailed = true; 9108 } 9109 } 9110 } else if (mOverlays.containsKey(pkg.packageName) && 9111 !pkg.packageName.equals("android")) { 9112 // This is a regular package, with one or more known overlay packages. 9113 createIdmapsForPackageLI(pkg); 9114 } 9115 } 9116 9117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9118 9119 if (createIdmapFailed) { 9120 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9121 "scanPackageLI failed to createIdmap"); 9122 } 9123 } 9124 9125 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9126 PackageParser.Package update, int[] userIds) { 9127 if (existing.applicationInfo == null || update.applicationInfo == null) { 9128 // This isn't due to an app installation. 9129 return; 9130 } 9131 9132 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9133 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9134 9135 // The codePath hasn't changed, so there's nothing for us to do. 9136 if (Objects.equals(oldCodePath, newCodePath)) { 9137 return; 9138 } 9139 9140 File canonicalNewCodePath; 9141 try { 9142 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9143 } catch (IOException e) { 9144 Slog.w(TAG, "Failed to get canonical path.", e); 9145 return; 9146 } 9147 9148 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9149 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9150 // that the last component of the path (i.e, the name) doesn't need canonicalization 9151 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9152 // but may change in the future. Hopefully this function won't exist at that point. 9153 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9154 oldCodePath.getName()); 9155 9156 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9157 // with "@". 9158 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9159 if (!oldMarkerPrefix.endsWith("@")) { 9160 oldMarkerPrefix += "@"; 9161 } 9162 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9163 if (!newMarkerPrefix.endsWith("@")) { 9164 newMarkerPrefix += "@"; 9165 } 9166 9167 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9168 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9169 for (String updatedPath : updatedPaths) { 9170 String updatedPathName = new File(updatedPath).getName(); 9171 markerSuffixes.add(updatedPathName.replace('/', '@')); 9172 } 9173 9174 for (int userId : userIds) { 9175 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9176 9177 for (String markerSuffix : markerSuffixes) { 9178 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9179 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9180 if (oldForeignUseMark.exists()) { 9181 try { 9182 Os.rename(oldForeignUseMark.getAbsolutePath(), 9183 newForeignUseMark.getAbsolutePath()); 9184 } catch (ErrnoException e) { 9185 Slog.w(TAG, "Failed to rename foreign use marker", e); 9186 oldForeignUseMark.delete(); 9187 } 9188 } 9189 } 9190 } 9191 } 9192 9193 /** 9194 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9195 * is derived purely on the basis of the contents of {@code scanFile} and 9196 * {@code cpuAbiOverride}. 9197 * 9198 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9199 */ 9200 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9201 String cpuAbiOverride, boolean extractLibs, 9202 File appLib32InstallDir) 9203 throws PackageManagerException { 9204 // TODO: We can probably be smarter about this stuff. For installed apps, 9205 // we can calculate this information at install time once and for all. For 9206 // system apps, we can probably assume that this information doesn't change 9207 // after the first boot scan. As things stand, we do lots of unnecessary work. 9208 9209 // Give ourselves some initial paths; we'll come back for another 9210 // pass once we've determined ABI below. 9211 setNativeLibraryPaths(pkg, appLib32InstallDir); 9212 9213 // We would never need to extract libs for forward-locked and external packages, 9214 // since the container service will do it for us. We shouldn't attempt to 9215 // extract libs from system app when it was not updated. 9216 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9217 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9218 extractLibs = false; 9219 } 9220 9221 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9222 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9223 9224 NativeLibraryHelper.Handle handle = null; 9225 try { 9226 handle = NativeLibraryHelper.Handle.create(pkg); 9227 // TODO(multiArch): This can be null for apps that didn't go through the 9228 // usual installation process. We can calculate it again, like we 9229 // do during install time. 9230 // 9231 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9232 // unnecessary. 9233 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9234 9235 // Null out the abis so that they can be recalculated. 9236 pkg.applicationInfo.primaryCpuAbi = null; 9237 pkg.applicationInfo.secondaryCpuAbi = null; 9238 if (isMultiArch(pkg.applicationInfo)) { 9239 // Warn if we've set an abiOverride for multi-lib packages.. 9240 // By definition, we need to copy both 32 and 64 bit libraries for 9241 // such packages. 9242 if (pkg.cpuAbiOverride != null 9243 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9244 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9245 } 9246 9247 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9248 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9249 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9250 if (extractLibs) { 9251 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9252 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9253 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9254 useIsaSpecificSubdirs); 9255 } else { 9256 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9257 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9258 } 9259 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9260 } 9261 9262 maybeThrowExceptionForMultiArchCopy( 9263 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9264 9265 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9266 if (extractLibs) { 9267 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9268 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9269 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9270 useIsaSpecificSubdirs); 9271 } else { 9272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9273 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9274 } 9275 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9276 } 9277 9278 maybeThrowExceptionForMultiArchCopy( 9279 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9280 9281 if (abi64 >= 0) { 9282 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9283 } 9284 9285 if (abi32 >= 0) { 9286 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9287 if (abi64 >= 0) { 9288 if (pkg.use32bitAbi) { 9289 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9290 pkg.applicationInfo.primaryCpuAbi = abi; 9291 } else { 9292 pkg.applicationInfo.secondaryCpuAbi = abi; 9293 } 9294 } else { 9295 pkg.applicationInfo.primaryCpuAbi = abi; 9296 } 9297 } 9298 9299 } else { 9300 String[] abiList = (cpuAbiOverride != null) ? 9301 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9302 9303 // Enable gross and lame hacks for apps that are built with old 9304 // SDK tools. We must scan their APKs for renderscript bitcode and 9305 // not launch them if it's present. Don't bother checking on devices 9306 // that don't have 64 bit support. 9307 boolean needsRenderScriptOverride = false; 9308 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9309 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9310 abiList = Build.SUPPORTED_32_BIT_ABIS; 9311 needsRenderScriptOverride = true; 9312 } 9313 9314 final int copyRet; 9315 if (extractLibs) { 9316 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9317 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9318 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9319 } else { 9320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9321 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9322 } 9323 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9324 9325 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9326 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9327 "Error unpackaging native libs for app, errorCode=" + copyRet); 9328 } 9329 9330 if (copyRet >= 0) { 9331 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9332 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9333 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9334 } else if (needsRenderScriptOverride) { 9335 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9336 } 9337 } 9338 } catch (IOException ioe) { 9339 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9340 } finally { 9341 IoUtils.closeQuietly(handle); 9342 } 9343 9344 // Now that we've calculated the ABIs and determined if it's an internal app, 9345 // we will go ahead and populate the nativeLibraryPath. 9346 setNativeLibraryPaths(pkg, appLib32InstallDir); 9347 } 9348 9349 /** 9350 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9351 * i.e, so that all packages can be run inside a single process if required. 9352 * 9353 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9354 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9355 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9356 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9357 * updating a package that belongs to a shared user. 9358 * 9359 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9360 * adds unnecessary complexity. 9361 */ 9362 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9363 PackageParser.Package scannedPackage) { 9364 String requiredInstructionSet = null; 9365 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9366 requiredInstructionSet = VMRuntime.getInstructionSet( 9367 scannedPackage.applicationInfo.primaryCpuAbi); 9368 } 9369 9370 PackageSetting requirer = null; 9371 for (PackageSetting ps : packagesForUser) { 9372 // If packagesForUser contains scannedPackage, we skip it. This will happen 9373 // when scannedPackage is an update of an existing package. Without this check, 9374 // we will never be able to change the ABI of any package belonging to a shared 9375 // user, even if it's compatible with other packages. 9376 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9377 if (ps.primaryCpuAbiString == null) { 9378 continue; 9379 } 9380 9381 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9382 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9383 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9384 // this but there's not much we can do. 9385 String errorMessage = "Instruction set mismatch, " 9386 + ((requirer == null) ? "[caller]" : requirer) 9387 + " requires " + requiredInstructionSet + " whereas " + ps 9388 + " requires " + instructionSet; 9389 Slog.w(TAG, errorMessage); 9390 } 9391 9392 if (requiredInstructionSet == null) { 9393 requiredInstructionSet = instructionSet; 9394 requirer = ps; 9395 } 9396 } 9397 } 9398 9399 if (requiredInstructionSet != null) { 9400 String adjustedAbi; 9401 if (requirer != null) { 9402 // requirer != null implies that either scannedPackage was null or that scannedPackage 9403 // did not require an ABI, in which case we have to adjust scannedPackage to match 9404 // the ABI of the set (which is the same as requirer's ABI) 9405 adjustedAbi = requirer.primaryCpuAbiString; 9406 if (scannedPackage != null) { 9407 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9408 } 9409 } else { 9410 // requirer == null implies that we're updating all ABIs in the set to 9411 // match scannedPackage. 9412 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9413 } 9414 9415 for (PackageSetting ps : packagesForUser) { 9416 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9417 if (ps.primaryCpuAbiString != null) { 9418 continue; 9419 } 9420 9421 ps.primaryCpuAbiString = adjustedAbi; 9422 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9423 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9424 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9425 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9426 + " (requirer=" 9427 + (requirer == null ? "null" : requirer.pkg.packageName) 9428 + ", scannedPackage=" 9429 + (scannedPackage != null ? scannedPackage.packageName : "null") 9430 + ")"); 9431 try { 9432 mInstaller.rmdex(ps.codePathString, 9433 getDexCodeInstructionSet(getPreferredInstructionSet())); 9434 } catch (InstallerException ignored) { 9435 } 9436 } 9437 } 9438 } 9439 } 9440 } 9441 9442 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9443 synchronized (mPackages) { 9444 mResolverReplaced = true; 9445 // Set up information for custom user intent resolution activity. 9446 mResolveActivity.applicationInfo = pkg.applicationInfo; 9447 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9448 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9449 mResolveActivity.processName = pkg.applicationInfo.packageName; 9450 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9451 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9452 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9453 mResolveActivity.theme = 0; 9454 mResolveActivity.exported = true; 9455 mResolveActivity.enabled = true; 9456 mResolveInfo.activityInfo = mResolveActivity; 9457 mResolveInfo.priority = 0; 9458 mResolveInfo.preferredOrder = 0; 9459 mResolveInfo.match = 0; 9460 mResolveComponentName = mCustomResolverComponentName; 9461 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9462 mResolveComponentName); 9463 } 9464 } 9465 9466 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9467 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9468 9469 // Set up information for ephemeral installer activity 9470 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9471 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9472 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9473 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9474 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9475 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9476 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9477 mEphemeralInstallerActivity.theme = 0; 9478 mEphemeralInstallerActivity.exported = true; 9479 mEphemeralInstallerActivity.enabled = true; 9480 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9481 mEphemeralInstallerInfo.priority = 0; 9482 mEphemeralInstallerInfo.preferredOrder = 1; 9483 mEphemeralInstallerInfo.isDefault = true; 9484 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9485 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9486 9487 if (DEBUG_EPHEMERAL) { 9488 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9489 } 9490 } 9491 9492 private static String calculateBundledApkRoot(final String codePathString) { 9493 final File codePath = new File(codePathString); 9494 final File codeRoot; 9495 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9496 codeRoot = Environment.getRootDirectory(); 9497 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9498 codeRoot = Environment.getOemDirectory(); 9499 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9500 codeRoot = Environment.getVendorDirectory(); 9501 } else { 9502 // Unrecognized code path; take its top real segment as the apk root: 9503 // e.g. /something/app/blah.apk => /something 9504 try { 9505 File f = codePath.getCanonicalFile(); 9506 File parent = f.getParentFile(); // non-null because codePath is a file 9507 File tmp; 9508 while ((tmp = parent.getParentFile()) != null) { 9509 f = parent; 9510 parent = tmp; 9511 } 9512 codeRoot = f; 9513 Slog.w(TAG, "Unrecognized code path " 9514 + codePath + " - using " + codeRoot); 9515 } catch (IOException e) { 9516 // Can't canonicalize the code path -- shenanigans? 9517 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9518 return Environment.getRootDirectory().getPath(); 9519 } 9520 } 9521 return codeRoot.getPath(); 9522 } 9523 9524 /** 9525 * Derive and set the location of native libraries for the given package, 9526 * which varies depending on where and how the package was installed. 9527 */ 9528 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9529 final ApplicationInfo info = pkg.applicationInfo; 9530 final String codePath = pkg.codePath; 9531 final File codeFile = new File(codePath); 9532 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9533 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9534 9535 info.nativeLibraryRootDir = null; 9536 info.nativeLibraryRootRequiresIsa = false; 9537 info.nativeLibraryDir = null; 9538 info.secondaryNativeLibraryDir = null; 9539 9540 if (isApkFile(codeFile)) { 9541 // Monolithic install 9542 if (bundledApp) { 9543 // If "/system/lib64/apkname" exists, assume that is the per-package 9544 // native library directory to use; otherwise use "/system/lib/apkname". 9545 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9546 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9547 getPrimaryInstructionSet(info)); 9548 9549 // This is a bundled system app so choose the path based on the ABI. 9550 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9551 // is just the default path. 9552 final String apkName = deriveCodePathName(codePath); 9553 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9554 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9555 apkName).getAbsolutePath(); 9556 9557 if (info.secondaryCpuAbi != null) { 9558 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9559 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9560 secondaryLibDir, apkName).getAbsolutePath(); 9561 } 9562 } else if (asecApp) { 9563 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9564 .getAbsolutePath(); 9565 } else { 9566 final String apkName = deriveCodePathName(codePath); 9567 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9568 .getAbsolutePath(); 9569 } 9570 9571 info.nativeLibraryRootRequiresIsa = false; 9572 info.nativeLibraryDir = info.nativeLibraryRootDir; 9573 } else { 9574 // Cluster install 9575 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9576 info.nativeLibraryRootRequiresIsa = true; 9577 9578 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9579 getPrimaryInstructionSet(info)).getAbsolutePath(); 9580 9581 if (info.secondaryCpuAbi != null) { 9582 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9583 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9584 } 9585 } 9586 } 9587 9588 /** 9589 * Calculate the abis and roots for a bundled app. These can uniquely 9590 * be determined from the contents of the system partition, i.e whether 9591 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9592 * of this information, and instead assume that the system was built 9593 * sensibly. 9594 */ 9595 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9596 PackageSetting pkgSetting) { 9597 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9598 9599 // If "/system/lib64/apkname" exists, assume that is the per-package 9600 // native library directory to use; otherwise use "/system/lib/apkname". 9601 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9602 setBundledAppAbi(pkg, apkRoot, apkName); 9603 // pkgSetting might be null during rescan following uninstall of updates 9604 // to a bundled app, so accommodate that possibility. The settings in 9605 // that case will be established later from the parsed package. 9606 // 9607 // If the settings aren't null, sync them up with what we've just derived. 9608 // note that apkRoot isn't stored in the package settings. 9609 if (pkgSetting != null) { 9610 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9611 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9612 } 9613 } 9614 9615 /** 9616 * Deduces the ABI of a bundled app and sets the relevant fields on the 9617 * parsed pkg object. 9618 * 9619 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9620 * under which system libraries are installed. 9621 * @param apkName the name of the installed package. 9622 */ 9623 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9624 final File codeFile = new File(pkg.codePath); 9625 9626 final boolean has64BitLibs; 9627 final boolean has32BitLibs; 9628 if (isApkFile(codeFile)) { 9629 // Monolithic install 9630 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9631 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9632 } else { 9633 // Cluster install 9634 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9635 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9636 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9637 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9638 has64BitLibs = (new File(rootDir, isa)).exists(); 9639 } else { 9640 has64BitLibs = false; 9641 } 9642 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9643 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9644 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9645 has32BitLibs = (new File(rootDir, isa)).exists(); 9646 } else { 9647 has32BitLibs = false; 9648 } 9649 } 9650 9651 if (has64BitLibs && !has32BitLibs) { 9652 // The package has 64 bit libs, but not 32 bit libs. Its primary 9653 // ABI should be 64 bit. We can safely assume here that the bundled 9654 // native libraries correspond to the most preferred ABI in the list. 9655 9656 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9657 pkg.applicationInfo.secondaryCpuAbi = null; 9658 } else if (has32BitLibs && !has64BitLibs) { 9659 // The package has 32 bit libs but not 64 bit libs. Its primary 9660 // ABI should be 32 bit. 9661 9662 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9663 pkg.applicationInfo.secondaryCpuAbi = null; 9664 } else if (has32BitLibs && has64BitLibs) { 9665 // The application has both 64 and 32 bit bundled libraries. We check 9666 // here that the app declares multiArch support, and warn if it doesn't. 9667 // 9668 // We will be lenient here and record both ABIs. The primary will be the 9669 // ABI that's higher on the list, i.e, a device that's configured to prefer 9670 // 64 bit apps will see a 64 bit primary ABI, 9671 9672 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9673 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9674 } 9675 9676 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9677 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9678 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9679 } else { 9680 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9681 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9682 } 9683 } else { 9684 pkg.applicationInfo.primaryCpuAbi = null; 9685 pkg.applicationInfo.secondaryCpuAbi = null; 9686 } 9687 } 9688 9689 private void killApplication(String pkgName, int appId, String reason) { 9690 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9691 } 9692 9693 private void killApplication(String pkgName, int appId, int userId, String reason) { 9694 // Request the ActivityManager to kill the process(only for existing packages) 9695 // so that we do not end up in a confused state while the user is still using the older 9696 // version of the application while the new one gets installed. 9697 final long token = Binder.clearCallingIdentity(); 9698 try { 9699 IActivityManager am = ActivityManager.getService(); 9700 if (am != null) { 9701 try { 9702 am.killApplication(pkgName, appId, userId, reason); 9703 } catch (RemoteException e) { 9704 } 9705 } 9706 } finally { 9707 Binder.restoreCallingIdentity(token); 9708 } 9709 } 9710 9711 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9712 // Remove the parent package setting 9713 PackageSetting ps = (PackageSetting) pkg.mExtras; 9714 if (ps != null) { 9715 removePackageLI(ps, chatty); 9716 } 9717 // Remove the child package setting 9718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9719 for (int i = 0; i < childCount; i++) { 9720 PackageParser.Package childPkg = pkg.childPackages.get(i); 9721 ps = (PackageSetting) childPkg.mExtras; 9722 if (ps != null) { 9723 removePackageLI(ps, chatty); 9724 } 9725 } 9726 } 9727 9728 void removePackageLI(PackageSetting ps, boolean chatty) { 9729 if (DEBUG_INSTALL) { 9730 if (chatty) 9731 Log.d(TAG, "Removing package " + ps.name); 9732 } 9733 9734 // writer 9735 synchronized (mPackages) { 9736 mPackages.remove(ps.name); 9737 final PackageParser.Package pkg = ps.pkg; 9738 if (pkg != null) { 9739 cleanPackageDataStructuresLILPw(pkg, chatty); 9740 } 9741 } 9742 } 9743 9744 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9745 if (DEBUG_INSTALL) { 9746 if (chatty) 9747 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9748 } 9749 9750 // writer 9751 synchronized (mPackages) { 9752 // Remove the parent package 9753 mPackages.remove(pkg.applicationInfo.packageName); 9754 cleanPackageDataStructuresLILPw(pkg, chatty); 9755 9756 // Remove the child packages 9757 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9758 for (int i = 0; i < childCount; i++) { 9759 PackageParser.Package childPkg = pkg.childPackages.get(i); 9760 mPackages.remove(childPkg.applicationInfo.packageName); 9761 cleanPackageDataStructuresLILPw(childPkg, chatty); 9762 } 9763 } 9764 } 9765 9766 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9767 int N = pkg.providers.size(); 9768 StringBuilder r = null; 9769 int i; 9770 for (i=0; i<N; i++) { 9771 PackageParser.Provider p = pkg.providers.get(i); 9772 mProviders.removeProvider(p); 9773 if (p.info.authority == null) { 9774 9775 /* There was another ContentProvider with this authority when 9776 * this app was installed so this authority is null, 9777 * Ignore it as we don't have to unregister the provider. 9778 */ 9779 continue; 9780 } 9781 String names[] = p.info.authority.split(";"); 9782 for (int j = 0; j < names.length; j++) { 9783 if (mProvidersByAuthority.get(names[j]) == p) { 9784 mProvidersByAuthority.remove(names[j]); 9785 if (DEBUG_REMOVE) { 9786 if (chatty) 9787 Log.d(TAG, "Unregistered content provider: " + names[j] 9788 + ", className = " + p.info.name + ", isSyncable = " 9789 + p.info.isSyncable); 9790 } 9791 } 9792 } 9793 if (DEBUG_REMOVE && chatty) { 9794 if (r == null) { 9795 r = new StringBuilder(256); 9796 } else { 9797 r.append(' '); 9798 } 9799 r.append(p.info.name); 9800 } 9801 } 9802 if (r != null) { 9803 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9804 } 9805 9806 N = pkg.services.size(); 9807 r = null; 9808 for (i=0; i<N; i++) { 9809 PackageParser.Service s = pkg.services.get(i); 9810 mServices.removeService(s); 9811 if (chatty) { 9812 if (r == null) { 9813 r = new StringBuilder(256); 9814 } else { 9815 r.append(' '); 9816 } 9817 r.append(s.info.name); 9818 } 9819 } 9820 if (r != null) { 9821 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9822 } 9823 9824 N = pkg.receivers.size(); 9825 r = null; 9826 for (i=0; i<N; i++) { 9827 PackageParser.Activity a = pkg.receivers.get(i); 9828 mReceivers.removeActivity(a, "receiver"); 9829 if (DEBUG_REMOVE && chatty) { 9830 if (r == null) { 9831 r = new StringBuilder(256); 9832 } else { 9833 r.append(' '); 9834 } 9835 r.append(a.info.name); 9836 } 9837 } 9838 if (r != null) { 9839 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9840 } 9841 9842 N = pkg.activities.size(); 9843 r = null; 9844 for (i=0; i<N; i++) { 9845 PackageParser.Activity a = pkg.activities.get(i); 9846 mActivities.removeActivity(a, "activity"); 9847 if (DEBUG_REMOVE && chatty) { 9848 if (r == null) { 9849 r = new StringBuilder(256); 9850 } else { 9851 r.append(' '); 9852 } 9853 r.append(a.info.name); 9854 } 9855 } 9856 if (r != null) { 9857 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9858 } 9859 9860 N = pkg.permissions.size(); 9861 r = null; 9862 for (i=0; i<N; i++) { 9863 PackageParser.Permission p = pkg.permissions.get(i); 9864 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9865 if (bp == null) { 9866 bp = mSettings.mPermissionTrees.get(p.info.name); 9867 } 9868 if (bp != null && bp.perm == p) { 9869 bp.perm = null; 9870 if (DEBUG_REMOVE && chatty) { 9871 if (r == null) { 9872 r = new StringBuilder(256); 9873 } else { 9874 r.append(' '); 9875 } 9876 r.append(p.info.name); 9877 } 9878 } 9879 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9880 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9881 if (appOpPkgs != null) { 9882 appOpPkgs.remove(pkg.packageName); 9883 } 9884 } 9885 } 9886 if (r != null) { 9887 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9888 } 9889 9890 N = pkg.requestedPermissions.size(); 9891 r = null; 9892 for (i=0; i<N; i++) { 9893 String perm = pkg.requestedPermissions.get(i); 9894 BasePermission bp = mSettings.mPermissions.get(perm); 9895 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9896 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9897 if (appOpPkgs != null) { 9898 appOpPkgs.remove(pkg.packageName); 9899 if (appOpPkgs.isEmpty()) { 9900 mAppOpPermissionPackages.remove(perm); 9901 } 9902 } 9903 } 9904 } 9905 if (r != null) { 9906 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9907 } 9908 9909 N = pkg.instrumentation.size(); 9910 r = null; 9911 for (i=0; i<N; i++) { 9912 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9913 mInstrumentation.remove(a.getComponentName()); 9914 if (DEBUG_REMOVE && chatty) { 9915 if (r == null) { 9916 r = new StringBuilder(256); 9917 } else { 9918 r.append(' '); 9919 } 9920 r.append(a.info.name); 9921 } 9922 } 9923 if (r != null) { 9924 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9925 } 9926 9927 r = null; 9928 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9929 // Only system apps can hold shared libraries. 9930 if (pkg.libraryNames != null) { 9931 for (i=0; i<pkg.libraryNames.size(); i++) { 9932 String name = pkg.libraryNames.get(i); 9933 SharedLibraryEntry cur = mSharedLibraries.get(name); 9934 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9935 mSharedLibraries.remove(name); 9936 if (DEBUG_REMOVE && chatty) { 9937 if (r == null) { 9938 r = new StringBuilder(256); 9939 } else { 9940 r.append(' '); 9941 } 9942 r.append(name); 9943 } 9944 } 9945 } 9946 } 9947 } 9948 if (r != null) { 9949 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9950 } 9951 } 9952 9953 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9954 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9955 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9956 return true; 9957 } 9958 } 9959 return false; 9960 } 9961 9962 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9963 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9964 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9965 9966 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9967 // Update the parent permissions 9968 updatePermissionsLPw(pkg.packageName, pkg, flags); 9969 // Update the child permissions 9970 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9971 for (int i = 0; i < childCount; i++) { 9972 PackageParser.Package childPkg = pkg.childPackages.get(i); 9973 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9974 } 9975 } 9976 9977 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9978 int flags) { 9979 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9980 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9981 } 9982 9983 private void updatePermissionsLPw(String changingPkg, 9984 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9985 // Make sure there are no dangling permission trees. 9986 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9987 while (it.hasNext()) { 9988 final BasePermission bp = it.next(); 9989 if (bp.packageSetting == null) { 9990 // We may not yet have parsed the package, so just see if 9991 // we still know about its settings. 9992 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9993 } 9994 if (bp.packageSetting == null) { 9995 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9996 + " from package " + bp.sourcePackage); 9997 it.remove(); 9998 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9999 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10000 Slog.i(TAG, "Removing old permission tree: " + bp.name 10001 + " from package " + bp.sourcePackage); 10002 flags |= UPDATE_PERMISSIONS_ALL; 10003 it.remove(); 10004 } 10005 } 10006 } 10007 10008 // Make sure all dynamic permissions have been assigned to a package, 10009 // and make sure there are no dangling permissions. 10010 it = mSettings.mPermissions.values().iterator(); 10011 while (it.hasNext()) { 10012 final BasePermission bp = it.next(); 10013 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10014 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10015 + bp.name + " pkg=" + bp.sourcePackage 10016 + " info=" + bp.pendingInfo); 10017 if (bp.packageSetting == null && bp.pendingInfo != null) { 10018 final BasePermission tree = findPermissionTreeLP(bp.name); 10019 if (tree != null && tree.perm != null) { 10020 bp.packageSetting = tree.packageSetting; 10021 bp.perm = new PackageParser.Permission(tree.perm.owner, 10022 new PermissionInfo(bp.pendingInfo)); 10023 bp.perm.info.packageName = tree.perm.info.packageName; 10024 bp.perm.info.name = bp.name; 10025 bp.uid = tree.uid; 10026 } 10027 } 10028 } 10029 if (bp.packageSetting == null) { 10030 // We may not yet have parsed the package, so just see if 10031 // we still know about its settings. 10032 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10033 } 10034 if (bp.packageSetting == null) { 10035 Slog.w(TAG, "Removing dangling permission: " + bp.name 10036 + " from package " + bp.sourcePackage); 10037 it.remove(); 10038 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10039 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10040 Slog.i(TAG, "Removing old permission: " + bp.name 10041 + " from package " + bp.sourcePackage); 10042 flags |= UPDATE_PERMISSIONS_ALL; 10043 it.remove(); 10044 } 10045 } 10046 } 10047 10048 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10049 // Now update the permissions for all packages, in particular 10050 // replace the granted permissions of the system packages. 10051 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10052 for (PackageParser.Package pkg : mPackages.values()) { 10053 if (pkg != pkgInfo) { 10054 // Only replace for packages on requested volume 10055 final String volumeUuid = getVolumeUuidForPackage(pkg); 10056 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10057 && Objects.equals(replaceVolumeUuid, volumeUuid); 10058 grantPermissionsLPw(pkg, replace, changingPkg); 10059 } 10060 } 10061 } 10062 10063 if (pkgInfo != null) { 10064 // Only replace for packages on requested volume 10065 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10066 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10067 && Objects.equals(replaceVolumeUuid, volumeUuid); 10068 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10069 } 10070 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10071 } 10072 10073 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10074 String packageOfInterest) { 10075 // IMPORTANT: There are two types of permissions: install and runtime. 10076 // Install time permissions are granted when the app is installed to 10077 // all device users and users added in the future. Runtime permissions 10078 // are granted at runtime explicitly to specific users. Normal and signature 10079 // protected permissions are install time permissions. Dangerous permissions 10080 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10081 // otherwise they are runtime permissions. This function does not manage 10082 // runtime permissions except for the case an app targeting Lollipop MR1 10083 // being upgraded to target a newer SDK, in which case dangerous permissions 10084 // are transformed from install time to runtime ones. 10085 10086 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10087 if (ps == null) { 10088 return; 10089 } 10090 10091 PermissionsState permissionsState = ps.getPermissionsState(); 10092 PermissionsState origPermissions = permissionsState; 10093 10094 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10095 10096 boolean runtimePermissionsRevoked = false; 10097 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10098 10099 boolean changedInstallPermission = false; 10100 10101 if (replace) { 10102 ps.installPermissionsFixed = false; 10103 if (!ps.isSharedUser()) { 10104 origPermissions = new PermissionsState(permissionsState); 10105 permissionsState.reset(); 10106 } else { 10107 // We need to know only about runtime permission changes since the 10108 // calling code always writes the install permissions state but 10109 // the runtime ones are written only if changed. The only cases of 10110 // changed runtime permissions here are promotion of an install to 10111 // runtime and revocation of a runtime from a shared user. 10112 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10113 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10114 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10115 runtimePermissionsRevoked = true; 10116 } 10117 } 10118 } 10119 10120 permissionsState.setGlobalGids(mGlobalGids); 10121 10122 final int N = pkg.requestedPermissions.size(); 10123 for (int i=0; i<N; i++) { 10124 final String name = pkg.requestedPermissions.get(i); 10125 final BasePermission bp = mSettings.mPermissions.get(name); 10126 10127 if (DEBUG_INSTALL) { 10128 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10129 } 10130 10131 if (bp == null || bp.packageSetting == null) { 10132 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10133 Slog.w(TAG, "Unknown permission " + name 10134 + " in package " + pkg.packageName); 10135 } 10136 continue; 10137 } 10138 10139 10140 // Limit ephemeral apps to ephemeral allowed permissions. 10141 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10142 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10143 + pkg.packageName); 10144 continue; 10145 } 10146 10147 final String perm = bp.name; 10148 boolean allowedSig = false; 10149 int grant = GRANT_DENIED; 10150 10151 // Keep track of app op permissions. 10152 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10153 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10154 if (pkgs == null) { 10155 pkgs = new ArraySet<>(); 10156 mAppOpPermissionPackages.put(bp.name, pkgs); 10157 } 10158 pkgs.add(pkg.packageName); 10159 } 10160 10161 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10162 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10163 >= Build.VERSION_CODES.M; 10164 switch (level) { 10165 case PermissionInfo.PROTECTION_NORMAL: { 10166 // For all apps normal permissions are install time ones. 10167 grant = GRANT_INSTALL; 10168 } break; 10169 10170 case PermissionInfo.PROTECTION_DANGEROUS: { 10171 // If a permission review is required for legacy apps we represent 10172 // their permissions as always granted runtime ones since we need 10173 // to keep the review required permission flag per user while an 10174 // install permission's state is shared across all users. 10175 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10176 // For legacy apps dangerous permissions are install time ones. 10177 grant = GRANT_INSTALL; 10178 } else if (origPermissions.hasInstallPermission(bp.name)) { 10179 // For legacy apps that became modern, install becomes runtime. 10180 grant = GRANT_UPGRADE; 10181 } else if (mPromoteSystemApps 10182 && isSystemApp(ps) 10183 && mExistingSystemPackages.contains(ps.name)) { 10184 // For legacy system apps, install becomes runtime. 10185 // We cannot check hasInstallPermission() for system apps since those 10186 // permissions were granted implicitly and not persisted pre-M. 10187 grant = GRANT_UPGRADE; 10188 } else { 10189 // For modern apps keep runtime permissions unchanged. 10190 grant = GRANT_RUNTIME; 10191 } 10192 } break; 10193 10194 case PermissionInfo.PROTECTION_SIGNATURE: { 10195 // For all apps signature permissions are install time ones. 10196 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10197 if (allowedSig) { 10198 grant = GRANT_INSTALL; 10199 } 10200 } break; 10201 } 10202 10203 if (DEBUG_INSTALL) { 10204 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10205 } 10206 10207 if (grant != GRANT_DENIED) { 10208 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10209 // If this is an existing, non-system package, then 10210 // we can't add any new permissions to it. 10211 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10212 // Except... if this is a permission that was added 10213 // to the platform (note: need to only do this when 10214 // updating the platform). 10215 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10216 grant = GRANT_DENIED; 10217 } 10218 } 10219 } 10220 10221 switch (grant) { 10222 case GRANT_INSTALL: { 10223 // Revoke this as runtime permission to handle the case of 10224 // a runtime permission being downgraded to an install one. 10225 // Also in permission review mode we keep dangerous permissions 10226 // for legacy apps 10227 for (int userId : UserManagerService.getInstance().getUserIds()) { 10228 if (origPermissions.getRuntimePermissionState( 10229 bp.name, userId) != null) { 10230 // Revoke the runtime permission and clear the flags. 10231 origPermissions.revokeRuntimePermission(bp, userId); 10232 origPermissions.updatePermissionFlags(bp, userId, 10233 PackageManager.MASK_PERMISSION_FLAGS, 0); 10234 // If we revoked a permission permission, we have to write. 10235 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10236 changedRuntimePermissionUserIds, userId); 10237 } 10238 } 10239 // Grant an install permission. 10240 if (permissionsState.grantInstallPermission(bp) != 10241 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10242 changedInstallPermission = true; 10243 } 10244 } break; 10245 10246 case GRANT_RUNTIME: { 10247 // Grant previously granted runtime permissions. 10248 for (int userId : UserManagerService.getInstance().getUserIds()) { 10249 PermissionState permissionState = origPermissions 10250 .getRuntimePermissionState(bp.name, userId); 10251 int flags = permissionState != null 10252 ? permissionState.getFlags() : 0; 10253 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10254 if (permissionsState.grantRuntimePermission(bp, userId) == 10255 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10256 // If we cannot put the permission as it was, we have to write. 10257 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10258 changedRuntimePermissionUserIds, userId); 10259 } 10260 // If the app supports runtime permissions no need for a review. 10261 if (mPermissionReviewRequired 10262 && appSupportsRuntimePermissions 10263 && (flags & PackageManager 10264 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10265 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10266 // Since we changed the flags, we have to write. 10267 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10268 changedRuntimePermissionUserIds, userId); 10269 } 10270 } else if (mPermissionReviewRequired 10271 && !appSupportsRuntimePermissions) { 10272 // For legacy apps that need a permission review, every new 10273 // runtime permission is granted but it is pending a review. 10274 // We also need to review only platform defined runtime 10275 // permissions as these are the only ones the platform knows 10276 // how to disable the API to simulate revocation as legacy 10277 // apps don't expect to run with revoked permissions. 10278 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10279 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10280 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10281 // We changed the flags, hence have to write. 10282 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10283 changedRuntimePermissionUserIds, userId); 10284 } 10285 } 10286 if (permissionsState.grantRuntimePermission(bp, userId) 10287 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10288 // We changed the permission, hence have to write. 10289 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10290 changedRuntimePermissionUserIds, userId); 10291 } 10292 } 10293 // Propagate the permission flags. 10294 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10295 } 10296 } break; 10297 10298 case GRANT_UPGRADE: { 10299 // Grant runtime permissions for a previously held install permission. 10300 PermissionState permissionState = origPermissions 10301 .getInstallPermissionState(bp.name); 10302 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10303 10304 if (origPermissions.revokeInstallPermission(bp) 10305 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10306 // We will be transferring the permission flags, so clear them. 10307 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10308 PackageManager.MASK_PERMISSION_FLAGS, 0); 10309 changedInstallPermission = true; 10310 } 10311 10312 // If the permission is not to be promoted to runtime we ignore it and 10313 // also its other flags as they are not applicable to install permissions. 10314 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10315 for (int userId : currentUserIds) { 10316 if (permissionsState.grantRuntimePermission(bp, userId) != 10317 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10318 // Transfer the permission flags. 10319 permissionsState.updatePermissionFlags(bp, userId, 10320 flags, flags); 10321 // If we granted the permission, we have to write. 10322 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10323 changedRuntimePermissionUserIds, userId); 10324 } 10325 } 10326 } 10327 } break; 10328 10329 default: { 10330 if (packageOfInterest == null 10331 || packageOfInterest.equals(pkg.packageName)) { 10332 Slog.w(TAG, "Not granting permission " + perm 10333 + " to package " + pkg.packageName 10334 + " because it was previously installed without"); 10335 } 10336 } break; 10337 } 10338 } else { 10339 if (permissionsState.revokeInstallPermission(bp) != 10340 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10341 // Also drop the permission flags. 10342 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10343 PackageManager.MASK_PERMISSION_FLAGS, 0); 10344 changedInstallPermission = true; 10345 Slog.i(TAG, "Un-granting permission " + perm 10346 + " from package " + pkg.packageName 10347 + " (protectionLevel=" + bp.protectionLevel 10348 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10349 + ")"); 10350 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10351 // Don't print warning for app op permissions, since it is fine for them 10352 // not to be granted, there is a UI for the user to decide. 10353 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10354 Slog.w(TAG, "Not granting permission " + perm 10355 + " to package " + pkg.packageName 10356 + " (protectionLevel=" + bp.protectionLevel 10357 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10358 + ")"); 10359 } 10360 } 10361 } 10362 } 10363 10364 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10365 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10366 // This is the first that we have heard about this package, so the 10367 // permissions we have now selected are fixed until explicitly 10368 // changed. 10369 ps.installPermissionsFixed = true; 10370 } 10371 10372 // Persist the runtime permissions state for users with changes. If permissions 10373 // were revoked because no app in the shared user declares them we have to 10374 // write synchronously to avoid losing runtime permissions state. 10375 for (int userId : changedRuntimePermissionUserIds) { 10376 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10377 } 10378 } 10379 10380 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10381 boolean allowed = false; 10382 final int NP = PackageParser.NEW_PERMISSIONS.length; 10383 for (int ip=0; ip<NP; ip++) { 10384 final PackageParser.NewPermissionInfo npi 10385 = PackageParser.NEW_PERMISSIONS[ip]; 10386 if (npi.name.equals(perm) 10387 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10388 allowed = true; 10389 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10390 + pkg.packageName); 10391 break; 10392 } 10393 } 10394 return allowed; 10395 } 10396 10397 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10398 BasePermission bp, PermissionsState origPermissions) { 10399 boolean privilegedPermission = (bp.protectionLevel 10400 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10401 boolean controlPrivappPermissions = RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS; 10402 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10403 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10404 if (controlPrivappPermissions && privilegedPermission && pkg.isPrivilegedApp() 10405 && !platformPackage && platformPermission) { 10406 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10407 .getPrivAppPermissions(pkg.packageName); 10408 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10409 if (!whitelisted) { 10410 // Log for now. TODO Enforce permissions 10411 Slog.w(TAG, "Privileged permission " + perm + " for package " 10412 + pkg.packageName + " - not in privapp-permissions whitelist"); 10413 } 10414 } 10415 boolean allowed = (compareSignatures( 10416 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10417 == PackageManager.SIGNATURE_MATCH) 10418 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10419 == PackageManager.SIGNATURE_MATCH); 10420 if (!allowed && privilegedPermission) { 10421 if (isSystemApp(pkg)) { 10422 // For updated system applications, a system permission 10423 // is granted only if it had been defined by the original application. 10424 if (pkg.isUpdatedSystemApp()) { 10425 final PackageSetting sysPs = mSettings 10426 .getDisabledSystemPkgLPr(pkg.packageName); 10427 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10428 // If the original was granted this permission, we take 10429 // that grant decision as read and propagate it to the 10430 // update. 10431 if (sysPs.isPrivileged()) { 10432 allowed = true; 10433 } 10434 } else { 10435 // The system apk may have been updated with an older 10436 // version of the one on the data partition, but which 10437 // granted a new system permission that it didn't have 10438 // before. In this case we do want to allow the app to 10439 // now get the new permission if the ancestral apk is 10440 // privileged to get it. 10441 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10442 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10443 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10444 allowed = true; 10445 break; 10446 } 10447 } 10448 } 10449 // Also if a privileged parent package on the system image or any of 10450 // its children requested a privileged permission, the updated child 10451 // packages can also get the permission. 10452 if (pkg.parentPackage != null) { 10453 final PackageSetting disabledSysParentPs = mSettings 10454 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10455 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10456 && disabledSysParentPs.isPrivileged()) { 10457 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10458 allowed = true; 10459 } else if (disabledSysParentPs.pkg.childPackages != null) { 10460 final int count = disabledSysParentPs.pkg.childPackages.size(); 10461 for (int i = 0; i < count; i++) { 10462 PackageParser.Package disabledSysChildPkg = 10463 disabledSysParentPs.pkg.childPackages.get(i); 10464 if (isPackageRequestingPermission(disabledSysChildPkg, 10465 perm)) { 10466 allowed = true; 10467 break; 10468 } 10469 } 10470 } 10471 } 10472 } 10473 } 10474 } else { 10475 allowed = isPrivilegedApp(pkg); 10476 } 10477 } 10478 } 10479 if (!allowed) { 10480 if (!allowed && (bp.protectionLevel 10481 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10482 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10483 // If this was a previously normal/dangerous permission that got moved 10484 // to a system permission as part of the runtime permission redesign, then 10485 // we still want to blindly grant it to old apps. 10486 allowed = true; 10487 } 10488 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10489 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10490 // If this permission is to be granted to the system installer and 10491 // this app is an installer, then it gets the permission. 10492 allowed = true; 10493 } 10494 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10495 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10496 // If this permission is to be granted to the system verifier and 10497 // this app is a verifier, then it gets the permission. 10498 allowed = true; 10499 } 10500 if (!allowed && (bp.protectionLevel 10501 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10502 && isSystemApp(pkg)) { 10503 // Any pre-installed system app is allowed to get this permission. 10504 allowed = true; 10505 } 10506 if (!allowed && (bp.protectionLevel 10507 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10508 // For development permissions, a development permission 10509 // is granted only if it was already granted. 10510 allowed = origPermissions.hasInstallPermission(perm); 10511 } 10512 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10513 && pkg.packageName.equals(mSetupWizardPackage)) { 10514 // If this permission is to be granted to the system setup wizard and 10515 // this app is a setup wizard, then it gets the permission. 10516 allowed = true; 10517 } 10518 } 10519 return allowed; 10520 } 10521 10522 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10523 final int permCount = pkg.requestedPermissions.size(); 10524 for (int j = 0; j < permCount; j++) { 10525 String requestedPermission = pkg.requestedPermissions.get(j); 10526 if (permission.equals(requestedPermission)) { 10527 return true; 10528 } 10529 } 10530 return false; 10531 } 10532 10533 final class ActivityIntentResolver 10534 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10535 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10536 boolean defaultOnly, int userId) { 10537 if (!sUserManager.exists(userId)) return null; 10538 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10539 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10540 } 10541 10542 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10543 int userId) { 10544 if (!sUserManager.exists(userId)) return null; 10545 mFlags = flags; 10546 return super.queryIntent(intent, resolvedType, 10547 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10548 } 10549 10550 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10551 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10552 if (!sUserManager.exists(userId)) return null; 10553 if (packageActivities == null) { 10554 return null; 10555 } 10556 mFlags = flags; 10557 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10558 final int N = packageActivities.size(); 10559 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10560 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10561 10562 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10563 for (int i = 0; i < N; ++i) { 10564 intentFilters = packageActivities.get(i).intents; 10565 if (intentFilters != null && intentFilters.size() > 0) { 10566 PackageParser.ActivityIntentInfo[] array = 10567 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10568 intentFilters.toArray(array); 10569 listCut.add(array); 10570 } 10571 } 10572 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10573 } 10574 10575 /** 10576 * Finds a privileged activity that matches the specified activity names. 10577 */ 10578 private PackageParser.Activity findMatchingActivity( 10579 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10580 for (PackageParser.Activity sysActivity : activityList) { 10581 if (sysActivity.info.name.equals(activityInfo.name)) { 10582 return sysActivity; 10583 } 10584 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10585 return sysActivity; 10586 } 10587 if (sysActivity.info.targetActivity != null) { 10588 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10589 return sysActivity; 10590 } 10591 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10592 return sysActivity; 10593 } 10594 } 10595 } 10596 return null; 10597 } 10598 10599 public class IterGenerator<E> { 10600 public Iterator<E> generate(ActivityIntentInfo info) { 10601 return null; 10602 } 10603 } 10604 10605 public class ActionIterGenerator extends IterGenerator<String> { 10606 @Override 10607 public Iterator<String> generate(ActivityIntentInfo info) { 10608 return info.actionsIterator(); 10609 } 10610 } 10611 10612 public class CategoriesIterGenerator extends IterGenerator<String> { 10613 @Override 10614 public Iterator<String> generate(ActivityIntentInfo info) { 10615 return info.categoriesIterator(); 10616 } 10617 } 10618 10619 public class SchemesIterGenerator extends IterGenerator<String> { 10620 @Override 10621 public Iterator<String> generate(ActivityIntentInfo info) { 10622 return info.schemesIterator(); 10623 } 10624 } 10625 10626 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10627 @Override 10628 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10629 return info.authoritiesIterator(); 10630 } 10631 } 10632 10633 /** 10634 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10635 * MODIFIED. Do not pass in a list that should not be changed. 10636 */ 10637 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10638 IterGenerator<T> generator, Iterator<T> searchIterator) { 10639 // loop through the set of actions; every one must be found in the intent filter 10640 while (searchIterator.hasNext()) { 10641 // we must have at least one filter in the list to consider a match 10642 if (intentList.size() == 0) { 10643 break; 10644 } 10645 10646 final T searchAction = searchIterator.next(); 10647 10648 // loop through the set of intent filters 10649 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10650 while (intentIter.hasNext()) { 10651 final ActivityIntentInfo intentInfo = intentIter.next(); 10652 boolean selectionFound = false; 10653 10654 // loop through the intent filter's selection criteria; at least one 10655 // of them must match the searched criteria 10656 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10657 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10658 final T intentSelection = intentSelectionIter.next(); 10659 if (intentSelection != null && intentSelection.equals(searchAction)) { 10660 selectionFound = true; 10661 break; 10662 } 10663 } 10664 10665 // the selection criteria wasn't found in this filter's set; this filter 10666 // is not a potential match 10667 if (!selectionFound) { 10668 intentIter.remove(); 10669 } 10670 } 10671 } 10672 } 10673 10674 private boolean isProtectedAction(ActivityIntentInfo filter) { 10675 final Iterator<String> actionsIter = filter.actionsIterator(); 10676 while (actionsIter != null && actionsIter.hasNext()) { 10677 final String filterAction = actionsIter.next(); 10678 if (PROTECTED_ACTIONS.contains(filterAction)) { 10679 return true; 10680 } 10681 } 10682 return false; 10683 } 10684 10685 /** 10686 * Adjusts the priority of the given intent filter according to policy. 10687 * <p> 10688 * <ul> 10689 * <li>The priority for non privileged applications is capped to '0'</li> 10690 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10691 * <li>The priority for unbundled updates to privileged applications is capped to the 10692 * priority defined on the system partition</li> 10693 * </ul> 10694 * <p> 10695 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10696 * allowed to obtain any priority on any action. 10697 */ 10698 private void adjustPriority( 10699 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10700 // nothing to do; priority is fine as-is 10701 if (intent.getPriority() <= 0) { 10702 return; 10703 } 10704 10705 final ActivityInfo activityInfo = intent.activity.info; 10706 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10707 10708 final boolean privilegedApp = 10709 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10710 if (!privilegedApp) { 10711 // non-privileged applications can never define a priority >0 10712 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10713 + " package: " + applicationInfo.packageName 10714 + " activity: " + intent.activity.className 10715 + " origPrio: " + intent.getPriority()); 10716 intent.setPriority(0); 10717 return; 10718 } 10719 10720 if (systemActivities == null) { 10721 // the system package is not disabled; we're parsing the system partition 10722 if (isProtectedAction(intent)) { 10723 if (mDeferProtectedFilters) { 10724 // We can't deal with these just yet. No component should ever obtain a 10725 // >0 priority for a protected actions, with ONE exception -- the setup 10726 // wizard. The setup wizard, however, cannot be known until we're able to 10727 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10728 // until all intent filters have been processed. Chicken, meet egg. 10729 // Let the filter temporarily have a high priority and rectify the 10730 // priorities after all system packages have been scanned. 10731 mProtectedFilters.add(intent); 10732 if (DEBUG_FILTERS) { 10733 Slog.i(TAG, "Protected action; save for later;" 10734 + " package: " + applicationInfo.packageName 10735 + " activity: " + intent.activity.className 10736 + " origPrio: " + intent.getPriority()); 10737 } 10738 return; 10739 } else { 10740 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10741 Slog.i(TAG, "No setup wizard;" 10742 + " All protected intents capped to priority 0"); 10743 } 10744 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10745 if (DEBUG_FILTERS) { 10746 Slog.i(TAG, "Found setup wizard;" 10747 + " allow priority " + intent.getPriority() + ";" 10748 + " package: " + intent.activity.info.packageName 10749 + " activity: " + intent.activity.className 10750 + " priority: " + intent.getPriority()); 10751 } 10752 // setup wizard gets whatever it wants 10753 return; 10754 } 10755 Slog.w(TAG, "Protected action; cap priority to 0;" 10756 + " package: " + intent.activity.info.packageName 10757 + " activity: " + intent.activity.className 10758 + " origPrio: " + intent.getPriority()); 10759 intent.setPriority(0); 10760 return; 10761 } 10762 } 10763 // privileged apps on the system image get whatever priority they request 10764 return; 10765 } 10766 10767 // privileged app unbundled update ... try to find the same activity 10768 final PackageParser.Activity foundActivity = 10769 findMatchingActivity(systemActivities, activityInfo); 10770 if (foundActivity == null) { 10771 // this is a new activity; it cannot obtain >0 priority 10772 if (DEBUG_FILTERS) { 10773 Slog.i(TAG, "New activity; cap priority to 0;" 10774 + " package: " + applicationInfo.packageName 10775 + " activity: " + intent.activity.className 10776 + " origPrio: " + intent.getPriority()); 10777 } 10778 intent.setPriority(0); 10779 return; 10780 } 10781 10782 // found activity, now check for filter equivalence 10783 10784 // a shallow copy is enough; we modify the list, not its contents 10785 final List<ActivityIntentInfo> intentListCopy = 10786 new ArrayList<>(foundActivity.intents); 10787 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10788 10789 // find matching action subsets 10790 final Iterator<String> actionsIterator = intent.actionsIterator(); 10791 if (actionsIterator != null) { 10792 getIntentListSubset( 10793 intentListCopy, new ActionIterGenerator(), actionsIterator); 10794 if (intentListCopy.size() == 0) { 10795 // no more intents to match; we're not equivalent 10796 if (DEBUG_FILTERS) { 10797 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10798 + " package: " + applicationInfo.packageName 10799 + " activity: " + intent.activity.className 10800 + " origPrio: " + intent.getPriority()); 10801 } 10802 intent.setPriority(0); 10803 return; 10804 } 10805 } 10806 10807 // find matching category subsets 10808 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10809 if (categoriesIterator != null) { 10810 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10811 categoriesIterator); 10812 if (intentListCopy.size() == 0) { 10813 // no more intents to match; we're not equivalent 10814 if (DEBUG_FILTERS) { 10815 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10816 + " package: " + applicationInfo.packageName 10817 + " activity: " + intent.activity.className 10818 + " origPrio: " + intent.getPriority()); 10819 } 10820 intent.setPriority(0); 10821 return; 10822 } 10823 } 10824 10825 // find matching schemes subsets 10826 final Iterator<String> schemesIterator = intent.schemesIterator(); 10827 if (schemesIterator != null) { 10828 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10829 schemesIterator); 10830 if (intentListCopy.size() == 0) { 10831 // no more intents to match; we're not equivalent 10832 if (DEBUG_FILTERS) { 10833 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10834 + " package: " + applicationInfo.packageName 10835 + " activity: " + intent.activity.className 10836 + " origPrio: " + intent.getPriority()); 10837 } 10838 intent.setPriority(0); 10839 return; 10840 } 10841 } 10842 10843 // find matching authorities subsets 10844 final Iterator<IntentFilter.AuthorityEntry> 10845 authoritiesIterator = intent.authoritiesIterator(); 10846 if (authoritiesIterator != null) { 10847 getIntentListSubset(intentListCopy, 10848 new AuthoritiesIterGenerator(), 10849 authoritiesIterator); 10850 if (intentListCopy.size() == 0) { 10851 // no more intents to match; we're not equivalent 10852 if (DEBUG_FILTERS) { 10853 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10854 + " package: " + applicationInfo.packageName 10855 + " activity: " + intent.activity.className 10856 + " origPrio: " + intent.getPriority()); 10857 } 10858 intent.setPriority(0); 10859 return; 10860 } 10861 } 10862 10863 // we found matching filter(s); app gets the max priority of all intents 10864 int cappedPriority = 0; 10865 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10866 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10867 } 10868 if (intent.getPriority() > cappedPriority) { 10869 if (DEBUG_FILTERS) { 10870 Slog.i(TAG, "Found matching filter(s);" 10871 + " cap priority to " + cappedPriority + ";" 10872 + " package: " + applicationInfo.packageName 10873 + " activity: " + intent.activity.className 10874 + " origPrio: " + intent.getPriority()); 10875 } 10876 intent.setPriority(cappedPriority); 10877 return; 10878 } 10879 // all this for nothing; the requested priority was <= what was on the system 10880 } 10881 10882 public final void addActivity(PackageParser.Activity a, String type) { 10883 mActivities.put(a.getComponentName(), a); 10884 if (DEBUG_SHOW_INFO) 10885 Log.v( 10886 TAG, " " + type + " " + 10887 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10888 if (DEBUG_SHOW_INFO) 10889 Log.v(TAG, " Class=" + a.info.name); 10890 final int NI = a.intents.size(); 10891 for (int j=0; j<NI; j++) { 10892 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10893 if ("activity".equals(type)) { 10894 final PackageSetting ps = 10895 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10896 final List<PackageParser.Activity> systemActivities = 10897 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10898 adjustPriority(systemActivities, intent); 10899 } 10900 if (DEBUG_SHOW_INFO) { 10901 Log.v(TAG, " IntentFilter:"); 10902 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10903 } 10904 if (!intent.debugCheck()) { 10905 Log.w(TAG, "==> For Activity " + a.info.name); 10906 } 10907 addFilter(intent); 10908 } 10909 } 10910 10911 public final void removeActivity(PackageParser.Activity a, String type) { 10912 mActivities.remove(a.getComponentName()); 10913 if (DEBUG_SHOW_INFO) { 10914 Log.v(TAG, " " + type + " " 10915 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10916 : a.info.name) + ":"); 10917 Log.v(TAG, " Class=" + a.info.name); 10918 } 10919 final int NI = a.intents.size(); 10920 for (int j=0; j<NI; j++) { 10921 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10922 if (DEBUG_SHOW_INFO) { 10923 Log.v(TAG, " IntentFilter:"); 10924 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10925 } 10926 removeFilter(intent); 10927 } 10928 } 10929 10930 @Override 10931 protected boolean allowFilterResult( 10932 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10933 ActivityInfo filterAi = filter.activity.info; 10934 for (int i=dest.size()-1; i>=0; i--) { 10935 ActivityInfo destAi = dest.get(i).activityInfo; 10936 if (destAi.name == filterAi.name 10937 && destAi.packageName == filterAi.packageName) { 10938 return false; 10939 } 10940 } 10941 return true; 10942 } 10943 10944 @Override 10945 protected ActivityIntentInfo[] newArray(int size) { 10946 return new ActivityIntentInfo[size]; 10947 } 10948 10949 @Override 10950 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10951 if (!sUserManager.exists(userId)) return true; 10952 PackageParser.Package p = filter.activity.owner; 10953 if (p != null) { 10954 PackageSetting ps = (PackageSetting)p.mExtras; 10955 if (ps != null) { 10956 // System apps are never considered stopped for purposes of 10957 // filtering, because there may be no way for the user to 10958 // actually re-launch them. 10959 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10960 && ps.getStopped(userId); 10961 } 10962 } 10963 return false; 10964 } 10965 10966 @Override 10967 protected boolean isPackageForFilter(String packageName, 10968 PackageParser.ActivityIntentInfo info) { 10969 return packageName.equals(info.activity.owner.packageName); 10970 } 10971 10972 @Override 10973 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10974 int match, int userId) { 10975 if (!sUserManager.exists(userId)) return null; 10976 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10977 return null; 10978 } 10979 final PackageParser.Activity activity = info.activity; 10980 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10981 if (ps == null) { 10982 return null; 10983 } 10984 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10985 ps.readUserState(userId), userId); 10986 if (ai == null) { 10987 return null; 10988 } 10989 final ResolveInfo res = new ResolveInfo(); 10990 res.activityInfo = ai; 10991 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10992 res.filter = info; 10993 } 10994 if (info != null) { 10995 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10996 } 10997 res.priority = info.getPriority(); 10998 res.preferredOrder = activity.owner.mPreferredOrder; 10999 //System.out.println("Result: " + res.activityInfo.className + 11000 // " = " + res.priority); 11001 res.match = match; 11002 res.isDefault = info.hasDefault; 11003 res.labelRes = info.labelRes; 11004 res.nonLocalizedLabel = info.nonLocalizedLabel; 11005 if (userNeedsBadging(userId)) { 11006 res.noResourceId = true; 11007 } else { 11008 res.icon = info.icon; 11009 } 11010 res.iconResourceId = info.icon; 11011 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11012 return res; 11013 } 11014 11015 @Override 11016 protected void sortResults(List<ResolveInfo> results) { 11017 Collections.sort(results, mResolvePrioritySorter); 11018 } 11019 11020 @Override 11021 protected void dumpFilter(PrintWriter out, String prefix, 11022 PackageParser.ActivityIntentInfo filter) { 11023 out.print(prefix); out.print( 11024 Integer.toHexString(System.identityHashCode(filter.activity))); 11025 out.print(' '); 11026 filter.activity.printComponentShortName(out); 11027 out.print(" filter "); 11028 out.println(Integer.toHexString(System.identityHashCode(filter))); 11029 } 11030 11031 @Override 11032 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11033 return filter.activity; 11034 } 11035 11036 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11037 PackageParser.Activity activity = (PackageParser.Activity)label; 11038 out.print(prefix); out.print( 11039 Integer.toHexString(System.identityHashCode(activity))); 11040 out.print(' '); 11041 activity.printComponentShortName(out); 11042 if (count > 1) { 11043 out.print(" ("); out.print(count); out.print(" filters)"); 11044 } 11045 out.println(); 11046 } 11047 11048 // Keys are String (activity class name), values are Activity. 11049 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11050 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11051 private int mFlags; 11052 } 11053 11054 private final class ServiceIntentResolver 11055 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11056 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11057 boolean defaultOnly, int userId) { 11058 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11059 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11060 } 11061 11062 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11063 int userId) { 11064 if (!sUserManager.exists(userId)) return null; 11065 mFlags = flags; 11066 return super.queryIntent(intent, resolvedType, 11067 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11068 } 11069 11070 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11071 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11072 if (!sUserManager.exists(userId)) return null; 11073 if (packageServices == null) { 11074 return null; 11075 } 11076 mFlags = flags; 11077 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11078 final int N = packageServices.size(); 11079 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11080 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11081 11082 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11083 for (int i = 0; i < N; ++i) { 11084 intentFilters = packageServices.get(i).intents; 11085 if (intentFilters != null && intentFilters.size() > 0) { 11086 PackageParser.ServiceIntentInfo[] array = 11087 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11088 intentFilters.toArray(array); 11089 listCut.add(array); 11090 } 11091 } 11092 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11093 } 11094 11095 public final void addService(PackageParser.Service s) { 11096 mServices.put(s.getComponentName(), s); 11097 if (DEBUG_SHOW_INFO) { 11098 Log.v(TAG, " " 11099 + (s.info.nonLocalizedLabel != null 11100 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11101 Log.v(TAG, " Class=" + s.info.name); 11102 } 11103 final int NI = s.intents.size(); 11104 int j; 11105 for (j=0; j<NI; j++) { 11106 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11107 if (DEBUG_SHOW_INFO) { 11108 Log.v(TAG, " IntentFilter:"); 11109 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11110 } 11111 if (!intent.debugCheck()) { 11112 Log.w(TAG, "==> For Service " + s.info.name); 11113 } 11114 addFilter(intent); 11115 } 11116 } 11117 11118 public final void removeService(PackageParser.Service s) { 11119 mServices.remove(s.getComponentName()); 11120 if (DEBUG_SHOW_INFO) { 11121 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11122 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11123 Log.v(TAG, " Class=" + s.info.name); 11124 } 11125 final int NI = s.intents.size(); 11126 int j; 11127 for (j=0; j<NI; j++) { 11128 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11129 if (DEBUG_SHOW_INFO) { 11130 Log.v(TAG, " IntentFilter:"); 11131 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11132 } 11133 removeFilter(intent); 11134 } 11135 } 11136 11137 @Override 11138 protected boolean allowFilterResult( 11139 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11140 ServiceInfo filterSi = filter.service.info; 11141 for (int i=dest.size()-1; i>=0; i--) { 11142 ServiceInfo destAi = dest.get(i).serviceInfo; 11143 if (destAi.name == filterSi.name 11144 && destAi.packageName == filterSi.packageName) { 11145 return false; 11146 } 11147 } 11148 return true; 11149 } 11150 11151 @Override 11152 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11153 return new PackageParser.ServiceIntentInfo[size]; 11154 } 11155 11156 @Override 11157 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11158 if (!sUserManager.exists(userId)) return true; 11159 PackageParser.Package p = filter.service.owner; 11160 if (p != null) { 11161 PackageSetting ps = (PackageSetting)p.mExtras; 11162 if (ps != null) { 11163 // System apps are never considered stopped for purposes of 11164 // filtering, because there may be no way for the user to 11165 // actually re-launch them. 11166 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11167 && ps.getStopped(userId); 11168 } 11169 } 11170 return false; 11171 } 11172 11173 @Override 11174 protected boolean isPackageForFilter(String packageName, 11175 PackageParser.ServiceIntentInfo info) { 11176 return packageName.equals(info.service.owner.packageName); 11177 } 11178 11179 @Override 11180 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11181 int match, int userId) { 11182 if (!sUserManager.exists(userId)) return null; 11183 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11184 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11185 return null; 11186 } 11187 final PackageParser.Service service = info.service; 11188 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11189 if (ps == null) { 11190 return null; 11191 } 11192 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11193 ps.readUserState(userId), userId); 11194 if (si == null) { 11195 return null; 11196 } 11197 final ResolveInfo res = new ResolveInfo(); 11198 res.serviceInfo = si; 11199 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11200 res.filter = filter; 11201 } 11202 res.priority = info.getPriority(); 11203 res.preferredOrder = service.owner.mPreferredOrder; 11204 res.match = match; 11205 res.isDefault = info.hasDefault; 11206 res.labelRes = info.labelRes; 11207 res.nonLocalizedLabel = info.nonLocalizedLabel; 11208 res.icon = info.icon; 11209 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11210 return res; 11211 } 11212 11213 @Override 11214 protected void sortResults(List<ResolveInfo> results) { 11215 Collections.sort(results, mResolvePrioritySorter); 11216 } 11217 11218 @Override 11219 protected void dumpFilter(PrintWriter out, String prefix, 11220 PackageParser.ServiceIntentInfo filter) { 11221 out.print(prefix); out.print( 11222 Integer.toHexString(System.identityHashCode(filter.service))); 11223 out.print(' '); 11224 filter.service.printComponentShortName(out); 11225 out.print(" filter "); 11226 out.println(Integer.toHexString(System.identityHashCode(filter))); 11227 } 11228 11229 @Override 11230 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11231 return filter.service; 11232 } 11233 11234 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11235 PackageParser.Service service = (PackageParser.Service)label; 11236 out.print(prefix); out.print( 11237 Integer.toHexString(System.identityHashCode(service))); 11238 out.print(' '); 11239 service.printComponentShortName(out); 11240 if (count > 1) { 11241 out.print(" ("); out.print(count); out.print(" filters)"); 11242 } 11243 out.println(); 11244 } 11245 11246// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11247// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11248// final List<ResolveInfo> retList = Lists.newArrayList(); 11249// while (i.hasNext()) { 11250// final ResolveInfo resolveInfo = (ResolveInfo) i; 11251// if (isEnabledLP(resolveInfo.serviceInfo)) { 11252// retList.add(resolveInfo); 11253// } 11254// } 11255// return retList; 11256// } 11257 11258 // Keys are String (activity class name), values are Activity. 11259 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11260 = new ArrayMap<ComponentName, PackageParser.Service>(); 11261 private int mFlags; 11262 }; 11263 11264 private final class ProviderIntentResolver 11265 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11266 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11267 boolean defaultOnly, int userId) { 11268 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11269 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11270 } 11271 11272 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11273 int userId) { 11274 if (!sUserManager.exists(userId)) 11275 return null; 11276 mFlags = flags; 11277 return super.queryIntent(intent, resolvedType, 11278 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11279 } 11280 11281 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11282 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11283 if (!sUserManager.exists(userId)) 11284 return null; 11285 if (packageProviders == null) { 11286 return null; 11287 } 11288 mFlags = flags; 11289 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11290 final int N = packageProviders.size(); 11291 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11292 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11293 11294 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11295 for (int i = 0; i < N; ++i) { 11296 intentFilters = packageProviders.get(i).intents; 11297 if (intentFilters != null && intentFilters.size() > 0) { 11298 PackageParser.ProviderIntentInfo[] array = 11299 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11300 intentFilters.toArray(array); 11301 listCut.add(array); 11302 } 11303 } 11304 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11305 } 11306 11307 public final void addProvider(PackageParser.Provider p) { 11308 if (mProviders.containsKey(p.getComponentName())) { 11309 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11310 return; 11311 } 11312 11313 mProviders.put(p.getComponentName(), p); 11314 if (DEBUG_SHOW_INFO) { 11315 Log.v(TAG, " " 11316 + (p.info.nonLocalizedLabel != null 11317 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11318 Log.v(TAG, " Class=" + p.info.name); 11319 } 11320 final int NI = p.intents.size(); 11321 int j; 11322 for (j = 0; j < NI; j++) { 11323 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11324 if (DEBUG_SHOW_INFO) { 11325 Log.v(TAG, " IntentFilter:"); 11326 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11327 } 11328 if (!intent.debugCheck()) { 11329 Log.w(TAG, "==> For Provider " + p.info.name); 11330 } 11331 addFilter(intent); 11332 } 11333 } 11334 11335 public final void removeProvider(PackageParser.Provider p) { 11336 mProviders.remove(p.getComponentName()); 11337 if (DEBUG_SHOW_INFO) { 11338 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11339 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11340 Log.v(TAG, " Class=" + p.info.name); 11341 } 11342 final int NI = p.intents.size(); 11343 int j; 11344 for (j = 0; j < NI; j++) { 11345 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11346 if (DEBUG_SHOW_INFO) { 11347 Log.v(TAG, " IntentFilter:"); 11348 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11349 } 11350 removeFilter(intent); 11351 } 11352 } 11353 11354 @Override 11355 protected boolean allowFilterResult( 11356 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11357 ProviderInfo filterPi = filter.provider.info; 11358 for (int i = dest.size() - 1; i >= 0; i--) { 11359 ProviderInfo destPi = dest.get(i).providerInfo; 11360 if (destPi.name == filterPi.name 11361 && destPi.packageName == filterPi.packageName) { 11362 return false; 11363 } 11364 } 11365 return true; 11366 } 11367 11368 @Override 11369 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11370 return new PackageParser.ProviderIntentInfo[size]; 11371 } 11372 11373 @Override 11374 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11375 if (!sUserManager.exists(userId)) 11376 return true; 11377 PackageParser.Package p = filter.provider.owner; 11378 if (p != null) { 11379 PackageSetting ps = (PackageSetting) p.mExtras; 11380 if (ps != null) { 11381 // System apps are never considered stopped for purposes of 11382 // filtering, because there may be no way for the user to 11383 // actually re-launch them. 11384 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11385 && ps.getStopped(userId); 11386 } 11387 } 11388 return false; 11389 } 11390 11391 @Override 11392 protected boolean isPackageForFilter(String packageName, 11393 PackageParser.ProviderIntentInfo info) { 11394 return packageName.equals(info.provider.owner.packageName); 11395 } 11396 11397 @Override 11398 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11399 int match, int userId) { 11400 if (!sUserManager.exists(userId)) 11401 return null; 11402 final PackageParser.ProviderIntentInfo info = filter; 11403 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11404 return null; 11405 } 11406 final PackageParser.Provider provider = info.provider; 11407 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11408 if (ps == null) { 11409 return null; 11410 } 11411 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11412 ps.readUserState(userId), userId); 11413 if (pi == null) { 11414 return null; 11415 } 11416 final ResolveInfo res = new ResolveInfo(); 11417 res.providerInfo = pi; 11418 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11419 res.filter = filter; 11420 } 11421 res.priority = info.getPriority(); 11422 res.preferredOrder = provider.owner.mPreferredOrder; 11423 res.match = match; 11424 res.isDefault = info.hasDefault; 11425 res.labelRes = info.labelRes; 11426 res.nonLocalizedLabel = info.nonLocalizedLabel; 11427 res.icon = info.icon; 11428 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11429 return res; 11430 } 11431 11432 @Override 11433 protected void sortResults(List<ResolveInfo> results) { 11434 Collections.sort(results, mResolvePrioritySorter); 11435 } 11436 11437 @Override 11438 protected void dumpFilter(PrintWriter out, String prefix, 11439 PackageParser.ProviderIntentInfo filter) { 11440 out.print(prefix); 11441 out.print( 11442 Integer.toHexString(System.identityHashCode(filter.provider))); 11443 out.print(' '); 11444 filter.provider.printComponentShortName(out); 11445 out.print(" filter "); 11446 out.println(Integer.toHexString(System.identityHashCode(filter))); 11447 } 11448 11449 @Override 11450 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11451 return filter.provider; 11452 } 11453 11454 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11455 PackageParser.Provider provider = (PackageParser.Provider)label; 11456 out.print(prefix); out.print( 11457 Integer.toHexString(System.identityHashCode(provider))); 11458 out.print(' '); 11459 provider.printComponentShortName(out); 11460 if (count > 1) { 11461 out.print(" ("); out.print(count); out.print(" filters)"); 11462 } 11463 out.println(); 11464 } 11465 11466 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11467 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11468 private int mFlags; 11469 } 11470 11471 private static final class EphemeralIntentResolver 11472 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveIntentInfo> { 11473 /** 11474 * The result that has the highest defined order. Ordering applies on a 11475 * per-package basis. Mapping is from package name to Pair of order and 11476 * EphemeralResolveInfo. 11477 * <p> 11478 * NOTE: This is implemented as a field variable for convenience and efficiency. 11479 * By having a field variable, we're able to track filter ordering as soon as 11480 * a non-zero order is defined. Otherwise, multiple loops across the result set 11481 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11482 * this needs to be contained entirely within {@link #filterResults()}. 11483 */ 11484 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11485 11486 @Override 11487 protected EphemeralResolveIntentInfo[] newArray(int size) { 11488 return new EphemeralResolveIntentInfo[size]; 11489 } 11490 11491 @Override 11492 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11493 return true; 11494 } 11495 11496 @Override 11497 protected EphemeralResolveIntentInfo newResult(EphemeralResolveIntentInfo info, int match, 11498 int userId) { 11499 if (!sUserManager.exists(userId)) { 11500 return null; 11501 } 11502 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11503 final Integer order = info.getOrder(); 11504 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11505 mOrderResult.get(packageName); 11506 // ordering is enabled and this item's order isn't high enough 11507 if (lastOrderResult != null && lastOrderResult.first >= order) { 11508 return null; 11509 } 11510 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11511 if (order > 0) { 11512 // non-zero order, enable ordering 11513 mOrderResult.put(packageName, new Pair<>(order, res)); 11514 } 11515 return info; 11516 } 11517 11518 @Override 11519 protected void filterResults(List<EphemeralResolveIntentInfo> results) { 11520 // only do work if ordering is enabled [most of the time it won't be] 11521 if (mOrderResult.size() == 0) { 11522 return; 11523 } 11524 int resultSize = results.size(); 11525 for (int i = 0; i < resultSize; i++) { 11526 final EphemeralResolveInfo info = results.get(i).getEphemeralResolveInfo(); 11527 final String packageName = info.getPackageName(); 11528 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11529 if (savedInfo == null) { 11530 // package doesn't having ordering 11531 continue; 11532 } 11533 if (savedInfo.second == info) { 11534 // circled back to the highest ordered item; remove from order list 11535 mOrderResult.remove(savedInfo); 11536 if (mOrderResult.size() == 0) { 11537 // no more ordered items 11538 break; 11539 } 11540 continue; 11541 } 11542 // item has a worse order, remove it from the result list 11543 results.remove(i); 11544 resultSize--; 11545 i--; 11546 } 11547 } 11548 } 11549 11550 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11551 new Comparator<ResolveInfo>() { 11552 public int compare(ResolveInfo r1, ResolveInfo r2) { 11553 int v1 = r1.priority; 11554 int v2 = r2.priority; 11555 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11556 if (v1 != v2) { 11557 return (v1 > v2) ? -1 : 1; 11558 } 11559 v1 = r1.preferredOrder; 11560 v2 = r2.preferredOrder; 11561 if (v1 != v2) { 11562 return (v1 > v2) ? -1 : 1; 11563 } 11564 if (r1.isDefault != r2.isDefault) { 11565 return r1.isDefault ? -1 : 1; 11566 } 11567 v1 = r1.match; 11568 v2 = r2.match; 11569 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11570 if (v1 != v2) { 11571 return (v1 > v2) ? -1 : 1; 11572 } 11573 if (r1.system != r2.system) { 11574 return r1.system ? -1 : 1; 11575 } 11576 if (r1.activityInfo != null) { 11577 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11578 } 11579 if (r1.serviceInfo != null) { 11580 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11581 } 11582 if (r1.providerInfo != null) { 11583 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11584 } 11585 return 0; 11586 } 11587 }; 11588 11589 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11590 new Comparator<ProviderInfo>() { 11591 public int compare(ProviderInfo p1, ProviderInfo p2) { 11592 final int v1 = p1.initOrder; 11593 final int v2 = p2.initOrder; 11594 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11595 } 11596 }; 11597 11598 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11599 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11600 final int[] userIds) { 11601 mHandler.post(new Runnable() { 11602 @Override 11603 public void run() { 11604 try { 11605 final IActivityManager am = ActivityManager.getService(); 11606 if (am == null) return; 11607 final int[] resolvedUserIds; 11608 if (userIds == null) { 11609 resolvedUserIds = am.getRunningUserIds(); 11610 } else { 11611 resolvedUserIds = userIds; 11612 } 11613 for (int id : resolvedUserIds) { 11614 final Intent intent = new Intent(action, 11615 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11616 if (extras != null) { 11617 intent.putExtras(extras); 11618 } 11619 if (targetPkg != null) { 11620 intent.setPackage(targetPkg); 11621 } 11622 // Modify the UID when posting to other users 11623 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11624 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11625 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11626 intent.putExtra(Intent.EXTRA_UID, uid); 11627 } 11628 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11629 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11630 if (DEBUG_BROADCASTS) { 11631 RuntimeException here = new RuntimeException("here"); 11632 here.fillInStackTrace(); 11633 Slog.d(TAG, "Sending to user " + id + ": " 11634 + intent.toShortString(false, true, false, false) 11635 + " " + intent.getExtras(), here); 11636 } 11637 am.broadcastIntent(null, intent, null, finishedReceiver, 11638 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11639 null, finishedReceiver != null, false, id); 11640 } 11641 } catch (RemoteException ex) { 11642 } 11643 } 11644 }); 11645 } 11646 11647 /** 11648 * Check if the external storage media is available. This is true if there 11649 * is a mounted external storage medium or if the external storage is 11650 * emulated. 11651 */ 11652 private boolean isExternalMediaAvailable() { 11653 return mMediaMounted || Environment.isExternalStorageEmulated(); 11654 } 11655 11656 @Override 11657 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11658 // writer 11659 synchronized (mPackages) { 11660 if (!isExternalMediaAvailable()) { 11661 // If the external storage is no longer mounted at this point, 11662 // the caller may not have been able to delete all of this 11663 // packages files and can not delete any more. Bail. 11664 return null; 11665 } 11666 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11667 if (lastPackage != null) { 11668 pkgs.remove(lastPackage); 11669 } 11670 if (pkgs.size() > 0) { 11671 return pkgs.get(0); 11672 } 11673 } 11674 return null; 11675 } 11676 11677 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11678 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11679 userId, andCode ? 1 : 0, packageName); 11680 if (mSystemReady) { 11681 msg.sendToTarget(); 11682 } else { 11683 if (mPostSystemReadyMessages == null) { 11684 mPostSystemReadyMessages = new ArrayList<>(); 11685 } 11686 mPostSystemReadyMessages.add(msg); 11687 } 11688 } 11689 11690 void startCleaningPackages() { 11691 // reader 11692 if (!isExternalMediaAvailable()) { 11693 return; 11694 } 11695 synchronized (mPackages) { 11696 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11697 return; 11698 } 11699 } 11700 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11701 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11702 IActivityManager am = ActivityManager.getService(); 11703 if (am != null) { 11704 try { 11705 am.startService(null, intent, null, mContext.getOpPackageName(), 11706 UserHandle.USER_SYSTEM); 11707 } catch (RemoteException e) { 11708 } 11709 } 11710 } 11711 11712 @Override 11713 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11714 int installFlags, String installerPackageName, int userId) { 11715 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11716 11717 final int callingUid = Binder.getCallingUid(); 11718 enforceCrossUserPermission(callingUid, userId, 11719 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11720 11721 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11722 try { 11723 if (observer != null) { 11724 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11725 } 11726 } catch (RemoteException re) { 11727 } 11728 return; 11729 } 11730 11731 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11732 installFlags |= PackageManager.INSTALL_FROM_ADB; 11733 11734 } else { 11735 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11736 // about installerPackageName. 11737 11738 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11739 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11740 } 11741 11742 UserHandle user; 11743 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11744 user = UserHandle.ALL; 11745 } else { 11746 user = new UserHandle(userId); 11747 } 11748 11749 // Only system components can circumvent runtime permissions when installing. 11750 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11751 && mContext.checkCallingOrSelfPermission(Manifest.permission 11752 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11753 throw new SecurityException("You need the " 11754 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11755 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11756 } 11757 11758 final File originFile = new File(originPath); 11759 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11760 11761 final Message msg = mHandler.obtainMessage(INIT_COPY); 11762 final VerificationInfo verificationInfo = new VerificationInfo( 11763 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11764 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11765 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11766 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11767 null /*certificates*/); 11768 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11769 msg.obj = params; 11770 11771 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11772 System.identityHashCode(msg.obj)); 11773 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11774 System.identityHashCode(msg.obj)); 11775 11776 mHandler.sendMessage(msg); 11777 } 11778 11779 void installStage(String packageName, File stagedDir, String stagedCid, 11780 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11781 String installerPackageName, int installerUid, UserHandle user, 11782 Certificate[][] certificates) { 11783 if (DEBUG_EPHEMERAL) { 11784 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11785 Slog.d(TAG, "Ephemeral install of " + packageName); 11786 } 11787 } 11788 final VerificationInfo verificationInfo = new VerificationInfo( 11789 sessionParams.originatingUri, sessionParams.referrerUri, 11790 sessionParams.originatingUid, installerUid); 11791 11792 final OriginInfo origin; 11793 if (stagedDir != null) { 11794 origin = OriginInfo.fromStagedFile(stagedDir); 11795 } else { 11796 origin = OriginInfo.fromStagedContainer(stagedCid); 11797 } 11798 11799 final Message msg = mHandler.obtainMessage(INIT_COPY); 11800 final InstallParams params = new InstallParams(origin, null, observer, 11801 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11802 verificationInfo, user, sessionParams.abiOverride, 11803 sessionParams.grantedRuntimePermissions, certificates); 11804 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11805 msg.obj = params; 11806 11807 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11808 System.identityHashCode(msg.obj)); 11809 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11810 System.identityHashCode(msg.obj)); 11811 11812 mHandler.sendMessage(msg); 11813 } 11814 11815 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11816 int userId) { 11817 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11818 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 11819 } 11820 11821 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 11822 int appId, int... userIds) { 11823 if (ArrayUtils.isEmpty(userIds)) { 11824 return; 11825 } 11826 Bundle extras = new Bundle(1); 11827 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 11828 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 11829 11830 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11831 packageName, extras, 0, null, null, userIds); 11832 if (isSystem) { 11833 mHandler.post(() -> { 11834 for (int userId : userIds) { 11835 sendBootCompletedBroadcastToSystemApp(packageName, userId); 11836 } 11837 } 11838 ); 11839 } 11840 } 11841 11842 /** 11843 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 11844 * automatically without needing an explicit launch. 11845 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 11846 */ 11847 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 11848 // If user is not running, the app didn't miss any broadcast 11849 if (!mUserManagerInternal.isUserRunning(userId)) { 11850 return; 11851 } 11852 final IActivityManager am = ActivityManager.getService(); 11853 try { 11854 // Deliver LOCKED_BOOT_COMPLETED first 11855 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 11856 .setPackage(packageName); 11857 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 11858 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 11859 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11860 11861 // Deliver BOOT_COMPLETED only if user is unlocked 11862 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 11863 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 11864 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 11865 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11866 } 11867 } catch (RemoteException e) { 11868 throw e.rethrowFromSystemServer(); 11869 } 11870 } 11871 11872 @Override 11873 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11874 int userId) { 11875 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11876 PackageSetting pkgSetting; 11877 final int uid = Binder.getCallingUid(); 11878 enforceCrossUserPermission(uid, userId, 11879 true /* requireFullPermission */, true /* checkShell */, 11880 "setApplicationHiddenSetting for user " + userId); 11881 11882 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11883 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11884 return false; 11885 } 11886 11887 long callingId = Binder.clearCallingIdentity(); 11888 try { 11889 boolean sendAdded = false; 11890 boolean sendRemoved = false; 11891 // writer 11892 synchronized (mPackages) { 11893 pkgSetting = mSettings.mPackages.get(packageName); 11894 if (pkgSetting == null) { 11895 return false; 11896 } 11897 // Do not allow "android" is being disabled 11898 if ("android".equals(packageName)) { 11899 Slog.w(TAG, "Cannot hide package: android"); 11900 return false; 11901 } 11902 // Only allow protected packages to hide themselves. 11903 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11904 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11905 Slog.w(TAG, "Not hiding protected package: " + packageName); 11906 return false; 11907 } 11908 11909 if (pkgSetting.getHidden(userId) != hidden) { 11910 pkgSetting.setHidden(hidden, userId); 11911 mSettings.writePackageRestrictionsLPr(userId); 11912 if (hidden) { 11913 sendRemoved = true; 11914 } else { 11915 sendAdded = true; 11916 } 11917 } 11918 } 11919 if (sendAdded) { 11920 sendPackageAddedForUser(packageName, pkgSetting, userId); 11921 return true; 11922 } 11923 if (sendRemoved) { 11924 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11925 "hiding pkg"); 11926 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11927 return true; 11928 } 11929 } finally { 11930 Binder.restoreCallingIdentity(callingId); 11931 } 11932 return false; 11933 } 11934 11935 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11936 int userId) { 11937 final PackageRemovedInfo info = new PackageRemovedInfo(); 11938 info.removedPackage = packageName; 11939 info.removedUsers = new int[] {userId}; 11940 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11941 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11942 } 11943 11944 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11945 if (pkgList.length > 0) { 11946 Bundle extras = new Bundle(1); 11947 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11948 11949 sendPackageBroadcast( 11950 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11951 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11952 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11953 new int[] {userId}); 11954 } 11955 } 11956 11957 /** 11958 * Returns true if application is not found or there was an error. Otherwise it returns 11959 * the hidden state of the package for the given user. 11960 */ 11961 @Override 11962 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11964 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11965 true /* requireFullPermission */, false /* checkShell */, 11966 "getApplicationHidden for user " + userId); 11967 PackageSetting pkgSetting; 11968 long callingId = Binder.clearCallingIdentity(); 11969 try { 11970 // writer 11971 synchronized (mPackages) { 11972 pkgSetting = mSettings.mPackages.get(packageName); 11973 if (pkgSetting == null) { 11974 return true; 11975 } 11976 return pkgSetting.getHidden(userId); 11977 } 11978 } finally { 11979 Binder.restoreCallingIdentity(callingId); 11980 } 11981 } 11982 11983 /** 11984 * @hide 11985 */ 11986 @Override 11987 public int installExistingPackageAsUser(String packageName, int userId) { 11988 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11989 null); 11990 PackageSetting pkgSetting; 11991 final int uid = Binder.getCallingUid(); 11992 enforceCrossUserPermission(uid, userId, 11993 true /* requireFullPermission */, true /* checkShell */, 11994 "installExistingPackage for user " + userId); 11995 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11996 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11997 } 11998 11999 long callingId = Binder.clearCallingIdentity(); 12000 try { 12001 boolean installed = false; 12002 12003 // writer 12004 synchronized (mPackages) { 12005 pkgSetting = mSettings.mPackages.get(packageName); 12006 if (pkgSetting == null) { 12007 return PackageManager.INSTALL_FAILED_INVALID_URI; 12008 } 12009 if (!pkgSetting.getInstalled(userId)) { 12010 pkgSetting.setInstalled(true, userId); 12011 pkgSetting.setHidden(false, userId); 12012 mSettings.writePackageRestrictionsLPr(userId); 12013 installed = true; 12014 } 12015 } 12016 12017 if (installed) { 12018 if (pkgSetting.pkg != null) { 12019 synchronized (mInstallLock) { 12020 // We don't need to freeze for a brand new install 12021 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12022 } 12023 } 12024 sendPackageAddedForUser(packageName, pkgSetting, userId); 12025 } 12026 } finally { 12027 Binder.restoreCallingIdentity(callingId); 12028 } 12029 12030 return PackageManager.INSTALL_SUCCEEDED; 12031 } 12032 12033 boolean isUserRestricted(int userId, String restrictionKey) { 12034 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12035 if (restrictions.getBoolean(restrictionKey, false)) { 12036 Log.w(TAG, "User is restricted: " + restrictionKey); 12037 return true; 12038 } 12039 return false; 12040 } 12041 12042 @Override 12043 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12044 int userId) { 12045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12046 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12047 true /* requireFullPermission */, true /* checkShell */, 12048 "setPackagesSuspended for user " + userId); 12049 12050 if (ArrayUtils.isEmpty(packageNames)) { 12051 return packageNames; 12052 } 12053 12054 // List of package names for whom the suspended state has changed. 12055 List<String> changedPackages = new ArrayList<>(packageNames.length); 12056 // List of package names for whom the suspended state is not set as requested in this 12057 // method. 12058 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12059 long callingId = Binder.clearCallingIdentity(); 12060 try { 12061 for (int i = 0; i < packageNames.length; i++) { 12062 String packageName = packageNames[i]; 12063 boolean changed = false; 12064 final int appId; 12065 synchronized (mPackages) { 12066 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12067 if (pkgSetting == null) { 12068 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12069 + "\". Skipping suspending/un-suspending."); 12070 unactionedPackages.add(packageName); 12071 continue; 12072 } 12073 appId = pkgSetting.appId; 12074 if (pkgSetting.getSuspended(userId) != suspended) { 12075 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12076 unactionedPackages.add(packageName); 12077 continue; 12078 } 12079 pkgSetting.setSuspended(suspended, userId); 12080 mSettings.writePackageRestrictionsLPr(userId); 12081 changed = true; 12082 changedPackages.add(packageName); 12083 } 12084 } 12085 12086 if (changed && suspended) { 12087 killApplication(packageName, UserHandle.getUid(userId, appId), 12088 "suspending package"); 12089 } 12090 } 12091 } finally { 12092 Binder.restoreCallingIdentity(callingId); 12093 } 12094 12095 if (!changedPackages.isEmpty()) { 12096 sendPackagesSuspendedForUser(changedPackages.toArray( 12097 new String[changedPackages.size()]), userId, suspended); 12098 } 12099 12100 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12101 } 12102 12103 @Override 12104 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12105 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12106 true /* requireFullPermission */, false /* checkShell */, 12107 "isPackageSuspendedForUser for user " + userId); 12108 synchronized (mPackages) { 12109 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12110 if (pkgSetting == null) { 12111 throw new IllegalArgumentException("Unknown target package: " + packageName); 12112 } 12113 return pkgSetting.getSuspended(userId); 12114 } 12115 } 12116 12117 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12118 if (isPackageDeviceAdmin(packageName, userId)) { 12119 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12120 + "\": has an active device admin"); 12121 return false; 12122 } 12123 12124 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12125 if (packageName.equals(activeLauncherPackageName)) { 12126 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12127 + "\": contains the active launcher"); 12128 return false; 12129 } 12130 12131 if (packageName.equals(mRequiredInstallerPackage)) { 12132 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12133 + "\": required for package installation"); 12134 return false; 12135 } 12136 12137 if (packageName.equals(mRequiredUninstallerPackage)) { 12138 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12139 + "\": required for package uninstallation"); 12140 return false; 12141 } 12142 12143 if (packageName.equals(mRequiredVerifierPackage)) { 12144 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12145 + "\": required for package verification"); 12146 return false; 12147 } 12148 12149 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12150 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12151 + "\": is the default dialer"); 12152 return false; 12153 } 12154 12155 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12156 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12157 + "\": protected package"); 12158 return false; 12159 } 12160 12161 return true; 12162 } 12163 12164 private String getActiveLauncherPackageName(int userId) { 12165 Intent intent = new Intent(Intent.ACTION_MAIN); 12166 intent.addCategory(Intent.CATEGORY_HOME); 12167 ResolveInfo resolveInfo = resolveIntent( 12168 intent, 12169 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12170 PackageManager.MATCH_DEFAULT_ONLY, 12171 userId); 12172 12173 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12174 } 12175 12176 private String getDefaultDialerPackageName(int userId) { 12177 synchronized (mPackages) { 12178 return mSettings.getDefaultDialerPackageNameLPw(userId); 12179 } 12180 } 12181 12182 @Override 12183 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12184 mContext.enforceCallingOrSelfPermission( 12185 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12186 "Only package verification agents can verify applications"); 12187 12188 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12189 final PackageVerificationResponse response = new PackageVerificationResponse( 12190 verificationCode, Binder.getCallingUid()); 12191 msg.arg1 = id; 12192 msg.obj = response; 12193 mHandler.sendMessage(msg); 12194 } 12195 12196 @Override 12197 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12198 long millisecondsToDelay) { 12199 mContext.enforceCallingOrSelfPermission( 12200 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12201 "Only package verification agents can extend verification timeouts"); 12202 12203 final PackageVerificationState state = mPendingVerification.get(id); 12204 final PackageVerificationResponse response = new PackageVerificationResponse( 12205 verificationCodeAtTimeout, Binder.getCallingUid()); 12206 12207 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12208 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12209 } 12210 if (millisecondsToDelay < 0) { 12211 millisecondsToDelay = 0; 12212 } 12213 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12214 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12215 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12216 } 12217 12218 if ((state != null) && !state.timeoutExtended()) { 12219 state.extendTimeout(); 12220 12221 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12222 msg.arg1 = id; 12223 msg.obj = response; 12224 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12225 } 12226 } 12227 12228 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12229 int verificationCode, UserHandle user) { 12230 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12231 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12232 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12233 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12234 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12235 12236 mContext.sendBroadcastAsUser(intent, user, 12237 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12238 } 12239 12240 private ComponentName matchComponentForVerifier(String packageName, 12241 List<ResolveInfo> receivers) { 12242 ActivityInfo targetReceiver = null; 12243 12244 final int NR = receivers.size(); 12245 for (int i = 0; i < NR; i++) { 12246 final ResolveInfo info = receivers.get(i); 12247 if (info.activityInfo == null) { 12248 continue; 12249 } 12250 12251 if (packageName.equals(info.activityInfo.packageName)) { 12252 targetReceiver = info.activityInfo; 12253 break; 12254 } 12255 } 12256 12257 if (targetReceiver == null) { 12258 return null; 12259 } 12260 12261 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12262 } 12263 12264 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12265 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12266 if (pkgInfo.verifiers.length == 0) { 12267 return null; 12268 } 12269 12270 final int N = pkgInfo.verifiers.length; 12271 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12272 for (int i = 0; i < N; i++) { 12273 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12274 12275 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12276 receivers); 12277 if (comp == null) { 12278 continue; 12279 } 12280 12281 final int verifierUid = getUidForVerifier(verifierInfo); 12282 if (verifierUid == -1) { 12283 continue; 12284 } 12285 12286 if (DEBUG_VERIFY) { 12287 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12288 + " with the correct signature"); 12289 } 12290 sufficientVerifiers.add(comp); 12291 verificationState.addSufficientVerifier(verifierUid); 12292 } 12293 12294 return sufficientVerifiers; 12295 } 12296 12297 private int getUidForVerifier(VerifierInfo verifierInfo) { 12298 synchronized (mPackages) { 12299 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12300 if (pkg == null) { 12301 return -1; 12302 } else if (pkg.mSignatures.length != 1) { 12303 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12304 + " has more than one signature; ignoring"); 12305 return -1; 12306 } 12307 12308 /* 12309 * If the public key of the package's signature does not match 12310 * our expected public key, then this is a different package and 12311 * we should skip. 12312 */ 12313 12314 final byte[] expectedPublicKey; 12315 try { 12316 final Signature verifierSig = pkg.mSignatures[0]; 12317 final PublicKey publicKey = verifierSig.getPublicKey(); 12318 expectedPublicKey = publicKey.getEncoded(); 12319 } catch (CertificateException e) { 12320 return -1; 12321 } 12322 12323 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12324 12325 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12326 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12327 + " does not have the expected public key; ignoring"); 12328 return -1; 12329 } 12330 12331 return pkg.applicationInfo.uid; 12332 } 12333 } 12334 12335 @Override 12336 public void finishPackageInstall(int token, boolean didLaunch) { 12337 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12338 12339 if (DEBUG_INSTALL) { 12340 Slog.v(TAG, "BM finishing package install for " + token); 12341 } 12342 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12343 12344 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12345 mHandler.sendMessage(msg); 12346 } 12347 12348 /** 12349 * Get the verification agent timeout. 12350 * 12351 * @return verification timeout in milliseconds 12352 */ 12353 private long getVerificationTimeout() { 12354 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12355 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12356 DEFAULT_VERIFICATION_TIMEOUT); 12357 } 12358 12359 /** 12360 * Get the default verification agent response code. 12361 * 12362 * @return default verification response code 12363 */ 12364 private int getDefaultVerificationResponse() { 12365 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12366 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12367 DEFAULT_VERIFICATION_RESPONSE); 12368 } 12369 12370 /** 12371 * Check whether or not package verification has been enabled. 12372 * 12373 * @return true if verification should be performed 12374 */ 12375 private boolean isVerificationEnabled(int userId, int installFlags) { 12376 if (!DEFAULT_VERIFY_ENABLE) { 12377 return false; 12378 } 12379 // Ephemeral apps don't get the full verification treatment 12380 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12381 if (DEBUG_EPHEMERAL) { 12382 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12383 } 12384 return false; 12385 } 12386 12387 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12388 12389 // Check if installing from ADB 12390 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12391 // Do not run verification in a test harness environment 12392 if (ActivityManager.isRunningInTestHarness()) { 12393 return false; 12394 } 12395 if (ensureVerifyAppsEnabled) { 12396 return true; 12397 } 12398 // Check if the developer does not want package verification for ADB installs 12399 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12400 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12401 return false; 12402 } 12403 } 12404 12405 if (ensureVerifyAppsEnabled) { 12406 return true; 12407 } 12408 12409 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12410 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12411 } 12412 12413 @Override 12414 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12415 throws RemoteException { 12416 mContext.enforceCallingOrSelfPermission( 12417 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12418 "Only intentfilter verification agents can verify applications"); 12419 12420 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12421 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12422 Binder.getCallingUid(), verificationCode, failedDomains); 12423 msg.arg1 = id; 12424 msg.obj = response; 12425 mHandler.sendMessage(msg); 12426 } 12427 12428 @Override 12429 public int getIntentVerificationStatus(String packageName, int userId) { 12430 synchronized (mPackages) { 12431 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12432 } 12433 } 12434 12435 @Override 12436 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12437 mContext.enforceCallingOrSelfPermission( 12438 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12439 12440 boolean result = false; 12441 synchronized (mPackages) { 12442 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12443 } 12444 if (result) { 12445 scheduleWritePackageRestrictionsLocked(userId); 12446 } 12447 return result; 12448 } 12449 12450 @Override 12451 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12452 String packageName) { 12453 synchronized (mPackages) { 12454 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12455 } 12456 } 12457 12458 @Override 12459 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12460 if (TextUtils.isEmpty(packageName)) { 12461 return ParceledListSlice.emptyList(); 12462 } 12463 synchronized (mPackages) { 12464 PackageParser.Package pkg = mPackages.get(packageName); 12465 if (pkg == null || pkg.activities == null) { 12466 return ParceledListSlice.emptyList(); 12467 } 12468 final int count = pkg.activities.size(); 12469 ArrayList<IntentFilter> result = new ArrayList<>(); 12470 for (int n=0; n<count; n++) { 12471 PackageParser.Activity activity = pkg.activities.get(n); 12472 if (activity.intents != null && activity.intents.size() > 0) { 12473 result.addAll(activity.intents); 12474 } 12475 } 12476 return new ParceledListSlice<>(result); 12477 } 12478 } 12479 12480 @Override 12481 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12482 mContext.enforceCallingOrSelfPermission( 12483 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12484 12485 synchronized (mPackages) { 12486 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12487 if (packageName != null) { 12488 result |= updateIntentVerificationStatus(packageName, 12489 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12490 userId); 12491 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12492 packageName, userId); 12493 } 12494 return result; 12495 } 12496 } 12497 12498 @Override 12499 public String getDefaultBrowserPackageName(int userId) { 12500 synchronized (mPackages) { 12501 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12502 } 12503 } 12504 12505 /** 12506 * Get the "allow unknown sources" setting. 12507 * 12508 * @return the current "allow unknown sources" setting 12509 */ 12510 private int getUnknownSourcesSettings() { 12511 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12512 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12513 -1); 12514 } 12515 12516 @Override 12517 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12518 final int uid = Binder.getCallingUid(); 12519 // writer 12520 synchronized (mPackages) { 12521 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12522 if (targetPackageSetting == null) { 12523 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12524 } 12525 12526 PackageSetting installerPackageSetting; 12527 if (installerPackageName != null) { 12528 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12529 if (installerPackageSetting == null) { 12530 throw new IllegalArgumentException("Unknown installer package: " 12531 + installerPackageName); 12532 } 12533 } else { 12534 installerPackageSetting = null; 12535 } 12536 12537 Signature[] callerSignature; 12538 Object obj = mSettings.getUserIdLPr(uid); 12539 if (obj != null) { 12540 if (obj instanceof SharedUserSetting) { 12541 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12542 } else if (obj instanceof PackageSetting) { 12543 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12544 } else { 12545 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12546 } 12547 } else { 12548 throw new SecurityException("Unknown calling UID: " + uid); 12549 } 12550 12551 // Verify: can't set installerPackageName to a package that is 12552 // not signed with the same cert as the caller. 12553 if (installerPackageSetting != null) { 12554 if (compareSignatures(callerSignature, 12555 installerPackageSetting.signatures.mSignatures) 12556 != PackageManager.SIGNATURE_MATCH) { 12557 throw new SecurityException( 12558 "Caller does not have same cert as new installer package " 12559 + installerPackageName); 12560 } 12561 } 12562 12563 // Verify: if target already has an installer package, it must 12564 // be signed with the same cert as the caller. 12565 if (targetPackageSetting.installerPackageName != null) { 12566 PackageSetting setting = mSettings.mPackages.get( 12567 targetPackageSetting.installerPackageName); 12568 // If the currently set package isn't valid, then it's always 12569 // okay to change it. 12570 if (setting != null) { 12571 if (compareSignatures(callerSignature, 12572 setting.signatures.mSignatures) 12573 != PackageManager.SIGNATURE_MATCH) { 12574 throw new SecurityException( 12575 "Caller does not have same cert as old installer package " 12576 + targetPackageSetting.installerPackageName); 12577 } 12578 } 12579 } 12580 12581 // Okay! 12582 targetPackageSetting.installerPackageName = installerPackageName; 12583 if (installerPackageName != null) { 12584 mSettings.mInstallerPackages.add(installerPackageName); 12585 } 12586 scheduleWriteSettingsLocked(); 12587 } 12588 } 12589 12590 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12591 // Queue up an async operation since the package installation may take a little while. 12592 mHandler.post(new Runnable() { 12593 public void run() { 12594 mHandler.removeCallbacks(this); 12595 // Result object to be returned 12596 PackageInstalledInfo res = new PackageInstalledInfo(); 12597 res.setReturnCode(currentStatus); 12598 res.uid = -1; 12599 res.pkg = null; 12600 res.removedInfo = null; 12601 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12602 args.doPreInstall(res.returnCode); 12603 synchronized (mInstallLock) { 12604 installPackageTracedLI(args, res); 12605 } 12606 args.doPostInstall(res.returnCode, res.uid); 12607 } 12608 12609 // A restore should be performed at this point if (a) the install 12610 // succeeded, (b) the operation is not an update, and (c) the new 12611 // package has not opted out of backup participation. 12612 final boolean update = res.removedInfo != null 12613 && res.removedInfo.removedPackage != null; 12614 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12615 boolean doRestore = !update 12616 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12617 12618 // Set up the post-install work request bookkeeping. This will be used 12619 // and cleaned up by the post-install event handling regardless of whether 12620 // there's a restore pass performed. Token values are >= 1. 12621 int token; 12622 if (mNextInstallToken < 0) mNextInstallToken = 1; 12623 token = mNextInstallToken++; 12624 12625 PostInstallData data = new PostInstallData(args, res); 12626 mRunningInstalls.put(token, data); 12627 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12628 12629 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12630 // Pass responsibility to the Backup Manager. It will perform a 12631 // restore if appropriate, then pass responsibility back to the 12632 // Package Manager to run the post-install observer callbacks 12633 // and broadcasts. 12634 IBackupManager bm = IBackupManager.Stub.asInterface( 12635 ServiceManager.getService(Context.BACKUP_SERVICE)); 12636 if (bm != null) { 12637 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12638 + " to BM for possible restore"); 12639 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12640 try { 12641 // TODO: http://b/22388012 12642 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12643 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12644 } else { 12645 doRestore = false; 12646 } 12647 } catch (RemoteException e) { 12648 // can't happen; the backup manager is local 12649 } catch (Exception e) { 12650 Slog.e(TAG, "Exception trying to enqueue restore", e); 12651 doRestore = false; 12652 } 12653 } else { 12654 Slog.e(TAG, "Backup Manager not found!"); 12655 doRestore = false; 12656 } 12657 } 12658 12659 if (!doRestore) { 12660 // No restore possible, or the Backup Manager was mysteriously not 12661 // available -- just fire the post-install work request directly. 12662 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12663 12664 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12665 12666 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12667 mHandler.sendMessage(msg); 12668 } 12669 } 12670 }); 12671 } 12672 12673 /** 12674 * Callback from PackageSettings whenever an app is first transitioned out of the 12675 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12676 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12677 * here whether the app is the target of an ongoing install, and only send the 12678 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12679 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12680 * handling. 12681 */ 12682 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12683 // Serialize this with the rest of the install-process message chain. In the 12684 // restore-at-install case, this Runnable will necessarily run before the 12685 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12686 // are coherent. In the non-restore case, the app has already completed install 12687 // and been launched through some other means, so it is not in a problematic 12688 // state for observers to see the FIRST_LAUNCH signal. 12689 mHandler.post(new Runnable() { 12690 @Override 12691 public void run() { 12692 for (int i = 0; i < mRunningInstalls.size(); i++) { 12693 final PostInstallData data = mRunningInstalls.valueAt(i); 12694 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12695 continue; 12696 } 12697 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12698 // right package; but is it for the right user? 12699 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12700 if (userId == data.res.newUsers[uIndex]) { 12701 if (DEBUG_BACKUP) { 12702 Slog.i(TAG, "Package " + pkgName 12703 + " being restored so deferring FIRST_LAUNCH"); 12704 } 12705 return; 12706 } 12707 } 12708 } 12709 } 12710 // didn't find it, so not being restored 12711 if (DEBUG_BACKUP) { 12712 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12713 } 12714 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12715 } 12716 }); 12717 } 12718 12719 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12720 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12721 installerPkg, null, userIds); 12722 } 12723 12724 private abstract class HandlerParams { 12725 private static final int MAX_RETRIES = 4; 12726 12727 /** 12728 * Number of times startCopy() has been attempted and had a non-fatal 12729 * error. 12730 */ 12731 private int mRetries = 0; 12732 12733 /** User handle for the user requesting the information or installation. */ 12734 private final UserHandle mUser; 12735 String traceMethod; 12736 int traceCookie; 12737 12738 HandlerParams(UserHandle user) { 12739 mUser = user; 12740 } 12741 12742 UserHandle getUser() { 12743 return mUser; 12744 } 12745 12746 HandlerParams setTraceMethod(String traceMethod) { 12747 this.traceMethod = traceMethod; 12748 return this; 12749 } 12750 12751 HandlerParams setTraceCookie(int traceCookie) { 12752 this.traceCookie = traceCookie; 12753 return this; 12754 } 12755 12756 final boolean startCopy() { 12757 boolean res; 12758 try { 12759 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12760 12761 if (++mRetries > MAX_RETRIES) { 12762 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12763 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12764 handleServiceError(); 12765 return false; 12766 } else { 12767 handleStartCopy(); 12768 res = true; 12769 } 12770 } catch (RemoteException e) { 12771 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12772 mHandler.sendEmptyMessage(MCS_RECONNECT); 12773 res = false; 12774 } 12775 handleReturnCode(); 12776 return res; 12777 } 12778 12779 final void serviceError() { 12780 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12781 handleServiceError(); 12782 handleReturnCode(); 12783 } 12784 12785 abstract void handleStartCopy() throws RemoteException; 12786 abstract void handleServiceError(); 12787 abstract void handleReturnCode(); 12788 } 12789 12790 class MeasureParams extends HandlerParams { 12791 private final PackageStats mStats; 12792 private boolean mSuccess; 12793 12794 private final IPackageStatsObserver mObserver; 12795 12796 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12797 super(new UserHandle(stats.userHandle)); 12798 mObserver = observer; 12799 mStats = stats; 12800 } 12801 12802 @Override 12803 public String toString() { 12804 return "MeasureParams{" 12805 + Integer.toHexString(System.identityHashCode(this)) 12806 + " " + mStats.packageName + "}"; 12807 } 12808 12809 @Override 12810 void handleStartCopy() throws RemoteException { 12811 synchronized (mInstallLock) { 12812 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12813 } 12814 12815 if (mSuccess) { 12816 boolean mounted = false; 12817 try { 12818 final String status = Environment.getExternalStorageState(); 12819 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12820 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12821 } catch (Exception e) { 12822 } 12823 12824 if (mounted) { 12825 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12826 12827 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12828 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12829 12830 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12831 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12832 12833 // Always subtract cache size, since it's a subdirectory 12834 mStats.externalDataSize -= mStats.externalCacheSize; 12835 12836 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12837 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12838 12839 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12840 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12841 } 12842 } 12843 } 12844 12845 @Override 12846 void handleReturnCode() { 12847 if (mObserver != null) { 12848 try { 12849 mObserver.onGetStatsCompleted(mStats, mSuccess); 12850 } catch (RemoteException e) { 12851 Slog.i(TAG, "Observer no longer exists."); 12852 } 12853 } 12854 } 12855 12856 @Override 12857 void handleServiceError() { 12858 Slog.e(TAG, "Could not measure application " + mStats.packageName 12859 + " external storage"); 12860 } 12861 } 12862 12863 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12864 throws RemoteException { 12865 long result = 0; 12866 for (File path : paths) { 12867 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12868 } 12869 return result; 12870 } 12871 12872 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12873 for (File path : paths) { 12874 try { 12875 mcs.clearDirectory(path.getAbsolutePath()); 12876 } catch (RemoteException e) { 12877 } 12878 } 12879 } 12880 12881 static class OriginInfo { 12882 /** 12883 * Location where install is coming from, before it has been 12884 * copied/renamed into place. This could be a single monolithic APK 12885 * file, or a cluster directory. This location may be untrusted. 12886 */ 12887 final File file; 12888 final String cid; 12889 12890 /** 12891 * Flag indicating that {@link #file} or {@link #cid} has already been 12892 * staged, meaning downstream users don't need to defensively copy the 12893 * contents. 12894 */ 12895 final boolean staged; 12896 12897 /** 12898 * Flag indicating that {@link #file} or {@link #cid} is an already 12899 * installed app that is being moved. 12900 */ 12901 final boolean existing; 12902 12903 final String resolvedPath; 12904 final File resolvedFile; 12905 12906 static OriginInfo fromNothing() { 12907 return new OriginInfo(null, null, false, false); 12908 } 12909 12910 static OriginInfo fromUntrustedFile(File file) { 12911 return new OriginInfo(file, null, false, false); 12912 } 12913 12914 static OriginInfo fromExistingFile(File file) { 12915 return new OriginInfo(file, null, false, true); 12916 } 12917 12918 static OriginInfo fromStagedFile(File file) { 12919 return new OriginInfo(file, null, true, false); 12920 } 12921 12922 static OriginInfo fromStagedContainer(String cid) { 12923 return new OriginInfo(null, cid, true, false); 12924 } 12925 12926 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12927 this.file = file; 12928 this.cid = cid; 12929 this.staged = staged; 12930 this.existing = existing; 12931 12932 if (cid != null) { 12933 resolvedPath = PackageHelper.getSdDir(cid); 12934 resolvedFile = new File(resolvedPath); 12935 } else if (file != null) { 12936 resolvedPath = file.getAbsolutePath(); 12937 resolvedFile = file; 12938 } else { 12939 resolvedPath = null; 12940 resolvedFile = null; 12941 } 12942 } 12943 } 12944 12945 static class MoveInfo { 12946 final int moveId; 12947 final String fromUuid; 12948 final String toUuid; 12949 final String packageName; 12950 final String dataAppName; 12951 final int appId; 12952 final String seinfo; 12953 final int targetSdkVersion; 12954 12955 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12956 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12957 this.moveId = moveId; 12958 this.fromUuid = fromUuid; 12959 this.toUuid = toUuid; 12960 this.packageName = packageName; 12961 this.dataAppName = dataAppName; 12962 this.appId = appId; 12963 this.seinfo = seinfo; 12964 this.targetSdkVersion = targetSdkVersion; 12965 } 12966 } 12967 12968 static class VerificationInfo { 12969 /** A constant used to indicate that a uid value is not present. */ 12970 public static final int NO_UID = -1; 12971 12972 /** URI referencing where the package was downloaded from. */ 12973 final Uri originatingUri; 12974 12975 /** HTTP referrer URI associated with the originatingURI. */ 12976 final Uri referrer; 12977 12978 /** UID of the application that the install request originated from. */ 12979 final int originatingUid; 12980 12981 /** UID of application requesting the install */ 12982 final int installerUid; 12983 12984 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12985 this.originatingUri = originatingUri; 12986 this.referrer = referrer; 12987 this.originatingUid = originatingUid; 12988 this.installerUid = installerUid; 12989 } 12990 } 12991 12992 class InstallParams extends HandlerParams { 12993 final OriginInfo origin; 12994 final MoveInfo move; 12995 final IPackageInstallObserver2 observer; 12996 int installFlags; 12997 final String installerPackageName; 12998 final String volumeUuid; 12999 private InstallArgs mArgs; 13000 private int mRet; 13001 final String packageAbiOverride; 13002 final String[] grantedRuntimePermissions; 13003 final VerificationInfo verificationInfo; 13004 final Certificate[][] certificates; 13005 13006 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13007 int installFlags, String installerPackageName, String volumeUuid, 13008 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13009 String[] grantedPermissions, Certificate[][] certificates) { 13010 super(user); 13011 this.origin = origin; 13012 this.move = move; 13013 this.observer = observer; 13014 this.installFlags = installFlags; 13015 this.installerPackageName = installerPackageName; 13016 this.volumeUuid = volumeUuid; 13017 this.verificationInfo = verificationInfo; 13018 this.packageAbiOverride = packageAbiOverride; 13019 this.grantedRuntimePermissions = grantedPermissions; 13020 this.certificates = certificates; 13021 } 13022 13023 @Override 13024 public String toString() { 13025 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13026 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13027 } 13028 13029 private int installLocationPolicy(PackageInfoLite pkgLite) { 13030 String packageName = pkgLite.packageName; 13031 int installLocation = pkgLite.installLocation; 13032 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13033 // reader 13034 synchronized (mPackages) { 13035 // Currently installed package which the new package is attempting to replace or 13036 // null if no such package is installed. 13037 PackageParser.Package installedPkg = mPackages.get(packageName); 13038 // Package which currently owns the data which the new package will own if installed. 13039 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13040 // will be null whereas dataOwnerPkg will contain information about the package 13041 // which was uninstalled while keeping its data. 13042 PackageParser.Package dataOwnerPkg = installedPkg; 13043 if (dataOwnerPkg == null) { 13044 PackageSetting ps = mSettings.mPackages.get(packageName); 13045 if (ps != null) { 13046 dataOwnerPkg = ps.pkg; 13047 } 13048 } 13049 13050 if (dataOwnerPkg != null) { 13051 // If installed, the package will get access to data left on the device by its 13052 // predecessor. As a security measure, this is permited only if this is not a 13053 // version downgrade or if the predecessor package is marked as debuggable and 13054 // a downgrade is explicitly requested. 13055 // 13056 // On debuggable platform builds, downgrades are permitted even for 13057 // non-debuggable packages to make testing easier. Debuggable platform builds do 13058 // not offer security guarantees and thus it's OK to disable some security 13059 // mechanisms to make debugging/testing easier on those builds. However, even on 13060 // debuggable builds downgrades of packages are permitted only if requested via 13061 // installFlags. This is because we aim to keep the behavior of debuggable 13062 // platform builds as close as possible to the behavior of non-debuggable 13063 // platform builds. 13064 final boolean downgradeRequested = 13065 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13066 final boolean packageDebuggable = 13067 (dataOwnerPkg.applicationInfo.flags 13068 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13069 final boolean downgradePermitted = 13070 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13071 if (!downgradePermitted) { 13072 try { 13073 checkDowngrade(dataOwnerPkg, pkgLite); 13074 } catch (PackageManagerException e) { 13075 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13076 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13077 } 13078 } 13079 } 13080 13081 if (installedPkg != null) { 13082 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13083 // Check for updated system application. 13084 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13085 if (onSd) { 13086 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13087 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13088 } 13089 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13090 } else { 13091 if (onSd) { 13092 // Install flag overrides everything. 13093 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13094 } 13095 // If current upgrade specifies particular preference 13096 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13097 // Application explicitly specified internal. 13098 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13099 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13100 // App explictly prefers external. Let policy decide 13101 } else { 13102 // Prefer previous location 13103 if (isExternal(installedPkg)) { 13104 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13105 } 13106 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13107 } 13108 } 13109 } else { 13110 // Invalid install. Return error code 13111 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13112 } 13113 } 13114 } 13115 // All the special cases have been taken care of. 13116 // Return result based on recommended install location. 13117 if (onSd) { 13118 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13119 } 13120 return pkgLite.recommendedInstallLocation; 13121 } 13122 13123 /* 13124 * Invoke remote method to get package information and install 13125 * location values. Override install location based on default 13126 * policy if needed and then create install arguments based 13127 * on the install location. 13128 */ 13129 public void handleStartCopy() throws RemoteException { 13130 int ret = PackageManager.INSTALL_SUCCEEDED; 13131 13132 // If we're already staged, we've firmly committed to an install location 13133 if (origin.staged) { 13134 if (origin.file != null) { 13135 installFlags |= PackageManager.INSTALL_INTERNAL; 13136 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13137 } else if (origin.cid != null) { 13138 installFlags |= PackageManager.INSTALL_EXTERNAL; 13139 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13140 } else { 13141 throw new IllegalStateException("Invalid stage location"); 13142 } 13143 } 13144 13145 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13146 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13147 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13148 PackageInfoLite pkgLite = null; 13149 13150 if (onInt && onSd) { 13151 // Check if both bits are set. 13152 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13153 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13154 } else if (onSd && ephemeral) { 13155 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13156 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13157 } else { 13158 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13159 packageAbiOverride); 13160 13161 if (DEBUG_EPHEMERAL && ephemeral) { 13162 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13163 } 13164 13165 /* 13166 * If we have too little free space, try to free cache 13167 * before giving up. 13168 */ 13169 if (!origin.staged && pkgLite.recommendedInstallLocation 13170 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13171 // TODO: focus freeing disk space on the target device 13172 final StorageManager storage = StorageManager.from(mContext); 13173 final long lowThreshold = storage.getStorageLowBytes( 13174 Environment.getDataDirectory()); 13175 13176 final long sizeBytes = mContainerService.calculateInstalledSize( 13177 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13178 13179 try { 13180 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13181 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13182 installFlags, packageAbiOverride); 13183 } catch (InstallerException e) { 13184 Slog.w(TAG, "Failed to free cache", e); 13185 } 13186 13187 /* 13188 * The cache free must have deleted the file we 13189 * downloaded to install. 13190 * 13191 * TODO: fix the "freeCache" call to not delete 13192 * the file we care about. 13193 */ 13194 if (pkgLite.recommendedInstallLocation 13195 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13196 pkgLite.recommendedInstallLocation 13197 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13198 } 13199 } 13200 } 13201 13202 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13203 int loc = pkgLite.recommendedInstallLocation; 13204 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13205 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13206 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13207 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13208 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13209 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13210 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13211 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13212 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13213 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13214 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13215 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13216 } else { 13217 // Override with defaults if needed. 13218 loc = installLocationPolicy(pkgLite); 13219 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13220 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13221 } else if (!onSd && !onInt) { 13222 // Override install location with flags 13223 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13224 // Set the flag to install on external media. 13225 installFlags |= PackageManager.INSTALL_EXTERNAL; 13226 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13227 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13228 if (DEBUG_EPHEMERAL) { 13229 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13230 } 13231 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13232 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13233 |PackageManager.INSTALL_INTERNAL); 13234 } else { 13235 // Make sure the flag for installing on external 13236 // media is unset 13237 installFlags |= PackageManager.INSTALL_INTERNAL; 13238 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13239 } 13240 } 13241 } 13242 } 13243 13244 final InstallArgs args = createInstallArgs(this); 13245 mArgs = args; 13246 13247 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13248 // TODO: http://b/22976637 13249 // Apps installed for "all" users use the device owner to verify the app 13250 UserHandle verifierUser = getUser(); 13251 if (verifierUser == UserHandle.ALL) { 13252 verifierUser = UserHandle.SYSTEM; 13253 } 13254 13255 /* 13256 * Determine if we have any installed package verifiers. If we 13257 * do, then we'll defer to them to verify the packages. 13258 */ 13259 final int requiredUid = mRequiredVerifierPackage == null ? -1 13260 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13261 verifierUser.getIdentifier()); 13262 if (!origin.existing && requiredUid != -1 13263 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13264 final Intent verification = new Intent( 13265 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13266 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13267 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13268 PACKAGE_MIME_TYPE); 13269 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13270 13271 // Query all live verifiers based on current user state 13272 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13273 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13274 13275 if (DEBUG_VERIFY) { 13276 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13277 + verification.toString() + " with " + pkgLite.verifiers.length 13278 + " optional verifiers"); 13279 } 13280 13281 final int verificationId = mPendingVerificationToken++; 13282 13283 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13284 13285 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13286 installerPackageName); 13287 13288 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13289 installFlags); 13290 13291 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13292 pkgLite.packageName); 13293 13294 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13295 pkgLite.versionCode); 13296 13297 if (verificationInfo != null) { 13298 if (verificationInfo.originatingUri != null) { 13299 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13300 verificationInfo.originatingUri); 13301 } 13302 if (verificationInfo.referrer != null) { 13303 verification.putExtra(Intent.EXTRA_REFERRER, 13304 verificationInfo.referrer); 13305 } 13306 if (verificationInfo.originatingUid >= 0) { 13307 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13308 verificationInfo.originatingUid); 13309 } 13310 if (verificationInfo.installerUid >= 0) { 13311 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13312 verificationInfo.installerUid); 13313 } 13314 } 13315 13316 final PackageVerificationState verificationState = new PackageVerificationState( 13317 requiredUid, args); 13318 13319 mPendingVerification.append(verificationId, verificationState); 13320 13321 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13322 receivers, verificationState); 13323 13324 /* 13325 * If any sufficient verifiers were listed in the package 13326 * manifest, attempt to ask them. 13327 */ 13328 if (sufficientVerifiers != null) { 13329 final int N = sufficientVerifiers.size(); 13330 if (N == 0) { 13331 Slog.i(TAG, "Additional verifiers required, but none installed."); 13332 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13333 } else { 13334 for (int i = 0; i < N; i++) { 13335 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13336 13337 final Intent sufficientIntent = new Intent(verification); 13338 sufficientIntent.setComponent(verifierComponent); 13339 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13340 } 13341 } 13342 } 13343 13344 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13345 mRequiredVerifierPackage, receivers); 13346 if (ret == PackageManager.INSTALL_SUCCEEDED 13347 && mRequiredVerifierPackage != null) { 13348 Trace.asyncTraceBegin( 13349 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13350 /* 13351 * Send the intent to the required verification agent, 13352 * but only start the verification timeout after the 13353 * target BroadcastReceivers have run. 13354 */ 13355 verification.setComponent(requiredVerifierComponent); 13356 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13357 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13358 new BroadcastReceiver() { 13359 @Override 13360 public void onReceive(Context context, Intent intent) { 13361 final Message msg = mHandler 13362 .obtainMessage(CHECK_PENDING_VERIFICATION); 13363 msg.arg1 = verificationId; 13364 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13365 } 13366 }, null, 0, null, null); 13367 13368 /* 13369 * We don't want the copy to proceed until verification 13370 * succeeds, so null out this field. 13371 */ 13372 mArgs = null; 13373 } 13374 } else { 13375 /* 13376 * No package verification is enabled, so immediately start 13377 * the remote call to initiate copy using temporary file. 13378 */ 13379 ret = args.copyApk(mContainerService, true); 13380 } 13381 } 13382 13383 mRet = ret; 13384 } 13385 13386 @Override 13387 void handleReturnCode() { 13388 // If mArgs is null, then MCS couldn't be reached. When it 13389 // reconnects, it will try again to install. At that point, this 13390 // will succeed. 13391 if (mArgs != null) { 13392 processPendingInstall(mArgs, mRet); 13393 } 13394 } 13395 13396 @Override 13397 void handleServiceError() { 13398 mArgs = createInstallArgs(this); 13399 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13400 } 13401 13402 public boolean isForwardLocked() { 13403 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13404 } 13405 } 13406 13407 /** 13408 * Used during creation of InstallArgs 13409 * 13410 * @param installFlags package installation flags 13411 * @return true if should be installed on external storage 13412 */ 13413 private static boolean installOnExternalAsec(int installFlags) { 13414 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13415 return false; 13416 } 13417 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13418 return true; 13419 } 13420 return false; 13421 } 13422 13423 /** 13424 * Used during creation of InstallArgs 13425 * 13426 * @param installFlags package installation flags 13427 * @return true if should be installed as forward locked 13428 */ 13429 private static boolean installForwardLocked(int installFlags) { 13430 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13431 } 13432 13433 private InstallArgs createInstallArgs(InstallParams params) { 13434 if (params.move != null) { 13435 return new MoveInstallArgs(params); 13436 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13437 return new AsecInstallArgs(params); 13438 } else { 13439 return new FileInstallArgs(params); 13440 } 13441 } 13442 13443 /** 13444 * Create args that describe an existing installed package. Typically used 13445 * when cleaning up old installs, or used as a move source. 13446 */ 13447 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13448 String resourcePath, String[] instructionSets) { 13449 final boolean isInAsec; 13450 if (installOnExternalAsec(installFlags)) { 13451 /* Apps on SD card are always in ASEC containers. */ 13452 isInAsec = true; 13453 } else if (installForwardLocked(installFlags) 13454 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13455 /* 13456 * Forward-locked apps are only in ASEC containers if they're the 13457 * new style 13458 */ 13459 isInAsec = true; 13460 } else { 13461 isInAsec = false; 13462 } 13463 13464 if (isInAsec) { 13465 return new AsecInstallArgs(codePath, instructionSets, 13466 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13467 } else { 13468 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13469 } 13470 } 13471 13472 static abstract class InstallArgs { 13473 /** @see InstallParams#origin */ 13474 final OriginInfo origin; 13475 /** @see InstallParams#move */ 13476 final MoveInfo move; 13477 13478 final IPackageInstallObserver2 observer; 13479 // Always refers to PackageManager flags only 13480 final int installFlags; 13481 final String installerPackageName; 13482 final String volumeUuid; 13483 final UserHandle user; 13484 final String abiOverride; 13485 final String[] installGrantPermissions; 13486 /** If non-null, drop an async trace when the install completes */ 13487 final String traceMethod; 13488 final int traceCookie; 13489 final Certificate[][] certificates; 13490 13491 // The list of instruction sets supported by this app. This is currently 13492 // only used during the rmdex() phase to clean up resources. We can get rid of this 13493 // if we move dex files under the common app path. 13494 /* nullable */ String[] instructionSets; 13495 13496 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13497 int installFlags, String installerPackageName, String volumeUuid, 13498 UserHandle user, String[] instructionSets, 13499 String abiOverride, String[] installGrantPermissions, 13500 String traceMethod, int traceCookie, Certificate[][] certificates) { 13501 this.origin = origin; 13502 this.move = move; 13503 this.installFlags = installFlags; 13504 this.observer = observer; 13505 this.installerPackageName = installerPackageName; 13506 this.volumeUuid = volumeUuid; 13507 this.user = user; 13508 this.instructionSets = instructionSets; 13509 this.abiOverride = abiOverride; 13510 this.installGrantPermissions = installGrantPermissions; 13511 this.traceMethod = traceMethod; 13512 this.traceCookie = traceCookie; 13513 this.certificates = certificates; 13514 } 13515 13516 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13517 abstract int doPreInstall(int status); 13518 13519 /** 13520 * Rename package into final resting place. All paths on the given 13521 * scanned package should be updated to reflect the rename. 13522 */ 13523 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13524 abstract int doPostInstall(int status, int uid); 13525 13526 /** @see PackageSettingBase#codePathString */ 13527 abstract String getCodePath(); 13528 /** @see PackageSettingBase#resourcePathString */ 13529 abstract String getResourcePath(); 13530 13531 // Need installer lock especially for dex file removal. 13532 abstract void cleanUpResourcesLI(); 13533 abstract boolean doPostDeleteLI(boolean delete); 13534 13535 /** 13536 * Called before the source arguments are copied. This is used mostly 13537 * for MoveParams when it needs to read the source file to put it in the 13538 * destination. 13539 */ 13540 int doPreCopy() { 13541 return PackageManager.INSTALL_SUCCEEDED; 13542 } 13543 13544 /** 13545 * Called after the source arguments are copied. This is used mostly for 13546 * MoveParams when it needs to read the source file to put it in the 13547 * destination. 13548 */ 13549 int doPostCopy(int uid) { 13550 return PackageManager.INSTALL_SUCCEEDED; 13551 } 13552 13553 protected boolean isFwdLocked() { 13554 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13555 } 13556 13557 protected boolean isExternalAsec() { 13558 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13559 } 13560 13561 protected boolean isEphemeral() { 13562 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13563 } 13564 13565 UserHandle getUser() { 13566 return user; 13567 } 13568 } 13569 13570 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13571 if (!allCodePaths.isEmpty()) { 13572 if (instructionSets == null) { 13573 throw new IllegalStateException("instructionSet == null"); 13574 } 13575 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13576 for (String codePath : allCodePaths) { 13577 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13578 try { 13579 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13580 } catch (InstallerException ignored) { 13581 } 13582 } 13583 } 13584 } 13585 } 13586 13587 /** 13588 * Logic to handle installation of non-ASEC applications, including copying 13589 * and renaming logic. 13590 */ 13591 class FileInstallArgs extends InstallArgs { 13592 private File codeFile; 13593 private File resourceFile; 13594 13595 // Example topology: 13596 // /data/app/com.example/base.apk 13597 // /data/app/com.example/split_foo.apk 13598 // /data/app/com.example/lib/arm/libfoo.so 13599 // /data/app/com.example/lib/arm64/libfoo.so 13600 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13601 13602 /** New install */ 13603 FileInstallArgs(InstallParams params) { 13604 super(params.origin, params.move, params.observer, params.installFlags, 13605 params.installerPackageName, params.volumeUuid, 13606 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13607 params.grantedRuntimePermissions, 13608 params.traceMethod, params.traceCookie, params.certificates); 13609 if (isFwdLocked()) { 13610 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13611 } 13612 } 13613 13614 /** Existing install */ 13615 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13616 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13617 null, null, null, 0, null /*certificates*/); 13618 this.codeFile = (codePath != null) ? new File(codePath) : null; 13619 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13620 } 13621 13622 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13623 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13624 try { 13625 return doCopyApk(imcs, temp); 13626 } finally { 13627 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13628 } 13629 } 13630 13631 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13632 if (origin.staged) { 13633 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13634 codeFile = origin.file; 13635 resourceFile = origin.file; 13636 return PackageManager.INSTALL_SUCCEEDED; 13637 } 13638 13639 try { 13640 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13641 final File tempDir = 13642 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13643 codeFile = tempDir; 13644 resourceFile = tempDir; 13645 } catch (IOException e) { 13646 Slog.w(TAG, "Failed to create copy file: " + e); 13647 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13648 } 13649 13650 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13651 @Override 13652 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13653 if (!FileUtils.isValidExtFilename(name)) { 13654 throw new IllegalArgumentException("Invalid filename: " + name); 13655 } 13656 try { 13657 final File file = new File(codeFile, name); 13658 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13659 O_RDWR | O_CREAT, 0644); 13660 Os.chmod(file.getAbsolutePath(), 0644); 13661 return new ParcelFileDescriptor(fd); 13662 } catch (ErrnoException e) { 13663 throw new RemoteException("Failed to open: " + e.getMessage()); 13664 } 13665 } 13666 }; 13667 13668 int ret = PackageManager.INSTALL_SUCCEEDED; 13669 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13670 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13671 Slog.e(TAG, "Failed to copy package"); 13672 return ret; 13673 } 13674 13675 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13676 NativeLibraryHelper.Handle handle = null; 13677 try { 13678 handle = NativeLibraryHelper.Handle.create(codeFile); 13679 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13680 abiOverride); 13681 } catch (IOException e) { 13682 Slog.e(TAG, "Copying native libraries failed", e); 13683 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13684 } finally { 13685 IoUtils.closeQuietly(handle); 13686 } 13687 13688 return ret; 13689 } 13690 13691 int doPreInstall(int status) { 13692 if (status != PackageManager.INSTALL_SUCCEEDED) { 13693 cleanUp(); 13694 } 13695 return status; 13696 } 13697 13698 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13699 if (status != PackageManager.INSTALL_SUCCEEDED) { 13700 cleanUp(); 13701 return false; 13702 } 13703 13704 final File targetDir = codeFile.getParentFile(); 13705 final File beforeCodeFile = codeFile; 13706 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13707 13708 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13709 try { 13710 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13711 } catch (ErrnoException e) { 13712 Slog.w(TAG, "Failed to rename", e); 13713 return false; 13714 } 13715 13716 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13717 Slog.w(TAG, "Failed to restorecon"); 13718 return false; 13719 } 13720 13721 // Reflect the rename internally 13722 codeFile = afterCodeFile; 13723 resourceFile = afterCodeFile; 13724 13725 // Reflect the rename in scanned details 13726 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13727 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13728 afterCodeFile, pkg.baseCodePath)); 13729 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13730 afterCodeFile, pkg.splitCodePaths)); 13731 13732 // Reflect the rename in app info 13733 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13734 pkg.setApplicationInfoCodePath(pkg.codePath); 13735 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13736 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13737 pkg.setApplicationInfoResourcePath(pkg.codePath); 13738 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13739 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13740 13741 return true; 13742 } 13743 13744 int doPostInstall(int status, int uid) { 13745 if (status != PackageManager.INSTALL_SUCCEEDED) { 13746 cleanUp(); 13747 } 13748 return status; 13749 } 13750 13751 @Override 13752 String getCodePath() { 13753 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13754 } 13755 13756 @Override 13757 String getResourcePath() { 13758 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13759 } 13760 13761 private boolean cleanUp() { 13762 if (codeFile == null || !codeFile.exists()) { 13763 return false; 13764 } 13765 13766 removeCodePathLI(codeFile); 13767 13768 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13769 resourceFile.delete(); 13770 } 13771 13772 return true; 13773 } 13774 13775 void cleanUpResourcesLI() { 13776 // Try enumerating all code paths before deleting 13777 List<String> allCodePaths = Collections.EMPTY_LIST; 13778 if (codeFile != null && codeFile.exists()) { 13779 try { 13780 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13781 allCodePaths = pkg.getAllCodePaths(); 13782 } catch (PackageParserException e) { 13783 // Ignored; we tried our best 13784 } 13785 } 13786 13787 cleanUp(); 13788 removeDexFiles(allCodePaths, instructionSets); 13789 } 13790 13791 boolean doPostDeleteLI(boolean delete) { 13792 // XXX err, shouldn't we respect the delete flag? 13793 cleanUpResourcesLI(); 13794 return true; 13795 } 13796 } 13797 13798 private boolean isAsecExternal(String cid) { 13799 final String asecPath = PackageHelper.getSdFilesystem(cid); 13800 return !asecPath.startsWith(mAsecInternalPath); 13801 } 13802 13803 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13804 PackageManagerException { 13805 if (copyRet < 0) { 13806 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13807 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13808 throw new PackageManagerException(copyRet, message); 13809 } 13810 } 13811 } 13812 13813 /** 13814 * Extract the StorageManagerService "container ID" from the full code path of an 13815 * .apk. 13816 */ 13817 static String cidFromCodePath(String fullCodePath) { 13818 int eidx = fullCodePath.lastIndexOf("/"); 13819 String subStr1 = fullCodePath.substring(0, eidx); 13820 int sidx = subStr1.lastIndexOf("/"); 13821 return subStr1.substring(sidx+1, eidx); 13822 } 13823 13824 /** 13825 * Logic to handle installation of ASEC applications, including copying and 13826 * renaming logic. 13827 */ 13828 class AsecInstallArgs extends InstallArgs { 13829 static final String RES_FILE_NAME = "pkg.apk"; 13830 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13831 13832 String cid; 13833 String packagePath; 13834 String resourcePath; 13835 13836 /** New install */ 13837 AsecInstallArgs(InstallParams params) { 13838 super(params.origin, params.move, params.observer, params.installFlags, 13839 params.installerPackageName, params.volumeUuid, 13840 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13841 params.grantedRuntimePermissions, 13842 params.traceMethod, params.traceCookie, params.certificates); 13843 } 13844 13845 /** Existing install */ 13846 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13847 boolean isExternal, boolean isForwardLocked) { 13848 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13849 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13850 instructionSets, null, null, null, 0, null /*certificates*/); 13851 // Hackily pretend we're still looking at a full code path 13852 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13853 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13854 } 13855 13856 // Extract cid from fullCodePath 13857 int eidx = fullCodePath.lastIndexOf("/"); 13858 String subStr1 = fullCodePath.substring(0, eidx); 13859 int sidx = subStr1.lastIndexOf("/"); 13860 cid = subStr1.substring(sidx+1, eidx); 13861 setMountPath(subStr1); 13862 } 13863 13864 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13865 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13866 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13867 instructionSets, null, null, null, 0, null /*certificates*/); 13868 this.cid = cid; 13869 setMountPath(PackageHelper.getSdDir(cid)); 13870 } 13871 13872 void createCopyFile() { 13873 cid = mInstallerService.allocateExternalStageCidLegacy(); 13874 } 13875 13876 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13877 if (origin.staged && origin.cid != null) { 13878 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13879 cid = origin.cid; 13880 setMountPath(PackageHelper.getSdDir(cid)); 13881 return PackageManager.INSTALL_SUCCEEDED; 13882 } 13883 13884 if (temp) { 13885 createCopyFile(); 13886 } else { 13887 /* 13888 * Pre-emptively destroy the container since it's destroyed if 13889 * copying fails due to it existing anyway. 13890 */ 13891 PackageHelper.destroySdDir(cid); 13892 } 13893 13894 final String newMountPath = imcs.copyPackageToContainer( 13895 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13896 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13897 13898 if (newMountPath != null) { 13899 setMountPath(newMountPath); 13900 return PackageManager.INSTALL_SUCCEEDED; 13901 } else { 13902 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13903 } 13904 } 13905 13906 @Override 13907 String getCodePath() { 13908 return packagePath; 13909 } 13910 13911 @Override 13912 String getResourcePath() { 13913 return resourcePath; 13914 } 13915 13916 int doPreInstall(int status) { 13917 if (status != PackageManager.INSTALL_SUCCEEDED) { 13918 // Destroy container 13919 PackageHelper.destroySdDir(cid); 13920 } else { 13921 boolean mounted = PackageHelper.isContainerMounted(cid); 13922 if (!mounted) { 13923 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13924 Process.SYSTEM_UID); 13925 if (newMountPath != null) { 13926 setMountPath(newMountPath); 13927 } else { 13928 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13929 } 13930 } 13931 } 13932 return status; 13933 } 13934 13935 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13936 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13937 String newMountPath = null; 13938 if (PackageHelper.isContainerMounted(cid)) { 13939 // Unmount the container 13940 if (!PackageHelper.unMountSdDir(cid)) { 13941 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13942 return false; 13943 } 13944 } 13945 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13946 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13947 " which might be stale. Will try to clean up."); 13948 // Clean up the stale container and proceed to recreate. 13949 if (!PackageHelper.destroySdDir(newCacheId)) { 13950 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13951 return false; 13952 } 13953 // Successfully cleaned up stale container. Try to rename again. 13954 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13955 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13956 + " inspite of cleaning it up."); 13957 return false; 13958 } 13959 } 13960 if (!PackageHelper.isContainerMounted(newCacheId)) { 13961 Slog.w(TAG, "Mounting container " + newCacheId); 13962 newMountPath = PackageHelper.mountSdDir(newCacheId, 13963 getEncryptKey(), Process.SYSTEM_UID); 13964 } else { 13965 newMountPath = PackageHelper.getSdDir(newCacheId); 13966 } 13967 if (newMountPath == null) { 13968 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13969 return false; 13970 } 13971 Log.i(TAG, "Succesfully renamed " + cid + 13972 " to " + newCacheId + 13973 " at new path: " + newMountPath); 13974 cid = newCacheId; 13975 13976 final File beforeCodeFile = new File(packagePath); 13977 setMountPath(newMountPath); 13978 final File afterCodeFile = new File(packagePath); 13979 13980 // Reflect the rename in scanned details 13981 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13982 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13983 afterCodeFile, pkg.baseCodePath)); 13984 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13985 afterCodeFile, pkg.splitCodePaths)); 13986 13987 // Reflect the rename in app info 13988 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13989 pkg.setApplicationInfoCodePath(pkg.codePath); 13990 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13991 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13992 pkg.setApplicationInfoResourcePath(pkg.codePath); 13993 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13994 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13995 13996 return true; 13997 } 13998 13999 private void setMountPath(String mountPath) { 14000 final File mountFile = new File(mountPath); 14001 14002 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14003 if (monolithicFile.exists()) { 14004 packagePath = monolithicFile.getAbsolutePath(); 14005 if (isFwdLocked()) { 14006 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14007 } else { 14008 resourcePath = packagePath; 14009 } 14010 } else { 14011 packagePath = mountFile.getAbsolutePath(); 14012 resourcePath = packagePath; 14013 } 14014 } 14015 14016 int doPostInstall(int status, int uid) { 14017 if (status != PackageManager.INSTALL_SUCCEEDED) { 14018 cleanUp(); 14019 } else { 14020 final int groupOwner; 14021 final String protectedFile; 14022 if (isFwdLocked()) { 14023 groupOwner = UserHandle.getSharedAppGid(uid); 14024 protectedFile = RES_FILE_NAME; 14025 } else { 14026 groupOwner = -1; 14027 protectedFile = null; 14028 } 14029 14030 if (uid < Process.FIRST_APPLICATION_UID 14031 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14032 Slog.e(TAG, "Failed to finalize " + cid); 14033 PackageHelper.destroySdDir(cid); 14034 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14035 } 14036 14037 boolean mounted = PackageHelper.isContainerMounted(cid); 14038 if (!mounted) { 14039 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14040 } 14041 } 14042 return status; 14043 } 14044 14045 private void cleanUp() { 14046 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14047 14048 // Destroy secure container 14049 PackageHelper.destroySdDir(cid); 14050 } 14051 14052 private List<String> getAllCodePaths() { 14053 final File codeFile = new File(getCodePath()); 14054 if (codeFile != null && codeFile.exists()) { 14055 try { 14056 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14057 return pkg.getAllCodePaths(); 14058 } catch (PackageParserException e) { 14059 // Ignored; we tried our best 14060 } 14061 } 14062 return Collections.EMPTY_LIST; 14063 } 14064 14065 void cleanUpResourcesLI() { 14066 // Enumerate all code paths before deleting 14067 cleanUpResourcesLI(getAllCodePaths()); 14068 } 14069 14070 private void cleanUpResourcesLI(List<String> allCodePaths) { 14071 cleanUp(); 14072 removeDexFiles(allCodePaths, instructionSets); 14073 } 14074 14075 String getPackageName() { 14076 return getAsecPackageName(cid); 14077 } 14078 14079 boolean doPostDeleteLI(boolean delete) { 14080 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14081 final List<String> allCodePaths = getAllCodePaths(); 14082 boolean mounted = PackageHelper.isContainerMounted(cid); 14083 if (mounted) { 14084 // Unmount first 14085 if (PackageHelper.unMountSdDir(cid)) { 14086 mounted = false; 14087 } 14088 } 14089 if (!mounted && delete) { 14090 cleanUpResourcesLI(allCodePaths); 14091 } 14092 return !mounted; 14093 } 14094 14095 @Override 14096 int doPreCopy() { 14097 if (isFwdLocked()) { 14098 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14099 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14100 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14101 } 14102 } 14103 14104 return PackageManager.INSTALL_SUCCEEDED; 14105 } 14106 14107 @Override 14108 int doPostCopy(int uid) { 14109 if (isFwdLocked()) { 14110 if (uid < Process.FIRST_APPLICATION_UID 14111 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14112 RES_FILE_NAME)) { 14113 Slog.e(TAG, "Failed to finalize " + cid); 14114 PackageHelper.destroySdDir(cid); 14115 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14116 } 14117 } 14118 14119 return PackageManager.INSTALL_SUCCEEDED; 14120 } 14121 } 14122 14123 /** 14124 * Logic to handle movement of existing installed applications. 14125 */ 14126 class MoveInstallArgs extends InstallArgs { 14127 private File codeFile; 14128 private File resourceFile; 14129 14130 /** New install */ 14131 MoveInstallArgs(InstallParams params) { 14132 super(params.origin, params.move, params.observer, params.installFlags, 14133 params.installerPackageName, params.volumeUuid, 14134 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14135 params.grantedRuntimePermissions, 14136 params.traceMethod, params.traceCookie, params.certificates); 14137 } 14138 14139 int copyApk(IMediaContainerService imcs, boolean temp) { 14140 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14141 + move.fromUuid + " to " + move.toUuid); 14142 synchronized (mInstaller) { 14143 try { 14144 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14145 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14146 } catch (InstallerException e) { 14147 Slog.w(TAG, "Failed to move app", e); 14148 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14149 } 14150 } 14151 14152 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14153 resourceFile = codeFile; 14154 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14155 14156 return PackageManager.INSTALL_SUCCEEDED; 14157 } 14158 14159 int doPreInstall(int status) { 14160 if (status != PackageManager.INSTALL_SUCCEEDED) { 14161 cleanUp(move.toUuid); 14162 } 14163 return status; 14164 } 14165 14166 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14167 if (status != PackageManager.INSTALL_SUCCEEDED) { 14168 cleanUp(move.toUuid); 14169 return false; 14170 } 14171 14172 // Reflect the move in app info 14173 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14174 pkg.setApplicationInfoCodePath(pkg.codePath); 14175 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14176 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14177 pkg.setApplicationInfoResourcePath(pkg.codePath); 14178 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14179 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14180 14181 return true; 14182 } 14183 14184 int doPostInstall(int status, int uid) { 14185 if (status == PackageManager.INSTALL_SUCCEEDED) { 14186 cleanUp(move.fromUuid); 14187 } else { 14188 cleanUp(move.toUuid); 14189 } 14190 return status; 14191 } 14192 14193 @Override 14194 String getCodePath() { 14195 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14196 } 14197 14198 @Override 14199 String getResourcePath() { 14200 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14201 } 14202 14203 private boolean cleanUp(String volumeUuid) { 14204 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14205 move.dataAppName); 14206 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14207 final int[] userIds = sUserManager.getUserIds(); 14208 synchronized (mInstallLock) { 14209 // Clean up both app data and code 14210 // All package moves are frozen until finished 14211 for (int userId : userIds) { 14212 try { 14213 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14214 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14215 } catch (InstallerException e) { 14216 Slog.w(TAG, String.valueOf(e)); 14217 } 14218 } 14219 removeCodePathLI(codeFile); 14220 } 14221 return true; 14222 } 14223 14224 void cleanUpResourcesLI() { 14225 throw new UnsupportedOperationException(); 14226 } 14227 14228 boolean doPostDeleteLI(boolean delete) { 14229 throw new UnsupportedOperationException(); 14230 } 14231 } 14232 14233 static String getAsecPackageName(String packageCid) { 14234 int idx = packageCid.lastIndexOf("-"); 14235 if (idx == -1) { 14236 return packageCid; 14237 } 14238 return packageCid.substring(0, idx); 14239 } 14240 14241 // Utility method used to create code paths based on package name and available index. 14242 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14243 String idxStr = ""; 14244 int idx = 1; 14245 // Fall back to default value of idx=1 if prefix is not 14246 // part of oldCodePath 14247 if (oldCodePath != null) { 14248 String subStr = oldCodePath; 14249 // Drop the suffix right away 14250 if (suffix != null && subStr.endsWith(suffix)) { 14251 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14252 } 14253 // If oldCodePath already contains prefix find out the 14254 // ending index to either increment or decrement. 14255 int sidx = subStr.lastIndexOf(prefix); 14256 if (sidx != -1) { 14257 subStr = subStr.substring(sidx + prefix.length()); 14258 if (subStr != null) { 14259 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14260 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14261 } 14262 try { 14263 idx = Integer.parseInt(subStr); 14264 if (idx <= 1) { 14265 idx++; 14266 } else { 14267 idx--; 14268 } 14269 } catch(NumberFormatException e) { 14270 } 14271 } 14272 } 14273 } 14274 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14275 return prefix + idxStr; 14276 } 14277 14278 private File getNextCodePath(File targetDir, String packageName) { 14279 int suffix = 1; 14280 File result; 14281 do { 14282 result = new File(targetDir, packageName + "-" + suffix); 14283 suffix++; 14284 } while (result.exists()); 14285 return result; 14286 } 14287 14288 // Utility method that returns the relative package path with respect 14289 // to the installation directory. Like say for /data/data/com.test-1.apk 14290 // string com.test-1 is returned. 14291 static String deriveCodePathName(String codePath) { 14292 if (codePath == null) { 14293 return null; 14294 } 14295 final File codeFile = new File(codePath); 14296 final String name = codeFile.getName(); 14297 if (codeFile.isDirectory()) { 14298 return name; 14299 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14300 final int lastDot = name.lastIndexOf('.'); 14301 return name.substring(0, lastDot); 14302 } else { 14303 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14304 return null; 14305 } 14306 } 14307 14308 static class PackageInstalledInfo { 14309 String name; 14310 int uid; 14311 // The set of users that originally had this package installed. 14312 int[] origUsers; 14313 // The set of users that now have this package installed. 14314 int[] newUsers; 14315 PackageParser.Package pkg; 14316 int returnCode; 14317 String returnMsg; 14318 PackageRemovedInfo removedInfo; 14319 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14320 14321 public void setError(int code, String msg) { 14322 setReturnCode(code); 14323 setReturnMessage(msg); 14324 Slog.w(TAG, msg); 14325 } 14326 14327 public void setError(String msg, PackageParserException e) { 14328 setReturnCode(e.error); 14329 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14330 Slog.w(TAG, msg, e); 14331 } 14332 14333 public void setError(String msg, PackageManagerException e) { 14334 returnCode = e.error; 14335 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14336 Slog.w(TAG, msg, e); 14337 } 14338 14339 public void setReturnCode(int returnCode) { 14340 this.returnCode = returnCode; 14341 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14342 for (int i = 0; i < childCount; i++) { 14343 addedChildPackages.valueAt(i).returnCode = returnCode; 14344 } 14345 } 14346 14347 private void setReturnMessage(String returnMsg) { 14348 this.returnMsg = returnMsg; 14349 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14350 for (int i = 0; i < childCount; i++) { 14351 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14352 } 14353 } 14354 14355 // In some error cases we want to convey more info back to the observer 14356 String origPackage; 14357 String origPermission; 14358 } 14359 14360 /* 14361 * Install a non-existing package. 14362 */ 14363 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14364 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14365 PackageInstalledInfo res) { 14366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14367 14368 // Remember this for later, in case we need to rollback this install 14369 String pkgName = pkg.packageName; 14370 14371 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14372 14373 synchronized(mPackages) { 14374 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14375 if (renamedPackage != null) { 14376 // A package with the same name is already installed, though 14377 // it has been renamed to an older name. The package we 14378 // are trying to install should be installed as an update to 14379 // the existing one, but that has not been requested, so bail. 14380 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14381 + " without first uninstalling package running as " 14382 + renamedPackage); 14383 return; 14384 } 14385 if (mPackages.containsKey(pkgName)) { 14386 // Don't allow installation over an existing package with the same name. 14387 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14388 + " without first uninstalling."); 14389 return; 14390 } 14391 } 14392 14393 try { 14394 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14395 System.currentTimeMillis(), user); 14396 14397 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14398 14399 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14400 prepareAppDataAfterInstallLIF(newPackage); 14401 14402 } else { 14403 // Remove package from internal structures, but keep around any 14404 // data that might have already existed 14405 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14406 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14407 } 14408 } catch (PackageManagerException e) { 14409 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14410 } 14411 14412 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14413 } 14414 14415 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14416 // Can't rotate keys during boot or if sharedUser. 14417 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14418 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14419 return false; 14420 } 14421 // app is using upgradeKeySets; make sure all are valid 14422 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14423 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14424 for (int i = 0; i < upgradeKeySets.length; i++) { 14425 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14426 Slog.wtf(TAG, "Package " 14427 + (oldPs.name != null ? oldPs.name : "<null>") 14428 + " contains upgrade-key-set reference to unknown key-set: " 14429 + upgradeKeySets[i] 14430 + " reverting to signatures check."); 14431 return false; 14432 } 14433 } 14434 return true; 14435 } 14436 14437 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14438 // Upgrade keysets are being used. Determine if new package has a superset of the 14439 // required keys. 14440 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14441 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14442 for (int i = 0; i < upgradeKeySets.length; i++) { 14443 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14444 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14445 return true; 14446 } 14447 } 14448 return false; 14449 } 14450 14451 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14452 try (DigestInputStream digestStream = 14453 new DigestInputStream(new FileInputStream(file), digest)) { 14454 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14455 } 14456 } 14457 14458 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14459 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14460 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14461 14462 final PackageParser.Package oldPackage; 14463 final String pkgName = pkg.packageName; 14464 final int[] allUsers; 14465 final int[] installedUsers; 14466 14467 synchronized(mPackages) { 14468 oldPackage = mPackages.get(pkgName); 14469 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14470 14471 // don't allow upgrade to target a release SDK from a pre-release SDK 14472 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14473 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14474 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14475 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14476 if (oldTargetsPreRelease 14477 && !newTargetsPreRelease 14478 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14479 Slog.w(TAG, "Can't install package targeting released sdk"); 14480 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14481 return; 14482 } 14483 14484 // don't allow an upgrade from full to ephemeral 14485 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14486 if (isEphemeral && !oldIsEphemeral) { 14487 // can't downgrade from full to ephemeral 14488 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14489 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14490 return; 14491 } 14492 14493 // verify signatures are valid 14494 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14495 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14496 if (!checkUpgradeKeySetLP(ps, pkg)) { 14497 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14498 "New package not signed by keys specified by upgrade-keysets: " 14499 + pkgName); 14500 return; 14501 } 14502 } else { 14503 // default to original signature matching 14504 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14505 != PackageManager.SIGNATURE_MATCH) { 14506 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14507 "New package has a different signature: " + pkgName); 14508 return; 14509 } 14510 } 14511 14512 // don't allow a system upgrade unless the upgrade hash matches 14513 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14514 byte[] digestBytes = null; 14515 try { 14516 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14517 updateDigest(digest, new File(pkg.baseCodePath)); 14518 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14519 for (String path : pkg.splitCodePaths) { 14520 updateDigest(digest, new File(path)); 14521 } 14522 } 14523 digestBytes = digest.digest(); 14524 } catch (NoSuchAlgorithmException | IOException e) { 14525 res.setError(INSTALL_FAILED_INVALID_APK, 14526 "Could not compute hash: " + pkgName); 14527 return; 14528 } 14529 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14530 res.setError(INSTALL_FAILED_INVALID_APK, 14531 "New package fails restrict-update check: " + pkgName); 14532 return; 14533 } 14534 // retain upgrade restriction 14535 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14536 } 14537 14538 // Check for shared user id changes 14539 String invalidPackageName = 14540 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14541 if (invalidPackageName != null) { 14542 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14543 "Package " + invalidPackageName + " tried to change user " 14544 + oldPackage.mSharedUserId); 14545 return; 14546 } 14547 14548 // In case of rollback, remember per-user/profile install state 14549 allUsers = sUserManager.getUserIds(); 14550 installedUsers = ps.queryInstalledUsers(allUsers, true); 14551 } 14552 14553 // Update what is removed 14554 res.removedInfo = new PackageRemovedInfo(); 14555 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14556 res.removedInfo.removedPackage = oldPackage.packageName; 14557 res.removedInfo.isUpdate = true; 14558 res.removedInfo.origUsers = installedUsers; 14559 final int childCount = (oldPackage.childPackages != null) 14560 ? oldPackage.childPackages.size() : 0; 14561 for (int i = 0; i < childCount; i++) { 14562 boolean childPackageUpdated = false; 14563 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14564 if (res.addedChildPackages != null) { 14565 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14566 if (childRes != null) { 14567 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14568 childRes.removedInfo.removedPackage = childPkg.packageName; 14569 childRes.removedInfo.isUpdate = true; 14570 childPackageUpdated = true; 14571 } 14572 } 14573 if (!childPackageUpdated) { 14574 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14575 childRemovedRes.removedPackage = childPkg.packageName; 14576 childRemovedRes.isUpdate = false; 14577 childRemovedRes.dataRemoved = true; 14578 synchronized (mPackages) { 14579 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14580 if (childPs != null) { 14581 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14582 } 14583 } 14584 if (res.removedInfo.removedChildPackages == null) { 14585 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14586 } 14587 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14588 } 14589 } 14590 14591 boolean sysPkg = (isSystemApp(oldPackage)); 14592 if (sysPkg) { 14593 // Set the system/privileged flags as needed 14594 final boolean privileged = 14595 (oldPackage.applicationInfo.privateFlags 14596 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14597 final int systemPolicyFlags = policyFlags 14598 | PackageParser.PARSE_IS_SYSTEM 14599 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14600 14601 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14602 user, allUsers, installerPackageName, res); 14603 } else { 14604 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14605 user, allUsers, installerPackageName, res); 14606 } 14607 } 14608 14609 public List<String> getPreviousCodePaths(String packageName) { 14610 final PackageSetting ps = mSettings.mPackages.get(packageName); 14611 final List<String> result = new ArrayList<String>(); 14612 if (ps != null && ps.oldCodePaths != null) { 14613 result.addAll(ps.oldCodePaths); 14614 } 14615 return result; 14616 } 14617 14618 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14619 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14620 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14621 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14622 + deletedPackage); 14623 14624 String pkgName = deletedPackage.packageName; 14625 boolean deletedPkg = true; 14626 boolean addedPkg = false; 14627 boolean updatedSettings = false; 14628 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14629 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14630 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14631 14632 final long origUpdateTime = (pkg.mExtras != null) 14633 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14634 14635 // First delete the existing package while retaining the data directory 14636 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14637 res.removedInfo, true, pkg)) { 14638 // If the existing package wasn't successfully deleted 14639 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14640 deletedPkg = false; 14641 } else { 14642 // Successfully deleted the old package; proceed with replace. 14643 14644 // If deleted package lived in a container, give users a chance to 14645 // relinquish resources before killing. 14646 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14647 if (DEBUG_INSTALL) { 14648 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14649 } 14650 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14651 final ArrayList<String> pkgList = new ArrayList<String>(1); 14652 pkgList.add(deletedPackage.applicationInfo.packageName); 14653 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14654 } 14655 14656 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14657 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14658 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14659 14660 try { 14661 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14662 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14663 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14664 14665 // Update the in-memory copy of the previous code paths. 14666 PackageSetting ps = mSettings.mPackages.get(pkgName); 14667 if (!killApp) { 14668 if (ps.oldCodePaths == null) { 14669 ps.oldCodePaths = new ArraySet<>(); 14670 } 14671 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14672 if (deletedPackage.splitCodePaths != null) { 14673 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14674 } 14675 } else { 14676 ps.oldCodePaths = null; 14677 } 14678 if (ps.childPackageNames != null) { 14679 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14680 final String childPkgName = ps.childPackageNames.get(i); 14681 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14682 childPs.oldCodePaths = ps.oldCodePaths; 14683 } 14684 } 14685 prepareAppDataAfterInstallLIF(newPackage); 14686 addedPkg = true; 14687 } catch (PackageManagerException e) { 14688 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14689 } 14690 } 14691 14692 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14693 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14694 14695 // Revert all internal state mutations and added folders for the failed install 14696 if (addedPkg) { 14697 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14698 res.removedInfo, true, null); 14699 } 14700 14701 // Restore the old package 14702 if (deletedPkg) { 14703 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14704 File restoreFile = new File(deletedPackage.codePath); 14705 // Parse old package 14706 boolean oldExternal = isExternal(deletedPackage); 14707 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14708 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14709 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14710 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14711 try { 14712 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14713 null); 14714 } catch (PackageManagerException e) { 14715 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14716 + e.getMessage()); 14717 return; 14718 } 14719 14720 synchronized (mPackages) { 14721 // Ensure the installer package name up to date 14722 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14723 14724 // Update permissions for restored package 14725 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14726 14727 mSettings.writeLPr(); 14728 } 14729 14730 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14731 } 14732 } else { 14733 synchronized (mPackages) { 14734 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 14735 if (ps != null) { 14736 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14737 if (res.removedInfo.removedChildPackages != null) { 14738 final int childCount = res.removedInfo.removedChildPackages.size(); 14739 // Iterate in reverse as we may modify the collection 14740 for (int i = childCount - 1; i >= 0; i--) { 14741 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14742 if (res.addedChildPackages.containsKey(childPackageName)) { 14743 res.removedInfo.removedChildPackages.removeAt(i); 14744 } else { 14745 PackageRemovedInfo childInfo = res.removedInfo 14746 .removedChildPackages.valueAt(i); 14747 childInfo.removedForAllUsers = mPackages.get( 14748 childInfo.removedPackage) == null; 14749 } 14750 } 14751 } 14752 } 14753 } 14754 } 14755 } 14756 14757 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14758 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14759 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14760 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14761 + ", old=" + deletedPackage); 14762 14763 final boolean disabledSystem; 14764 14765 // Remove existing system package 14766 removePackageLI(deletedPackage, true); 14767 14768 synchronized (mPackages) { 14769 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14770 } 14771 if (!disabledSystem) { 14772 // We didn't need to disable the .apk as a current system package, 14773 // which means we are replacing another update that is already 14774 // installed. We need to make sure to delete the older one's .apk. 14775 res.removedInfo.args = createInstallArgsForExisting(0, 14776 deletedPackage.applicationInfo.getCodePath(), 14777 deletedPackage.applicationInfo.getResourcePath(), 14778 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14779 } else { 14780 res.removedInfo.args = null; 14781 } 14782 14783 // Successfully disabled the old package. Now proceed with re-installation 14784 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14785 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14786 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14787 14788 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14789 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14790 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14791 14792 PackageParser.Package newPackage = null; 14793 try { 14794 // Add the package to the internal data structures 14795 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14796 14797 // Set the update and install times 14798 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14799 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14800 System.currentTimeMillis()); 14801 14802 // Update the package dynamic state if succeeded 14803 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14804 // Now that the install succeeded make sure we remove data 14805 // directories for any child package the update removed. 14806 final int deletedChildCount = (deletedPackage.childPackages != null) 14807 ? deletedPackage.childPackages.size() : 0; 14808 final int newChildCount = (newPackage.childPackages != null) 14809 ? newPackage.childPackages.size() : 0; 14810 for (int i = 0; i < deletedChildCount; i++) { 14811 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14812 boolean childPackageDeleted = true; 14813 for (int j = 0; j < newChildCount; j++) { 14814 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14815 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14816 childPackageDeleted = false; 14817 break; 14818 } 14819 } 14820 if (childPackageDeleted) { 14821 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14822 deletedChildPkg.packageName); 14823 if (ps != null && res.removedInfo.removedChildPackages != null) { 14824 PackageRemovedInfo removedChildRes = res.removedInfo 14825 .removedChildPackages.get(deletedChildPkg.packageName); 14826 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14827 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14828 } 14829 } 14830 } 14831 14832 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14833 prepareAppDataAfterInstallLIF(newPackage); 14834 } 14835 } catch (PackageManagerException e) { 14836 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14837 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14838 } 14839 14840 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14841 // Re installation failed. Restore old information 14842 // Remove new pkg information 14843 if (newPackage != null) { 14844 removeInstalledPackageLI(newPackage, true); 14845 } 14846 // Add back the old system package 14847 try { 14848 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14849 } catch (PackageManagerException e) { 14850 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14851 } 14852 14853 synchronized (mPackages) { 14854 if (disabledSystem) { 14855 enableSystemPackageLPw(deletedPackage); 14856 } 14857 14858 // Ensure the installer package name up to date 14859 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14860 14861 // Update permissions for restored package 14862 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14863 14864 mSettings.writeLPr(); 14865 } 14866 14867 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14868 + " after failed upgrade"); 14869 } 14870 } 14871 14872 /** 14873 * Checks whether the parent or any of the child packages have a change shared 14874 * user. For a package to be a valid update the shred users of the parent and 14875 * the children should match. We may later support changing child shared users. 14876 * @param oldPkg The updated package. 14877 * @param newPkg The update package. 14878 * @return The shared user that change between the versions. 14879 */ 14880 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14881 PackageParser.Package newPkg) { 14882 // Check parent shared user 14883 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14884 return newPkg.packageName; 14885 } 14886 // Check child shared users 14887 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14888 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14889 for (int i = 0; i < newChildCount; i++) { 14890 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14891 // If this child was present, did it have the same shared user? 14892 for (int j = 0; j < oldChildCount; j++) { 14893 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14894 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14895 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14896 return newChildPkg.packageName; 14897 } 14898 } 14899 } 14900 return null; 14901 } 14902 14903 private void removeNativeBinariesLI(PackageSetting ps) { 14904 // Remove the lib path for the parent package 14905 if (ps != null) { 14906 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14907 // Remove the lib path for the child packages 14908 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14909 for (int i = 0; i < childCount; i++) { 14910 PackageSetting childPs = null; 14911 synchronized (mPackages) { 14912 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 14913 } 14914 if (childPs != null) { 14915 NativeLibraryHelper.removeNativeBinariesLI(childPs 14916 .legacyNativeLibraryPathString); 14917 } 14918 } 14919 } 14920 } 14921 14922 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14923 // Enable the parent package 14924 mSettings.enableSystemPackageLPw(pkg.packageName); 14925 // Enable the child packages 14926 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14927 for (int i = 0; i < childCount; i++) { 14928 PackageParser.Package childPkg = pkg.childPackages.get(i); 14929 mSettings.enableSystemPackageLPw(childPkg.packageName); 14930 } 14931 } 14932 14933 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14934 PackageParser.Package newPkg) { 14935 // Disable the parent package (parent always replaced) 14936 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14937 // Disable the child packages 14938 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14939 for (int i = 0; i < childCount; i++) { 14940 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14941 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14942 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14943 } 14944 return disabled; 14945 } 14946 14947 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14948 String installerPackageName) { 14949 // Enable the parent package 14950 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14951 // Enable the child packages 14952 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14953 for (int i = 0; i < childCount; i++) { 14954 PackageParser.Package childPkg = pkg.childPackages.get(i); 14955 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14956 } 14957 } 14958 14959 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14960 // Collect all used permissions in the UID 14961 ArraySet<String> usedPermissions = new ArraySet<>(); 14962 final int packageCount = su.packages.size(); 14963 for (int i = 0; i < packageCount; i++) { 14964 PackageSetting ps = su.packages.valueAt(i); 14965 if (ps.pkg == null) { 14966 continue; 14967 } 14968 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14969 for (int j = 0; j < requestedPermCount; j++) { 14970 String permission = ps.pkg.requestedPermissions.get(j); 14971 BasePermission bp = mSettings.mPermissions.get(permission); 14972 if (bp != null) { 14973 usedPermissions.add(permission); 14974 } 14975 } 14976 } 14977 14978 PermissionsState permissionsState = su.getPermissionsState(); 14979 // Prune install permissions 14980 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14981 final int installPermCount = installPermStates.size(); 14982 for (int i = installPermCount - 1; i >= 0; i--) { 14983 PermissionState permissionState = installPermStates.get(i); 14984 if (!usedPermissions.contains(permissionState.getName())) { 14985 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14986 if (bp != null) { 14987 permissionsState.revokeInstallPermission(bp); 14988 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14989 PackageManager.MASK_PERMISSION_FLAGS, 0); 14990 } 14991 } 14992 } 14993 14994 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14995 14996 // Prune runtime permissions 14997 for (int userId : allUserIds) { 14998 List<PermissionState> runtimePermStates = permissionsState 14999 .getRuntimePermissionStates(userId); 15000 final int runtimePermCount = runtimePermStates.size(); 15001 for (int i = runtimePermCount - 1; i >= 0; i--) { 15002 PermissionState permissionState = runtimePermStates.get(i); 15003 if (!usedPermissions.contains(permissionState.getName())) { 15004 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15005 if (bp != null) { 15006 permissionsState.revokeRuntimePermission(bp, userId); 15007 permissionsState.updatePermissionFlags(bp, userId, 15008 PackageManager.MASK_PERMISSION_FLAGS, 0); 15009 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15010 runtimePermissionChangedUserIds, userId); 15011 } 15012 } 15013 } 15014 } 15015 15016 return runtimePermissionChangedUserIds; 15017 } 15018 15019 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15020 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15021 // Update the parent package setting 15022 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15023 res, user); 15024 // Update the child packages setting 15025 final int childCount = (newPackage.childPackages != null) 15026 ? newPackage.childPackages.size() : 0; 15027 for (int i = 0; i < childCount; i++) { 15028 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15029 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15030 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15031 childRes.origUsers, childRes, user); 15032 } 15033 } 15034 15035 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15036 String installerPackageName, int[] allUsers, int[] installedForUsers, 15037 PackageInstalledInfo res, UserHandle user) { 15038 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15039 15040 String pkgName = newPackage.packageName; 15041 synchronized (mPackages) { 15042 //write settings. the installStatus will be incomplete at this stage. 15043 //note that the new package setting would have already been 15044 //added to mPackages. It hasn't been persisted yet. 15045 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15046 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15047 mSettings.writeLPr(); 15048 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15049 } 15050 15051 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15052 synchronized (mPackages) { 15053 updatePermissionsLPw(newPackage.packageName, newPackage, 15054 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15055 ? UPDATE_PERMISSIONS_ALL : 0)); 15056 // For system-bundled packages, we assume that installing an upgraded version 15057 // of the package implies that the user actually wants to run that new code, 15058 // so we enable the package. 15059 PackageSetting ps = mSettings.mPackages.get(pkgName); 15060 final int userId = user.getIdentifier(); 15061 if (ps != null) { 15062 if (isSystemApp(newPackage)) { 15063 if (DEBUG_INSTALL) { 15064 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15065 } 15066 // Enable system package for requested users 15067 if (res.origUsers != null) { 15068 for (int origUserId : res.origUsers) { 15069 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15070 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15071 origUserId, installerPackageName); 15072 } 15073 } 15074 } 15075 // Also convey the prior install/uninstall state 15076 if (allUsers != null && installedForUsers != null) { 15077 for (int currentUserId : allUsers) { 15078 final boolean installed = ArrayUtils.contains( 15079 installedForUsers, currentUserId); 15080 if (DEBUG_INSTALL) { 15081 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15082 } 15083 ps.setInstalled(installed, currentUserId); 15084 } 15085 // these install state changes will be persisted in the 15086 // upcoming call to mSettings.writeLPr(). 15087 } 15088 } 15089 // It's implied that when a user requests installation, they want the app to be 15090 // installed and enabled. 15091 if (userId != UserHandle.USER_ALL) { 15092 ps.setInstalled(true, userId); 15093 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15094 } 15095 } 15096 res.name = pkgName; 15097 res.uid = newPackage.applicationInfo.uid; 15098 res.pkg = newPackage; 15099 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15100 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15101 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15102 //to update install status 15103 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15104 mSettings.writeLPr(); 15105 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15106 } 15107 15108 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15109 } 15110 15111 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15112 try { 15113 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15114 installPackageLI(args, res); 15115 } finally { 15116 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15117 } 15118 } 15119 15120 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15121 final int installFlags = args.installFlags; 15122 final String installerPackageName = args.installerPackageName; 15123 final String volumeUuid = args.volumeUuid; 15124 final File tmpPackageFile = new File(args.getCodePath()); 15125 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15126 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15127 || (args.volumeUuid != null)); 15128 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15129 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15130 boolean replace = false; 15131 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15132 if (args.move != null) { 15133 // moving a complete application; perform an initial scan on the new install location 15134 scanFlags |= SCAN_INITIAL; 15135 } 15136 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15137 scanFlags |= SCAN_DONT_KILL_APP; 15138 } 15139 15140 // Result object to be returned 15141 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15142 15143 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15144 15145 // Sanity check 15146 if (ephemeral && (forwardLocked || onExternal)) { 15147 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15148 + " external=" + onExternal); 15149 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15150 return; 15151 } 15152 15153 // Retrieve PackageSettings and parse package 15154 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15155 | PackageParser.PARSE_ENFORCE_CODE 15156 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15157 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15158 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15159 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15160 PackageParser pp = new PackageParser(); 15161 pp.setSeparateProcesses(mSeparateProcesses); 15162 pp.setDisplayMetrics(mMetrics); 15163 15164 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15165 final PackageParser.Package pkg; 15166 try { 15167 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15168 } catch (PackageParserException e) { 15169 res.setError("Failed parse during installPackageLI", e); 15170 return; 15171 } finally { 15172 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15173 } 15174 15175 // If we are installing a clustered package add results for the children 15176 if (pkg.childPackages != null) { 15177 synchronized (mPackages) { 15178 final int childCount = pkg.childPackages.size(); 15179 for (int i = 0; i < childCount; i++) { 15180 PackageParser.Package childPkg = pkg.childPackages.get(i); 15181 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15182 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15183 childRes.pkg = childPkg; 15184 childRes.name = childPkg.packageName; 15185 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15186 if (childPs != null) { 15187 childRes.origUsers = childPs.queryInstalledUsers( 15188 sUserManager.getUserIds(), true); 15189 } 15190 if ((mPackages.containsKey(childPkg.packageName))) { 15191 childRes.removedInfo = new PackageRemovedInfo(); 15192 childRes.removedInfo.removedPackage = childPkg.packageName; 15193 } 15194 if (res.addedChildPackages == null) { 15195 res.addedChildPackages = new ArrayMap<>(); 15196 } 15197 res.addedChildPackages.put(childPkg.packageName, childRes); 15198 } 15199 } 15200 } 15201 15202 // If package doesn't declare API override, mark that we have an install 15203 // time CPU ABI override. 15204 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15205 pkg.cpuAbiOverride = args.abiOverride; 15206 } 15207 15208 String pkgName = res.name = pkg.packageName; 15209 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15210 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15211 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15212 return; 15213 } 15214 } 15215 15216 try { 15217 // either use what we've been given or parse directly from the APK 15218 if (args.certificates != null) { 15219 try { 15220 PackageParser.populateCertificates(pkg, args.certificates); 15221 } catch (PackageParserException e) { 15222 // there was something wrong with the certificates we were given; 15223 // try to pull them from the APK 15224 PackageParser.collectCertificates(pkg, parseFlags); 15225 } 15226 } else { 15227 PackageParser.collectCertificates(pkg, parseFlags); 15228 } 15229 } catch (PackageParserException e) { 15230 res.setError("Failed collect during installPackageLI", e); 15231 return; 15232 } 15233 15234 // Get rid of all references to package scan path via parser. 15235 pp = null; 15236 String oldCodePath = null; 15237 boolean systemApp = false; 15238 synchronized (mPackages) { 15239 // Check if installing already existing package 15240 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15241 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15242 if (pkg.mOriginalPackages != null 15243 && pkg.mOriginalPackages.contains(oldName) 15244 && mPackages.containsKey(oldName)) { 15245 // This package is derived from an original package, 15246 // and this device has been updating from that original 15247 // name. We must continue using the original name, so 15248 // rename the new package here. 15249 pkg.setPackageName(oldName); 15250 pkgName = pkg.packageName; 15251 replace = true; 15252 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15253 + oldName + " pkgName=" + pkgName); 15254 } else if (mPackages.containsKey(pkgName)) { 15255 // This package, under its official name, already exists 15256 // on the device; we should replace it. 15257 replace = true; 15258 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15259 } 15260 15261 // Child packages are installed through the parent package 15262 if (pkg.parentPackage != null) { 15263 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15264 "Package " + pkg.packageName + " is child of package " 15265 + pkg.parentPackage.parentPackage + ". Child packages " 15266 + "can be updated only through the parent package."); 15267 return; 15268 } 15269 15270 if (replace) { 15271 // Prevent apps opting out from runtime permissions 15272 PackageParser.Package oldPackage = mPackages.get(pkgName); 15273 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15274 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15275 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15276 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15277 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15278 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15279 + " doesn't support runtime permissions but the old" 15280 + " target SDK " + oldTargetSdk + " does."); 15281 return; 15282 } 15283 15284 // Prevent installing of child packages 15285 if (oldPackage.parentPackage != null) { 15286 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15287 "Package " + pkg.packageName + " is child of package " 15288 + oldPackage.parentPackage + ". Child packages " 15289 + "can be updated only through the parent package."); 15290 return; 15291 } 15292 } 15293 } 15294 15295 PackageSetting ps = mSettings.mPackages.get(pkgName); 15296 if (ps != null) { 15297 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15298 15299 // Quick sanity check that we're signed correctly if updating; 15300 // we'll check this again later when scanning, but we want to 15301 // bail early here before tripping over redefined permissions. 15302 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15303 if (!checkUpgradeKeySetLP(ps, pkg)) { 15304 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15305 + pkg.packageName + " upgrade keys do not match the " 15306 + "previously installed version"); 15307 return; 15308 } 15309 } else { 15310 try { 15311 verifySignaturesLP(ps, pkg); 15312 } catch (PackageManagerException e) { 15313 res.setError(e.error, e.getMessage()); 15314 return; 15315 } 15316 } 15317 15318 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15319 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15320 systemApp = (ps.pkg.applicationInfo.flags & 15321 ApplicationInfo.FLAG_SYSTEM) != 0; 15322 } 15323 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15324 } 15325 15326 // Check whether the newly-scanned package wants to define an already-defined perm 15327 int N = pkg.permissions.size(); 15328 for (int i = N-1; i >= 0; i--) { 15329 PackageParser.Permission perm = pkg.permissions.get(i); 15330 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15331 if (bp != null) { 15332 // If the defining package is signed with our cert, it's okay. This 15333 // also includes the "updating the same package" case, of course. 15334 // "updating same package" could also involve key-rotation. 15335 final boolean sigsOk; 15336 if (bp.sourcePackage.equals(pkg.packageName) 15337 && (bp.packageSetting instanceof PackageSetting) 15338 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15339 scanFlags))) { 15340 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15341 } else { 15342 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15343 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15344 } 15345 if (!sigsOk) { 15346 // If the owning package is the system itself, we log but allow 15347 // install to proceed; we fail the install on all other permission 15348 // redefinitions. 15349 if (!bp.sourcePackage.equals("android")) { 15350 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15351 + pkg.packageName + " attempting to redeclare permission " 15352 + perm.info.name + " already owned by " + bp.sourcePackage); 15353 res.origPermission = perm.info.name; 15354 res.origPackage = bp.sourcePackage; 15355 return; 15356 } else { 15357 Slog.w(TAG, "Package " + pkg.packageName 15358 + " attempting to redeclare system permission " 15359 + perm.info.name + "; ignoring new declaration"); 15360 pkg.permissions.remove(i); 15361 } 15362 } 15363 } 15364 } 15365 } 15366 15367 if (systemApp) { 15368 if (onExternal) { 15369 // Abort update; system app can't be replaced with app on sdcard 15370 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15371 "Cannot install updates to system apps on sdcard"); 15372 return; 15373 } else if (ephemeral) { 15374 // Abort update; system app can't be replaced with an ephemeral app 15375 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15376 "Cannot update a system app with an ephemeral app"); 15377 return; 15378 } 15379 } 15380 15381 if (args.move != null) { 15382 // We did an in-place move, so dex is ready to roll 15383 scanFlags |= SCAN_NO_DEX; 15384 scanFlags |= SCAN_MOVE; 15385 15386 synchronized (mPackages) { 15387 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15388 if (ps == null) { 15389 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15390 "Missing settings for moved package " + pkgName); 15391 } 15392 15393 // We moved the entire application as-is, so bring over the 15394 // previously derived ABI information. 15395 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15396 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15397 } 15398 15399 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15400 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15401 scanFlags |= SCAN_NO_DEX; 15402 15403 try { 15404 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15405 args.abiOverride : pkg.cpuAbiOverride); 15406 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15407 true /*extractLibs*/, mAppLib32InstallDir); 15408 } catch (PackageManagerException pme) { 15409 Slog.e(TAG, "Error deriving application ABI", pme); 15410 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15411 return; 15412 } 15413 15414 // Shared libraries for the package need to be updated. 15415 synchronized (mPackages) { 15416 try { 15417 updateSharedLibrariesLPr(pkg, null); 15418 } catch (PackageManagerException e) { 15419 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15420 } 15421 } 15422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15423 // Do not run PackageDexOptimizer through the local performDexOpt 15424 // method because `pkg` may not be in `mPackages` yet. 15425 // 15426 // Also, don't fail application installs if the dexopt step fails. 15427 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15428 null /* instructionSets */, false /* checkProfiles */, 15429 getCompilerFilterForReason(REASON_INSTALL), 15430 getOrCreateCompilerPackageStats(pkg)); 15431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15432 15433 // Notify BackgroundDexOptService that the package has been changed. 15434 // If this is an update of a package which used to fail to compile, 15435 // BDOS will remove it from its blacklist. 15436 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15437 } 15438 15439 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15440 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15441 return; 15442 } 15443 15444 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15445 15446 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15447 "installPackageLI")) { 15448 if (replace) { 15449 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15450 installerPackageName, res); 15451 } else { 15452 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15453 args.user, installerPackageName, volumeUuid, res); 15454 } 15455 } 15456 synchronized (mPackages) { 15457 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15458 if (ps != null) { 15459 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15460 } 15461 15462 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15463 for (int i = 0; i < childCount; i++) { 15464 PackageParser.Package childPkg = pkg.childPackages.get(i); 15465 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15466 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15467 if (childPs != null) { 15468 childRes.newUsers = childPs.queryInstalledUsers( 15469 sUserManager.getUserIds(), true); 15470 } 15471 } 15472 } 15473 } 15474 15475 private void startIntentFilterVerifications(int userId, boolean replacing, 15476 PackageParser.Package pkg) { 15477 if (mIntentFilterVerifierComponent == null) { 15478 Slog.w(TAG, "No IntentFilter verification will not be done as " 15479 + "there is no IntentFilterVerifier available!"); 15480 return; 15481 } 15482 15483 final int verifierUid = getPackageUid( 15484 mIntentFilterVerifierComponent.getPackageName(), 15485 MATCH_DEBUG_TRIAGED_MISSING, 15486 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15487 15488 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15489 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15490 mHandler.sendMessage(msg); 15491 15492 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15493 for (int i = 0; i < childCount; i++) { 15494 PackageParser.Package childPkg = pkg.childPackages.get(i); 15495 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15496 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15497 mHandler.sendMessage(msg); 15498 } 15499 } 15500 15501 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15502 PackageParser.Package pkg) { 15503 int size = pkg.activities.size(); 15504 if (size == 0) { 15505 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15506 "No activity, so no need to verify any IntentFilter!"); 15507 return; 15508 } 15509 15510 final boolean hasDomainURLs = hasDomainURLs(pkg); 15511 if (!hasDomainURLs) { 15512 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15513 "No domain URLs, so no need to verify any IntentFilter!"); 15514 return; 15515 } 15516 15517 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15518 + " if any IntentFilter from the " + size 15519 + " Activities needs verification ..."); 15520 15521 int count = 0; 15522 final String packageName = pkg.packageName; 15523 15524 synchronized (mPackages) { 15525 // If this is a new install and we see that we've already run verification for this 15526 // package, we have nothing to do: it means the state was restored from backup. 15527 if (!replacing) { 15528 IntentFilterVerificationInfo ivi = 15529 mSettings.getIntentFilterVerificationLPr(packageName); 15530 if (ivi != null) { 15531 if (DEBUG_DOMAIN_VERIFICATION) { 15532 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15533 + ivi.getStatusString()); 15534 } 15535 return; 15536 } 15537 } 15538 15539 // If any filters need to be verified, then all need to be. 15540 boolean needToVerify = false; 15541 for (PackageParser.Activity a : pkg.activities) { 15542 for (ActivityIntentInfo filter : a.intents) { 15543 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15544 if (DEBUG_DOMAIN_VERIFICATION) { 15545 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15546 } 15547 needToVerify = true; 15548 break; 15549 } 15550 } 15551 } 15552 15553 if (needToVerify) { 15554 final int verificationId = mIntentFilterVerificationToken++; 15555 for (PackageParser.Activity a : pkg.activities) { 15556 for (ActivityIntentInfo filter : a.intents) { 15557 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15558 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15559 "Verification needed for IntentFilter:" + filter.toString()); 15560 mIntentFilterVerifier.addOneIntentFilterVerification( 15561 verifierUid, userId, verificationId, filter, packageName); 15562 count++; 15563 } 15564 } 15565 } 15566 } 15567 } 15568 15569 if (count > 0) { 15570 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15571 + " IntentFilter verification" + (count > 1 ? "s" : "") 15572 + " for userId:" + userId); 15573 mIntentFilterVerifier.startVerifications(userId); 15574 } else { 15575 if (DEBUG_DOMAIN_VERIFICATION) { 15576 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15577 } 15578 } 15579 } 15580 15581 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15582 final ComponentName cn = filter.activity.getComponentName(); 15583 final String packageName = cn.getPackageName(); 15584 15585 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15586 packageName); 15587 if (ivi == null) { 15588 return true; 15589 } 15590 int status = ivi.getStatus(); 15591 switch (status) { 15592 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15593 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15594 return true; 15595 15596 default: 15597 // Nothing to do 15598 return false; 15599 } 15600 } 15601 15602 private static boolean isMultiArch(ApplicationInfo info) { 15603 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15604 } 15605 15606 private static boolean isExternal(PackageParser.Package pkg) { 15607 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15608 } 15609 15610 private static boolean isExternal(PackageSetting ps) { 15611 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15612 } 15613 15614 private static boolean isEphemeral(PackageParser.Package pkg) { 15615 return pkg.applicationInfo.isEphemeralApp(); 15616 } 15617 15618 private static boolean isEphemeral(PackageSetting ps) { 15619 return ps.pkg != null && isEphemeral(ps.pkg); 15620 } 15621 15622 private static boolean isSystemApp(PackageParser.Package pkg) { 15623 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15624 } 15625 15626 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15627 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15628 } 15629 15630 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15631 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15632 } 15633 15634 private static boolean isSystemApp(PackageSetting ps) { 15635 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15636 } 15637 15638 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15639 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15640 } 15641 15642 private int packageFlagsToInstallFlags(PackageSetting ps) { 15643 int installFlags = 0; 15644 if (isEphemeral(ps)) { 15645 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15646 } 15647 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15648 // This existing package was an external ASEC install when we have 15649 // the external flag without a UUID 15650 installFlags |= PackageManager.INSTALL_EXTERNAL; 15651 } 15652 if (ps.isForwardLocked()) { 15653 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15654 } 15655 return installFlags; 15656 } 15657 15658 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15659 if (isExternal(pkg)) { 15660 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15661 return StorageManager.UUID_PRIMARY_PHYSICAL; 15662 } else { 15663 return pkg.volumeUuid; 15664 } 15665 } else { 15666 return StorageManager.UUID_PRIVATE_INTERNAL; 15667 } 15668 } 15669 15670 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15671 if (isExternal(pkg)) { 15672 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15673 return mSettings.getExternalVersion(); 15674 } else { 15675 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15676 } 15677 } else { 15678 return mSettings.getInternalVersion(); 15679 } 15680 } 15681 15682 private void deleteTempPackageFiles() { 15683 final FilenameFilter filter = new FilenameFilter() { 15684 public boolean accept(File dir, String name) { 15685 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15686 } 15687 }; 15688 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15689 file.delete(); 15690 } 15691 } 15692 15693 @Override 15694 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15695 int flags) { 15696 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15697 flags); 15698 } 15699 15700 @Override 15701 public void deletePackage(final String packageName, 15702 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15703 mContext.enforceCallingOrSelfPermission( 15704 android.Manifest.permission.DELETE_PACKAGES, null); 15705 Preconditions.checkNotNull(packageName); 15706 Preconditions.checkNotNull(observer); 15707 final int uid = Binder.getCallingUid(); 15708 if (!isOrphaned(packageName) 15709 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15710 try { 15711 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15712 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15713 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15714 observer.onUserActionRequired(intent); 15715 } catch (RemoteException re) { 15716 } 15717 return; 15718 } 15719 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15720 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15721 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15722 mContext.enforceCallingOrSelfPermission( 15723 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15724 "deletePackage for user " + userId); 15725 } 15726 15727 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15728 try { 15729 observer.onPackageDeleted(packageName, 15730 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15731 } catch (RemoteException re) { 15732 } 15733 return; 15734 } 15735 15736 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15737 try { 15738 observer.onPackageDeleted(packageName, 15739 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15740 } catch (RemoteException re) { 15741 } 15742 return; 15743 } 15744 15745 if (DEBUG_REMOVE) { 15746 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15747 + " deleteAllUsers: " + deleteAllUsers ); 15748 } 15749 // Queue up an async operation since the package deletion may take a little while. 15750 mHandler.post(new Runnable() { 15751 public void run() { 15752 mHandler.removeCallbacks(this); 15753 int returnCode; 15754 if (!deleteAllUsers) { 15755 returnCode = deletePackageX(packageName, userId, deleteFlags); 15756 } else { 15757 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15758 // If nobody is blocking uninstall, proceed with delete for all users 15759 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15760 returnCode = deletePackageX(packageName, userId, deleteFlags); 15761 } else { 15762 // Otherwise uninstall individually for users with blockUninstalls=false 15763 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15764 for (int userId : users) { 15765 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15766 returnCode = deletePackageX(packageName, userId, userFlags); 15767 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15768 Slog.w(TAG, "Package delete failed for user " + userId 15769 + ", returnCode " + returnCode); 15770 } 15771 } 15772 } 15773 // The app has only been marked uninstalled for certain users. 15774 // We still need to report that delete was blocked 15775 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15776 } 15777 } 15778 try { 15779 observer.onPackageDeleted(packageName, returnCode, null); 15780 } catch (RemoteException e) { 15781 Log.i(TAG, "Observer no longer exists."); 15782 } //end catch 15783 } //end run 15784 }); 15785 } 15786 15787 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15788 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15789 || callingUid == Process.SYSTEM_UID) { 15790 return true; 15791 } 15792 final int callingUserId = UserHandle.getUserId(callingUid); 15793 // If the caller installed the pkgName, then allow it to silently uninstall. 15794 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15795 return true; 15796 } 15797 15798 // Allow package verifier to silently uninstall. 15799 if (mRequiredVerifierPackage != null && 15800 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15801 return true; 15802 } 15803 15804 // Allow package uninstaller to silently uninstall. 15805 if (mRequiredUninstallerPackage != null && 15806 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15807 return true; 15808 } 15809 15810 // Allow storage manager to silently uninstall. 15811 if (mStorageManagerPackage != null && 15812 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15813 return true; 15814 } 15815 return false; 15816 } 15817 15818 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15819 int[] result = EMPTY_INT_ARRAY; 15820 for (int userId : userIds) { 15821 if (getBlockUninstallForUser(packageName, userId)) { 15822 result = ArrayUtils.appendInt(result, userId); 15823 } 15824 } 15825 return result; 15826 } 15827 15828 @Override 15829 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15830 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15831 } 15832 15833 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15834 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15835 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15836 try { 15837 if (dpm != null) { 15838 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15839 /* callingUserOnly =*/ false); 15840 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15841 : deviceOwnerComponentName.getPackageName(); 15842 // Does the package contains the device owner? 15843 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15844 // this check is probably not needed, since DO should be registered as a device 15845 // admin on some user too. (Original bug for this: b/17657954) 15846 if (packageName.equals(deviceOwnerPackageName)) { 15847 return true; 15848 } 15849 // Does it contain a device admin for any user? 15850 int[] users; 15851 if (userId == UserHandle.USER_ALL) { 15852 users = sUserManager.getUserIds(); 15853 } else { 15854 users = new int[]{userId}; 15855 } 15856 for (int i = 0; i < users.length; ++i) { 15857 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15858 return true; 15859 } 15860 } 15861 } 15862 } catch (RemoteException e) { 15863 } 15864 return false; 15865 } 15866 15867 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15868 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15869 } 15870 15871 /** 15872 * This method is an internal method that could be get invoked either 15873 * to delete an installed package or to clean up a failed installation. 15874 * After deleting an installed package, a broadcast is sent to notify any 15875 * listeners that the package has been removed. For cleaning up a failed 15876 * installation, the broadcast is not necessary since the package's 15877 * installation wouldn't have sent the initial broadcast either 15878 * The key steps in deleting a package are 15879 * deleting the package information in internal structures like mPackages, 15880 * deleting the packages base directories through installd 15881 * updating mSettings to reflect current status 15882 * persisting settings for later use 15883 * sending a broadcast if necessary 15884 */ 15885 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15886 final PackageRemovedInfo info = new PackageRemovedInfo(); 15887 final boolean res; 15888 15889 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15890 ? UserHandle.USER_ALL : userId; 15891 15892 if (isPackageDeviceAdmin(packageName, removeUser)) { 15893 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15894 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15895 } 15896 15897 PackageSetting uninstalledPs = null; 15898 15899 // for the uninstall-updates case and restricted profiles, remember the per- 15900 // user handle installed state 15901 int[] allUsers; 15902 synchronized (mPackages) { 15903 uninstalledPs = mSettings.mPackages.get(packageName); 15904 if (uninstalledPs == null) { 15905 Slog.w(TAG, "Not removing non-existent package " + packageName); 15906 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15907 } 15908 allUsers = sUserManager.getUserIds(); 15909 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15910 } 15911 15912 final int freezeUser; 15913 if (isUpdatedSystemApp(uninstalledPs) 15914 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15915 // We're downgrading a system app, which will apply to all users, so 15916 // freeze them all during the downgrade 15917 freezeUser = UserHandle.USER_ALL; 15918 } else { 15919 freezeUser = removeUser; 15920 } 15921 15922 synchronized (mInstallLock) { 15923 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15924 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15925 deleteFlags, "deletePackageX")) { 15926 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15927 deleteFlags | REMOVE_CHATTY, info, true, null); 15928 } 15929 synchronized (mPackages) { 15930 if (res) { 15931 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15932 } 15933 } 15934 } 15935 15936 if (res) { 15937 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15938 info.sendPackageRemovedBroadcasts(killApp); 15939 info.sendSystemPackageUpdatedBroadcasts(); 15940 info.sendSystemPackageAppearedBroadcasts(); 15941 } 15942 // Force a gc here. 15943 Runtime.getRuntime().gc(); 15944 // Delete the resources here after sending the broadcast to let 15945 // other processes clean up before deleting resources. 15946 if (info.args != null) { 15947 synchronized (mInstallLock) { 15948 info.args.doPostDeleteLI(true); 15949 } 15950 } 15951 15952 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15953 } 15954 15955 class PackageRemovedInfo { 15956 String removedPackage; 15957 int uid = -1; 15958 int removedAppId = -1; 15959 int[] origUsers; 15960 int[] removedUsers = null; 15961 boolean isRemovedPackageSystemUpdate = false; 15962 boolean isUpdate; 15963 boolean dataRemoved; 15964 boolean removedForAllUsers; 15965 // Clean up resources deleted packages. 15966 InstallArgs args = null; 15967 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15968 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15969 15970 void sendPackageRemovedBroadcasts(boolean killApp) { 15971 sendPackageRemovedBroadcastInternal(killApp); 15972 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15973 for (int i = 0; i < childCount; i++) { 15974 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15975 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15976 } 15977 } 15978 15979 void sendSystemPackageUpdatedBroadcasts() { 15980 if (isRemovedPackageSystemUpdate) { 15981 sendSystemPackageUpdatedBroadcastsInternal(); 15982 final int childCount = (removedChildPackages != null) 15983 ? removedChildPackages.size() : 0; 15984 for (int i = 0; i < childCount; i++) { 15985 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15986 if (childInfo.isRemovedPackageSystemUpdate) { 15987 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15988 } 15989 } 15990 } 15991 } 15992 15993 void sendSystemPackageAppearedBroadcasts() { 15994 final int packageCount = (appearedChildPackages != null) 15995 ? appearedChildPackages.size() : 0; 15996 for (int i = 0; i < packageCount; i++) { 15997 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15998 sendPackageAddedForNewUsers(installedInfo.name, true, 15999 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16000 } 16001 } 16002 16003 private void sendSystemPackageUpdatedBroadcastsInternal() { 16004 Bundle extras = new Bundle(2); 16005 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16006 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16007 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16008 extras, 0, null, null, null); 16009 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16010 extras, 0, null, null, null); 16011 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16012 null, 0, removedPackage, null, null); 16013 } 16014 16015 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16016 Bundle extras = new Bundle(2); 16017 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16018 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16019 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16020 if (isUpdate || isRemovedPackageSystemUpdate) { 16021 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16022 } 16023 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16024 if (removedPackage != null) { 16025 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16026 extras, 0, null, null, removedUsers); 16027 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16028 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16029 removedPackage, extras, 0, null, null, removedUsers); 16030 } 16031 } 16032 if (removedAppId >= 0) { 16033 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16034 removedUsers); 16035 } 16036 } 16037 } 16038 16039 /* 16040 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16041 * flag is not set, the data directory is removed as well. 16042 * make sure this flag is set for partially installed apps. If not its meaningless to 16043 * delete a partially installed application. 16044 */ 16045 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16046 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16047 String packageName = ps.name; 16048 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16049 // Retrieve object to delete permissions for shared user later on 16050 final PackageParser.Package deletedPkg; 16051 final PackageSetting deletedPs; 16052 // reader 16053 synchronized (mPackages) { 16054 deletedPkg = mPackages.get(packageName); 16055 deletedPs = mSettings.mPackages.get(packageName); 16056 if (outInfo != null) { 16057 outInfo.removedPackage = packageName; 16058 outInfo.removedUsers = deletedPs != null 16059 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16060 : null; 16061 } 16062 } 16063 16064 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16065 16066 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16067 final PackageParser.Package resolvedPkg; 16068 if (deletedPkg != null) { 16069 resolvedPkg = deletedPkg; 16070 } else { 16071 // We don't have a parsed package when it lives on an ejected 16072 // adopted storage device, so fake something together 16073 resolvedPkg = new PackageParser.Package(ps.name); 16074 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16075 } 16076 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16077 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16078 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16079 if (outInfo != null) { 16080 outInfo.dataRemoved = true; 16081 } 16082 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16083 } 16084 16085 // writer 16086 synchronized (mPackages) { 16087 if (deletedPs != null) { 16088 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16089 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16090 clearDefaultBrowserIfNeeded(packageName); 16091 if (outInfo != null) { 16092 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16093 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16094 } 16095 updatePermissionsLPw(deletedPs.name, null, 0); 16096 if (deletedPs.sharedUser != null) { 16097 // Remove permissions associated with package. Since runtime 16098 // permissions are per user we have to kill the removed package 16099 // or packages running under the shared user of the removed 16100 // package if revoking the permissions requested only by the removed 16101 // package is successful and this causes a change in gids. 16102 for (int userId : UserManagerService.getInstance().getUserIds()) { 16103 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16104 userId); 16105 if (userIdToKill == UserHandle.USER_ALL 16106 || userIdToKill >= UserHandle.USER_SYSTEM) { 16107 // If gids changed for this user, kill all affected packages. 16108 mHandler.post(new Runnable() { 16109 @Override 16110 public void run() { 16111 // This has to happen with no lock held. 16112 killApplication(deletedPs.name, deletedPs.appId, 16113 KILL_APP_REASON_GIDS_CHANGED); 16114 } 16115 }); 16116 break; 16117 } 16118 } 16119 } 16120 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16121 } 16122 // make sure to preserve per-user disabled state if this removal was just 16123 // a downgrade of a system app to the factory package 16124 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16125 if (DEBUG_REMOVE) { 16126 Slog.d(TAG, "Propagating install state across downgrade"); 16127 } 16128 for (int userId : allUserHandles) { 16129 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16130 if (DEBUG_REMOVE) { 16131 Slog.d(TAG, " user " + userId + " => " + installed); 16132 } 16133 ps.setInstalled(installed, userId); 16134 } 16135 } 16136 } 16137 // can downgrade to reader 16138 if (writeSettings) { 16139 // Save settings now 16140 mSettings.writeLPr(); 16141 } 16142 } 16143 if (outInfo != null) { 16144 // A user ID was deleted here. Go through all users and remove it 16145 // from KeyStore. 16146 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16147 } 16148 } 16149 16150 static boolean locationIsPrivileged(File path) { 16151 try { 16152 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16153 .getCanonicalPath(); 16154 return path.getCanonicalPath().startsWith(privilegedAppDir); 16155 } catch (IOException e) { 16156 Slog.e(TAG, "Unable to access code path " + path); 16157 } 16158 return false; 16159 } 16160 16161 /* 16162 * Tries to delete system package. 16163 */ 16164 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16165 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16166 boolean writeSettings) { 16167 if (deletedPs.parentPackageName != null) { 16168 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16169 return false; 16170 } 16171 16172 final boolean applyUserRestrictions 16173 = (allUserHandles != null) && (outInfo.origUsers != null); 16174 final PackageSetting disabledPs; 16175 // Confirm if the system package has been updated 16176 // An updated system app can be deleted. This will also have to restore 16177 // the system pkg from system partition 16178 // reader 16179 synchronized (mPackages) { 16180 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16181 } 16182 16183 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16184 + " disabledPs=" + disabledPs); 16185 16186 if (disabledPs == null) { 16187 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16188 return false; 16189 } else if (DEBUG_REMOVE) { 16190 Slog.d(TAG, "Deleting system pkg from data partition"); 16191 } 16192 16193 if (DEBUG_REMOVE) { 16194 if (applyUserRestrictions) { 16195 Slog.d(TAG, "Remembering install states:"); 16196 for (int userId : allUserHandles) { 16197 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16198 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16199 } 16200 } 16201 } 16202 16203 // Delete the updated package 16204 outInfo.isRemovedPackageSystemUpdate = true; 16205 if (outInfo.removedChildPackages != null) { 16206 final int childCount = (deletedPs.childPackageNames != null) 16207 ? deletedPs.childPackageNames.size() : 0; 16208 for (int i = 0; i < childCount; i++) { 16209 String childPackageName = deletedPs.childPackageNames.get(i); 16210 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16211 .contains(childPackageName)) { 16212 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16213 childPackageName); 16214 if (childInfo != null) { 16215 childInfo.isRemovedPackageSystemUpdate = true; 16216 } 16217 } 16218 } 16219 } 16220 16221 if (disabledPs.versionCode < deletedPs.versionCode) { 16222 // Delete data for downgrades 16223 flags &= ~PackageManager.DELETE_KEEP_DATA; 16224 } else { 16225 // Preserve data by setting flag 16226 flags |= PackageManager.DELETE_KEEP_DATA; 16227 } 16228 16229 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16230 outInfo, writeSettings, disabledPs.pkg); 16231 if (!ret) { 16232 return false; 16233 } 16234 16235 // writer 16236 synchronized (mPackages) { 16237 // Reinstate the old system package 16238 enableSystemPackageLPw(disabledPs.pkg); 16239 // Remove any native libraries from the upgraded package. 16240 removeNativeBinariesLI(deletedPs); 16241 } 16242 16243 // Install the system package 16244 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16245 int parseFlags = mDefParseFlags 16246 | PackageParser.PARSE_MUST_BE_APK 16247 | PackageParser.PARSE_IS_SYSTEM 16248 | PackageParser.PARSE_IS_SYSTEM_DIR; 16249 if (locationIsPrivileged(disabledPs.codePath)) { 16250 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16251 } 16252 16253 final PackageParser.Package newPkg; 16254 try { 16255 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16256 } catch (PackageManagerException e) { 16257 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16258 + e.getMessage()); 16259 return false; 16260 } 16261 try { 16262 // update shared libraries for the newly re-installed system package 16263 updateSharedLibrariesLPr(newPkg, null); 16264 } catch (PackageManagerException e) { 16265 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16266 } 16267 16268 prepareAppDataAfterInstallLIF(newPkg); 16269 16270 // writer 16271 synchronized (mPackages) { 16272 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16273 16274 // Propagate the permissions state as we do not want to drop on the floor 16275 // runtime permissions. The update permissions method below will take 16276 // care of removing obsolete permissions and grant install permissions. 16277 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16278 updatePermissionsLPw(newPkg.packageName, newPkg, 16279 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16280 16281 if (applyUserRestrictions) { 16282 if (DEBUG_REMOVE) { 16283 Slog.d(TAG, "Propagating install state across reinstall"); 16284 } 16285 for (int userId : allUserHandles) { 16286 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16287 if (DEBUG_REMOVE) { 16288 Slog.d(TAG, " user " + userId + " => " + installed); 16289 } 16290 ps.setInstalled(installed, userId); 16291 16292 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16293 } 16294 // Regardless of writeSettings we need to ensure that this restriction 16295 // state propagation is persisted 16296 mSettings.writeAllUsersPackageRestrictionsLPr(); 16297 } 16298 // can downgrade to reader here 16299 if (writeSettings) { 16300 mSettings.writeLPr(); 16301 } 16302 } 16303 return true; 16304 } 16305 16306 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16307 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16308 PackageRemovedInfo outInfo, boolean writeSettings, 16309 PackageParser.Package replacingPackage) { 16310 synchronized (mPackages) { 16311 if (outInfo != null) { 16312 outInfo.uid = ps.appId; 16313 } 16314 16315 if (outInfo != null && outInfo.removedChildPackages != null) { 16316 final int childCount = (ps.childPackageNames != null) 16317 ? ps.childPackageNames.size() : 0; 16318 for (int i = 0; i < childCount; i++) { 16319 String childPackageName = ps.childPackageNames.get(i); 16320 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16321 if (childPs == null) { 16322 return false; 16323 } 16324 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16325 childPackageName); 16326 if (childInfo != null) { 16327 childInfo.uid = childPs.appId; 16328 } 16329 } 16330 } 16331 } 16332 16333 // Delete package data from internal structures and also remove data if flag is set 16334 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16335 16336 // Delete the child packages data 16337 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16338 for (int i = 0; i < childCount; i++) { 16339 PackageSetting childPs; 16340 synchronized (mPackages) { 16341 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16342 } 16343 if (childPs != null) { 16344 PackageRemovedInfo childOutInfo = (outInfo != null 16345 && outInfo.removedChildPackages != null) 16346 ? outInfo.removedChildPackages.get(childPs.name) : null; 16347 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16348 && (replacingPackage != null 16349 && !replacingPackage.hasChildPackage(childPs.name)) 16350 ? flags & ~DELETE_KEEP_DATA : flags; 16351 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16352 deleteFlags, writeSettings); 16353 } 16354 } 16355 16356 // Delete application code and resources only for parent packages 16357 if (ps.parentPackageName == null) { 16358 if (deleteCodeAndResources && (outInfo != null)) { 16359 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16360 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16361 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16362 } 16363 } 16364 16365 return true; 16366 } 16367 16368 @Override 16369 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16370 int userId) { 16371 mContext.enforceCallingOrSelfPermission( 16372 android.Manifest.permission.DELETE_PACKAGES, null); 16373 synchronized (mPackages) { 16374 PackageSetting ps = mSettings.mPackages.get(packageName); 16375 if (ps == null) { 16376 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16377 return false; 16378 } 16379 if (!ps.getInstalled(userId)) { 16380 // Can't block uninstall for an app that is not installed or enabled. 16381 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16382 return false; 16383 } 16384 ps.setBlockUninstall(blockUninstall, userId); 16385 mSettings.writePackageRestrictionsLPr(userId); 16386 } 16387 return true; 16388 } 16389 16390 @Override 16391 public boolean getBlockUninstallForUser(String packageName, int userId) { 16392 synchronized (mPackages) { 16393 PackageSetting ps = mSettings.mPackages.get(packageName); 16394 if (ps == null) { 16395 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16396 return false; 16397 } 16398 return ps.getBlockUninstall(userId); 16399 } 16400 } 16401 16402 @Override 16403 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16404 int callingUid = Binder.getCallingUid(); 16405 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16406 throw new SecurityException( 16407 "setRequiredForSystemUser can only be run by the system or root"); 16408 } 16409 synchronized (mPackages) { 16410 PackageSetting ps = mSettings.mPackages.get(packageName); 16411 if (ps == null) { 16412 Log.w(TAG, "Package doesn't exist: " + packageName); 16413 return false; 16414 } 16415 if (systemUserApp) { 16416 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16417 } else { 16418 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16419 } 16420 mSettings.writeLPr(); 16421 } 16422 return true; 16423 } 16424 16425 /* 16426 * This method handles package deletion in general 16427 */ 16428 private boolean deletePackageLIF(String packageName, UserHandle user, 16429 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16430 PackageRemovedInfo outInfo, boolean writeSettings, 16431 PackageParser.Package replacingPackage) { 16432 if (packageName == null) { 16433 Slog.w(TAG, "Attempt to delete null packageName."); 16434 return false; 16435 } 16436 16437 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16438 16439 PackageSetting ps; 16440 16441 synchronized (mPackages) { 16442 ps = mSettings.mPackages.get(packageName); 16443 if (ps == null) { 16444 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16445 return false; 16446 } 16447 16448 if (ps.parentPackageName != null && (!isSystemApp(ps) 16449 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16450 if (DEBUG_REMOVE) { 16451 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16452 + ((user == null) ? UserHandle.USER_ALL : user)); 16453 } 16454 final int removedUserId = (user != null) ? user.getIdentifier() 16455 : UserHandle.USER_ALL; 16456 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16457 return false; 16458 } 16459 markPackageUninstalledForUserLPw(ps, user); 16460 scheduleWritePackageRestrictionsLocked(user); 16461 return true; 16462 } 16463 } 16464 16465 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16466 && user.getIdentifier() != UserHandle.USER_ALL)) { 16467 // The caller is asking that the package only be deleted for a single 16468 // user. To do this, we just mark its uninstalled state and delete 16469 // its data. If this is a system app, we only allow this to happen if 16470 // they have set the special DELETE_SYSTEM_APP which requests different 16471 // semantics than normal for uninstalling system apps. 16472 markPackageUninstalledForUserLPw(ps, user); 16473 16474 if (!isSystemApp(ps)) { 16475 // Do not uninstall the APK if an app should be cached 16476 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16477 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16478 // Other user still have this package installed, so all 16479 // we need to do is clear this user's data and save that 16480 // it is uninstalled. 16481 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16482 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16483 return false; 16484 } 16485 scheduleWritePackageRestrictionsLocked(user); 16486 return true; 16487 } else { 16488 // We need to set it back to 'installed' so the uninstall 16489 // broadcasts will be sent correctly. 16490 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16491 ps.setInstalled(true, user.getIdentifier()); 16492 } 16493 } else { 16494 // This is a system app, so we assume that the 16495 // other users still have this package installed, so all 16496 // we need to do is clear this user's data and save that 16497 // it is uninstalled. 16498 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16499 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16500 return false; 16501 } 16502 scheduleWritePackageRestrictionsLocked(user); 16503 return true; 16504 } 16505 } 16506 16507 // If we are deleting a composite package for all users, keep track 16508 // of result for each child. 16509 if (ps.childPackageNames != null && outInfo != null) { 16510 synchronized (mPackages) { 16511 final int childCount = ps.childPackageNames.size(); 16512 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16513 for (int i = 0; i < childCount; i++) { 16514 String childPackageName = ps.childPackageNames.get(i); 16515 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16516 childInfo.removedPackage = childPackageName; 16517 outInfo.removedChildPackages.put(childPackageName, childInfo); 16518 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16519 if (childPs != null) { 16520 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16521 } 16522 } 16523 } 16524 } 16525 16526 boolean ret = false; 16527 if (isSystemApp(ps)) { 16528 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16529 // When an updated system application is deleted we delete the existing resources 16530 // as well and fall back to existing code in system partition 16531 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16532 } else { 16533 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16534 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16535 outInfo, writeSettings, replacingPackage); 16536 } 16537 16538 // Take a note whether we deleted the package for all users 16539 if (outInfo != null) { 16540 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16541 if (outInfo.removedChildPackages != null) { 16542 synchronized (mPackages) { 16543 final int childCount = outInfo.removedChildPackages.size(); 16544 for (int i = 0; i < childCount; i++) { 16545 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16546 if (childInfo != null) { 16547 childInfo.removedForAllUsers = mPackages.get( 16548 childInfo.removedPackage) == null; 16549 } 16550 } 16551 } 16552 } 16553 // If we uninstalled an update to a system app there may be some 16554 // child packages that appeared as they are declared in the system 16555 // app but were not declared in the update. 16556 if (isSystemApp(ps)) { 16557 synchronized (mPackages) { 16558 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16559 final int childCount = (updatedPs.childPackageNames != null) 16560 ? updatedPs.childPackageNames.size() : 0; 16561 for (int i = 0; i < childCount; i++) { 16562 String childPackageName = updatedPs.childPackageNames.get(i); 16563 if (outInfo.removedChildPackages == null 16564 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16565 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16566 if (childPs == null) { 16567 continue; 16568 } 16569 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16570 installRes.name = childPackageName; 16571 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16572 installRes.pkg = mPackages.get(childPackageName); 16573 installRes.uid = childPs.pkg.applicationInfo.uid; 16574 if (outInfo.appearedChildPackages == null) { 16575 outInfo.appearedChildPackages = new ArrayMap<>(); 16576 } 16577 outInfo.appearedChildPackages.put(childPackageName, installRes); 16578 } 16579 } 16580 } 16581 } 16582 } 16583 16584 return ret; 16585 } 16586 16587 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16588 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16589 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16590 for (int nextUserId : userIds) { 16591 if (DEBUG_REMOVE) { 16592 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16593 } 16594 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16595 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16596 false /*hidden*/, false /*suspended*/, null, null, null, 16597 false /*blockUninstall*/, 16598 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16599 } 16600 } 16601 16602 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16603 PackageRemovedInfo outInfo) { 16604 final PackageParser.Package pkg; 16605 synchronized (mPackages) { 16606 pkg = mPackages.get(ps.name); 16607 } 16608 16609 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16610 : new int[] {userId}; 16611 for (int nextUserId : userIds) { 16612 if (DEBUG_REMOVE) { 16613 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16614 + nextUserId); 16615 } 16616 16617 destroyAppDataLIF(pkg, userId, 16618 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16619 destroyAppProfilesLIF(pkg, userId); 16620 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16621 schedulePackageCleaning(ps.name, nextUserId, false); 16622 synchronized (mPackages) { 16623 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16624 scheduleWritePackageRestrictionsLocked(nextUserId); 16625 } 16626 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16627 } 16628 } 16629 16630 if (outInfo != null) { 16631 outInfo.removedPackage = ps.name; 16632 outInfo.removedAppId = ps.appId; 16633 outInfo.removedUsers = userIds; 16634 } 16635 16636 return true; 16637 } 16638 16639 private final class ClearStorageConnection implements ServiceConnection { 16640 IMediaContainerService mContainerService; 16641 16642 @Override 16643 public void onServiceConnected(ComponentName name, IBinder service) { 16644 synchronized (this) { 16645 mContainerService = IMediaContainerService.Stub 16646 .asInterface(Binder.allowBlocking(service)); 16647 notifyAll(); 16648 } 16649 } 16650 16651 @Override 16652 public void onServiceDisconnected(ComponentName name) { 16653 } 16654 } 16655 16656 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16657 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16658 16659 final boolean mounted; 16660 if (Environment.isExternalStorageEmulated()) { 16661 mounted = true; 16662 } else { 16663 final String status = Environment.getExternalStorageState(); 16664 16665 mounted = status.equals(Environment.MEDIA_MOUNTED) 16666 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16667 } 16668 16669 if (!mounted) { 16670 return; 16671 } 16672 16673 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16674 int[] users; 16675 if (userId == UserHandle.USER_ALL) { 16676 users = sUserManager.getUserIds(); 16677 } else { 16678 users = new int[] { userId }; 16679 } 16680 final ClearStorageConnection conn = new ClearStorageConnection(); 16681 if (mContext.bindServiceAsUser( 16682 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16683 try { 16684 for (int curUser : users) { 16685 long timeout = SystemClock.uptimeMillis() + 5000; 16686 synchronized (conn) { 16687 long now; 16688 while (conn.mContainerService == null && 16689 (now = SystemClock.uptimeMillis()) < timeout) { 16690 try { 16691 conn.wait(timeout - now); 16692 } catch (InterruptedException e) { 16693 } 16694 } 16695 } 16696 if (conn.mContainerService == null) { 16697 return; 16698 } 16699 16700 final UserEnvironment userEnv = new UserEnvironment(curUser); 16701 clearDirectory(conn.mContainerService, 16702 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16703 if (allData) { 16704 clearDirectory(conn.mContainerService, 16705 userEnv.buildExternalStorageAppDataDirs(packageName)); 16706 clearDirectory(conn.mContainerService, 16707 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16708 } 16709 } 16710 } finally { 16711 mContext.unbindService(conn); 16712 } 16713 } 16714 } 16715 16716 @Override 16717 public void clearApplicationProfileData(String packageName) { 16718 enforceSystemOrRoot("Only the system can clear all profile data"); 16719 16720 final PackageParser.Package pkg; 16721 synchronized (mPackages) { 16722 pkg = mPackages.get(packageName); 16723 } 16724 16725 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16726 synchronized (mInstallLock) { 16727 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16728 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16729 true /* removeBaseMarker */); 16730 } 16731 } 16732 } 16733 16734 @Override 16735 public void clearApplicationUserData(final String packageName, 16736 final IPackageDataObserver observer, final int userId) { 16737 mContext.enforceCallingOrSelfPermission( 16738 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16739 16740 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16741 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16742 16743 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16744 throw new SecurityException("Cannot clear data for a protected package: " 16745 + packageName); 16746 } 16747 // Queue up an async operation since the package deletion may take a little while. 16748 mHandler.post(new Runnable() { 16749 public void run() { 16750 mHandler.removeCallbacks(this); 16751 final boolean succeeded; 16752 try (PackageFreezer freezer = freezePackage(packageName, 16753 "clearApplicationUserData")) { 16754 synchronized (mInstallLock) { 16755 succeeded = clearApplicationUserDataLIF(packageName, userId); 16756 } 16757 clearExternalStorageDataSync(packageName, userId, true); 16758 } 16759 if (succeeded) { 16760 // invoke DeviceStorageMonitor's update method to clear any notifications 16761 DeviceStorageMonitorInternal dsm = LocalServices 16762 .getService(DeviceStorageMonitorInternal.class); 16763 if (dsm != null) { 16764 dsm.checkMemory(); 16765 } 16766 } 16767 if(observer != null) { 16768 try { 16769 observer.onRemoveCompleted(packageName, succeeded); 16770 } catch (RemoteException e) { 16771 Log.i(TAG, "Observer no longer exists."); 16772 } 16773 } //end if observer 16774 } //end run 16775 }); 16776 } 16777 16778 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16779 if (packageName == null) { 16780 Slog.w(TAG, "Attempt to delete null packageName."); 16781 return false; 16782 } 16783 16784 // Try finding details about the requested package 16785 PackageParser.Package pkg; 16786 synchronized (mPackages) { 16787 pkg = mPackages.get(packageName); 16788 if (pkg == null) { 16789 final PackageSetting ps = mSettings.mPackages.get(packageName); 16790 if (ps != null) { 16791 pkg = ps.pkg; 16792 } 16793 } 16794 16795 if (pkg == null) { 16796 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16797 return false; 16798 } 16799 16800 PackageSetting ps = (PackageSetting) pkg.mExtras; 16801 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16802 } 16803 16804 clearAppDataLIF(pkg, userId, 16805 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16806 16807 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16808 removeKeystoreDataIfNeeded(userId, appId); 16809 16810 UserManagerInternal umInternal = getUserManagerInternal(); 16811 final int flags; 16812 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16813 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16814 } else if (umInternal.isUserRunning(userId)) { 16815 flags = StorageManager.FLAG_STORAGE_DE; 16816 } else { 16817 flags = 0; 16818 } 16819 prepareAppDataContentsLIF(pkg, userId, flags); 16820 16821 return true; 16822 } 16823 16824 /** 16825 * Reverts user permission state changes (permissions and flags) in 16826 * all packages for a given user. 16827 * 16828 * @param userId The device user for which to do a reset. 16829 */ 16830 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16831 final int packageCount = mPackages.size(); 16832 for (int i = 0; i < packageCount; i++) { 16833 PackageParser.Package pkg = mPackages.valueAt(i); 16834 PackageSetting ps = (PackageSetting) pkg.mExtras; 16835 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16836 } 16837 } 16838 16839 private void resetNetworkPolicies(int userId) { 16840 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16841 } 16842 16843 /** 16844 * Reverts user permission state changes (permissions and flags). 16845 * 16846 * @param ps The package for which to reset. 16847 * @param userId The device user for which to do a reset. 16848 */ 16849 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16850 final PackageSetting ps, final int userId) { 16851 if (ps.pkg == null) { 16852 return; 16853 } 16854 16855 // These are flags that can change base on user actions. 16856 final int userSettableMask = FLAG_PERMISSION_USER_SET 16857 | FLAG_PERMISSION_USER_FIXED 16858 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16859 | FLAG_PERMISSION_REVIEW_REQUIRED; 16860 16861 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16862 | FLAG_PERMISSION_POLICY_FIXED; 16863 16864 boolean writeInstallPermissions = false; 16865 boolean writeRuntimePermissions = false; 16866 16867 final int permissionCount = ps.pkg.requestedPermissions.size(); 16868 for (int i = 0; i < permissionCount; i++) { 16869 String permission = ps.pkg.requestedPermissions.get(i); 16870 16871 BasePermission bp = mSettings.mPermissions.get(permission); 16872 if (bp == null) { 16873 continue; 16874 } 16875 16876 // If shared user we just reset the state to which only this app contributed. 16877 if (ps.sharedUser != null) { 16878 boolean used = false; 16879 final int packageCount = ps.sharedUser.packages.size(); 16880 for (int j = 0; j < packageCount; j++) { 16881 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16882 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16883 && pkg.pkg.requestedPermissions.contains(permission)) { 16884 used = true; 16885 break; 16886 } 16887 } 16888 if (used) { 16889 continue; 16890 } 16891 } 16892 16893 PermissionsState permissionsState = ps.getPermissionsState(); 16894 16895 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16896 16897 // Always clear the user settable flags. 16898 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16899 bp.name) != null; 16900 // If permission review is enabled and this is a legacy app, mark the 16901 // permission as requiring a review as this is the initial state. 16902 int flags = 0; 16903 if (mPermissionReviewRequired 16904 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16905 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16906 } 16907 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16908 if (hasInstallState) { 16909 writeInstallPermissions = true; 16910 } else { 16911 writeRuntimePermissions = true; 16912 } 16913 } 16914 16915 // Below is only runtime permission handling. 16916 if (!bp.isRuntime()) { 16917 continue; 16918 } 16919 16920 // Never clobber system or policy. 16921 if ((oldFlags & policyOrSystemFlags) != 0) { 16922 continue; 16923 } 16924 16925 // If this permission was granted by default, make sure it is. 16926 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16927 if (permissionsState.grantRuntimePermission(bp, userId) 16928 != PERMISSION_OPERATION_FAILURE) { 16929 writeRuntimePermissions = true; 16930 } 16931 // If permission review is enabled the permissions for a legacy apps 16932 // are represented as constantly granted runtime ones, so don't revoke. 16933 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16934 // Otherwise, reset the permission. 16935 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16936 switch (revokeResult) { 16937 case PERMISSION_OPERATION_SUCCESS: 16938 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16939 writeRuntimePermissions = true; 16940 final int appId = ps.appId; 16941 mHandler.post(new Runnable() { 16942 @Override 16943 public void run() { 16944 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16945 } 16946 }); 16947 } break; 16948 } 16949 } 16950 } 16951 16952 // Synchronously write as we are taking permissions away. 16953 if (writeRuntimePermissions) { 16954 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16955 } 16956 16957 // Synchronously write as we are taking permissions away. 16958 if (writeInstallPermissions) { 16959 mSettings.writeLPr(); 16960 } 16961 } 16962 16963 /** 16964 * Remove entries from the keystore daemon. Will only remove it if the 16965 * {@code appId} is valid. 16966 */ 16967 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16968 if (appId < 0) { 16969 return; 16970 } 16971 16972 final KeyStore keyStore = KeyStore.getInstance(); 16973 if (keyStore != null) { 16974 if (userId == UserHandle.USER_ALL) { 16975 for (final int individual : sUserManager.getUserIds()) { 16976 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16977 } 16978 } else { 16979 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16980 } 16981 } else { 16982 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16983 } 16984 } 16985 16986 @Override 16987 public void deleteApplicationCacheFiles(final String packageName, 16988 final IPackageDataObserver observer) { 16989 final int userId = UserHandle.getCallingUserId(); 16990 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16991 } 16992 16993 @Override 16994 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16995 final IPackageDataObserver observer) { 16996 mContext.enforceCallingOrSelfPermission( 16997 android.Manifest.permission.DELETE_CACHE_FILES, null); 16998 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16999 /* requireFullPermission= */ true, /* checkShell= */ false, 17000 "delete application cache files"); 17001 17002 final PackageParser.Package pkg; 17003 synchronized (mPackages) { 17004 pkg = mPackages.get(packageName); 17005 } 17006 17007 // Queue up an async operation since the package deletion may take a little while. 17008 mHandler.post(new Runnable() { 17009 public void run() { 17010 synchronized (mInstallLock) { 17011 final int flags = StorageManager.FLAG_STORAGE_DE 17012 | StorageManager.FLAG_STORAGE_CE; 17013 // We're only clearing cache files, so we don't care if the 17014 // app is unfrozen and still able to run 17015 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17016 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17017 } 17018 clearExternalStorageDataSync(packageName, userId, false); 17019 if (observer != null) { 17020 try { 17021 observer.onRemoveCompleted(packageName, true); 17022 } catch (RemoteException e) { 17023 Log.i(TAG, "Observer no longer exists."); 17024 } 17025 } 17026 } 17027 }); 17028 } 17029 17030 @Override 17031 public void getPackageSizeInfo(final String packageName, int userHandle, 17032 final IPackageStatsObserver observer) { 17033 mContext.enforceCallingOrSelfPermission( 17034 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17035 if (packageName == null) { 17036 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17037 } 17038 17039 PackageStats stats = new PackageStats(packageName, userHandle); 17040 17041 /* 17042 * Queue up an async operation since the package measurement may take a 17043 * little while. 17044 */ 17045 Message msg = mHandler.obtainMessage(INIT_COPY); 17046 msg.obj = new MeasureParams(stats, observer); 17047 mHandler.sendMessage(msg); 17048 } 17049 17050 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17051 final PackageSetting ps; 17052 synchronized (mPackages) { 17053 ps = mSettings.mPackages.get(packageName); 17054 if (ps == null) { 17055 Slog.w(TAG, "Failed to find settings for " + packageName); 17056 return false; 17057 } 17058 } 17059 try { 17060 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17061 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17062 ps.getCeDataInode(userId), ps.codePathString, stats); 17063 } catch (InstallerException e) { 17064 Slog.w(TAG, String.valueOf(e)); 17065 return false; 17066 } 17067 17068 // For now, ignore code size of packages on system partition 17069 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17070 stats.codeSize = 0; 17071 } 17072 17073 return true; 17074 } 17075 17076 private int getUidTargetSdkVersionLockedLPr(int uid) { 17077 Object obj = mSettings.getUserIdLPr(uid); 17078 if (obj instanceof SharedUserSetting) { 17079 final SharedUserSetting sus = (SharedUserSetting) obj; 17080 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17081 final Iterator<PackageSetting> it = sus.packages.iterator(); 17082 while (it.hasNext()) { 17083 final PackageSetting ps = it.next(); 17084 if (ps.pkg != null) { 17085 int v = ps.pkg.applicationInfo.targetSdkVersion; 17086 if (v < vers) vers = v; 17087 } 17088 } 17089 return vers; 17090 } else if (obj instanceof PackageSetting) { 17091 final PackageSetting ps = (PackageSetting) obj; 17092 if (ps.pkg != null) { 17093 return ps.pkg.applicationInfo.targetSdkVersion; 17094 } 17095 } 17096 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17097 } 17098 17099 @Override 17100 public void addPreferredActivity(IntentFilter filter, int match, 17101 ComponentName[] set, ComponentName activity, int userId) { 17102 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17103 "Adding preferred"); 17104 } 17105 17106 private void addPreferredActivityInternal(IntentFilter filter, int match, 17107 ComponentName[] set, ComponentName activity, boolean always, int userId, 17108 String opname) { 17109 // writer 17110 int callingUid = Binder.getCallingUid(); 17111 enforceCrossUserPermission(callingUid, userId, 17112 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17113 if (filter.countActions() == 0) { 17114 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17115 return; 17116 } 17117 synchronized (mPackages) { 17118 if (mContext.checkCallingOrSelfPermission( 17119 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17120 != PackageManager.PERMISSION_GRANTED) { 17121 if (getUidTargetSdkVersionLockedLPr(callingUid) 17122 < Build.VERSION_CODES.FROYO) { 17123 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17124 + callingUid); 17125 return; 17126 } 17127 mContext.enforceCallingOrSelfPermission( 17128 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17129 } 17130 17131 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17132 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17133 + userId + ":"); 17134 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17135 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17136 scheduleWritePackageRestrictionsLocked(userId); 17137 postPreferredActivityChangedBroadcast(userId); 17138 } 17139 } 17140 17141 private void postPreferredActivityChangedBroadcast(int userId) { 17142 mHandler.post(() -> { 17143 final IActivityManager am = ActivityManager.getService(); 17144 if (am == null) { 17145 return; 17146 } 17147 17148 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17149 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17150 try { 17151 am.broadcastIntent(null, intent, null, null, 17152 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17153 null, false, false, userId); 17154 } catch (RemoteException e) { 17155 } 17156 }); 17157 } 17158 17159 @Override 17160 public void replacePreferredActivity(IntentFilter filter, int match, 17161 ComponentName[] set, ComponentName activity, int userId) { 17162 if (filter.countActions() != 1) { 17163 throw new IllegalArgumentException( 17164 "replacePreferredActivity expects filter to have only 1 action."); 17165 } 17166 if (filter.countDataAuthorities() != 0 17167 || filter.countDataPaths() != 0 17168 || filter.countDataSchemes() > 1 17169 || filter.countDataTypes() != 0) { 17170 throw new IllegalArgumentException( 17171 "replacePreferredActivity expects filter to have no data authorities, " + 17172 "paths, or types; and at most one scheme."); 17173 } 17174 17175 final int callingUid = Binder.getCallingUid(); 17176 enforceCrossUserPermission(callingUid, userId, 17177 true /* requireFullPermission */, false /* checkShell */, 17178 "replace preferred activity"); 17179 synchronized (mPackages) { 17180 if (mContext.checkCallingOrSelfPermission( 17181 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17182 != PackageManager.PERMISSION_GRANTED) { 17183 if (getUidTargetSdkVersionLockedLPr(callingUid) 17184 < Build.VERSION_CODES.FROYO) { 17185 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17186 + Binder.getCallingUid()); 17187 return; 17188 } 17189 mContext.enforceCallingOrSelfPermission( 17190 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17191 } 17192 17193 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17194 if (pir != null) { 17195 // Get all of the existing entries that exactly match this filter. 17196 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17197 if (existing != null && existing.size() == 1) { 17198 PreferredActivity cur = existing.get(0); 17199 if (DEBUG_PREFERRED) { 17200 Slog.i(TAG, "Checking replace of preferred:"); 17201 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17202 if (!cur.mPref.mAlways) { 17203 Slog.i(TAG, " -- CUR; not mAlways!"); 17204 } else { 17205 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17206 Slog.i(TAG, " -- CUR: mSet=" 17207 + Arrays.toString(cur.mPref.mSetComponents)); 17208 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17209 Slog.i(TAG, " -- NEW: mMatch=" 17210 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17211 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17212 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17213 } 17214 } 17215 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17216 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17217 && cur.mPref.sameSet(set)) { 17218 // Setting the preferred activity to what it happens to be already 17219 if (DEBUG_PREFERRED) { 17220 Slog.i(TAG, "Replacing with same preferred activity " 17221 + cur.mPref.mShortComponent + " for user " 17222 + userId + ":"); 17223 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17224 } 17225 return; 17226 } 17227 } 17228 17229 if (existing != null) { 17230 if (DEBUG_PREFERRED) { 17231 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17232 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17233 } 17234 for (int i = 0; i < existing.size(); i++) { 17235 PreferredActivity pa = existing.get(i); 17236 if (DEBUG_PREFERRED) { 17237 Slog.i(TAG, "Removing existing preferred activity " 17238 + pa.mPref.mComponent + ":"); 17239 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17240 } 17241 pir.removeFilter(pa); 17242 } 17243 } 17244 } 17245 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17246 "Replacing preferred"); 17247 } 17248 } 17249 17250 @Override 17251 public void clearPackagePreferredActivities(String packageName) { 17252 final int uid = Binder.getCallingUid(); 17253 // writer 17254 synchronized (mPackages) { 17255 PackageParser.Package pkg = mPackages.get(packageName); 17256 if (pkg == null || pkg.applicationInfo.uid != uid) { 17257 if (mContext.checkCallingOrSelfPermission( 17258 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17259 != PackageManager.PERMISSION_GRANTED) { 17260 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17261 < Build.VERSION_CODES.FROYO) { 17262 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17263 + Binder.getCallingUid()); 17264 return; 17265 } 17266 mContext.enforceCallingOrSelfPermission( 17267 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17268 } 17269 } 17270 17271 int user = UserHandle.getCallingUserId(); 17272 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17273 scheduleWritePackageRestrictionsLocked(user); 17274 } 17275 } 17276 } 17277 17278 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17279 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17280 ArrayList<PreferredActivity> removed = null; 17281 boolean changed = false; 17282 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17283 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17284 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17285 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17286 continue; 17287 } 17288 Iterator<PreferredActivity> it = pir.filterIterator(); 17289 while (it.hasNext()) { 17290 PreferredActivity pa = it.next(); 17291 // Mark entry for removal only if it matches the package name 17292 // and the entry is of type "always". 17293 if (packageName == null || 17294 (pa.mPref.mComponent.getPackageName().equals(packageName) 17295 && pa.mPref.mAlways)) { 17296 if (removed == null) { 17297 removed = new ArrayList<PreferredActivity>(); 17298 } 17299 removed.add(pa); 17300 } 17301 } 17302 if (removed != null) { 17303 for (int j=0; j<removed.size(); j++) { 17304 PreferredActivity pa = removed.get(j); 17305 pir.removeFilter(pa); 17306 } 17307 changed = true; 17308 } 17309 } 17310 if (changed) { 17311 postPreferredActivityChangedBroadcast(userId); 17312 } 17313 return changed; 17314 } 17315 17316 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17317 private void clearIntentFilterVerificationsLPw(int userId) { 17318 final int packageCount = mPackages.size(); 17319 for (int i = 0; i < packageCount; i++) { 17320 PackageParser.Package pkg = mPackages.valueAt(i); 17321 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17322 } 17323 } 17324 17325 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17326 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17327 if (userId == UserHandle.USER_ALL) { 17328 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17329 sUserManager.getUserIds())) { 17330 for (int oneUserId : sUserManager.getUserIds()) { 17331 scheduleWritePackageRestrictionsLocked(oneUserId); 17332 } 17333 } 17334 } else { 17335 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17336 scheduleWritePackageRestrictionsLocked(userId); 17337 } 17338 } 17339 } 17340 17341 void clearDefaultBrowserIfNeeded(String packageName) { 17342 for (int oneUserId : sUserManager.getUserIds()) { 17343 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17344 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17345 if (packageName.equals(defaultBrowserPackageName)) { 17346 setDefaultBrowserPackageName(null, oneUserId); 17347 } 17348 } 17349 } 17350 17351 @Override 17352 public void resetApplicationPreferences(int userId) { 17353 mContext.enforceCallingOrSelfPermission( 17354 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17355 final long identity = Binder.clearCallingIdentity(); 17356 // writer 17357 try { 17358 synchronized (mPackages) { 17359 clearPackagePreferredActivitiesLPw(null, userId); 17360 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17361 // TODO: We have to reset the default SMS and Phone. This requires 17362 // significant refactoring to keep all default apps in the package 17363 // manager (cleaner but more work) or have the services provide 17364 // callbacks to the package manager to request a default app reset. 17365 applyFactoryDefaultBrowserLPw(userId); 17366 clearIntentFilterVerificationsLPw(userId); 17367 primeDomainVerificationsLPw(userId); 17368 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17369 scheduleWritePackageRestrictionsLocked(userId); 17370 } 17371 resetNetworkPolicies(userId); 17372 } finally { 17373 Binder.restoreCallingIdentity(identity); 17374 } 17375 } 17376 17377 @Override 17378 public int getPreferredActivities(List<IntentFilter> outFilters, 17379 List<ComponentName> outActivities, String packageName) { 17380 17381 int num = 0; 17382 final int userId = UserHandle.getCallingUserId(); 17383 // reader 17384 synchronized (mPackages) { 17385 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17386 if (pir != null) { 17387 final Iterator<PreferredActivity> it = pir.filterIterator(); 17388 while (it.hasNext()) { 17389 final PreferredActivity pa = it.next(); 17390 if (packageName == null 17391 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17392 && pa.mPref.mAlways)) { 17393 if (outFilters != null) { 17394 outFilters.add(new IntentFilter(pa)); 17395 } 17396 if (outActivities != null) { 17397 outActivities.add(pa.mPref.mComponent); 17398 } 17399 } 17400 } 17401 } 17402 } 17403 17404 return num; 17405 } 17406 17407 @Override 17408 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17409 int userId) { 17410 int callingUid = Binder.getCallingUid(); 17411 if (callingUid != Process.SYSTEM_UID) { 17412 throw new SecurityException( 17413 "addPersistentPreferredActivity can only be run by the system"); 17414 } 17415 if (filter.countActions() == 0) { 17416 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17417 return; 17418 } 17419 synchronized (mPackages) { 17420 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17421 ":"); 17422 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17423 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17424 new PersistentPreferredActivity(filter, activity)); 17425 scheduleWritePackageRestrictionsLocked(userId); 17426 postPreferredActivityChangedBroadcast(userId); 17427 } 17428 } 17429 17430 @Override 17431 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17432 int callingUid = Binder.getCallingUid(); 17433 if (callingUid != Process.SYSTEM_UID) { 17434 throw new SecurityException( 17435 "clearPackagePersistentPreferredActivities can only be run by the system"); 17436 } 17437 ArrayList<PersistentPreferredActivity> removed = null; 17438 boolean changed = false; 17439 synchronized (mPackages) { 17440 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17441 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17442 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17443 .valueAt(i); 17444 if (userId != thisUserId) { 17445 continue; 17446 } 17447 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17448 while (it.hasNext()) { 17449 PersistentPreferredActivity ppa = it.next(); 17450 // Mark entry for removal only if it matches the package name. 17451 if (ppa.mComponent.getPackageName().equals(packageName)) { 17452 if (removed == null) { 17453 removed = new ArrayList<PersistentPreferredActivity>(); 17454 } 17455 removed.add(ppa); 17456 } 17457 } 17458 if (removed != null) { 17459 for (int j=0; j<removed.size(); j++) { 17460 PersistentPreferredActivity ppa = removed.get(j); 17461 ppir.removeFilter(ppa); 17462 } 17463 changed = true; 17464 } 17465 } 17466 17467 if (changed) { 17468 scheduleWritePackageRestrictionsLocked(userId); 17469 postPreferredActivityChangedBroadcast(userId); 17470 } 17471 } 17472 } 17473 17474 /** 17475 * Common machinery for picking apart a restored XML blob and passing 17476 * it to a caller-supplied functor to be applied to the running system. 17477 */ 17478 private void restoreFromXml(XmlPullParser parser, int userId, 17479 String expectedStartTag, BlobXmlRestorer functor) 17480 throws IOException, XmlPullParserException { 17481 int type; 17482 while ((type = parser.next()) != XmlPullParser.START_TAG 17483 && type != XmlPullParser.END_DOCUMENT) { 17484 } 17485 if (type != XmlPullParser.START_TAG) { 17486 // oops didn't find a start tag?! 17487 if (DEBUG_BACKUP) { 17488 Slog.e(TAG, "Didn't find start tag during restore"); 17489 } 17490 return; 17491 } 17492Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17493 // this is supposed to be TAG_PREFERRED_BACKUP 17494 if (!expectedStartTag.equals(parser.getName())) { 17495 if (DEBUG_BACKUP) { 17496 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17497 } 17498 return; 17499 } 17500 17501 // skip interfering stuff, then we're aligned with the backing implementation 17502 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17503Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17504 functor.apply(parser, userId); 17505 } 17506 17507 private interface BlobXmlRestorer { 17508 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17509 } 17510 17511 /** 17512 * Non-Binder method, support for the backup/restore mechanism: write the 17513 * full set of preferred activities in its canonical XML format. Returns the 17514 * XML output as a byte array, or null if there is none. 17515 */ 17516 @Override 17517 public byte[] getPreferredActivityBackup(int userId) { 17518 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17519 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17520 } 17521 17522 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17523 try { 17524 final XmlSerializer serializer = new FastXmlSerializer(); 17525 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17526 serializer.startDocument(null, true); 17527 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17528 17529 synchronized (mPackages) { 17530 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17531 } 17532 17533 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17534 serializer.endDocument(); 17535 serializer.flush(); 17536 } catch (Exception e) { 17537 if (DEBUG_BACKUP) { 17538 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17539 } 17540 return null; 17541 } 17542 17543 return dataStream.toByteArray(); 17544 } 17545 17546 @Override 17547 public void restorePreferredActivities(byte[] backup, int userId) { 17548 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17549 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17550 } 17551 17552 try { 17553 final XmlPullParser parser = Xml.newPullParser(); 17554 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17555 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17556 new BlobXmlRestorer() { 17557 @Override 17558 public void apply(XmlPullParser parser, int userId) 17559 throws XmlPullParserException, IOException { 17560 synchronized (mPackages) { 17561 mSettings.readPreferredActivitiesLPw(parser, userId); 17562 } 17563 } 17564 } ); 17565 } catch (Exception e) { 17566 if (DEBUG_BACKUP) { 17567 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17568 } 17569 } 17570 } 17571 17572 /** 17573 * Non-Binder method, support for the backup/restore mechanism: write the 17574 * default browser (etc) settings in its canonical XML format. Returns the default 17575 * browser XML representation as a byte array, or null if there is none. 17576 */ 17577 @Override 17578 public byte[] getDefaultAppsBackup(int userId) { 17579 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17580 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17581 } 17582 17583 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17584 try { 17585 final XmlSerializer serializer = new FastXmlSerializer(); 17586 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17587 serializer.startDocument(null, true); 17588 serializer.startTag(null, TAG_DEFAULT_APPS); 17589 17590 synchronized (mPackages) { 17591 mSettings.writeDefaultAppsLPr(serializer, userId); 17592 } 17593 17594 serializer.endTag(null, TAG_DEFAULT_APPS); 17595 serializer.endDocument(); 17596 serializer.flush(); 17597 } catch (Exception e) { 17598 if (DEBUG_BACKUP) { 17599 Slog.e(TAG, "Unable to write default apps for backup", e); 17600 } 17601 return null; 17602 } 17603 17604 return dataStream.toByteArray(); 17605 } 17606 17607 @Override 17608 public void restoreDefaultApps(byte[] backup, int userId) { 17609 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17610 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17611 } 17612 17613 try { 17614 final XmlPullParser parser = Xml.newPullParser(); 17615 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17616 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17617 new BlobXmlRestorer() { 17618 @Override 17619 public void apply(XmlPullParser parser, int userId) 17620 throws XmlPullParserException, IOException { 17621 synchronized (mPackages) { 17622 mSettings.readDefaultAppsLPw(parser, userId); 17623 } 17624 } 17625 } ); 17626 } catch (Exception e) { 17627 if (DEBUG_BACKUP) { 17628 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17629 } 17630 } 17631 } 17632 17633 @Override 17634 public byte[] getIntentFilterVerificationBackup(int userId) { 17635 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17636 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17637 } 17638 17639 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17640 try { 17641 final XmlSerializer serializer = new FastXmlSerializer(); 17642 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17643 serializer.startDocument(null, true); 17644 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17645 17646 synchronized (mPackages) { 17647 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17648 } 17649 17650 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17651 serializer.endDocument(); 17652 serializer.flush(); 17653 } catch (Exception e) { 17654 if (DEBUG_BACKUP) { 17655 Slog.e(TAG, "Unable to write default apps for backup", e); 17656 } 17657 return null; 17658 } 17659 17660 return dataStream.toByteArray(); 17661 } 17662 17663 @Override 17664 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17665 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17666 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17667 } 17668 17669 try { 17670 final XmlPullParser parser = Xml.newPullParser(); 17671 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17672 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17673 new BlobXmlRestorer() { 17674 @Override 17675 public void apply(XmlPullParser parser, int userId) 17676 throws XmlPullParserException, IOException { 17677 synchronized (mPackages) { 17678 mSettings.readAllDomainVerificationsLPr(parser, userId); 17679 mSettings.writeLPr(); 17680 } 17681 } 17682 } ); 17683 } catch (Exception e) { 17684 if (DEBUG_BACKUP) { 17685 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17686 } 17687 } 17688 } 17689 17690 @Override 17691 public byte[] getPermissionGrantBackup(int userId) { 17692 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17693 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17694 } 17695 17696 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17697 try { 17698 final XmlSerializer serializer = new FastXmlSerializer(); 17699 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17700 serializer.startDocument(null, true); 17701 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17702 17703 synchronized (mPackages) { 17704 serializeRuntimePermissionGrantsLPr(serializer, userId); 17705 } 17706 17707 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17708 serializer.endDocument(); 17709 serializer.flush(); 17710 } catch (Exception e) { 17711 if (DEBUG_BACKUP) { 17712 Slog.e(TAG, "Unable to write default apps for backup", e); 17713 } 17714 return null; 17715 } 17716 17717 return dataStream.toByteArray(); 17718 } 17719 17720 @Override 17721 public void restorePermissionGrants(byte[] backup, int userId) { 17722 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17723 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17724 } 17725 17726 try { 17727 final XmlPullParser parser = Xml.newPullParser(); 17728 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17729 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17730 new BlobXmlRestorer() { 17731 @Override 17732 public void apply(XmlPullParser parser, int userId) 17733 throws XmlPullParserException, IOException { 17734 synchronized (mPackages) { 17735 processRestoredPermissionGrantsLPr(parser, userId); 17736 } 17737 } 17738 } ); 17739 } catch (Exception e) { 17740 if (DEBUG_BACKUP) { 17741 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17742 } 17743 } 17744 } 17745 17746 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17747 throws IOException { 17748 serializer.startTag(null, TAG_ALL_GRANTS); 17749 17750 final int N = mSettings.mPackages.size(); 17751 for (int i = 0; i < N; i++) { 17752 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17753 boolean pkgGrantsKnown = false; 17754 17755 PermissionsState packagePerms = ps.getPermissionsState(); 17756 17757 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17758 final int grantFlags = state.getFlags(); 17759 // only look at grants that are not system/policy fixed 17760 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17761 final boolean isGranted = state.isGranted(); 17762 // And only back up the user-twiddled state bits 17763 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17764 final String packageName = mSettings.mPackages.keyAt(i); 17765 if (!pkgGrantsKnown) { 17766 serializer.startTag(null, TAG_GRANT); 17767 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17768 pkgGrantsKnown = true; 17769 } 17770 17771 final boolean userSet = 17772 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17773 final boolean userFixed = 17774 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17775 final boolean revoke = 17776 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17777 17778 serializer.startTag(null, TAG_PERMISSION); 17779 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17780 if (isGranted) { 17781 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17782 } 17783 if (userSet) { 17784 serializer.attribute(null, ATTR_USER_SET, "true"); 17785 } 17786 if (userFixed) { 17787 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17788 } 17789 if (revoke) { 17790 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17791 } 17792 serializer.endTag(null, TAG_PERMISSION); 17793 } 17794 } 17795 } 17796 17797 if (pkgGrantsKnown) { 17798 serializer.endTag(null, TAG_GRANT); 17799 } 17800 } 17801 17802 serializer.endTag(null, TAG_ALL_GRANTS); 17803 } 17804 17805 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17806 throws XmlPullParserException, IOException { 17807 String pkgName = null; 17808 int outerDepth = parser.getDepth(); 17809 int type; 17810 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17811 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17812 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17813 continue; 17814 } 17815 17816 final String tagName = parser.getName(); 17817 if (tagName.equals(TAG_GRANT)) { 17818 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17819 if (DEBUG_BACKUP) { 17820 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17821 } 17822 } else if (tagName.equals(TAG_PERMISSION)) { 17823 17824 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17825 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17826 17827 int newFlagSet = 0; 17828 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17829 newFlagSet |= FLAG_PERMISSION_USER_SET; 17830 } 17831 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17832 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17833 } 17834 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17835 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17836 } 17837 if (DEBUG_BACKUP) { 17838 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17839 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17840 } 17841 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17842 if (ps != null) { 17843 // Already installed so we apply the grant immediately 17844 if (DEBUG_BACKUP) { 17845 Slog.v(TAG, " + already installed; applying"); 17846 } 17847 PermissionsState perms = ps.getPermissionsState(); 17848 BasePermission bp = mSettings.mPermissions.get(permName); 17849 if (bp != null) { 17850 if (isGranted) { 17851 perms.grantRuntimePermission(bp, userId); 17852 } 17853 if (newFlagSet != 0) { 17854 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17855 } 17856 } 17857 } else { 17858 // Need to wait for post-restore install to apply the grant 17859 if (DEBUG_BACKUP) { 17860 Slog.v(TAG, " - not yet installed; saving for later"); 17861 } 17862 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17863 isGranted, newFlagSet, userId); 17864 } 17865 } else { 17866 PackageManagerService.reportSettingsProblem(Log.WARN, 17867 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17868 XmlUtils.skipCurrentTag(parser); 17869 } 17870 } 17871 17872 scheduleWriteSettingsLocked(); 17873 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17874 } 17875 17876 @Override 17877 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17878 int sourceUserId, int targetUserId, int flags) { 17879 mContext.enforceCallingOrSelfPermission( 17880 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17881 int callingUid = Binder.getCallingUid(); 17882 enforceOwnerRights(ownerPackage, callingUid); 17883 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17884 if (intentFilter.countActions() == 0) { 17885 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17886 return; 17887 } 17888 synchronized (mPackages) { 17889 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17890 ownerPackage, targetUserId, flags); 17891 CrossProfileIntentResolver resolver = 17892 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17893 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17894 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17895 if (existing != null) { 17896 int size = existing.size(); 17897 for (int i = 0; i < size; i++) { 17898 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17899 return; 17900 } 17901 } 17902 } 17903 resolver.addFilter(newFilter); 17904 scheduleWritePackageRestrictionsLocked(sourceUserId); 17905 } 17906 } 17907 17908 @Override 17909 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17910 mContext.enforceCallingOrSelfPermission( 17911 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17912 int callingUid = Binder.getCallingUid(); 17913 enforceOwnerRights(ownerPackage, callingUid); 17914 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17915 synchronized (mPackages) { 17916 CrossProfileIntentResolver resolver = 17917 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17918 ArraySet<CrossProfileIntentFilter> set = 17919 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17920 for (CrossProfileIntentFilter filter : set) { 17921 if (filter.getOwnerPackage().equals(ownerPackage)) { 17922 resolver.removeFilter(filter); 17923 } 17924 } 17925 scheduleWritePackageRestrictionsLocked(sourceUserId); 17926 } 17927 } 17928 17929 // Enforcing that callingUid is owning pkg on userId 17930 private void enforceOwnerRights(String pkg, int callingUid) { 17931 // The system owns everything. 17932 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17933 return; 17934 } 17935 int callingUserId = UserHandle.getUserId(callingUid); 17936 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17937 if (pi == null) { 17938 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17939 + callingUserId); 17940 } 17941 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17942 throw new SecurityException("Calling uid " + callingUid 17943 + " does not own package " + pkg); 17944 } 17945 } 17946 17947 @Override 17948 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17949 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17950 } 17951 17952 private Intent getHomeIntent() { 17953 Intent intent = new Intent(Intent.ACTION_MAIN); 17954 intent.addCategory(Intent.CATEGORY_HOME); 17955 intent.addCategory(Intent.CATEGORY_DEFAULT); 17956 return intent; 17957 } 17958 17959 private IntentFilter getHomeFilter() { 17960 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17961 filter.addCategory(Intent.CATEGORY_HOME); 17962 filter.addCategory(Intent.CATEGORY_DEFAULT); 17963 return filter; 17964 } 17965 17966 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17967 int userId) { 17968 Intent intent = getHomeIntent(); 17969 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17970 PackageManager.GET_META_DATA, userId); 17971 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17972 true, false, false, userId); 17973 17974 allHomeCandidates.clear(); 17975 if (list != null) { 17976 for (ResolveInfo ri : list) { 17977 allHomeCandidates.add(ri); 17978 } 17979 } 17980 return (preferred == null || preferred.activityInfo == null) 17981 ? null 17982 : new ComponentName(preferred.activityInfo.packageName, 17983 preferred.activityInfo.name); 17984 } 17985 17986 @Override 17987 public void setHomeActivity(ComponentName comp, int userId) { 17988 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17989 getHomeActivitiesAsUser(homeActivities, userId); 17990 17991 boolean found = false; 17992 17993 final int size = homeActivities.size(); 17994 final ComponentName[] set = new ComponentName[size]; 17995 for (int i = 0; i < size; i++) { 17996 final ResolveInfo candidate = homeActivities.get(i); 17997 final ActivityInfo info = candidate.activityInfo; 17998 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17999 set[i] = activityName; 18000 if (!found && activityName.equals(comp)) { 18001 found = true; 18002 } 18003 } 18004 if (!found) { 18005 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18006 + userId); 18007 } 18008 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18009 set, comp, userId); 18010 } 18011 18012 private @Nullable String getSetupWizardPackageName() { 18013 final Intent intent = new Intent(Intent.ACTION_MAIN); 18014 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18015 18016 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18017 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18018 | MATCH_DISABLED_COMPONENTS, 18019 UserHandle.myUserId()); 18020 if (matches.size() == 1) { 18021 return matches.get(0).getComponentInfo().packageName; 18022 } else { 18023 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18024 + ": matches=" + matches); 18025 return null; 18026 } 18027 } 18028 18029 private @Nullable String getStorageManagerPackageName() { 18030 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18031 18032 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18033 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18034 | MATCH_DISABLED_COMPONENTS, 18035 UserHandle.myUserId()); 18036 if (matches.size() == 1) { 18037 return matches.get(0).getComponentInfo().packageName; 18038 } else { 18039 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18040 + matches.size() + ": matches=" + matches); 18041 return null; 18042 } 18043 } 18044 18045 @Override 18046 public void setApplicationEnabledSetting(String appPackageName, 18047 int newState, int flags, int userId, String callingPackage) { 18048 if (!sUserManager.exists(userId)) return; 18049 if (callingPackage == null) { 18050 callingPackage = Integer.toString(Binder.getCallingUid()); 18051 } 18052 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18053 } 18054 18055 @Override 18056 public void setComponentEnabledSetting(ComponentName componentName, 18057 int newState, int flags, int userId) { 18058 if (!sUserManager.exists(userId)) return; 18059 setEnabledSetting(componentName.getPackageName(), 18060 componentName.getClassName(), newState, flags, userId, null); 18061 } 18062 18063 private void setEnabledSetting(final String packageName, String className, int newState, 18064 final int flags, int userId, String callingPackage) { 18065 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18066 || newState == COMPONENT_ENABLED_STATE_ENABLED 18067 || newState == COMPONENT_ENABLED_STATE_DISABLED 18068 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18069 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18070 throw new IllegalArgumentException("Invalid new component state: " 18071 + newState); 18072 } 18073 PackageSetting pkgSetting; 18074 final int uid = Binder.getCallingUid(); 18075 final int permission; 18076 if (uid == Process.SYSTEM_UID) { 18077 permission = PackageManager.PERMISSION_GRANTED; 18078 } else { 18079 permission = mContext.checkCallingOrSelfPermission( 18080 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18081 } 18082 enforceCrossUserPermission(uid, userId, 18083 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18084 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18085 boolean sendNow = false; 18086 boolean isApp = (className == null); 18087 String componentName = isApp ? packageName : className; 18088 int packageUid = -1; 18089 ArrayList<String> components; 18090 18091 // writer 18092 synchronized (mPackages) { 18093 pkgSetting = mSettings.mPackages.get(packageName); 18094 if (pkgSetting == null) { 18095 if (className == null) { 18096 throw new IllegalArgumentException("Unknown package: " + packageName); 18097 } 18098 throw new IllegalArgumentException( 18099 "Unknown component: " + packageName + "/" + className); 18100 } 18101 } 18102 18103 // Limit who can change which apps 18104 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18105 // Don't allow apps that don't have permission to modify other apps 18106 if (!allowedByPermission) { 18107 throw new SecurityException( 18108 "Permission Denial: attempt to change component state from pid=" 18109 + Binder.getCallingPid() 18110 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18111 } 18112 // Don't allow changing protected packages. 18113 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18114 throw new SecurityException("Cannot disable a protected package: " + packageName); 18115 } 18116 } 18117 18118 synchronized (mPackages) { 18119 if (uid == Process.SHELL_UID 18120 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18121 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18122 // unless it is a test package. 18123 int oldState = pkgSetting.getEnabled(userId); 18124 if (className == null 18125 && 18126 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18127 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18128 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18129 && 18130 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18131 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18132 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18133 // ok 18134 } else { 18135 throw new SecurityException( 18136 "Shell cannot change component state for " + packageName + "/" 18137 + className + " to " + newState); 18138 } 18139 } 18140 if (className == null) { 18141 // We're dealing with an application/package level state change 18142 if (pkgSetting.getEnabled(userId) == newState) { 18143 // Nothing to do 18144 return; 18145 } 18146 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18147 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18148 // Don't care about who enables an app. 18149 callingPackage = null; 18150 } 18151 pkgSetting.setEnabled(newState, userId, callingPackage); 18152 // pkgSetting.pkg.mSetEnabled = newState; 18153 } else { 18154 // We're dealing with a component level state change 18155 // First, verify that this is a valid class name. 18156 PackageParser.Package pkg = pkgSetting.pkg; 18157 if (pkg == null || !pkg.hasComponentClassName(className)) { 18158 if (pkg != null && 18159 pkg.applicationInfo.targetSdkVersion >= 18160 Build.VERSION_CODES.JELLY_BEAN) { 18161 throw new IllegalArgumentException("Component class " + className 18162 + " does not exist in " + packageName); 18163 } else { 18164 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18165 + className + " does not exist in " + packageName); 18166 } 18167 } 18168 switch (newState) { 18169 case COMPONENT_ENABLED_STATE_ENABLED: 18170 if (!pkgSetting.enableComponentLPw(className, userId)) { 18171 return; 18172 } 18173 break; 18174 case COMPONENT_ENABLED_STATE_DISABLED: 18175 if (!pkgSetting.disableComponentLPw(className, userId)) { 18176 return; 18177 } 18178 break; 18179 case COMPONENT_ENABLED_STATE_DEFAULT: 18180 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18181 return; 18182 } 18183 break; 18184 default: 18185 Slog.e(TAG, "Invalid new component state: " + newState); 18186 return; 18187 } 18188 } 18189 scheduleWritePackageRestrictionsLocked(userId); 18190 components = mPendingBroadcasts.get(userId, packageName); 18191 final boolean newPackage = components == null; 18192 if (newPackage) { 18193 components = new ArrayList<String>(); 18194 } 18195 if (!components.contains(componentName)) { 18196 components.add(componentName); 18197 } 18198 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18199 sendNow = true; 18200 // Purge entry from pending broadcast list if another one exists already 18201 // since we are sending one right away. 18202 mPendingBroadcasts.remove(userId, packageName); 18203 } else { 18204 if (newPackage) { 18205 mPendingBroadcasts.put(userId, packageName, components); 18206 } 18207 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18208 // Schedule a message 18209 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18210 } 18211 } 18212 } 18213 18214 long callingId = Binder.clearCallingIdentity(); 18215 try { 18216 if (sendNow) { 18217 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18218 sendPackageChangedBroadcast(packageName, 18219 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18220 } 18221 } finally { 18222 Binder.restoreCallingIdentity(callingId); 18223 } 18224 } 18225 18226 @Override 18227 public void flushPackageRestrictionsAsUser(int userId) { 18228 if (!sUserManager.exists(userId)) { 18229 return; 18230 } 18231 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18232 false /* checkShell */, "flushPackageRestrictions"); 18233 synchronized (mPackages) { 18234 mSettings.writePackageRestrictionsLPr(userId); 18235 mDirtyUsers.remove(userId); 18236 if (mDirtyUsers.isEmpty()) { 18237 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18238 } 18239 } 18240 } 18241 18242 private void sendPackageChangedBroadcast(String packageName, 18243 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18244 if (DEBUG_INSTALL) 18245 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18246 + componentNames); 18247 Bundle extras = new Bundle(4); 18248 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18249 String nameList[] = new String[componentNames.size()]; 18250 componentNames.toArray(nameList); 18251 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18252 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18253 extras.putInt(Intent.EXTRA_UID, packageUid); 18254 // If this is not reporting a change of the overall package, then only send it 18255 // to registered receivers. We don't want to launch a swath of apps for every 18256 // little component state change. 18257 final int flags = !componentNames.contains(packageName) 18258 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18259 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18260 new int[] {UserHandle.getUserId(packageUid)}); 18261 } 18262 18263 @Override 18264 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18265 if (!sUserManager.exists(userId)) return; 18266 final int uid = Binder.getCallingUid(); 18267 final int permission = mContext.checkCallingOrSelfPermission( 18268 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18269 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18270 enforceCrossUserPermission(uid, userId, 18271 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18272 // writer 18273 synchronized (mPackages) { 18274 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18275 allowedByPermission, uid, userId)) { 18276 scheduleWritePackageRestrictionsLocked(userId); 18277 } 18278 } 18279 } 18280 18281 @Override 18282 public String getInstallerPackageName(String packageName) { 18283 // reader 18284 synchronized (mPackages) { 18285 return mSettings.getInstallerPackageNameLPr(packageName); 18286 } 18287 } 18288 18289 public boolean isOrphaned(String packageName) { 18290 // reader 18291 synchronized (mPackages) { 18292 return mSettings.isOrphaned(packageName); 18293 } 18294 } 18295 18296 @Override 18297 public int getApplicationEnabledSetting(String packageName, int userId) { 18298 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18299 int uid = Binder.getCallingUid(); 18300 enforceCrossUserPermission(uid, userId, 18301 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18302 // reader 18303 synchronized (mPackages) { 18304 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18305 } 18306 } 18307 18308 @Override 18309 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18310 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18311 int uid = Binder.getCallingUid(); 18312 enforceCrossUserPermission(uid, userId, 18313 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18314 // reader 18315 synchronized (mPackages) { 18316 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18317 } 18318 } 18319 18320 @Override 18321 public void enterSafeMode() { 18322 enforceSystemOrRoot("Only the system can request entering safe mode"); 18323 18324 if (!mSystemReady) { 18325 mSafeMode = true; 18326 } 18327 } 18328 18329 @Override 18330 public void systemReady() { 18331 mSystemReady = true; 18332 18333 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18334 // disabled after already being started. 18335 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18336 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18337 18338 // Read the compatibilty setting when the system is ready. 18339 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18340 mContext.getContentResolver(), 18341 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18342 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18343 if (DEBUG_SETTINGS) { 18344 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18345 } 18346 18347 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18348 18349 synchronized (mPackages) { 18350 // Verify that all of the preferred activity components actually 18351 // exist. It is possible for applications to be updated and at 18352 // that point remove a previously declared activity component that 18353 // had been set as a preferred activity. We try to clean this up 18354 // the next time we encounter that preferred activity, but it is 18355 // possible for the user flow to never be able to return to that 18356 // situation so here we do a sanity check to make sure we haven't 18357 // left any junk around. 18358 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18359 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18360 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18361 removed.clear(); 18362 for (PreferredActivity pa : pir.filterSet()) { 18363 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18364 removed.add(pa); 18365 } 18366 } 18367 if (removed.size() > 0) { 18368 for (int r=0; r<removed.size(); r++) { 18369 PreferredActivity pa = removed.get(r); 18370 Slog.w(TAG, "Removing dangling preferred activity: " 18371 + pa.mPref.mComponent); 18372 pir.removeFilter(pa); 18373 } 18374 mSettings.writePackageRestrictionsLPr( 18375 mSettings.mPreferredActivities.keyAt(i)); 18376 } 18377 } 18378 18379 for (int userId : UserManagerService.getInstance().getUserIds()) { 18380 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18381 grantPermissionsUserIds = ArrayUtils.appendInt( 18382 grantPermissionsUserIds, userId); 18383 } 18384 } 18385 } 18386 sUserManager.systemReady(); 18387 18388 // If we upgraded grant all default permissions before kicking off. 18389 for (int userId : grantPermissionsUserIds) { 18390 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18391 } 18392 18393 // If we did not grant default permissions, we preload from this the 18394 // default permission exceptions lazily to ensure we don't hit the 18395 // disk on a new user creation. 18396 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18397 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18398 } 18399 18400 // Kick off any messages waiting for system ready 18401 if (mPostSystemReadyMessages != null) { 18402 for (Message msg : mPostSystemReadyMessages) { 18403 msg.sendToTarget(); 18404 } 18405 mPostSystemReadyMessages = null; 18406 } 18407 18408 // Watch for external volumes that come and go over time 18409 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18410 storage.registerListener(mStorageListener); 18411 18412 mInstallerService.systemReady(); 18413 mPackageDexOptimizer.systemReady(); 18414 18415 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18416 StorageManagerInternal.class); 18417 StorageManagerInternal.addExternalStoragePolicy( 18418 new StorageManagerInternal.ExternalStorageMountPolicy() { 18419 @Override 18420 public int getMountMode(int uid, String packageName) { 18421 if (Process.isIsolated(uid)) { 18422 return Zygote.MOUNT_EXTERNAL_NONE; 18423 } 18424 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18425 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18426 } 18427 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18428 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18429 } 18430 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18431 return Zygote.MOUNT_EXTERNAL_READ; 18432 } 18433 return Zygote.MOUNT_EXTERNAL_WRITE; 18434 } 18435 18436 @Override 18437 public boolean hasExternalStorage(int uid, String packageName) { 18438 return true; 18439 } 18440 }); 18441 18442 // Now that we're mostly running, clean up stale users and apps 18443 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18444 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18445 } 18446 18447 @Override 18448 public boolean isSafeMode() { 18449 return mSafeMode; 18450 } 18451 18452 @Override 18453 public boolean hasSystemUidErrors() { 18454 return mHasSystemUidErrors; 18455 } 18456 18457 static String arrayToString(int[] array) { 18458 StringBuffer buf = new StringBuffer(128); 18459 buf.append('['); 18460 if (array != null) { 18461 for (int i=0; i<array.length; i++) { 18462 if (i > 0) buf.append(", "); 18463 buf.append(array[i]); 18464 } 18465 } 18466 buf.append(']'); 18467 return buf.toString(); 18468 } 18469 18470 static class DumpState { 18471 public static final int DUMP_LIBS = 1 << 0; 18472 public static final int DUMP_FEATURES = 1 << 1; 18473 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18474 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18475 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18476 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18477 public static final int DUMP_PERMISSIONS = 1 << 6; 18478 public static final int DUMP_PACKAGES = 1 << 7; 18479 public static final int DUMP_SHARED_USERS = 1 << 8; 18480 public static final int DUMP_MESSAGES = 1 << 9; 18481 public static final int DUMP_PROVIDERS = 1 << 10; 18482 public static final int DUMP_VERIFIERS = 1 << 11; 18483 public static final int DUMP_PREFERRED = 1 << 12; 18484 public static final int DUMP_PREFERRED_XML = 1 << 13; 18485 public static final int DUMP_KEYSETS = 1 << 14; 18486 public static final int DUMP_VERSION = 1 << 15; 18487 public static final int DUMP_INSTALLS = 1 << 16; 18488 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18489 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18490 public static final int DUMP_FROZEN = 1 << 19; 18491 public static final int DUMP_DEXOPT = 1 << 20; 18492 public static final int DUMP_COMPILER_STATS = 1 << 21; 18493 18494 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18495 18496 private int mTypes; 18497 18498 private int mOptions; 18499 18500 private boolean mTitlePrinted; 18501 18502 private SharedUserSetting mSharedUser; 18503 18504 public boolean isDumping(int type) { 18505 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18506 return true; 18507 } 18508 18509 return (mTypes & type) != 0; 18510 } 18511 18512 public void setDump(int type) { 18513 mTypes |= type; 18514 } 18515 18516 public boolean isOptionEnabled(int option) { 18517 return (mOptions & option) != 0; 18518 } 18519 18520 public void setOptionEnabled(int option) { 18521 mOptions |= option; 18522 } 18523 18524 public boolean onTitlePrinted() { 18525 final boolean printed = mTitlePrinted; 18526 mTitlePrinted = true; 18527 return printed; 18528 } 18529 18530 public boolean getTitlePrinted() { 18531 return mTitlePrinted; 18532 } 18533 18534 public void setTitlePrinted(boolean enabled) { 18535 mTitlePrinted = enabled; 18536 } 18537 18538 public SharedUserSetting getSharedUser() { 18539 return mSharedUser; 18540 } 18541 18542 public void setSharedUser(SharedUserSetting user) { 18543 mSharedUser = user; 18544 } 18545 } 18546 18547 @Override 18548 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18549 FileDescriptor err, String[] args, ShellCallback callback, 18550 ResultReceiver resultReceiver) { 18551 (new PackageManagerShellCommand(this)).exec( 18552 this, in, out, err, args, callback, resultReceiver); 18553 } 18554 18555 @Override 18556 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18557 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18558 != PackageManager.PERMISSION_GRANTED) { 18559 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18560 + Binder.getCallingPid() 18561 + ", uid=" + Binder.getCallingUid() 18562 + " without permission " 18563 + android.Manifest.permission.DUMP); 18564 return; 18565 } 18566 18567 DumpState dumpState = new DumpState(); 18568 boolean fullPreferred = false; 18569 boolean checkin = false; 18570 18571 String packageName = null; 18572 ArraySet<String> permissionNames = null; 18573 18574 int opti = 0; 18575 while (opti < args.length) { 18576 String opt = args[opti]; 18577 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18578 break; 18579 } 18580 opti++; 18581 18582 if ("-a".equals(opt)) { 18583 // Right now we only know how to print all. 18584 } else if ("-h".equals(opt)) { 18585 pw.println("Package manager dump options:"); 18586 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18587 pw.println(" --checkin: dump for a checkin"); 18588 pw.println(" -f: print details of intent filters"); 18589 pw.println(" -h: print this help"); 18590 pw.println(" cmd may be one of:"); 18591 pw.println(" l[ibraries]: list known shared libraries"); 18592 pw.println(" f[eatures]: list device features"); 18593 pw.println(" k[eysets]: print known keysets"); 18594 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18595 pw.println(" perm[issions]: dump permissions"); 18596 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18597 pw.println(" pref[erred]: print preferred package settings"); 18598 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18599 pw.println(" prov[iders]: dump content providers"); 18600 pw.println(" p[ackages]: dump installed packages"); 18601 pw.println(" s[hared-users]: dump shared user IDs"); 18602 pw.println(" m[essages]: print collected runtime messages"); 18603 pw.println(" v[erifiers]: print package verifier info"); 18604 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18605 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18606 pw.println(" version: print database version info"); 18607 pw.println(" write: write current settings now"); 18608 pw.println(" installs: details about install sessions"); 18609 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18610 pw.println(" dexopt: dump dexopt state"); 18611 pw.println(" compiler-stats: dump compiler statistics"); 18612 pw.println(" <package.name>: info about given package"); 18613 return; 18614 } else if ("--checkin".equals(opt)) { 18615 checkin = true; 18616 } else if ("-f".equals(opt)) { 18617 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18618 } else { 18619 pw.println("Unknown argument: " + opt + "; use -h for help"); 18620 } 18621 } 18622 18623 // Is the caller requesting to dump a particular piece of data? 18624 if (opti < args.length) { 18625 String cmd = args[opti]; 18626 opti++; 18627 // Is this a package name? 18628 if ("android".equals(cmd) || cmd.contains(".")) { 18629 packageName = cmd; 18630 // When dumping a single package, we always dump all of its 18631 // filter information since the amount of data will be reasonable. 18632 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18633 } else if ("check-permission".equals(cmd)) { 18634 if (opti >= args.length) { 18635 pw.println("Error: check-permission missing permission argument"); 18636 return; 18637 } 18638 String perm = args[opti]; 18639 opti++; 18640 if (opti >= args.length) { 18641 pw.println("Error: check-permission missing package argument"); 18642 return; 18643 } 18644 String pkg = args[opti]; 18645 opti++; 18646 int user = UserHandle.getUserId(Binder.getCallingUid()); 18647 if (opti < args.length) { 18648 try { 18649 user = Integer.parseInt(args[opti]); 18650 } catch (NumberFormatException e) { 18651 pw.println("Error: check-permission user argument is not a number: " 18652 + args[opti]); 18653 return; 18654 } 18655 } 18656 pw.println(checkPermission(perm, pkg, user)); 18657 return; 18658 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18659 dumpState.setDump(DumpState.DUMP_LIBS); 18660 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18661 dumpState.setDump(DumpState.DUMP_FEATURES); 18662 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18663 if (opti >= args.length) { 18664 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18665 | DumpState.DUMP_SERVICE_RESOLVERS 18666 | DumpState.DUMP_RECEIVER_RESOLVERS 18667 | DumpState.DUMP_CONTENT_RESOLVERS); 18668 } else { 18669 while (opti < args.length) { 18670 String name = args[opti]; 18671 if ("a".equals(name) || "activity".equals(name)) { 18672 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18673 } else if ("s".equals(name) || "service".equals(name)) { 18674 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18675 } else if ("r".equals(name) || "receiver".equals(name)) { 18676 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18677 } else if ("c".equals(name) || "content".equals(name)) { 18678 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18679 } else { 18680 pw.println("Error: unknown resolver table type: " + name); 18681 return; 18682 } 18683 opti++; 18684 } 18685 } 18686 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18687 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18688 } else if ("permission".equals(cmd)) { 18689 if (opti >= args.length) { 18690 pw.println("Error: permission requires permission name"); 18691 return; 18692 } 18693 permissionNames = new ArraySet<>(); 18694 while (opti < args.length) { 18695 permissionNames.add(args[opti]); 18696 opti++; 18697 } 18698 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18699 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18700 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18701 dumpState.setDump(DumpState.DUMP_PREFERRED); 18702 } else if ("preferred-xml".equals(cmd)) { 18703 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18704 if (opti < args.length && "--full".equals(args[opti])) { 18705 fullPreferred = true; 18706 opti++; 18707 } 18708 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18709 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18710 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18711 dumpState.setDump(DumpState.DUMP_PACKAGES); 18712 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18713 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18714 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18715 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18716 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18717 dumpState.setDump(DumpState.DUMP_MESSAGES); 18718 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18719 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18720 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18721 || "intent-filter-verifiers".equals(cmd)) { 18722 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18723 } else if ("version".equals(cmd)) { 18724 dumpState.setDump(DumpState.DUMP_VERSION); 18725 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18726 dumpState.setDump(DumpState.DUMP_KEYSETS); 18727 } else if ("installs".equals(cmd)) { 18728 dumpState.setDump(DumpState.DUMP_INSTALLS); 18729 } else if ("frozen".equals(cmd)) { 18730 dumpState.setDump(DumpState.DUMP_FROZEN); 18731 } else if ("dexopt".equals(cmd)) { 18732 dumpState.setDump(DumpState.DUMP_DEXOPT); 18733 } else if ("compiler-stats".equals(cmd)) { 18734 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18735 } else if ("write".equals(cmd)) { 18736 synchronized (mPackages) { 18737 mSettings.writeLPr(); 18738 pw.println("Settings written."); 18739 return; 18740 } 18741 } 18742 } 18743 18744 if (checkin) { 18745 pw.println("vers,1"); 18746 } 18747 18748 // reader 18749 synchronized (mPackages) { 18750 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18751 if (!checkin) { 18752 if (dumpState.onTitlePrinted()) 18753 pw.println(); 18754 pw.println("Database versions:"); 18755 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18756 } 18757 } 18758 18759 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18760 if (!checkin) { 18761 if (dumpState.onTitlePrinted()) 18762 pw.println(); 18763 pw.println("Verifiers:"); 18764 pw.print(" Required: "); 18765 pw.print(mRequiredVerifierPackage); 18766 pw.print(" (uid="); 18767 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18768 UserHandle.USER_SYSTEM)); 18769 pw.println(")"); 18770 } else if (mRequiredVerifierPackage != null) { 18771 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18772 pw.print(","); 18773 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18774 UserHandle.USER_SYSTEM)); 18775 } 18776 } 18777 18778 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18779 packageName == null) { 18780 if (mIntentFilterVerifierComponent != null) { 18781 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18782 if (!checkin) { 18783 if (dumpState.onTitlePrinted()) 18784 pw.println(); 18785 pw.println("Intent Filter Verifier:"); 18786 pw.print(" Using: "); 18787 pw.print(verifierPackageName); 18788 pw.print(" (uid="); 18789 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18790 UserHandle.USER_SYSTEM)); 18791 pw.println(")"); 18792 } else if (verifierPackageName != null) { 18793 pw.print("ifv,"); pw.print(verifierPackageName); 18794 pw.print(","); 18795 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18796 UserHandle.USER_SYSTEM)); 18797 } 18798 } else { 18799 pw.println(); 18800 pw.println("No Intent Filter Verifier available!"); 18801 } 18802 } 18803 18804 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18805 boolean printedHeader = false; 18806 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18807 while (it.hasNext()) { 18808 String name = it.next(); 18809 SharedLibraryEntry ent = mSharedLibraries.get(name); 18810 if (!checkin) { 18811 if (!printedHeader) { 18812 if (dumpState.onTitlePrinted()) 18813 pw.println(); 18814 pw.println("Libraries:"); 18815 printedHeader = true; 18816 } 18817 pw.print(" "); 18818 } else { 18819 pw.print("lib,"); 18820 } 18821 pw.print(name); 18822 if (!checkin) { 18823 pw.print(" -> "); 18824 } 18825 if (ent.path != null) { 18826 if (!checkin) { 18827 pw.print("(jar) "); 18828 pw.print(ent.path); 18829 } else { 18830 pw.print(",jar,"); 18831 pw.print(ent.path); 18832 } 18833 } else { 18834 if (!checkin) { 18835 pw.print("(apk) "); 18836 pw.print(ent.apk); 18837 } else { 18838 pw.print(",apk,"); 18839 pw.print(ent.apk); 18840 } 18841 } 18842 pw.println(); 18843 } 18844 } 18845 18846 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18847 if (dumpState.onTitlePrinted()) 18848 pw.println(); 18849 if (!checkin) { 18850 pw.println("Features:"); 18851 } 18852 18853 for (FeatureInfo feat : mAvailableFeatures.values()) { 18854 if (checkin) { 18855 pw.print("feat,"); 18856 pw.print(feat.name); 18857 pw.print(","); 18858 pw.println(feat.version); 18859 } else { 18860 pw.print(" "); 18861 pw.print(feat.name); 18862 if (feat.version > 0) { 18863 pw.print(" version="); 18864 pw.print(feat.version); 18865 } 18866 pw.println(); 18867 } 18868 } 18869 } 18870 18871 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18872 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18873 : "Activity Resolver Table:", " ", packageName, 18874 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18875 dumpState.setTitlePrinted(true); 18876 } 18877 } 18878 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18879 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18880 : "Receiver Resolver Table:", " ", packageName, 18881 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18882 dumpState.setTitlePrinted(true); 18883 } 18884 } 18885 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18886 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18887 : "Service Resolver Table:", " ", packageName, 18888 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18889 dumpState.setTitlePrinted(true); 18890 } 18891 } 18892 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18893 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18894 : "Provider Resolver Table:", " ", packageName, 18895 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18896 dumpState.setTitlePrinted(true); 18897 } 18898 } 18899 18900 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18901 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18902 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18903 int user = mSettings.mPreferredActivities.keyAt(i); 18904 if (pir.dump(pw, 18905 dumpState.getTitlePrinted() 18906 ? "\nPreferred Activities User " + user + ":" 18907 : "Preferred Activities User " + user + ":", " ", 18908 packageName, true, false)) { 18909 dumpState.setTitlePrinted(true); 18910 } 18911 } 18912 } 18913 18914 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18915 pw.flush(); 18916 FileOutputStream fout = new FileOutputStream(fd); 18917 BufferedOutputStream str = new BufferedOutputStream(fout); 18918 XmlSerializer serializer = new FastXmlSerializer(); 18919 try { 18920 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18921 serializer.startDocument(null, true); 18922 serializer.setFeature( 18923 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18924 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18925 serializer.endDocument(); 18926 serializer.flush(); 18927 } catch (IllegalArgumentException e) { 18928 pw.println("Failed writing: " + e); 18929 } catch (IllegalStateException e) { 18930 pw.println("Failed writing: " + e); 18931 } catch (IOException e) { 18932 pw.println("Failed writing: " + e); 18933 } 18934 } 18935 18936 if (!checkin 18937 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18938 && packageName == null) { 18939 pw.println(); 18940 int count = mSettings.mPackages.size(); 18941 if (count == 0) { 18942 pw.println("No applications!"); 18943 pw.println(); 18944 } else { 18945 final String prefix = " "; 18946 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18947 if (allPackageSettings.size() == 0) { 18948 pw.println("No domain preferred apps!"); 18949 pw.println(); 18950 } else { 18951 pw.println("App verification status:"); 18952 pw.println(); 18953 count = 0; 18954 for (PackageSetting ps : allPackageSettings) { 18955 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18956 if (ivi == null || ivi.getPackageName() == null) continue; 18957 pw.println(prefix + "Package: " + ivi.getPackageName()); 18958 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18959 pw.println(prefix + "Status: " + ivi.getStatusString()); 18960 pw.println(); 18961 count++; 18962 } 18963 if (count == 0) { 18964 pw.println(prefix + "No app verification established."); 18965 pw.println(); 18966 } 18967 for (int userId : sUserManager.getUserIds()) { 18968 pw.println("App linkages for user " + userId + ":"); 18969 pw.println(); 18970 count = 0; 18971 for (PackageSetting ps : allPackageSettings) { 18972 final long status = ps.getDomainVerificationStatusForUser(userId); 18973 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18974 continue; 18975 } 18976 pw.println(prefix + "Package: " + ps.name); 18977 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18978 String statusStr = IntentFilterVerificationInfo. 18979 getStatusStringFromValue(status); 18980 pw.println(prefix + "Status: " + statusStr); 18981 pw.println(); 18982 count++; 18983 } 18984 if (count == 0) { 18985 pw.println(prefix + "No configured app linkages."); 18986 pw.println(); 18987 } 18988 } 18989 } 18990 } 18991 } 18992 18993 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18994 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18995 if (packageName == null && permissionNames == null) { 18996 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18997 if (iperm == 0) { 18998 if (dumpState.onTitlePrinted()) 18999 pw.println(); 19000 pw.println("AppOp Permissions:"); 19001 } 19002 pw.print(" AppOp Permission "); 19003 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19004 pw.println(":"); 19005 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19006 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19007 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19008 } 19009 } 19010 } 19011 } 19012 19013 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19014 boolean printedSomething = false; 19015 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19016 if (packageName != null && !packageName.equals(p.info.packageName)) { 19017 continue; 19018 } 19019 if (!printedSomething) { 19020 if (dumpState.onTitlePrinted()) 19021 pw.println(); 19022 pw.println("Registered ContentProviders:"); 19023 printedSomething = true; 19024 } 19025 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19026 pw.print(" "); pw.println(p.toString()); 19027 } 19028 printedSomething = false; 19029 for (Map.Entry<String, PackageParser.Provider> entry : 19030 mProvidersByAuthority.entrySet()) { 19031 PackageParser.Provider p = entry.getValue(); 19032 if (packageName != null && !packageName.equals(p.info.packageName)) { 19033 continue; 19034 } 19035 if (!printedSomething) { 19036 if (dumpState.onTitlePrinted()) 19037 pw.println(); 19038 pw.println("ContentProvider Authorities:"); 19039 printedSomething = true; 19040 } 19041 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19042 pw.print(" "); pw.println(p.toString()); 19043 if (p.info != null && p.info.applicationInfo != null) { 19044 final String appInfo = p.info.applicationInfo.toString(); 19045 pw.print(" applicationInfo="); pw.println(appInfo); 19046 } 19047 } 19048 } 19049 19050 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19051 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19052 } 19053 19054 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19055 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19056 } 19057 19058 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19059 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19060 } 19061 19062 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19063 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19064 } 19065 19066 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19067 // XXX should handle packageName != null by dumping only install data that 19068 // the given package is involved with. 19069 if (dumpState.onTitlePrinted()) pw.println(); 19070 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19071 } 19072 19073 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19074 // XXX should handle packageName != null by dumping only install data that 19075 // the given package is involved with. 19076 if (dumpState.onTitlePrinted()) pw.println(); 19077 19078 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19079 ipw.println(); 19080 ipw.println("Frozen packages:"); 19081 ipw.increaseIndent(); 19082 if (mFrozenPackages.size() == 0) { 19083 ipw.println("(none)"); 19084 } else { 19085 for (int i = 0; i < mFrozenPackages.size(); i++) { 19086 ipw.println(mFrozenPackages.valueAt(i)); 19087 } 19088 } 19089 ipw.decreaseIndent(); 19090 } 19091 19092 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19093 if (dumpState.onTitlePrinted()) pw.println(); 19094 dumpDexoptStateLPr(pw, packageName); 19095 } 19096 19097 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19098 if (dumpState.onTitlePrinted()) pw.println(); 19099 dumpCompilerStatsLPr(pw, packageName); 19100 } 19101 19102 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19103 if (dumpState.onTitlePrinted()) pw.println(); 19104 mSettings.dumpReadMessagesLPr(pw, dumpState); 19105 19106 pw.println(); 19107 pw.println("Package warning messages:"); 19108 BufferedReader in = null; 19109 String line = null; 19110 try { 19111 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19112 while ((line = in.readLine()) != null) { 19113 if (line.contains("ignored: updated version")) continue; 19114 pw.println(line); 19115 } 19116 } catch (IOException ignored) { 19117 } finally { 19118 IoUtils.closeQuietly(in); 19119 } 19120 } 19121 19122 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19123 BufferedReader in = null; 19124 String line = null; 19125 try { 19126 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19127 while ((line = in.readLine()) != null) { 19128 if (line.contains("ignored: updated version")) continue; 19129 pw.print("msg,"); 19130 pw.println(line); 19131 } 19132 } catch (IOException ignored) { 19133 } finally { 19134 IoUtils.closeQuietly(in); 19135 } 19136 } 19137 } 19138 } 19139 19140 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19141 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19142 ipw.println(); 19143 ipw.println("Dexopt state:"); 19144 ipw.increaseIndent(); 19145 Collection<PackageParser.Package> packages = null; 19146 if (packageName != null) { 19147 PackageParser.Package targetPackage = mPackages.get(packageName); 19148 if (targetPackage != null) { 19149 packages = Collections.singletonList(targetPackage); 19150 } else { 19151 ipw.println("Unable to find package: " + packageName); 19152 return; 19153 } 19154 } else { 19155 packages = mPackages.values(); 19156 } 19157 19158 for (PackageParser.Package pkg : packages) { 19159 ipw.println("[" + pkg.packageName + "]"); 19160 ipw.increaseIndent(); 19161 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19162 ipw.decreaseIndent(); 19163 } 19164 } 19165 19166 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19167 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19168 ipw.println(); 19169 ipw.println("Compiler stats:"); 19170 ipw.increaseIndent(); 19171 Collection<PackageParser.Package> packages = null; 19172 if (packageName != null) { 19173 PackageParser.Package targetPackage = mPackages.get(packageName); 19174 if (targetPackage != null) { 19175 packages = Collections.singletonList(targetPackage); 19176 } else { 19177 ipw.println("Unable to find package: " + packageName); 19178 return; 19179 } 19180 } else { 19181 packages = mPackages.values(); 19182 } 19183 19184 for (PackageParser.Package pkg : packages) { 19185 ipw.println("[" + pkg.packageName + "]"); 19186 ipw.increaseIndent(); 19187 19188 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19189 if (stats == null) { 19190 ipw.println("(No recorded stats)"); 19191 } else { 19192 stats.dump(ipw); 19193 } 19194 ipw.decreaseIndent(); 19195 } 19196 } 19197 19198 private String dumpDomainString(String packageName) { 19199 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19200 .getList(); 19201 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19202 19203 ArraySet<String> result = new ArraySet<>(); 19204 if (iviList.size() > 0) { 19205 for (IntentFilterVerificationInfo ivi : iviList) { 19206 for (String host : ivi.getDomains()) { 19207 result.add(host); 19208 } 19209 } 19210 } 19211 if (filters != null && filters.size() > 0) { 19212 for (IntentFilter filter : filters) { 19213 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19214 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19215 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19216 result.addAll(filter.getHostsList()); 19217 } 19218 } 19219 } 19220 19221 StringBuilder sb = new StringBuilder(result.size() * 16); 19222 for (String domain : result) { 19223 if (sb.length() > 0) sb.append(" "); 19224 sb.append(domain); 19225 } 19226 return sb.toString(); 19227 } 19228 19229 // ------- apps on sdcard specific code ------- 19230 static final boolean DEBUG_SD_INSTALL = false; 19231 19232 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19233 19234 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19235 19236 private boolean mMediaMounted = false; 19237 19238 static String getEncryptKey() { 19239 try { 19240 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19241 SD_ENCRYPTION_KEYSTORE_NAME); 19242 if (sdEncKey == null) { 19243 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19244 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19245 if (sdEncKey == null) { 19246 Slog.e(TAG, "Failed to create encryption keys"); 19247 return null; 19248 } 19249 } 19250 return sdEncKey; 19251 } catch (NoSuchAlgorithmException nsae) { 19252 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19253 return null; 19254 } catch (IOException ioe) { 19255 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19256 return null; 19257 } 19258 } 19259 19260 /* 19261 * Update media status on PackageManager. 19262 */ 19263 @Override 19264 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19265 int callingUid = Binder.getCallingUid(); 19266 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19267 throw new SecurityException("Media status can only be updated by the system"); 19268 } 19269 // reader; this apparently protects mMediaMounted, but should probably 19270 // be a different lock in that case. 19271 synchronized (mPackages) { 19272 Log.i(TAG, "Updating external media status from " 19273 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19274 + (mediaStatus ? "mounted" : "unmounted")); 19275 if (DEBUG_SD_INSTALL) 19276 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19277 + ", mMediaMounted=" + mMediaMounted); 19278 if (mediaStatus == mMediaMounted) { 19279 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19280 : 0, -1); 19281 mHandler.sendMessage(msg); 19282 return; 19283 } 19284 mMediaMounted = mediaStatus; 19285 } 19286 // Queue up an async operation since the package installation may take a 19287 // little while. 19288 mHandler.post(new Runnable() { 19289 public void run() { 19290 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19291 } 19292 }); 19293 } 19294 19295 /** 19296 * Called by StorageManagerService when the initial ASECs to scan are available. 19297 * Should block until all the ASEC containers are finished being scanned. 19298 */ 19299 public void scanAvailableAsecs() { 19300 updateExternalMediaStatusInner(true, false, false); 19301 } 19302 19303 /* 19304 * Collect information of applications on external media, map them against 19305 * existing containers and update information based on current mount status. 19306 * Please note that we always have to report status if reportStatus has been 19307 * set to true especially when unloading packages. 19308 */ 19309 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19310 boolean externalStorage) { 19311 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19312 int[] uidArr = EmptyArray.INT; 19313 19314 final String[] list = PackageHelper.getSecureContainerList(); 19315 if (ArrayUtils.isEmpty(list)) { 19316 Log.i(TAG, "No secure containers found"); 19317 } else { 19318 // Process list of secure containers and categorize them 19319 // as active or stale based on their package internal state. 19320 19321 // reader 19322 synchronized (mPackages) { 19323 for (String cid : list) { 19324 // Leave stages untouched for now; installer service owns them 19325 if (PackageInstallerService.isStageName(cid)) continue; 19326 19327 if (DEBUG_SD_INSTALL) 19328 Log.i(TAG, "Processing container " + cid); 19329 String pkgName = getAsecPackageName(cid); 19330 if (pkgName == null) { 19331 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19332 continue; 19333 } 19334 if (DEBUG_SD_INSTALL) 19335 Log.i(TAG, "Looking for pkg : " + pkgName); 19336 19337 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19338 if (ps == null) { 19339 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19340 continue; 19341 } 19342 19343 /* 19344 * Skip packages that are not external if we're unmounting 19345 * external storage. 19346 */ 19347 if (externalStorage && !isMounted && !isExternal(ps)) { 19348 continue; 19349 } 19350 19351 final AsecInstallArgs args = new AsecInstallArgs(cid, 19352 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19353 // The package status is changed only if the code path 19354 // matches between settings and the container id. 19355 if (ps.codePathString != null 19356 && ps.codePathString.startsWith(args.getCodePath())) { 19357 if (DEBUG_SD_INSTALL) { 19358 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19359 + " at code path: " + ps.codePathString); 19360 } 19361 19362 // We do have a valid package installed on sdcard 19363 processCids.put(args, ps.codePathString); 19364 final int uid = ps.appId; 19365 if (uid != -1) { 19366 uidArr = ArrayUtils.appendInt(uidArr, uid); 19367 } 19368 } else { 19369 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19370 + ps.codePathString); 19371 } 19372 } 19373 } 19374 19375 Arrays.sort(uidArr); 19376 } 19377 19378 // Process packages with valid entries. 19379 if (isMounted) { 19380 if (DEBUG_SD_INSTALL) 19381 Log.i(TAG, "Loading packages"); 19382 loadMediaPackages(processCids, uidArr, externalStorage); 19383 startCleaningPackages(); 19384 mInstallerService.onSecureContainersAvailable(); 19385 } else { 19386 if (DEBUG_SD_INSTALL) 19387 Log.i(TAG, "Unloading packages"); 19388 unloadMediaPackages(processCids, uidArr, reportStatus); 19389 } 19390 } 19391 19392 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19393 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19394 final int size = infos.size(); 19395 final String[] packageNames = new String[size]; 19396 final int[] packageUids = new int[size]; 19397 for (int i = 0; i < size; i++) { 19398 final ApplicationInfo info = infos.get(i); 19399 packageNames[i] = info.packageName; 19400 packageUids[i] = info.uid; 19401 } 19402 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19403 finishedReceiver); 19404 } 19405 19406 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19407 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19408 sendResourcesChangedBroadcast(mediaStatus, replacing, 19409 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19410 } 19411 19412 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19413 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19414 int size = pkgList.length; 19415 if (size > 0) { 19416 // Send broadcasts here 19417 Bundle extras = new Bundle(); 19418 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19419 if (uidArr != null) { 19420 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19421 } 19422 if (replacing) { 19423 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19424 } 19425 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19426 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19427 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19428 } 19429 } 19430 19431 /* 19432 * Look at potentially valid container ids from processCids If package 19433 * information doesn't match the one on record or package scanning fails, 19434 * the cid is added to list of removeCids. We currently don't delete stale 19435 * containers. 19436 */ 19437 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19438 boolean externalStorage) { 19439 ArrayList<String> pkgList = new ArrayList<String>(); 19440 Set<AsecInstallArgs> keys = processCids.keySet(); 19441 19442 for (AsecInstallArgs args : keys) { 19443 String codePath = processCids.get(args); 19444 if (DEBUG_SD_INSTALL) 19445 Log.i(TAG, "Loading container : " + args.cid); 19446 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19447 try { 19448 // Make sure there are no container errors first. 19449 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19450 Slog.e(TAG, "Failed to mount cid : " + args.cid 19451 + " when installing from sdcard"); 19452 continue; 19453 } 19454 // Check code path here. 19455 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19456 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19457 + " does not match one in settings " + codePath); 19458 continue; 19459 } 19460 // Parse package 19461 int parseFlags = mDefParseFlags; 19462 if (args.isExternalAsec()) { 19463 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19464 } 19465 if (args.isFwdLocked()) { 19466 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19467 } 19468 19469 synchronized (mInstallLock) { 19470 PackageParser.Package pkg = null; 19471 try { 19472 // Sadly we don't know the package name yet to freeze it 19473 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19474 SCAN_IGNORE_FROZEN, 0, null); 19475 } catch (PackageManagerException e) { 19476 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19477 } 19478 // Scan the package 19479 if (pkg != null) { 19480 /* 19481 * TODO why is the lock being held? doPostInstall is 19482 * called in other places without the lock. This needs 19483 * to be straightened out. 19484 */ 19485 // writer 19486 synchronized (mPackages) { 19487 retCode = PackageManager.INSTALL_SUCCEEDED; 19488 pkgList.add(pkg.packageName); 19489 // Post process args 19490 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19491 pkg.applicationInfo.uid); 19492 } 19493 } else { 19494 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19495 } 19496 } 19497 19498 } finally { 19499 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19500 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19501 } 19502 } 19503 } 19504 // writer 19505 synchronized (mPackages) { 19506 // If the platform SDK has changed since the last time we booted, 19507 // we need to re-grant app permission to catch any new ones that 19508 // appear. This is really a hack, and means that apps can in some 19509 // cases get permissions that the user didn't initially explicitly 19510 // allow... it would be nice to have some better way to handle 19511 // this situation. 19512 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19513 : mSettings.getInternalVersion(); 19514 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19515 : StorageManager.UUID_PRIVATE_INTERNAL; 19516 19517 int updateFlags = UPDATE_PERMISSIONS_ALL; 19518 if (ver.sdkVersion != mSdkVersion) { 19519 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19520 + mSdkVersion + "; regranting permissions for external"); 19521 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19522 } 19523 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19524 19525 // Yay, everything is now upgraded 19526 ver.forceCurrent(); 19527 19528 // can downgrade to reader 19529 // Persist settings 19530 mSettings.writeLPr(); 19531 } 19532 // Send a broadcast to let everyone know we are done processing 19533 if (pkgList.size() > 0) { 19534 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19535 } 19536 } 19537 19538 /* 19539 * Utility method to unload a list of specified containers 19540 */ 19541 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19542 // Just unmount all valid containers. 19543 for (AsecInstallArgs arg : cidArgs) { 19544 synchronized (mInstallLock) { 19545 arg.doPostDeleteLI(false); 19546 } 19547 } 19548 } 19549 19550 /* 19551 * Unload packages mounted on external media. This involves deleting package 19552 * data from internal structures, sending broadcasts about disabled packages, 19553 * gc'ing to free up references, unmounting all secure containers 19554 * corresponding to packages on external media, and posting a 19555 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19556 * that we always have to post this message if status has been requested no 19557 * matter what. 19558 */ 19559 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19560 final boolean reportStatus) { 19561 if (DEBUG_SD_INSTALL) 19562 Log.i(TAG, "unloading media packages"); 19563 ArrayList<String> pkgList = new ArrayList<String>(); 19564 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19565 final Set<AsecInstallArgs> keys = processCids.keySet(); 19566 for (AsecInstallArgs args : keys) { 19567 String pkgName = args.getPackageName(); 19568 if (DEBUG_SD_INSTALL) 19569 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19570 // Delete package internally 19571 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19572 synchronized (mInstallLock) { 19573 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19574 final boolean res; 19575 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19576 "unloadMediaPackages")) { 19577 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19578 null); 19579 } 19580 if (res) { 19581 pkgList.add(pkgName); 19582 } else { 19583 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19584 failedList.add(args); 19585 } 19586 } 19587 } 19588 19589 // reader 19590 synchronized (mPackages) { 19591 // We didn't update the settings after removing each package; 19592 // write them now for all packages. 19593 mSettings.writeLPr(); 19594 } 19595 19596 // We have to absolutely send UPDATED_MEDIA_STATUS only 19597 // after confirming that all the receivers processed the ordered 19598 // broadcast when packages get disabled, force a gc to clean things up. 19599 // and unload all the containers. 19600 if (pkgList.size() > 0) { 19601 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19602 new IIntentReceiver.Stub() { 19603 public void performReceive(Intent intent, int resultCode, String data, 19604 Bundle extras, boolean ordered, boolean sticky, 19605 int sendingUser) throws RemoteException { 19606 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19607 reportStatus ? 1 : 0, 1, keys); 19608 mHandler.sendMessage(msg); 19609 } 19610 }); 19611 } else { 19612 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19613 keys); 19614 mHandler.sendMessage(msg); 19615 } 19616 } 19617 19618 private void loadPrivatePackages(final VolumeInfo vol) { 19619 mHandler.post(new Runnable() { 19620 @Override 19621 public void run() { 19622 loadPrivatePackagesInner(vol); 19623 } 19624 }); 19625 } 19626 19627 private void loadPrivatePackagesInner(VolumeInfo vol) { 19628 final String volumeUuid = vol.fsUuid; 19629 if (TextUtils.isEmpty(volumeUuid)) { 19630 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19631 return; 19632 } 19633 19634 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19635 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19636 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19637 19638 final VersionInfo ver; 19639 final List<PackageSetting> packages; 19640 synchronized (mPackages) { 19641 ver = mSettings.findOrCreateVersion(volumeUuid); 19642 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19643 } 19644 19645 for (PackageSetting ps : packages) { 19646 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19647 synchronized (mInstallLock) { 19648 final PackageParser.Package pkg; 19649 try { 19650 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19651 loaded.add(pkg.applicationInfo); 19652 19653 } catch (PackageManagerException e) { 19654 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19655 } 19656 19657 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19658 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19659 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19660 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19661 } 19662 } 19663 } 19664 19665 // Reconcile app data for all started/unlocked users 19666 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19667 final UserManager um = mContext.getSystemService(UserManager.class); 19668 UserManagerInternal umInternal = getUserManagerInternal(); 19669 for (UserInfo user : um.getUsers()) { 19670 final int flags; 19671 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19672 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19673 } else if (umInternal.isUserRunning(user.id)) { 19674 flags = StorageManager.FLAG_STORAGE_DE; 19675 } else { 19676 continue; 19677 } 19678 19679 try { 19680 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19681 synchronized (mInstallLock) { 19682 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19683 } 19684 } catch (IllegalStateException e) { 19685 // Device was probably ejected, and we'll process that event momentarily 19686 Slog.w(TAG, "Failed to prepare storage: " + e); 19687 } 19688 } 19689 19690 synchronized (mPackages) { 19691 int updateFlags = UPDATE_PERMISSIONS_ALL; 19692 if (ver.sdkVersion != mSdkVersion) { 19693 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19694 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19695 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19696 } 19697 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19698 19699 // Yay, everything is now upgraded 19700 ver.forceCurrent(); 19701 19702 mSettings.writeLPr(); 19703 } 19704 19705 for (PackageFreezer freezer : freezers) { 19706 freezer.close(); 19707 } 19708 19709 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19710 sendResourcesChangedBroadcast(true, false, loaded, null); 19711 } 19712 19713 private void unloadPrivatePackages(final VolumeInfo vol) { 19714 mHandler.post(new Runnable() { 19715 @Override 19716 public void run() { 19717 unloadPrivatePackagesInner(vol); 19718 } 19719 }); 19720 } 19721 19722 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19723 final String volumeUuid = vol.fsUuid; 19724 if (TextUtils.isEmpty(volumeUuid)) { 19725 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19726 return; 19727 } 19728 19729 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19730 synchronized (mInstallLock) { 19731 synchronized (mPackages) { 19732 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19733 for (PackageSetting ps : packages) { 19734 if (ps.pkg == null) continue; 19735 19736 final ApplicationInfo info = ps.pkg.applicationInfo; 19737 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19738 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19739 19740 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19741 "unloadPrivatePackagesInner")) { 19742 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19743 false, null)) { 19744 unloaded.add(info); 19745 } else { 19746 Slog.w(TAG, "Failed to unload " + ps.codePath); 19747 } 19748 } 19749 19750 // Try very hard to release any references to this package 19751 // so we don't risk the system server being killed due to 19752 // open FDs 19753 AttributeCache.instance().removePackage(ps.name); 19754 } 19755 19756 mSettings.writeLPr(); 19757 } 19758 } 19759 19760 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19761 sendResourcesChangedBroadcast(false, false, unloaded, null); 19762 19763 // Try very hard to release any references to this path so we don't risk 19764 // the system server being killed due to open FDs 19765 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19766 19767 for (int i = 0; i < 3; i++) { 19768 System.gc(); 19769 System.runFinalization(); 19770 } 19771 } 19772 19773 /** 19774 * Prepare storage areas for given user on all mounted devices. 19775 */ 19776 void prepareUserData(int userId, int userSerial, int flags) { 19777 synchronized (mInstallLock) { 19778 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19779 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19780 final String volumeUuid = vol.getFsUuid(); 19781 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19782 } 19783 } 19784 } 19785 19786 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19787 boolean allowRecover) { 19788 // Prepare storage and verify that serial numbers are consistent; if 19789 // there's a mismatch we need to destroy to avoid leaking data 19790 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19791 try { 19792 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19793 19794 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19795 UserManagerService.enforceSerialNumber( 19796 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19797 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19798 UserManagerService.enforceSerialNumber( 19799 Environment.getDataSystemDeDirectory(userId), userSerial); 19800 } 19801 } 19802 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19803 UserManagerService.enforceSerialNumber( 19804 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19805 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19806 UserManagerService.enforceSerialNumber( 19807 Environment.getDataSystemCeDirectory(userId), userSerial); 19808 } 19809 } 19810 19811 synchronized (mInstallLock) { 19812 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19813 } 19814 } catch (Exception e) { 19815 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19816 + " because we failed to prepare: " + e); 19817 destroyUserDataLI(volumeUuid, userId, 19818 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19819 19820 if (allowRecover) { 19821 // Try one last time; if we fail again we're really in trouble 19822 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19823 } 19824 } 19825 } 19826 19827 /** 19828 * Destroy storage areas for given user on all mounted devices. 19829 */ 19830 void destroyUserData(int userId, int flags) { 19831 synchronized (mInstallLock) { 19832 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19833 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19834 final String volumeUuid = vol.getFsUuid(); 19835 destroyUserDataLI(volumeUuid, userId, flags); 19836 } 19837 } 19838 } 19839 19840 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19841 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19842 try { 19843 // Clean up app data, profile data, and media data 19844 mInstaller.destroyUserData(volumeUuid, userId, flags); 19845 19846 // Clean up system data 19847 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19848 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19849 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19850 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19851 } 19852 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19853 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19854 } 19855 } 19856 19857 // Data with special labels is now gone, so finish the job 19858 storage.destroyUserStorage(volumeUuid, userId, flags); 19859 19860 } catch (Exception e) { 19861 logCriticalInfo(Log.WARN, 19862 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19863 } 19864 } 19865 19866 /** 19867 * Examine all users present on given mounted volume, and destroy data 19868 * belonging to users that are no longer valid, or whose user ID has been 19869 * recycled. 19870 */ 19871 private void reconcileUsers(String volumeUuid) { 19872 final List<File> files = new ArrayList<>(); 19873 Collections.addAll(files, FileUtils 19874 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19875 Collections.addAll(files, FileUtils 19876 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19877 Collections.addAll(files, FileUtils 19878 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19879 Collections.addAll(files, FileUtils 19880 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19881 for (File file : files) { 19882 if (!file.isDirectory()) continue; 19883 19884 final int userId; 19885 final UserInfo info; 19886 try { 19887 userId = Integer.parseInt(file.getName()); 19888 info = sUserManager.getUserInfo(userId); 19889 } catch (NumberFormatException e) { 19890 Slog.w(TAG, "Invalid user directory " + file); 19891 continue; 19892 } 19893 19894 boolean destroyUser = false; 19895 if (info == null) { 19896 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19897 + " because no matching user was found"); 19898 destroyUser = true; 19899 } else if (!mOnlyCore) { 19900 try { 19901 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19902 } catch (IOException e) { 19903 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19904 + " because we failed to enforce serial number: " + e); 19905 destroyUser = true; 19906 } 19907 } 19908 19909 if (destroyUser) { 19910 synchronized (mInstallLock) { 19911 destroyUserDataLI(volumeUuid, userId, 19912 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19913 } 19914 } 19915 } 19916 } 19917 19918 private void assertPackageKnown(String volumeUuid, String packageName) 19919 throws PackageManagerException { 19920 synchronized (mPackages) { 19921 final PackageSetting ps = mSettings.mPackages.get(packageName); 19922 if (ps == null) { 19923 throw new PackageManagerException("Package " + packageName + " is unknown"); 19924 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19925 throw new PackageManagerException( 19926 "Package " + packageName + " found on unknown volume " + volumeUuid 19927 + "; expected volume " + ps.volumeUuid); 19928 } 19929 } 19930 } 19931 19932 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19933 throws PackageManagerException { 19934 synchronized (mPackages) { 19935 final PackageSetting ps = mSettings.mPackages.get(packageName); 19936 if (ps == null) { 19937 throw new PackageManagerException("Package " + packageName + " is unknown"); 19938 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19939 throw new PackageManagerException( 19940 "Package " + packageName + " found on unknown volume " + volumeUuid 19941 + "; expected volume " + ps.volumeUuid); 19942 } else if (!ps.getInstalled(userId)) { 19943 throw new PackageManagerException( 19944 "Package " + packageName + " not installed for user " + userId); 19945 } 19946 } 19947 } 19948 19949 /** 19950 * Examine all apps present on given mounted volume, and destroy apps that 19951 * aren't expected, either due to uninstallation or reinstallation on 19952 * another volume. 19953 */ 19954 private void reconcileApps(String volumeUuid) { 19955 final File[] files = FileUtils 19956 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19957 for (File file : files) { 19958 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19959 && !PackageInstallerService.isStageName(file.getName()); 19960 if (!isPackage) { 19961 // Ignore entries which are not packages 19962 continue; 19963 } 19964 19965 try { 19966 final PackageLite pkg = PackageParser.parsePackageLite(file, 19967 PackageParser.PARSE_MUST_BE_APK); 19968 assertPackageKnown(volumeUuid, pkg.packageName); 19969 19970 } catch (PackageParserException | PackageManagerException e) { 19971 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19972 synchronized (mInstallLock) { 19973 removeCodePathLI(file); 19974 } 19975 } 19976 } 19977 } 19978 19979 /** 19980 * Reconcile all app data for the given user. 19981 * <p> 19982 * Verifies that directories exist and that ownership and labeling is 19983 * correct for all installed apps on all mounted volumes. 19984 */ 19985 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 19986 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19987 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19988 final String volumeUuid = vol.getFsUuid(); 19989 synchronized (mInstallLock) { 19990 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 19991 } 19992 } 19993 } 19994 19995 /** 19996 * Reconcile all app data on given mounted volume. 19997 * <p> 19998 * Destroys app data that isn't expected, either due to uninstallation or 19999 * reinstallation on another volume. 20000 * <p> 20001 * Verifies that directories exist and that ownership and labeling is 20002 * correct for all installed apps. 20003 */ 20004 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20005 boolean migrateAppData) { 20006 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20007 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20008 20009 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20010 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20011 20012 // First look for stale data that doesn't belong, and check if things 20013 // have changed since we did our last restorecon 20014 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20015 if (StorageManager.isFileEncryptedNativeOrEmulated() 20016 && !StorageManager.isUserKeyUnlocked(userId)) { 20017 throw new RuntimeException( 20018 "Yikes, someone asked us to reconcile CE storage while " + userId 20019 + " was still locked; this would have caused massive data loss!"); 20020 } 20021 20022 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20023 for (File file : files) { 20024 final String packageName = file.getName(); 20025 try { 20026 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20027 } catch (PackageManagerException e) { 20028 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20029 try { 20030 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20031 StorageManager.FLAG_STORAGE_CE, 0); 20032 } catch (InstallerException e2) { 20033 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20034 } 20035 } 20036 } 20037 } 20038 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20039 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20040 for (File file : files) { 20041 final String packageName = file.getName(); 20042 try { 20043 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20044 } catch (PackageManagerException e) { 20045 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20046 try { 20047 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20048 StorageManager.FLAG_STORAGE_DE, 0); 20049 } catch (InstallerException e2) { 20050 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20051 } 20052 } 20053 } 20054 } 20055 20056 // Ensure that data directories are ready to roll for all packages 20057 // installed for this volume and user 20058 final List<PackageSetting> packages; 20059 synchronized (mPackages) { 20060 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20061 } 20062 int preparedCount = 0; 20063 for (PackageSetting ps : packages) { 20064 final String packageName = ps.name; 20065 if (ps.pkg == null) { 20066 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20067 // TODO: might be due to legacy ASEC apps; we should circle back 20068 // and reconcile again once they're scanned 20069 continue; 20070 } 20071 20072 if (ps.getInstalled(userId)) { 20073 prepareAppDataLIF(ps.pkg, userId, flags); 20074 20075 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20076 // We may have just shuffled around app data directories, so 20077 // prepare them one more time 20078 prepareAppDataLIF(ps.pkg, userId, flags); 20079 } 20080 20081 preparedCount++; 20082 } 20083 } 20084 20085 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20086 } 20087 20088 /** 20089 * Prepare app data for the given app just after it was installed or 20090 * upgraded. This method carefully only touches users that it's installed 20091 * for, and it forces a restorecon to handle any seinfo changes. 20092 * <p> 20093 * Verifies that directories exist and that ownership and labeling is 20094 * correct for all installed apps. If there is an ownership mismatch, it 20095 * will try recovering system apps by wiping data; third-party app data is 20096 * left intact. 20097 * <p> 20098 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20099 */ 20100 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20101 final PackageSetting ps; 20102 synchronized (mPackages) { 20103 ps = mSettings.mPackages.get(pkg.packageName); 20104 mSettings.writeKernelMappingLPr(ps); 20105 } 20106 20107 final UserManager um = mContext.getSystemService(UserManager.class); 20108 UserManagerInternal umInternal = getUserManagerInternal(); 20109 for (UserInfo user : um.getUsers()) { 20110 final int flags; 20111 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20112 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20113 } else if (umInternal.isUserRunning(user.id)) { 20114 flags = StorageManager.FLAG_STORAGE_DE; 20115 } else { 20116 continue; 20117 } 20118 20119 if (ps.getInstalled(user.id)) { 20120 // TODO: when user data is locked, mark that we're still dirty 20121 prepareAppDataLIF(pkg, user.id, flags); 20122 } 20123 } 20124 } 20125 20126 /** 20127 * Prepare app data for the given app. 20128 * <p> 20129 * Verifies that directories exist and that ownership and labeling is 20130 * correct for all installed apps. If there is an ownership mismatch, this 20131 * will try recovering system apps by wiping data; third-party app data is 20132 * left intact. 20133 */ 20134 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20135 if (pkg == null) { 20136 Slog.wtf(TAG, "Package was null!", new Throwable()); 20137 return; 20138 } 20139 prepareAppDataLeafLIF(pkg, userId, flags); 20140 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20141 for (int i = 0; i < childCount; i++) { 20142 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20143 } 20144 } 20145 20146 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20147 if (DEBUG_APP_DATA) { 20148 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20149 + Integer.toHexString(flags)); 20150 } 20151 20152 final String volumeUuid = pkg.volumeUuid; 20153 final String packageName = pkg.packageName; 20154 final ApplicationInfo app = pkg.applicationInfo; 20155 final int appId = UserHandle.getAppId(app.uid); 20156 20157 Preconditions.checkNotNull(app.seinfo); 20158 20159 try { 20160 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20161 appId, app.seinfo, app.targetSdkVersion); 20162 } catch (InstallerException e) { 20163 if (app.isSystemApp()) { 20164 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20165 + ", but trying to recover: " + e); 20166 destroyAppDataLeafLIF(pkg, userId, flags); 20167 try { 20168 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20169 appId, app.seinfo, app.targetSdkVersion); 20170 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20171 } catch (InstallerException e2) { 20172 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20173 } 20174 } else { 20175 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20176 } 20177 } 20178 20179 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20180 try { 20181 // CE storage is unlocked right now, so read out the inode and 20182 // remember for use later when it's locked 20183 // TODO: mark this structure as dirty so we persist it! 20184 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20185 StorageManager.FLAG_STORAGE_CE); 20186 synchronized (mPackages) { 20187 final PackageSetting ps = mSettings.mPackages.get(packageName); 20188 if (ps != null) { 20189 ps.setCeDataInode(ceDataInode, userId); 20190 } 20191 } 20192 } catch (InstallerException e) { 20193 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20194 } 20195 } 20196 20197 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20198 } 20199 20200 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20201 if (pkg == null) { 20202 Slog.wtf(TAG, "Package was null!", new Throwable()); 20203 return; 20204 } 20205 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20206 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20207 for (int i = 0; i < childCount; i++) { 20208 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20209 } 20210 } 20211 20212 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20213 final String volumeUuid = pkg.volumeUuid; 20214 final String packageName = pkg.packageName; 20215 final ApplicationInfo app = pkg.applicationInfo; 20216 20217 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20218 // Create a native library symlink only if we have native libraries 20219 // and if the native libraries are 32 bit libraries. We do not provide 20220 // this symlink for 64 bit libraries. 20221 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20222 final String nativeLibPath = app.nativeLibraryDir; 20223 try { 20224 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20225 nativeLibPath, userId); 20226 } catch (InstallerException e) { 20227 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20228 } 20229 } 20230 } 20231 } 20232 20233 /** 20234 * For system apps on non-FBE devices, this method migrates any existing 20235 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20236 * requested by the app. 20237 */ 20238 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20239 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20240 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20241 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20242 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20243 try { 20244 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20245 storageTarget); 20246 } catch (InstallerException e) { 20247 logCriticalInfo(Log.WARN, 20248 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20249 } 20250 return true; 20251 } else { 20252 return false; 20253 } 20254 } 20255 20256 public PackageFreezer freezePackage(String packageName, String killReason) { 20257 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20258 } 20259 20260 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20261 return new PackageFreezer(packageName, userId, killReason); 20262 } 20263 20264 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20265 String killReason) { 20266 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20267 } 20268 20269 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20270 String killReason) { 20271 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20272 return new PackageFreezer(); 20273 } else { 20274 return freezePackage(packageName, userId, killReason); 20275 } 20276 } 20277 20278 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20279 String killReason) { 20280 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20281 } 20282 20283 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20284 String killReason) { 20285 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20286 return new PackageFreezer(); 20287 } else { 20288 return freezePackage(packageName, userId, killReason); 20289 } 20290 } 20291 20292 /** 20293 * Class that freezes and kills the given package upon creation, and 20294 * unfreezes it upon closing. This is typically used when doing surgery on 20295 * app code/data to prevent the app from running while you're working. 20296 */ 20297 private class PackageFreezer implements AutoCloseable { 20298 private final String mPackageName; 20299 private final PackageFreezer[] mChildren; 20300 20301 private final boolean mWeFroze; 20302 20303 private final AtomicBoolean mClosed = new AtomicBoolean(); 20304 private final CloseGuard mCloseGuard = CloseGuard.get(); 20305 20306 /** 20307 * Create and return a stub freezer that doesn't actually do anything, 20308 * typically used when someone requested 20309 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20310 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20311 */ 20312 public PackageFreezer() { 20313 mPackageName = null; 20314 mChildren = null; 20315 mWeFroze = false; 20316 mCloseGuard.open("close"); 20317 } 20318 20319 public PackageFreezer(String packageName, int userId, String killReason) { 20320 synchronized (mPackages) { 20321 mPackageName = packageName; 20322 mWeFroze = mFrozenPackages.add(mPackageName); 20323 20324 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20325 if (ps != null) { 20326 killApplication(ps.name, ps.appId, userId, killReason); 20327 } 20328 20329 final PackageParser.Package p = mPackages.get(packageName); 20330 if (p != null && p.childPackages != null) { 20331 final int N = p.childPackages.size(); 20332 mChildren = new PackageFreezer[N]; 20333 for (int i = 0; i < N; i++) { 20334 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20335 userId, killReason); 20336 } 20337 } else { 20338 mChildren = null; 20339 } 20340 } 20341 mCloseGuard.open("close"); 20342 } 20343 20344 @Override 20345 protected void finalize() throws Throwable { 20346 try { 20347 mCloseGuard.warnIfOpen(); 20348 close(); 20349 } finally { 20350 super.finalize(); 20351 } 20352 } 20353 20354 @Override 20355 public void close() { 20356 mCloseGuard.close(); 20357 if (mClosed.compareAndSet(false, true)) { 20358 synchronized (mPackages) { 20359 if (mWeFroze) { 20360 mFrozenPackages.remove(mPackageName); 20361 } 20362 20363 if (mChildren != null) { 20364 for (PackageFreezer freezer : mChildren) { 20365 freezer.close(); 20366 } 20367 } 20368 } 20369 } 20370 } 20371 } 20372 20373 /** 20374 * Verify that given package is currently frozen. 20375 */ 20376 private void checkPackageFrozen(String packageName) { 20377 synchronized (mPackages) { 20378 if (!mFrozenPackages.contains(packageName)) { 20379 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20380 } 20381 } 20382 } 20383 20384 @Override 20385 public int movePackage(final String packageName, final String volumeUuid) { 20386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20387 20388 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20389 final int moveId = mNextMoveId.getAndIncrement(); 20390 mHandler.post(new Runnable() { 20391 @Override 20392 public void run() { 20393 try { 20394 movePackageInternal(packageName, volumeUuid, moveId, user); 20395 } catch (PackageManagerException e) { 20396 Slog.w(TAG, "Failed to move " + packageName, e); 20397 mMoveCallbacks.notifyStatusChanged(moveId, 20398 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20399 } 20400 } 20401 }); 20402 return moveId; 20403 } 20404 20405 private void movePackageInternal(final String packageName, final String volumeUuid, 20406 final int moveId, UserHandle user) throws PackageManagerException { 20407 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20408 final PackageManager pm = mContext.getPackageManager(); 20409 20410 final boolean currentAsec; 20411 final String currentVolumeUuid; 20412 final File codeFile; 20413 final String installerPackageName; 20414 final String packageAbiOverride; 20415 final int appId; 20416 final String seinfo; 20417 final String label; 20418 final int targetSdkVersion; 20419 final PackageFreezer freezer; 20420 final int[] installedUserIds; 20421 20422 // reader 20423 synchronized (mPackages) { 20424 final PackageParser.Package pkg = mPackages.get(packageName); 20425 final PackageSetting ps = mSettings.mPackages.get(packageName); 20426 if (pkg == null || ps == null) { 20427 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20428 } 20429 20430 if (pkg.applicationInfo.isSystemApp()) { 20431 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20432 "Cannot move system application"); 20433 } 20434 20435 if (pkg.applicationInfo.isExternalAsec()) { 20436 currentAsec = true; 20437 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20438 } else if (pkg.applicationInfo.isForwardLocked()) { 20439 currentAsec = true; 20440 currentVolumeUuid = "forward_locked"; 20441 } else { 20442 currentAsec = false; 20443 currentVolumeUuid = ps.volumeUuid; 20444 20445 final File probe = new File(pkg.codePath); 20446 final File probeOat = new File(probe, "oat"); 20447 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20448 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20449 "Move only supported for modern cluster style installs"); 20450 } 20451 } 20452 20453 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20454 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20455 "Package already moved to " + volumeUuid); 20456 } 20457 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20458 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20459 "Device admin cannot be moved"); 20460 } 20461 20462 if (mFrozenPackages.contains(packageName)) { 20463 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20464 "Failed to move already frozen package"); 20465 } 20466 20467 codeFile = new File(pkg.codePath); 20468 installerPackageName = ps.installerPackageName; 20469 packageAbiOverride = ps.cpuAbiOverrideString; 20470 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20471 seinfo = pkg.applicationInfo.seinfo; 20472 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20473 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20474 freezer = freezePackage(packageName, "movePackageInternal"); 20475 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20476 } 20477 20478 final Bundle extras = new Bundle(); 20479 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20480 extras.putString(Intent.EXTRA_TITLE, label); 20481 mMoveCallbacks.notifyCreated(moveId, extras); 20482 20483 int installFlags; 20484 final boolean moveCompleteApp; 20485 final File measurePath; 20486 20487 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20488 installFlags = INSTALL_INTERNAL; 20489 moveCompleteApp = !currentAsec; 20490 measurePath = Environment.getDataAppDirectory(volumeUuid); 20491 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20492 installFlags = INSTALL_EXTERNAL; 20493 moveCompleteApp = false; 20494 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20495 } else { 20496 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20497 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20498 || !volume.isMountedWritable()) { 20499 freezer.close(); 20500 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20501 "Move location not mounted private volume"); 20502 } 20503 20504 Preconditions.checkState(!currentAsec); 20505 20506 installFlags = INSTALL_INTERNAL; 20507 moveCompleteApp = true; 20508 measurePath = Environment.getDataAppDirectory(volumeUuid); 20509 } 20510 20511 final PackageStats stats = new PackageStats(null, -1); 20512 synchronized (mInstaller) { 20513 for (int userId : installedUserIds) { 20514 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20515 freezer.close(); 20516 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20517 "Failed to measure package size"); 20518 } 20519 } 20520 } 20521 20522 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20523 + stats.dataSize); 20524 20525 final long startFreeBytes = measurePath.getFreeSpace(); 20526 final long sizeBytes; 20527 if (moveCompleteApp) { 20528 sizeBytes = stats.codeSize + stats.dataSize; 20529 } else { 20530 sizeBytes = stats.codeSize; 20531 } 20532 20533 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20534 freezer.close(); 20535 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20536 "Not enough free space to move"); 20537 } 20538 20539 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20540 20541 final CountDownLatch installedLatch = new CountDownLatch(1); 20542 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20543 @Override 20544 public void onUserActionRequired(Intent intent) throws RemoteException { 20545 throw new IllegalStateException(); 20546 } 20547 20548 @Override 20549 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20550 Bundle extras) throws RemoteException { 20551 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20552 + PackageManager.installStatusToString(returnCode, msg)); 20553 20554 installedLatch.countDown(); 20555 freezer.close(); 20556 20557 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20558 switch (status) { 20559 case PackageInstaller.STATUS_SUCCESS: 20560 mMoveCallbacks.notifyStatusChanged(moveId, 20561 PackageManager.MOVE_SUCCEEDED); 20562 break; 20563 case PackageInstaller.STATUS_FAILURE_STORAGE: 20564 mMoveCallbacks.notifyStatusChanged(moveId, 20565 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20566 break; 20567 default: 20568 mMoveCallbacks.notifyStatusChanged(moveId, 20569 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20570 break; 20571 } 20572 } 20573 }; 20574 20575 final MoveInfo move; 20576 if (moveCompleteApp) { 20577 // Kick off a thread to report progress estimates 20578 new Thread() { 20579 @Override 20580 public void run() { 20581 while (true) { 20582 try { 20583 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20584 break; 20585 } 20586 } catch (InterruptedException ignored) { 20587 } 20588 20589 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20590 final int progress = 10 + (int) MathUtils.constrain( 20591 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20592 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20593 } 20594 } 20595 }.start(); 20596 20597 final String dataAppName = codeFile.getName(); 20598 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20599 dataAppName, appId, seinfo, targetSdkVersion); 20600 } else { 20601 move = null; 20602 } 20603 20604 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20605 20606 final Message msg = mHandler.obtainMessage(INIT_COPY); 20607 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20608 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20609 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20610 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20611 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20612 msg.obj = params; 20613 20614 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20615 System.identityHashCode(msg.obj)); 20616 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20617 System.identityHashCode(msg.obj)); 20618 20619 mHandler.sendMessage(msg); 20620 } 20621 20622 @Override 20623 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20624 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20625 20626 final int realMoveId = mNextMoveId.getAndIncrement(); 20627 final Bundle extras = new Bundle(); 20628 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20629 mMoveCallbacks.notifyCreated(realMoveId, extras); 20630 20631 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20632 @Override 20633 public void onCreated(int moveId, Bundle extras) { 20634 // Ignored 20635 } 20636 20637 @Override 20638 public void onStatusChanged(int moveId, int status, long estMillis) { 20639 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20640 } 20641 }; 20642 20643 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20644 storage.setPrimaryStorageUuid(volumeUuid, callback); 20645 return realMoveId; 20646 } 20647 20648 @Override 20649 public int getMoveStatus(int moveId) { 20650 mContext.enforceCallingOrSelfPermission( 20651 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20652 return mMoveCallbacks.mLastStatus.get(moveId); 20653 } 20654 20655 @Override 20656 public void registerMoveCallback(IPackageMoveObserver callback) { 20657 mContext.enforceCallingOrSelfPermission( 20658 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20659 mMoveCallbacks.register(callback); 20660 } 20661 20662 @Override 20663 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20664 mContext.enforceCallingOrSelfPermission( 20665 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20666 mMoveCallbacks.unregister(callback); 20667 } 20668 20669 @Override 20670 public boolean setInstallLocation(int loc) { 20671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20672 null); 20673 if (getInstallLocation() == loc) { 20674 return true; 20675 } 20676 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20677 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20678 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20679 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20680 return true; 20681 } 20682 return false; 20683 } 20684 20685 @Override 20686 public int getInstallLocation() { 20687 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20688 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20689 PackageHelper.APP_INSTALL_AUTO); 20690 } 20691 20692 /** Called by UserManagerService */ 20693 void cleanUpUser(UserManagerService userManager, int userHandle) { 20694 synchronized (mPackages) { 20695 mDirtyUsers.remove(userHandle); 20696 mUserNeedsBadging.delete(userHandle); 20697 mSettings.removeUserLPw(userHandle); 20698 mPendingBroadcasts.remove(userHandle); 20699 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20700 removeUnusedPackagesLPw(userManager, userHandle); 20701 } 20702 } 20703 20704 /** 20705 * We're removing userHandle and would like to remove any downloaded packages 20706 * that are no longer in use by any other user. 20707 * @param userHandle the user being removed 20708 */ 20709 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20710 final boolean DEBUG_CLEAN_APKS = false; 20711 int [] users = userManager.getUserIds(); 20712 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20713 while (psit.hasNext()) { 20714 PackageSetting ps = psit.next(); 20715 if (ps.pkg == null) { 20716 continue; 20717 } 20718 final String packageName = ps.pkg.packageName; 20719 // Skip over if system app 20720 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20721 continue; 20722 } 20723 if (DEBUG_CLEAN_APKS) { 20724 Slog.i(TAG, "Checking package " + packageName); 20725 } 20726 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20727 if (keep) { 20728 if (DEBUG_CLEAN_APKS) { 20729 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20730 } 20731 } else { 20732 for (int i = 0; i < users.length; i++) { 20733 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20734 keep = true; 20735 if (DEBUG_CLEAN_APKS) { 20736 Slog.i(TAG, " Keeping package " + packageName + " for user " 20737 + users[i]); 20738 } 20739 break; 20740 } 20741 } 20742 } 20743 if (!keep) { 20744 if (DEBUG_CLEAN_APKS) { 20745 Slog.i(TAG, " Removing package " + packageName); 20746 } 20747 mHandler.post(new Runnable() { 20748 public void run() { 20749 deletePackageX(packageName, userHandle, 0); 20750 } //end run 20751 }); 20752 } 20753 } 20754 } 20755 20756 /** Called by UserManagerService */ 20757 void createNewUser(int userId, String[] disallowedPackages) { 20758 synchronized (mInstallLock) { 20759 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 20760 } 20761 synchronized (mPackages) { 20762 scheduleWritePackageRestrictionsLocked(userId); 20763 scheduleWritePackageListLocked(userId); 20764 applyFactoryDefaultBrowserLPw(userId); 20765 primeDomainVerificationsLPw(userId); 20766 } 20767 } 20768 20769 void onNewUserCreated(final int userId) { 20770 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20771 // If permission review for legacy apps is required, we represent 20772 // dagerous permissions for such apps as always granted runtime 20773 // permissions to keep per user flag state whether review is needed. 20774 // Hence, if a new user is added we have to propagate dangerous 20775 // permission grants for these legacy apps. 20776 if (mPermissionReviewRequired) { 20777 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20778 | UPDATE_PERMISSIONS_REPLACE_ALL); 20779 } 20780 } 20781 20782 @Override 20783 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20784 mContext.enforceCallingOrSelfPermission( 20785 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20786 "Only package verification agents can read the verifier device identity"); 20787 20788 synchronized (mPackages) { 20789 return mSettings.getVerifierDeviceIdentityLPw(); 20790 } 20791 } 20792 20793 @Override 20794 public void setPermissionEnforced(String permission, boolean enforced) { 20795 // TODO: Now that we no longer change GID for storage, this should to away. 20796 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20797 "setPermissionEnforced"); 20798 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20799 synchronized (mPackages) { 20800 if (mSettings.mReadExternalStorageEnforced == null 20801 || mSettings.mReadExternalStorageEnforced != enforced) { 20802 mSettings.mReadExternalStorageEnforced = enforced; 20803 mSettings.writeLPr(); 20804 } 20805 } 20806 // kill any non-foreground processes so we restart them and 20807 // grant/revoke the GID. 20808 final IActivityManager am = ActivityManager.getService(); 20809 if (am != null) { 20810 final long token = Binder.clearCallingIdentity(); 20811 try { 20812 am.killProcessesBelowForeground("setPermissionEnforcement"); 20813 } catch (RemoteException e) { 20814 } finally { 20815 Binder.restoreCallingIdentity(token); 20816 } 20817 } 20818 } else { 20819 throw new IllegalArgumentException("No selective enforcement for " + permission); 20820 } 20821 } 20822 20823 @Override 20824 @Deprecated 20825 public boolean isPermissionEnforced(String permission) { 20826 return true; 20827 } 20828 20829 @Override 20830 public boolean isStorageLow() { 20831 final long token = Binder.clearCallingIdentity(); 20832 try { 20833 final DeviceStorageMonitorInternal 20834 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20835 if (dsm != null) { 20836 return dsm.isMemoryLow(); 20837 } else { 20838 return false; 20839 } 20840 } finally { 20841 Binder.restoreCallingIdentity(token); 20842 } 20843 } 20844 20845 @Override 20846 public IPackageInstaller getPackageInstaller() { 20847 return mInstallerService; 20848 } 20849 20850 private boolean userNeedsBadging(int userId) { 20851 int index = mUserNeedsBadging.indexOfKey(userId); 20852 if (index < 0) { 20853 final UserInfo userInfo; 20854 final long token = Binder.clearCallingIdentity(); 20855 try { 20856 userInfo = sUserManager.getUserInfo(userId); 20857 } finally { 20858 Binder.restoreCallingIdentity(token); 20859 } 20860 final boolean b; 20861 if (userInfo != null && userInfo.isManagedProfile()) { 20862 b = true; 20863 } else { 20864 b = false; 20865 } 20866 mUserNeedsBadging.put(userId, b); 20867 return b; 20868 } 20869 return mUserNeedsBadging.valueAt(index); 20870 } 20871 20872 @Override 20873 public KeySet getKeySetByAlias(String packageName, String alias) { 20874 if (packageName == null || alias == null) { 20875 return null; 20876 } 20877 synchronized(mPackages) { 20878 final PackageParser.Package pkg = mPackages.get(packageName); 20879 if (pkg == null) { 20880 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20881 throw new IllegalArgumentException("Unknown package: " + packageName); 20882 } 20883 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20884 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20885 } 20886 } 20887 20888 @Override 20889 public KeySet getSigningKeySet(String packageName) { 20890 if (packageName == null) { 20891 return null; 20892 } 20893 synchronized(mPackages) { 20894 final PackageParser.Package pkg = mPackages.get(packageName); 20895 if (pkg == null) { 20896 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20897 throw new IllegalArgumentException("Unknown package: " + packageName); 20898 } 20899 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20900 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20901 throw new SecurityException("May not access signing KeySet of other apps."); 20902 } 20903 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20904 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20905 } 20906 } 20907 20908 @Override 20909 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20910 if (packageName == null || ks == null) { 20911 return false; 20912 } 20913 synchronized(mPackages) { 20914 final PackageParser.Package pkg = mPackages.get(packageName); 20915 if (pkg == null) { 20916 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20917 throw new IllegalArgumentException("Unknown package: " + packageName); 20918 } 20919 IBinder ksh = ks.getToken(); 20920 if (ksh instanceof KeySetHandle) { 20921 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20922 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20923 } 20924 return false; 20925 } 20926 } 20927 20928 @Override 20929 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20930 if (packageName == null || ks == null) { 20931 return false; 20932 } 20933 synchronized(mPackages) { 20934 final PackageParser.Package pkg = mPackages.get(packageName); 20935 if (pkg == null) { 20936 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20937 throw new IllegalArgumentException("Unknown package: " + packageName); 20938 } 20939 IBinder ksh = ks.getToken(); 20940 if (ksh instanceof KeySetHandle) { 20941 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20942 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20943 } 20944 return false; 20945 } 20946 } 20947 20948 private void deletePackageIfUnusedLPr(final String packageName) { 20949 PackageSetting ps = mSettings.mPackages.get(packageName); 20950 if (ps == null) { 20951 return; 20952 } 20953 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20954 // TODO Implement atomic delete if package is unused 20955 // It is currently possible that the package will be deleted even if it is installed 20956 // after this method returns. 20957 mHandler.post(new Runnable() { 20958 public void run() { 20959 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20960 } 20961 }); 20962 } 20963 } 20964 20965 /** 20966 * Check and throw if the given before/after packages would be considered a 20967 * downgrade. 20968 */ 20969 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20970 throws PackageManagerException { 20971 if (after.versionCode < before.mVersionCode) { 20972 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20973 "Update version code " + after.versionCode + " is older than current " 20974 + before.mVersionCode); 20975 } else if (after.versionCode == before.mVersionCode) { 20976 if (after.baseRevisionCode < before.baseRevisionCode) { 20977 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20978 "Update base revision code " + after.baseRevisionCode 20979 + " is older than current " + before.baseRevisionCode); 20980 } 20981 20982 if (!ArrayUtils.isEmpty(after.splitNames)) { 20983 for (int i = 0; i < after.splitNames.length; i++) { 20984 final String splitName = after.splitNames[i]; 20985 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20986 if (j != -1) { 20987 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20988 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20989 "Update split " + splitName + " revision code " 20990 + after.splitRevisionCodes[i] + " is older than current " 20991 + before.splitRevisionCodes[j]); 20992 } 20993 } 20994 } 20995 } 20996 } 20997 } 20998 20999 private static class MoveCallbacks extends Handler { 21000 private static final int MSG_CREATED = 1; 21001 private static final int MSG_STATUS_CHANGED = 2; 21002 21003 private final RemoteCallbackList<IPackageMoveObserver> 21004 mCallbacks = new RemoteCallbackList<>(); 21005 21006 private final SparseIntArray mLastStatus = new SparseIntArray(); 21007 21008 public MoveCallbacks(Looper looper) { 21009 super(looper); 21010 } 21011 21012 public void register(IPackageMoveObserver callback) { 21013 mCallbacks.register(callback); 21014 } 21015 21016 public void unregister(IPackageMoveObserver callback) { 21017 mCallbacks.unregister(callback); 21018 } 21019 21020 @Override 21021 public void handleMessage(Message msg) { 21022 final SomeArgs args = (SomeArgs) msg.obj; 21023 final int n = mCallbacks.beginBroadcast(); 21024 for (int i = 0; i < n; i++) { 21025 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21026 try { 21027 invokeCallback(callback, msg.what, args); 21028 } catch (RemoteException ignored) { 21029 } 21030 } 21031 mCallbacks.finishBroadcast(); 21032 args.recycle(); 21033 } 21034 21035 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21036 throws RemoteException { 21037 switch (what) { 21038 case MSG_CREATED: { 21039 callback.onCreated(args.argi1, (Bundle) args.arg2); 21040 break; 21041 } 21042 case MSG_STATUS_CHANGED: { 21043 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21044 break; 21045 } 21046 } 21047 } 21048 21049 private void notifyCreated(int moveId, Bundle extras) { 21050 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21051 21052 final SomeArgs args = SomeArgs.obtain(); 21053 args.argi1 = moveId; 21054 args.arg2 = extras; 21055 obtainMessage(MSG_CREATED, args).sendToTarget(); 21056 } 21057 21058 private void notifyStatusChanged(int moveId, int status) { 21059 notifyStatusChanged(moveId, status, -1); 21060 } 21061 21062 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21063 Slog.v(TAG, "Move " + moveId + " status " + status); 21064 21065 final SomeArgs args = SomeArgs.obtain(); 21066 args.argi1 = moveId; 21067 args.argi2 = status; 21068 args.arg3 = estMillis; 21069 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21070 21071 synchronized (mLastStatus) { 21072 mLastStatus.put(moveId, status); 21073 } 21074 } 21075 } 21076 21077 private final static class OnPermissionChangeListeners extends Handler { 21078 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21079 21080 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21081 new RemoteCallbackList<>(); 21082 21083 public OnPermissionChangeListeners(Looper looper) { 21084 super(looper); 21085 } 21086 21087 @Override 21088 public void handleMessage(Message msg) { 21089 switch (msg.what) { 21090 case MSG_ON_PERMISSIONS_CHANGED: { 21091 final int uid = msg.arg1; 21092 handleOnPermissionsChanged(uid); 21093 } break; 21094 } 21095 } 21096 21097 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21098 mPermissionListeners.register(listener); 21099 21100 } 21101 21102 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21103 mPermissionListeners.unregister(listener); 21104 } 21105 21106 public void onPermissionsChanged(int uid) { 21107 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21108 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21109 } 21110 } 21111 21112 private void handleOnPermissionsChanged(int uid) { 21113 final int count = mPermissionListeners.beginBroadcast(); 21114 try { 21115 for (int i = 0; i < count; i++) { 21116 IOnPermissionsChangeListener callback = mPermissionListeners 21117 .getBroadcastItem(i); 21118 try { 21119 callback.onPermissionsChanged(uid); 21120 } catch (RemoteException e) { 21121 Log.e(TAG, "Permission listener is dead", e); 21122 } 21123 } 21124 } finally { 21125 mPermissionListeners.finishBroadcast(); 21126 } 21127 } 21128 } 21129 21130 private class PackageManagerInternalImpl extends PackageManagerInternal { 21131 @Override 21132 public void setLocationPackagesProvider(PackagesProvider provider) { 21133 synchronized (mPackages) { 21134 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21135 } 21136 } 21137 21138 @Override 21139 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21140 synchronized (mPackages) { 21141 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21142 } 21143 } 21144 21145 @Override 21146 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21147 synchronized (mPackages) { 21148 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21149 } 21150 } 21151 21152 @Override 21153 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21154 synchronized (mPackages) { 21155 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21156 } 21157 } 21158 21159 @Override 21160 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21161 synchronized (mPackages) { 21162 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21163 } 21164 } 21165 21166 @Override 21167 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21168 synchronized (mPackages) { 21169 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21170 } 21171 } 21172 21173 @Override 21174 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21175 synchronized (mPackages) { 21176 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21177 packageName, userId); 21178 } 21179 } 21180 21181 @Override 21182 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21183 synchronized (mPackages) { 21184 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21185 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21186 packageName, userId); 21187 } 21188 } 21189 21190 @Override 21191 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21192 synchronized (mPackages) { 21193 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21194 packageName, userId); 21195 } 21196 } 21197 21198 @Override 21199 public void setKeepUninstalledPackages(final List<String> packageList) { 21200 Preconditions.checkNotNull(packageList); 21201 List<String> removedFromList = null; 21202 synchronized (mPackages) { 21203 if (mKeepUninstalledPackages != null) { 21204 final int packagesCount = mKeepUninstalledPackages.size(); 21205 for (int i = 0; i < packagesCount; i++) { 21206 String oldPackage = mKeepUninstalledPackages.get(i); 21207 if (packageList != null && packageList.contains(oldPackage)) { 21208 continue; 21209 } 21210 if (removedFromList == null) { 21211 removedFromList = new ArrayList<>(); 21212 } 21213 removedFromList.add(oldPackage); 21214 } 21215 } 21216 mKeepUninstalledPackages = new ArrayList<>(packageList); 21217 if (removedFromList != null) { 21218 final int removedCount = removedFromList.size(); 21219 for (int i = 0; i < removedCount; i++) { 21220 deletePackageIfUnusedLPr(removedFromList.get(i)); 21221 } 21222 } 21223 } 21224 } 21225 21226 @Override 21227 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21228 synchronized (mPackages) { 21229 // If we do not support permission review, done. 21230 if (!mPermissionReviewRequired) { 21231 return false; 21232 } 21233 21234 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21235 if (packageSetting == null) { 21236 return false; 21237 } 21238 21239 // Permission review applies only to apps not supporting the new permission model. 21240 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21241 return false; 21242 } 21243 21244 // Legacy apps have the permission and get user consent on launch. 21245 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21246 return permissionsState.isPermissionReviewRequired(userId); 21247 } 21248 } 21249 21250 @Override 21251 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21252 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21253 } 21254 21255 @Override 21256 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21257 int userId) { 21258 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21259 } 21260 21261 @Override 21262 public void setDeviceAndProfileOwnerPackages( 21263 int deviceOwnerUserId, String deviceOwnerPackage, 21264 SparseArray<String> profileOwnerPackages) { 21265 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21266 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21267 } 21268 21269 @Override 21270 public boolean isPackageDataProtected(int userId, String packageName) { 21271 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21272 } 21273 21274 @Override 21275 public boolean isPackageEphemeral(int userId, String packageName) { 21276 synchronized (mPackages) { 21277 PackageParser.Package p = mPackages.get(packageName); 21278 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21279 } 21280 } 21281 21282 @Override 21283 public boolean wasPackageEverLaunched(String packageName, int userId) { 21284 synchronized (mPackages) { 21285 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21286 } 21287 } 21288 21289 @Override 21290 public void grantRuntimePermission(String packageName, String name, int userId, 21291 boolean overridePolicy) { 21292 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21293 overridePolicy); 21294 } 21295 21296 @Override 21297 public void revokeRuntimePermission(String packageName, String name, int userId, 21298 boolean overridePolicy) { 21299 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21300 overridePolicy); 21301 } 21302 21303 @Override 21304 public String getNameForUid(int uid) { 21305 return PackageManagerService.this.getNameForUid(uid); 21306 } 21307 } 21308 21309 @Override 21310 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21311 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21312 synchronized (mPackages) { 21313 final long identity = Binder.clearCallingIdentity(); 21314 try { 21315 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21316 packageNames, userId); 21317 } finally { 21318 Binder.restoreCallingIdentity(identity); 21319 } 21320 } 21321 } 21322 21323 private static void enforceSystemOrPhoneCaller(String tag) { 21324 int callingUid = Binder.getCallingUid(); 21325 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21326 throw new SecurityException( 21327 "Cannot call " + tag + " from UID " + callingUid); 21328 } 21329 } 21330 21331 boolean isHistoricalPackageUsageAvailable() { 21332 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21333 } 21334 21335 /** 21336 * Return a <b>copy</b> of the collection of packages known to the package manager. 21337 * @return A copy of the values of mPackages. 21338 */ 21339 Collection<PackageParser.Package> getPackages() { 21340 synchronized (mPackages) { 21341 return new ArrayList<>(mPackages.values()); 21342 } 21343 } 21344 21345 /** 21346 * Logs process start information (including base APK hash) to the security log. 21347 * @hide 21348 */ 21349 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21350 String apkFile, int pid) { 21351 if (!SecurityLog.isLoggingEnabled()) { 21352 return; 21353 } 21354 Bundle data = new Bundle(); 21355 data.putLong("startTimestamp", System.currentTimeMillis()); 21356 data.putString("processName", processName); 21357 data.putInt("uid", uid); 21358 data.putString("seinfo", seinfo); 21359 data.putString("apkFile", apkFile); 21360 data.putInt("pid", pid); 21361 Message msg = mProcessLoggingHandler.obtainMessage( 21362 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21363 msg.setData(data); 21364 mProcessLoggingHandler.sendMessage(msg); 21365 } 21366 21367 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21368 return mCompilerStats.getPackageStats(pkgName); 21369 } 21370 21371 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21372 return getOrCreateCompilerPackageStats(pkg.packageName); 21373 } 21374 21375 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21376 return mCompilerStats.getOrCreatePackageStats(pkgName); 21377 } 21378 21379 public void deleteCompilerPackageStats(String pkgName) { 21380 mCompilerStats.deletePackageStats(pkgName); 21381 } 21382} 21383