PackageManagerService.java revision 2dc804be11444565e3d1d151c2a693db3ade94c0
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.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.ResourcesManager; 107import android.app.admin.IDevicePolicyManager; 108import android.app.admin.SecurityLog; 109import android.app.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.ContentResolver; 113import android.content.Context; 114import android.content.IIntentReceiver; 115import android.content.Intent; 116import android.content.IntentFilter; 117import android.content.IntentSender; 118import android.content.IntentSender.SendIntentException; 119import android.content.ServiceConnection; 120import android.content.pm.ActivityInfo; 121import android.content.pm.ApplicationInfo; 122import android.content.pm.AppsQueryHelper; 123import android.content.pm.ComponentInfo; 124import android.content.pm.EphemeralApplicationInfo; 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.IMountService; 196import android.os.storage.MountServiceInternal; 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.SomeArgs; 237import com.android.internal.os.Zygote; 238import com.android.internal.telephony.CarrierAppUtils; 239import com.android.internal.util.ArrayUtils; 240import com.android.internal.util.FastPrintWriter; 241import com.android.internal.util.FastXmlSerializer; 242import com.android.internal.util.IndentingPrintWriter; 243import com.android.internal.util.Preconditions; 244import com.android.internal.util.XmlUtils; 245import com.android.server.AttributeCache; 246import com.android.server.EventLogTags; 247import com.android.server.FgThread; 248import com.android.server.IntentResolver; 249import com.android.server.LocalServices; 250import com.android.server.ServiceThread; 251import com.android.server.SystemConfig; 252import com.android.server.Watchdog; 253import com.android.server.net.NetworkPolicyManagerInternal; 254import com.android.server.pm.PermissionsState.PermissionState; 255import com.android.server.pm.Settings.DatabaseVersion; 256import com.android.server.pm.Settings.VersionInfo; 257import com.android.server.storage.DeviceStorageMonitorInternal; 258 259import dalvik.system.CloseGuard; 260import dalvik.system.DexFile; 261import dalvik.system.VMRuntime; 262 263import libcore.io.IoUtils; 264import libcore.util.EmptyArray; 265 266import org.xmlpull.v1.XmlPullParser; 267import org.xmlpull.v1.XmlPullParserException; 268import org.xmlpull.v1.XmlSerializer; 269 270import java.io.BufferedOutputStream; 271import java.io.BufferedReader; 272import java.io.ByteArrayInputStream; 273import java.io.ByteArrayOutputStream; 274import java.io.File; 275import java.io.FileDescriptor; 276import java.io.FileInputStream; 277import java.io.FileNotFoundException; 278import java.io.FileOutputStream; 279import java.io.FileReader; 280import java.io.FilenameFilter; 281import java.io.IOException; 282import java.io.PrintWriter; 283import java.nio.charset.StandardCharsets; 284import java.security.DigestInputStream; 285import java.security.MessageDigest; 286import java.security.NoSuchAlgorithmException; 287import java.security.PublicKey; 288import java.security.cert.Certificate; 289import java.security.cert.CertificateEncodingException; 290import java.security.cert.CertificateException; 291import java.text.SimpleDateFormat; 292import java.util.ArrayList; 293import java.util.Arrays; 294import java.util.Collection; 295import java.util.Collections; 296import java.util.Comparator; 297import java.util.Date; 298import java.util.HashSet; 299import java.util.Iterator; 300import java.util.List; 301import java.util.Map; 302import java.util.Objects; 303import java.util.Set; 304import java.util.concurrent.CountDownLatch; 305import java.util.concurrent.TimeUnit; 306import java.util.concurrent.atomic.AtomicBoolean; 307import java.util.concurrent.atomic.AtomicInteger; 308 309/** 310 * Keep track of all those APKs everywhere. 311 * <p> 312 * Internally there are two important locks: 313 * <ul> 314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 315 * and other related state. It is a fine-grained lock that should only be held 316 * momentarily, as it's one of the most contended locks in the system. 317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 318 * operations typically involve heavy lifting of application data on disk. Since 319 * {@code installd} is single-threaded, and it's operations can often be slow, 320 * this lock should never be acquired while already holding {@link #mPackages}. 321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 322 * holding {@link #mInstallLock}. 323 * </ul> 324 * Many internal methods rely on the caller to hold the appropriate locks, and 325 * this contract is expressed through method name suffixes: 326 * <ul> 327 * <li>fooLI(): the caller must hold {@link #mInstallLock} 328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 329 * being modified must be frozen 330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 332 * </ul> 333 * <p> 334 * Because this class is very central to the platform's security; please run all 335 * CTS and unit tests whenever making modifications: 336 * 337 * <pre> 338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 340 * </pre> 341 */ 342public class PackageManagerService extends IPackageManager.Stub { 343 static final String TAG = "PackageManager"; 344 static final boolean DEBUG_SETTINGS = false; 345 static final boolean DEBUG_PREFERRED = false; 346 static final boolean DEBUG_UPGRADE = false; 347 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 348 private static final boolean DEBUG_BACKUP = false; 349 private static final boolean DEBUG_INSTALL = false; 350 private static final boolean DEBUG_REMOVE = false; 351 private static final boolean DEBUG_BROADCASTS = false; 352 private static final boolean DEBUG_SHOW_INFO = false; 353 private static final boolean DEBUG_PACKAGE_INFO = false; 354 private static final boolean DEBUG_INTENT_MATCHING = false; 355 private static final boolean DEBUG_PACKAGE_SCANNING = false; 356 private static final boolean DEBUG_VERIFY = false; 357 private static final boolean DEBUG_FILTERS = false; 358 359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 361 // user, but by default initialize to this. 362 static final boolean DEBUG_DEXOPT = false; 363 364 private static final boolean DEBUG_ABI_SELECTION = false; 365 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 366 private static final boolean DEBUG_TRIAGED_MISSING = false; 367 private static final boolean DEBUG_APP_DATA = false; 368 369 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 370 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 371 372 private static final boolean DISABLE_EPHEMERAL_APPS = false; 373 private static final boolean HIDE_EPHEMERAL_APIS = true; 374 375 private static final int RADIO_UID = Process.PHONE_UID; 376 private static final int LOG_UID = Process.LOG_UID; 377 private static final int NFC_UID = Process.NFC_UID; 378 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 379 private static final int SHELL_UID = Process.SHELL_UID; 380 381 // Cap the size of permission trees that 3rd party apps can define 382 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 383 384 // Suffix used during package installation when copying/moving 385 // package apks to install directory. 386 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 387 388 static final int SCAN_NO_DEX = 1<<1; 389 static final int SCAN_FORCE_DEX = 1<<2; 390 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 391 static final int SCAN_NEW_INSTALL = 1<<4; 392 static final int SCAN_NO_PATHS = 1<<5; 393 static final int SCAN_UPDATE_TIME = 1<<6; 394 static final int SCAN_DEFER_DEX = 1<<7; 395 static final int SCAN_BOOTING = 1<<8; 396 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 397 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 398 static final int SCAN_REPLACING = 1<<11; 399 static final int SCAN_REQUIRE_KNOWN = 1<<12; 400 static final int SCAN_MOVE = 1<<13; 401 static final int SCAN_INITIAL = 1<<14; 402 static final int SCAN_CHECK_ONLY = 1<<15; 403 static final int SCAN_DONT_KILL_APP = 1<<17; 404 static final int SCAN_IGNORE_FROZEN = 1<<18; 405 406 static final int REMOVE_CHATTY = 1<<16; 407 408 private static final int[] EMPTY_INT_ARRAY = new int[0]; 409 410 /** 411 * Timeout (in milliseconds) after which the watchdog should declare that 412 * our handler thread is wedged. The usual default for such things is one 413 * minute but we sometimes do very lengthy I/O operations on this thread, 414 * such as installing multi-gigabyte applications, so ours needs to be longer. 415 */ 416 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 417 418 /** 419 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 420 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 421 * settings entry if available, otherwise we use the hardcoded default. If it's been 422 * more than this long since the last fstrim, we force one during the boot sequence. 423 * 424 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 425 * one gets run at the next available charging+idle time. This final mandatory 426 * no-fstrim check kicks in only of the other scheduling criteria is never met. 427 */ 428 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 429 430 /** 431 * Whether verification is enabled by default. 432 */ 433 private static final boolean DEFAULT_VERIFY_ENABLE = true; 434 435 /** 436 * The default maximum time to wait for the verification agent to return in 437 * milliseconds. 438 */ 439 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 440 441 /** 442 * The default response for package verification timeout. 443 * 444 * This can be either PackageManager.VERIFICATION_ALLOW or 445 * PackageManager.VERIFICATION_REJECT. 446 */ 447 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 448 449 static final String PLATFORM_PACKAGE_NAME = "android"; 450 451 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 452 453 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 454 DEFAULT_CONTAINER_PACKAGE, 455 "com.android.defcontainer.DefaultContainerService"); 456 457 private static final String KILL_APP_REASON_GIDS_CHANGED = 458 "permission grant or revoke changed gids"; 459 460 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 461 "permissions revoked"; 462 463 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 464 465 private static final String PACKAGE_SCHEME = "package"; 466 467 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 468 /** 469 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 470 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 471 * VENDOR_OVERLAY_DIR. 472 */ 473 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 474 /** 475 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 476 * is in VENDOR_OVERLAY_THEME_PROPERTY. 477 */ 478 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 479 = "persist.vendor.overlay.theme"; 480 481 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 482 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 483 484 /** Permission grant: not grant the permission. */ 485 private static final int GRANT_DENIED = 1; 486 487 /** Permission grant: grant the permission as an install permission. */ 488 private static final int GRANT_INSTALL = 2; 489 490 /** Permission grant: grant the permission as a runtime one. */ 491 private static final int GRANT_RUNTIME = 3; 492 493 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 494 private static final int GRANT_UPGRADE = 4; 495 496 /** Canonical intent used to identify what counts as a "web browser" app */ 497 private static final Intent sBrowserIntent; 498 static { 499 sBrowserIntent = new Intent(); 500 sBrowserIntent.setAction(Intent.ACTION_VIEW); 501 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 502 sBrowserIntent.setData(Uri.parse("http:")); 503 } 504 505 /** 506 * The set of all protected actions [i.e. those actions for which a high priority 507 * intent filter is disallowed]. 508 */ 509 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 510 static { 511 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 512 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 513 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 514 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 515 } 516 517 // Compilation reasons. 518 public static final int REASON_FIRST_BOOT = 0; 519 public static final int REASON_BOOT = 1; 520 public static final int REASON_INSTALL = 2; 521 public static final int REASON_BACKGROUND_DEXOPT = 3; 522 public static final int REASON_AB_OTA = 4; 523 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 524 public static final int REASON_SHARED_APK = 6; 525 public static final int REASON_FORCED_DEXOPT = 7; 526 public static final int REASON_CORE_APP = 8; 527 528 public static final int REASON_LAST = REASON_CORE_APP; 529 530 /** Special library name that skips shared libraries check during compilation. */ 531 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 532 533 final ServiceThread mHandlerThread; 534 535 final PackageHandler mHandler; 536 537 private final ProcessLoggingHandler mProcessLoggingHandler; 538 539 /** 540 * Messages for {@link #mHandler} that need to wait for system ready before 541 * being dispatched. 542 */ 543 private ArrayList<Message> mPostSystemReadyMessages; 544 545 final int mSdkVersion = Build.VERSION.SDK_INT; 546 547 final Context mContext; 548 final boolean mFactoryTest; 549 final boolean mOnlyCore; 550 final DisplayMetrics mMetrics; 551 final int mDefParseFlags; 552 final String[] mSeparateProcesses; 553 final boolean mIsUpgrade; 554 final boolean mIsPreNUpgrade; 555 final boolean mIsPreNMR1Upgrade; 556 557 @GuardedBy("mPackages") 558 private boolean mDexOptDialogShown; 559 560 /** The location for ASEC container files on internal storage. */ 561 final String mAsecInternalPath; 562 563 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 564 // LOCK HELD. Can be called with mInstallLock held. 565 @GuardedBy("mInstallLock") 566 final Installer mInstaller; 567 568 /** Directory where installed third-party apps stored */ 569 final File mAppInstallDir; 570 final File mEphemeralInstallDir; 571 572 /** 573 * Directory to which applications installed internally have their 574 * 32 bit native libraries copied. 575 */ 576 private File mAppLib32InstallDir; 577 578 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 579 // apps. 580 final File mDrmAppPrivateInstallDir; 581 582 // ---------------------------------------------------------------- 583 584 // Lock for state used when installing and doing other long running 585 // operations. Methods that must be called with this lock held have 586 // the suffix "LI". 587 final Object mInstallLock = new Object(); 588 589 // ---------------------------------------------------------------- 590 591 // Keys are String (package name), values are Package. This also serves 592 // as the lock for the global state. Methods that must be called with 593 // this lock held have the prefix "LP". 594 @GuardedBy("mPackages") 595 final ArrayMap<String, PackageParser.Package> mPackages = 596 new ArrayMap<String, PackageParser.Package>(); 597 598 final ArrayMap<String, Set<String>> mKnownCodebase = 599 new ArrayMap<String, Set<String>>(); 600 601 // Tracks available target package names -> overlay package paths. 602 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 603 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 604 605 /** 606 * Tracks new system packages [received in an OTA] that we expect to 607 * find updated user-installed versions. Keys are package name, values 608 * are package location. 609 */ 610 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 611 /** 612 * Tracks high priority intent filters for protected actions. During boot, certain 613 * filter actions are protected and should never be allowed to have a high priority 614 * intent filter for them. However, there is one, and only one exception -- the 615 * setup wizard. It must be able to define a high priority intent filter for these 616 * actions to ensure there are no escapes from the wizard. We need to delay processing 617 * of these during boot as we need to look at all of the system packages in order 618 * to know which component is the setup wizard. 619 */ 620 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 621 /** 622 * Whether or not processing protected filters should be deferred. 623 */ 624 private boolean mDeferProtectedFilters = true; 625 626 /** 627 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 628 */ 629 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 630 /** 631 * Whether or not system app permissions should be promoted from install to runtime. 632 */ 633 boolean mPromoteSystemApps; 634 635 @GuardedBy("mPackages") 636 final Settings mSettings; 637 638 /** 639 * Set of package names that are currently "frozen", which means active 640 * surgery is being done on the code/data for that package. The platform 641 * will refuse to launch frozen packages to avoid race conditions. 642 * 643 * @see PackageFreezer 644 */ 645 @GuardedBy("mPackages") 646 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 647 648 final ProtectedPackages mProtectedPackages; 649 650 boolean mFirstBoot; 651 652 // System configuration read by SystemConfig. 653 final int[] mGlobalGids; 654 final SparseArray<ArraySet<String>> mSystemPermissions; 655 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 656 657 // If mac_permissions.xml was found for seinfo labeling. 658 boolean mFoundPolicyFile; 659 660 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 661 662 public static final class SharedLibraryEntry { 663 public final String path; 664 public final String apk; 665 666 SharedLibraryEntry(String _path, String _apk) { 667 path = _path; 668 apk = _apk; 669 } 670 } 671 672 // Currently known shared libraries. 673 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 674 new ArrayMap<String, SharedLibraryEntry>(); 675 676 // All available activities, for your resolving pleasure. 677 final ActivityIntentResolver mActivities = 678 new ActivityIntentResolver(); 679 680 // All available receivers, for your resolving pleasure. 681 final ActivityIntentResolver mReceivers = 682 new ActivityIntentResolver(); 683 684 // All available services, for your resolving pleasure. 685 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 686 687 // All available providers, for your resolving pleasure. 688 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 689 690 // Mapping from provider base names (first directory in content URI codePath) 691 // to the provider information. 692 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 693 new ArrayMap<String, PackageParser.Provider>(); 694 695 // Mapping from instrumentation class names to info about them. 696 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 697 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 698 699 // Mapping from permission names to info about them. 700 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 701 new ArrayMap<String, PackageParser.PermissionGroup>(); 702 703 // Packages whose data we have transfered into another package, thus 704 // should no longer exist. 705 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 706 707 // Broadcast actions that are only available to the system. 708 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 709 710 /** List of packages waiting for verification. */ 711 final SparseArray<PackageVerificationState> mPendingVerification 712 = new SparseArray<PackageVerificationState>(); 713 714 /** Set of packages associated with each app op permission. */ 715 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 716 717 final PackageInstallerService mInstallerService; 718 719 private final PackageDexOptimizer mPackageDexOptimizer; 720 721 private AtomicInteger mNextMoveId = new AtomicInteger(); 722 private final MoveCallbacks mMoveCallbacks; 723 724 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 725 726 // Cache of users who need badging. 727 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 728 729 /** Token for keys in mPendingVerification. */ 730 private int mPendingVerificationToken = 0; 731 732 volatile boolean mSystemReady; 733 volatile boolean mSafeMode; 734 volatile boolean mHasSystemUidErrors; 735 736 ApplicationInfo mAndroidApplication; 737 final ActivityInfo mResolveActivity = new ActivityInfo(); 738 final ResolveInfo mResolveInfo = new ResolveInfo(); 739 ComponentName mResolveComponentName; 740 PackageParser.Package mPlatformPackage; 741 ComponentName mCustomResolverComponentName; 742 743 boolean mResolverReplaced = false; 744 745 private final @Nullable ComponentName mIntentFilterVerifierComponent; 746 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 747 748 private int mIntentFilterVerificationToken = 0; 749 750 /** Component that knows whether or not an ephemeral application exists */ 751 final ComponentName mEphemeralResolverComponent; 752 /** The service connection to the ephemeral resolver */ 753 final EphemeralResolverConnection mEphemeralResolverConnection; 754 755 /** Component used to install ephemeral applications */ 756 final ComponentName mEphemeralInstallerComponent; 757 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 758 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 759 760 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 761 = new SparseArray<IntentFilterVerificationState>(); 762 763 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 764 765 // List of packages names to keep cached, even if they are uninstalled for all users 766 private List<String> mKeepUninstalledPackages; 767 768 private UserManagerInternal mUserManagerInternal; 769 770 private static class IFVerificationParams { 771 PackageParser.Package pkg; 772 boolean replacing; 773 int userId; 774 int verifierUid; 775 776 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 777 int _userId, int _verifierUid) { 778 pkg = _pkg; 779 replacing = _replacing; 780 userId = _userId; 781 replacing = _replacing; 782 verifierUid = _verifierUid; 783 } 784 } 785 786 private interface IntentFilterVerifier<T extends IntentFilter> { 787 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 788 T filter, String packageName); 789 void startVerifications(int userId); 790 void receiveVerificationResponse(int verificationId); 791 } 792 793 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 794 private Context mContext; 795 private ComponentName mIntentFilterVerifierComponent; 796 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 797 798 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 799 mContext = context; 800 mIntentFilterVerifierComponent = verifierComponent; 801 } 802 803 private String getDefaultScheme() { 804 return IntentFilter.SCHEME_HTTPS; 805 } 806 807 @Override 808 public void startVerifications(int userId) { 809 // Launch verifications requests 810 int count = mCurrentIntentFilterVerifications.size(); 811 for (int n=0; n<count; n++) { 812 int verificationId = mCurrentIntentFilterVerifications.get(n); 813 final IntentFilterVerificationState ivs = 814 mIntentFilterVerificationStates.get(verificationId); 815 816 String packageName = ivs.getPackageName(); 817 818 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 819 final int filterCount = filters.size(); 820 ArraySet<String> domainsSet = new ArraySet<>(); 821 for (int m=0; m<filterCount; m++) { 822 PackageParser.ActivityIntentInfo filter = filters.get(m); 823 domainsSet.addAll(filter.getHostsList()); 824 } 825 synchronized (mPackages) { 826 if (mSettings.createIntentFilterVerificationIfNeededLPw( 827 packageName, domainsSet) != null) { 828 scheduleWriteSettingsLocked(); 829 } 830 } 831 sendVerificationRequest(userId, verificationId, ivs); 832 } 833 mCurrentIntentFilterVerifications.clear(); 834 } 835 836 private void sendVerificationRequest(int userId, int verificationId, 837 IntentFilterVerificationState ivs) { 838 839 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 840 verificationIntent.putExtra( 841 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 842 verificationId); 843 verificationIntent.putExtra( 844 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 845 getDefaultScheme()); 846 verificationIntent.putExtra( 847 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 848 ivs.getHostsString()); 849 verificationIntent.putExtra( 850 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 851 ivs.getPackageName()); 852 verificationIntent.setComponent(mIntentFilterVerifierComponent); 853 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 854 855 UserHandle user = new UserHandle(userId); 856 mContext.sendBroadcastAsUser(verificationIntent, user); 857 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 858 "Sending IntentFilter verification broadcast"); 859 } 860 861 public void receiveVerificationResponse(int verificationId) { 862 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 863 864 final boolean verified = ivs.isVerified(); 865 866 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 867 final int count = filters.size(); 868 if (DEBUG_DOMAIN_VERIFICATION) { 869 Slog.i(TAG, "Received verification response " + verificationId 870 + " for " + count + " filters, verified=" + verified); 871 } 872 for (int n=0; n<count; n++) { 873 PackageParser.ActivityIntentInfo filter = filters.get(n); 874 filter.setVerified(verified); 875 876 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 877 + " verified with result:" + verified + " and hosts:" 878 + ivs.getHostsString()); 879 } 880 881 mIntentFilterVerificationStates.remove(verificationId); 882 883 final String packageName = ivs.getPackageName(); 884 IntentFilterVerificationInfo ivi = null; 885 886 synchronized (mPackages) { 887 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 888 } 889 if (ivi == null) { 890 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 891 + verificationId + " packageName:" + packageName); 892 return; 893 } 894 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 895 "Updating IntentFilterVerificationInfo for package " + packageName 896 +" verificationId:" + verificationId); 897 898 synchronized (mPackages) { 899 if (verified) { 900 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 901 } else { 902 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 903 } 904 scheduleWriteSettingsLocked(); 905 906 final int userId = ivs.getUserId(); 907 if (userId != UserHandle.USER_ALL) { 908 final int userStatus = 909 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 910 911 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 912 boolean needUpdate = false; 913 914 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 915 // already been set by the User thru the Disambiguation dialog 916 switch (userStatus) { 917 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 918 if (verified) { 919 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 920 } else { 921 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 922 } 923 needUpdate = true; 924 break; 925 926 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 927 if (verified) { 928 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 929 needUpdate = true; 930 } 931 break; 932 933 default: 934 // Nothing to do 935 } 936 937 if (needUpdate) { 938 mSettings.updateIntentFilterVerificationStatusLPw( 939 packageName, updatedStatus, userId); 940 scheduleWritePackageRestrictionsLocked(userId); 941 } 942 } 943 } 944 } 945 946 @Override 947 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 948 ActivityIntentInfo filter, String packageName) { 949 if (!hasValidDomains(filter)) { 950 return false; 951 } 952 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 953 if (ivs == null) { 954 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 955 packageName); 956 } 957 if (DEBUG_DOMAIN_VERIFICATION) { 958 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 959 } 960 ivs.addFilter(filter); 961 return true; 962 } 963 964 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 965 int userId, int verificationId, String packageName) { 966 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 967 verifierUid, userId, packageName); 968 ivs.setPendingState(); 969 synchronized (mPackages) { 970 mIntentFilterVerificationStates.append(verificationId, ivs); 971 mCurrentIntentFilterVerifications.add(verificationId); 972 } 973 return ivs; 974 } 975 } 976 977 private static boolean hasValidDomains(ActivityIntentInfo filter) { 978 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 979 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 980 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 981 } 982 983 // Set of pending broadcasts for aggregating enable/disable of components. 984 static class PendingPackageBroadcasts { 985 // for each user id, a map of <package name -> components within that package> 986 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 987 988 public PendingPackageBroadcasts() { 989 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 990 } 991 992 public ArrayList<String> get(int userId, String packageName) { 993 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 994 return packages.get(packageName); 995 } 996 997 public void put(int userId, String packageName, ArrayList<String> components) { 998 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 999 packages.put(packageName, components); 1000 } 1001 1002 public void remove(int userId, String packageName) { 1003 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1004 if (packages != null) { 1005 packages.remove(packageName); 1006 } 1007 } 1008 1009 public void remove(int userId) { 1010 mUidMap.remove(userId); 1011 } 1012 1013 public int userIdCount() { 1014 return mUidMap.size(); 1015 } 1016 1017 public int userIdAt(int n) { 1018 return mUidMap.keyAt(n); 1019 } 1020 1021 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1022 return mUidMap.get(userId); 1023 } 1024 1025 public int size() { 1026 // total number of pending broadcast entries across all userIds 1027 int num = 0; 1028 for (int i = 0; i< mUidMap.size(); i++) { 1029 num += mUidMap.valueAt(i).size(); 1030 } 1031 return num; 1032 } 1033 1034 public void clear() { 1035 mUidMap.clear(); 1036 } 1037 1038 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1039 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1040 if (map == null) { 1041 map = new ArrayMap<String, ArrayList<String>>(); 1042 mUidMap.put(userId, map); 1043 } 1044 return map; 1045 } 1046 } 1047 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1048 1049 // Service Connection to remote media container service to copy 1050 // package uri's from external media onto secure containers 1051 // or internal storage. 1052 private IMediaContainerService mContainerService = null; 1053 1054 static final int SEND_PENDING_BROADCAST = 1; 1055 static final int MCS_BOUND = 3; 1056 static final int END_COPY = 4; 1057 static final int INIT_COPY = 5; 1058 static final int MCS_UNBIND = 6; 1059 static final int START_CLEANING_PACKAGE = 7; 1060 static final int FIND_INSTALL_LOC = 8; 1061 static final int POST_INSTALL = 9; 1062 static final int MCS_RECONNECT = 10; 1063 static final int MCS_GIVE_UP = 11; 1064 static final int UPDATED_MEDIA_STATUS = 12; 1065 static final int WRITE_SETTINGS = 13; 1066 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1067 static final int PACKAGE_VERIFIED = 15; 1068 static final int CHECK_PENDING_VERIFICATION = 16; 1069 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1070 static final int INTENT_FILTER_VERIFIED = 18; 1071 static final int WRITE_PACKAGE_LIST = 19; 1072 1073 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1074 1075 // Delay time in millisecs 1076 static final int BROADCAST_DELAY = 10 * 1000; 1077 1078 static UserManagerService sUserManager; 1079 1080 // Stores a list of users whose package restrictions file needs to be updated 1081 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1082 1083 final private DefaultContainerConnection mDefContainerConn = 1084 new DefaultContainerConnection(); 1085 class DefaultContainerConnection implements ServiceConnection { 1086 public void onServiceConnected(ComponentName name, IBinder service) { 1087 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1088 IMediaContainerService imcs = 1089 IMediaContainerService.Stub.asInterface(service); 1090 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1091 } 1092 1093 public void onServiceDisconnected(ComponentName name) { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1095 } 1096 } 1097 1098 // Recordkeeping of restore-after-install operations that are currently in flight 1099 // between the Package Manager and the Backup Manager 1100 static class PostInstallData { 1101 public InstallArgs args; 1102 public PackageInstalledInfo res; 1103 1104 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1105 args = _a; 1106 res = _r; 1107 } 1108 } 1109 1110 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1111 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1112 1113 // XML tags for backup/restore of various bits of state 1114 private static final String TAG_PREFERRED_BACKUP = "pa"; 1115 private static final String TAG_DEFAULT_APPS = "da"; 1116 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1117 1118 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1119 private static final String TAG_ALL_GRANTS = "rt-grants"; 1120 private static final String TAG_GRANT = "grant"; 1121 private static final String ATTR_PACKAGE_NAME = "pkg"; 1122 1123 private static final String TAG_PERMISSION = "perm"; 1124 private static final String ATTR_PERMISSION_NAME = "name"; 1125 private static final String ATTR_IS_GRANTED = "g"; 1126 private static final String ATTR_USER_SET = "set"; 1127 private static final String ATTR_USER_FIXED = "fixed"; 1128 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1129 1130 // System/policy permission grants are not backed up 1131 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1132 FLAG_PERMISSION_POLICY_FIXED 1133 | FLAG_PERMISSION_SYSTEM_FIXED 1134 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1135 1136 // And we back up these user-adjusted states 1137 private static final int USER_RUNTIME_GRANT_MASK = 1138 FLAG_PERMISSION_USER_SET 1139 | FLAG_PERMISSION_USER_FIXED 1140 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1141 1142 final @Nullable String mRequiredVerifierPackage; 1143 final @NonNull String mRequiredInstallerPackage; 1144 final @NonNull String mRequiredUninstallerPackage; 1145 final @Nullable String mSetupWizardPackage; 1146 final @Nullable String mStorageManagerPackage; 1147 final @NonNull String mServicesSystemSharedLibraryPackageName; 1148 final @NonNull String mSharedSystemSharedLibraryPackageName; 1149 1150 final boolean mPermissionReviewRequired; 1151 1152 private final PackageUsage mPackageUsage = new PackageUsage(); 1153 private final CompilerStats mCompilerStats = new CompilerStats(); 1154 1155 class PackageHandler extends Handler { 1156 private boolean mBound = false; 1157 final ArrayList<HandlerParams> mPendingInstalls = 1158 new ArrayList<HandlerParams>(); 1159 1160 private boolean connectToService() { 1161 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1162 " DefaultContainerService"); 1163 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1164 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1165 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1166 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1167 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1168 mBound = true; 1169 return true; 1170 } 1171 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1172 return false; 1173 } 1174 1175 private void disconnectService() { 1176 mContainerService = null; 1177 mBound = false; 1178 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1179 mContext.unbindService(mDefContainerConn); 1180 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1181 } 1182 1183 PackageHandler(Looper looper) { 1184 super(looper); 1185 } 1186 1187 public void handleMessage(Message msg) { 1188 try { 1189 doHandleMessage(msg); 1190 } finally { 1191 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1192 } 1193 } 1194 1195 void doHandleMessage(Message msg) { 1196 switch (msg.what) { 1197 case INIT_COPY: { 1198 HandlerParams params = (HandlerParams) msg.obj; 1199 int idx = mPendingInstalls.size(); 1200 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1201 // If a bind was already initiated we dont really 1202 // need to do anything. The pending install 1203 // will be processed later on. 1204 if (!mBound) { 1205 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1206 System.identityHashCode(mHandler)); 1207 // If this is the only one pending we might 1208 // have to bind to the service again. 1209 if (!connectToService()) { 1210 Slog.e(TAG, "Failed to bind to media container service"); 1211 params.serviceError(); 1212 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1213 System.identityHashCode(mHandler)); 1214 if (params.traceMethod != null) { 1215 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1216 params.traceCookie); 1217 } 1218 return; 1219 } else { 1220 // Once we bind to the service, the first 1221 // pending request will be processed. 1222 mPendingInstalls.add(idx, params); 1223 } 1224 } else { 1225 mPendingInstalls.add(idx, params); 1226 // Already bound to the service. Just make 1227 // sure we trigger off processing the first request. 1228 if (idx == 0) { 1229 mHandler.sendEmptyMessage(MCS_BOUND); 1230 } 1231 } 1232 break; 1233 } 1234 case MCS_BOUND: { 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1236 if (msg.obj != null) { 1237 mContainerService = (IMediaContainerService) msg.obj; 1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1239 System.identityHashCode(mHandler)); 1240 } 1241 if (mContainerService == null) { 1242 if (!mBound) { 1243 // Something seriously wrong since we are not bound and we are not 1244 // waiting for connection. Bail out. 1245 Slog.e(TAG, "Cannot bind to media container service"); 1246 for (HandlerParams params : mPendingInstalls) { 1247 // Indicate service bind error 1248 params.serviceError(); 1249 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1250 System.identityHashCode(params)); 1251 if (params.traceMethod != null) { 1252 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1253 params.traceMethod, params.traceCookie); 1254 } 1255 return; 1256 } 1257 mPendingInstalls.clear(); 1258 } else { 1259 Slog.w(TAG, "Waiting to connect to media container service"); 1260 } 1261 } else if (mPendingInstalls.size() > 0) { 1262 HandlerParams params = mPendingInstalls.get(0); 1263 if (params != null) { 1264 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1265 System.identityHashCode(params)); 1266 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1267 if (params.startCopy()) { 1268 // We are done... look for more work or to 1269 // go idle. 1270 if (DEBUG_SD_INSTALL) Log.i(TAG, 1271 "Checking for more work or unbind..."); 1272 // Delete pending install 1273 if (mPendingInstalls.size() > 0) { 1274 mPendingInstalls.remove(0); 1275 } 1276 if (mPendingInstalls.size() == 0) { 1277 if (mBound) { 1278 if (DEBUG_SD_INSTALL) Log.i(TAG, 1279 "Posting delayed MCS_UNBIND"); 1280 removeMessages(MCS_UNBIND); 1281 Message ubmsg = obtainMessage(MCS_UNBIND); 1282 // Unbind after a little delay, to avoid 1283 // continual thrashing. 1284 sendMessageDelayed(ubmsg, 10000); 1285 } 1286 } else { 1287 // There are more pending requests in queue. 1288 // Just post MCS_BOUND message to trigger processing 1289 // of next pending install. 1290 if (DEBUG_SD_INSTALL) Log.i(TAG, 1291 "Posting MCS_BOUND for next work"); 1292 mHandler.sendEmptyMessage(MCS_BOUND); 1293 } 1294 } 1295 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1296 } 1297 } else { 1298 // Should never happen ideally. 1299 Slog.w(TAG, "Empty queue"); 1300 } 1301 break; 1302 } 1303 case MCS_RECONNECT: { 1304 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1305 if (mPendingInstalls.size() > 0) { 1306 if (mBound) { 1307 disconnectService(); 1308 } 1309 if (!connectToService()) { 1310 Slog.e(TAG, "Failed to bind to media container service"); 1311 for (HandlerParams params : mPendingInstalls) { 1312 // Indicate service bind error 1313 params.serviceError(); 1314 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1315 System.identityHashCode(params)); 1316 } 1317 mPendingInstalls.clear(); 1318 } 1319 } 1320 break; 1321 } 1322 case MCS_UNBIND: { 1323 // If there is no actual work left, then time to unbind. 1324 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1325 1326 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1327 if (mBound) { 1328 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1329 1330 disconnectService(); 1331 } 1332 } else if (mPendingInstalls.size() > 0) { 1333 // There are more pending requests in queue. 1334 // Just post MCS_BOUND message to trigger processing 1335 // of next pending install. 1336 mHandler.sendEmptyMessage(MCS_BOUND); 1337 } 1338 1339 break; 1340 } 1341 case MCS_GIVE_UP: { 1342 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1343 HandlerParams params = mPendingInstalls.remove(0); 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1345 System.identityHashCode(params)); 1346 break; 1347 } 1348 case SEND_PENDING_BROADCAST: { 1349 String packages[]; 1350 ArrayList<String> components[]; 1351 int size = 0; 1352 int uids[]; 1353 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1354 synchronized (mPackages) { 1355 if (mPendingBroadcasts == null) { 1356 return; 1357 } 1358 size = mPendingBroadcasts.size(); 1359 if (size <= 0) { 1360 // Nothing to be done. Just return 1361 return; 1362 } 1363 packages = new String[size]; 1364 components = new ArrayList[size]; 1365 uids = new int[size]; 1366 int i = 0; // filling out the above arrays 1367 1368 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1369 int packageUserId = mPendingBroadcasts.userIdAt(n); 1370 Iterator<Map.Entry<String, ArrayList<String>>> it 1371 = mPendingBroadcasts.packagesForUserId(packageUserId) 1372 .entrySet().iterator(); 1373 while (it.hasNext() && i < size) { 1374 Map.Entry<String, ArrayList<String>> ent = it.next(); 1375 packages[i] = ent.getKey(); 1376 components[i] = ent.getValue(); 1377 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1378 uids[i] = (ps != null) 1379 ? UserHandle.getUid(packageUserId, ps.appId) 1380 : -1; 1381 i++; 1382 } 1383 } 1384 size = i; 1385 mPendingBroadcasts.clear(); 1386 } 1387 // Send broadcasts 1388 for (int i = 0; i < size; i++) { 1389 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1390 } 1391 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1392 break; 1393 } 1394 case START_CLEANING_PACKAGE: { 1395 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1396 final String packageName = (String)msg.obj; 1397 final int userId = msg.arg1; 1398 final boolean andCode = msg.arg2 != 0; 1399 synchronized (mPackages) { 1400 if (userId == UserHandle.USER_ALL) { 1401 int[] users = sUserManager.getUserIds(); 1402 for (int user : users) { 1403 mSettings.addPackageToCleanLPw( 1404 new PackageCleanItem(user, packageName, andCode)); 1405 } 1406 } else { 1407 mSettings.addPackageToCleanLPw( 1408 new PackageCleanItem(userId, packageName, andCode)); 1409 } 1410 } 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 startCleaningPackages(); 1413 } break; 1414 case POST_INSTALL: { 1415 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1416 1417 PostInstallData data = mRunningInstalls.get(msg.arg1); 1418 final boolean didRestore = (msg.arg2 != 0); 1419 mRunningInstalls.delete(msg.arg1); 1420 1421 if (data != null) { 1422 InstallArgs args = data.args; 1423 PackageInstalledInfo parentRes = data.res; 1424 1425 final boolean grantPermissions = (args.installFlags 1426 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1427 final boolean killApp = (args.installFlags 1428 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1429 final String[] grantedPermissions = args.installGrantPermissions; 1430 1431 // Handle the parent package 1432 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1433 grantedPermissions, didRestore, args.installerPackageName, 1434 args.observer); 1435 1436 // Handle the child packages 1437 final int childCount = (parentRes.addedChildPackages != null) 1438 ? parentRes.addedChildPackages.size() : 0; 1439 for (int i = 0; i < childCount; i++) { 1440 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1441 handlePackagePostInstall(childRes, grantPermissions, killApp, 1442 grantedPermissions, false, args.installerPackageName, 1443 args.observer); 1444 } 1445 1446 // Log tracing if needed 1447 if (args.traceMethod != null) { 1448 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1449 args.traceCookie); 1450 } 1451 } else { 1452 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1453 } 1454 1455 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1456 } break; 1457 case UPDATED_MEDIA_STATUS: { 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1459 boolean reportStatus = msg.arg1 == 1; 1460 boolean doGc = msg.arg2 == 1; 1461 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1462 if (doGc) { 1463 // Force a gc to clear up stale containers. 1464 Runtime.getRuntime().gc(); 1465 } 1466 if (msg.obj != null) { 1467 @SuppressWarnings("unchecked") 1468 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1469 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1470 // Unload containers 1471 unloadAllContainers(args); 1472 } 1473 if (reportStatus) { 1474 try { 1475 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1476 PackageHelper.getMountService().finishMediaUpdate(); 1477 } catch (RemoteException e) { 1478 Log.e(TAG, "MountService not running?"); 1479 } 1480 } 1481 } break; 1482 case WRITE_SETTINGS: { 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1484 synchronized (mPackages) { 1485 removeMessages(WRITE_SETTINGS); 1486 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1487 mSettings.writeLPr(); 1488 mDirtyUsers.clear(); 1489 } 1490 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1491 } break; 1492 case WRITE_PACKAGE_RESTRICTIONS: { 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1494 synchronized (mPackages) { 1495 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1496 for (int userId : mDirtyUsers) { 1497 mSettings.writePackageRestrictionsLPr(userId); 1498 } 1499 mDirtyUsers.clear(); 1500 } 1501 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1502 } break; 1503 case WRITE_PACKAGE_LIST: { 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1505 synchronized (mPackages) { 1506 removeMessages(WRITE_PACKAGE_LIST); 1507 mSettings.writePackageListLPr(msg.arg1); 1508 } 1509 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1510 } break; 1511 case CHECK_PENDING_VERIFICATION: { 1512 final int verificationId = msg.arg1; 1513 final PackageVerificationState state = mPendingVerification.get(verificationId); 1514 1515 if ((state != null) && !state.timeoutExtended()) { 1516 final InstallArgs args = state.getInstallArgs(); 1517 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1518 1519 Slog.i(TAG, "Verification timed out for " + originUri); 1520 mPendingVerification.remove(verificationId); 1521 1522 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1523 1524 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1525 Slog.i(TAG, "Continuing with installation of " + originUri); 1526 state.setVerifierResponse(Binder.getCallingUid(), 1527 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1528 broadcastPackageVerified(verificationId, originUri, 1529 PackageManager.VERIFICATION_ALLOW, 1530 state.getInstallArgs().getUser()); 1531 try { 1532 ret = args.copyApk(mContainerService, true); 1533 } catch (RemoteException e) { 1534 Slog.e(TAG, "Could not contact the ContainerService"); 1535 } 1536 } else { 1537 broadcastPackageVerified(verificationId, originUri, 1538 PackageManager.VERIFICATION_REJECT, 1539 state.getInstallArgs().getUser()); 1540 } 1541 1542 Trace.asyncTraceEnd( 1543 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1544 1545 processPendingInstall(args, ret); 1546 mHandler.sendEmptyMessage(MCS_UNBIND); 1547 } 1548 break; 1549 } 1550 case PACKAGE_VERIFIED: { 1551 final int verificationId = msg.arg1; 1552 1553 final PackageVerificationState state = mPendingVerification.get(verificationId); 1554 if (state == null) { 1555 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1556 break; 1557 } 1558 1559 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1560 1561 state.setVerifierResponse(response.callerUid, response.code); 1562 1563 if (state.isVerificationComplete()) { 1564 mPendingVerification.remove(verificationId); 1565 1566 final InstallArgs args = state.getInstallArgs(); 1567 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1568 1569 int ret; 1570 if (state.isInstallAllowed()) { 1571 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1572 broadcastPackageVerified(verificationId, originUri, 1573 response.code, state.getInstallArgs().getUser()); 1574 try { 1575 ret = args.copyApk(mContainerService, true); 1576 } catch (RemoteException e) { 1577 Slog.e(TAG, "Could not contact the ContainerService"); 1578 } 1579 } else { 1580 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1581 } 1582 1583 Trace.asyncTraceEnd( 1584 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1585 1586 processPendingInstall(args, ret); 1587 mHandler.sendEmptyMessage(MCS_UNBIND); 1588 } 1589 1590 break; 1591 } 1592 case START_INTENT_FILTER_VERIFICATIONS: { 1593 IFVerificationParams params = (IFVerificationParams) msg.obj; 1594 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1595 params.replacing, params.pkg); 1596 break; 1597 } 1598 case INTENT_FILTER_VERIFIED: { 1599 final int verificationId = msg.arg1; 1600 1601 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1602 verificationId); 1603 if (state == null) { 1604 Slog.w(TAG, "Invalid IntentFilter verification token " 1605 + verificationId + " received"); 1606 break; 1607 } 1608 1609 final int userId = state.getUserId(); 1610 1611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1612 "Processing IntentFilter verification with token:" 1613 + verificationId + " and userId:" + userId); 1614 1615 final IntentFilterVerificationResponse response = 1616 (IntentFilterVerificationResponse) msg.obj; 1617 1618 state.setVerifierResponse(response.callerUid, response.code); 1619 1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1621 "IntentFilter verification with token:" + verificationId 1622 + " and userId:" + userId 1623 + " is settings verifier response with response code:" 1624 + response.code); 1625 1626 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1628 + response.getFailedDomainsString()); 1629 } 1630 1631 if (state.isVerificationComplete()) { 1632 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1633 } else { 1634 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1635 "IntentFilter verification with token:" + verificationId 1636 + " was not said to be complete"); 1637 } 1638 1639 break; 1640 } 1641 } 1642 } 1643 } 1644 1645 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1646 boolean killApp, String[] grantedPermissions, 1647 boolean launchedForRestore, String installerPackage, 1648 IPackageInstallObserver2 installObserver) { 1649 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1650 // Send the removed broadcasts 1651 if (res.removedInfo != null) { 1652 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1653 } 1654 1655 // Now that we successfully installed the package, grant runtime 1656 // permissions if requested before broadcasting the install. 1657 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1658 >= Build.VERSION_CODES.M) { 1659 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1660 } 1661 1662 final boolean update = res.removedInfo != null 1663 && res.removedInfo.removedPackage != null; 1664 1665 // If this is the first time we have child packages for a disabled privileged 1666 // app that had no children, we grant requested runtime permissions to the new 1667 // children if the parent on the system image had them already granted. 1668 if (res.pkg.parentPackage != null) { 1669 synchronized (mPackages) { 1670 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1671 } 1672 } 1673 1674 synchronized (mPackages) { 1675 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1676 } 1677 1678 final String packageName = res.pkg.applicationInfo.packageName; 1679 1680 // Determine the set of users who are adding this package for 1681 // the first time vs. those who are seeing an update. 1682 int[] firstUsers = EMPTY_INT_ARRAY; 1683 int[] updateUsers = EMPTY_INT_ARRAY; 1684 if (res.origUsers == null || res.origUsers.length == 0) { 1685 firstUsers = res.newUsers; 1686 } else { 1687 for (int newUser : res.newUsers) { 1688 boolean isNew = true; 1689 for (int origUser : res.origUsers) { 1690 if (origUser == newUser) { 1691 isNew = false; 1692 break; 1693 } 1694 } 1695 if (isNew) { 1696 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1697 } else { 1698 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1699 } 1700 } 1701 } 1702 1703 // Send installed broadcasts if the install/update is not ephemeral 1704 if (!isEphemeral(res.pkg)) { 1705 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1706 1707 // Send added for users that see the package for the first time 1708 // sendPackageAddedForNewUsers also deals with system apps 1709 int appId = UserHandle.getAppId(res.uid); 1710 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1711 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1712 1713 // Send added for users that don't see the package for the first time 1714 Bundle extras = new Bundle(1); 1715 extras.putInt(Intent.EXTRA_UID, res.uid); 1716 if (update) { 1717 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1718 } 1719 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1720 extras, 0 /*flags*/, null /*targetPackage*/, 1721 null /*finishedReceiver*/, updateUsers); 1722 1723 // Send replaced for users that don't see the package for the first time 1724 if (update) { 1725 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1726 packageName, extras, 0 /*flags*/, 1727 null /*targetPackage*/, null /*finishedReceiver*/, 1728 updateUsers); 1729 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1730 null /*package*/, null /*extras*/, 0 /*flags*/, 1731 packageName /*targetPackage*/, 1732 null /*finishedReceiver*/, updateUsers); 1733 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1734 // First-install and we did a restore, so we're responsible for the 1735 // first-launch broadcast. 1736 if (DEBUG_BACKUP) { 1737 Slog.i(TAG, "Post-restore of " + packageName 1738 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1739 } 1740 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1741 } 1742 1743 // Send broadcast package appeared if forward locked/external for all users 1744 // treat asec-hosted packages like removable media on upgrade 1745 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1746 if (DEBUG_INSTALL) { 1747 Slog.i(TAG, "upgrading pkg " + res.pkg 1748 + " is ASEC-hosted -> AVAILABLE"); 1749 } 1750 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1751 ArrayList<String> pkgList = new ArrayList<>(1); 1752 pkgList.add(packageName); 1753 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1754 } 1755 } 1756 1757 // Work that needs to happen on first install within each user 1758 if (firstUsers != null && firstUsers.length > 0) { 1759 synchronized (mPackages) { 1760 for (int userId : firstUsers) { 1761 // If this app is a browser and it's newly-installed for some 1762 // users, clear any default-browser state in those users. The 1763 // app's nature doesn't depend on the user, so we can just check 1764 // its browser nature in any user and generalize. 1765 if (packageIsBrowser(packageName, userId)) { 1766 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1767 } 1768 1769 // We may also need to apply pending (restored) runtime 1770 // permission grants within these users. 1771 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1772 } 1773 } 1774 } 1775 1776 // Log current value of "unknown sources" setting 1777 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1778 getUnknownSourcesSettings()); 1779 1780 // Force a gc to clear up things 1781 Runtime.getRuntime().gc(); 1782 1783 // Remove the replaced package's older resources safely now 1784 // We delete after a gc for applications on sdcard. 1785 if (res.removedInfo != null && res.removedInfo.args != null) { 1786 synchronized (mInstallLock) { 1787 res.removedInfo.args.doPostDeleteLI(true); 1788 } 1789 } 1790 } 1791 1792 // If someone is watching installs - notify them 1793 if (installObserver != null) { 1794 try { 1795 Bundle extras = extrasForInstallResult(res); 1796 installObserver.onPackageInstalled(res.name, res.returnCode, 1797 res.returnMsg, extras); 1798 } catch (RemoteException e) { 1799 Slog.i(TAG, "Observer no longer exists."); 1800 } 1801 } 1802 } 1803 1804 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1805 PackageParser.Package pkg) { 1806 if (pkg.parentPackage == null) { 1807 return; 1808 } 1809 if (pkg.requestedPermissions == null) { 1810 return; 1811 } 1812 final PackageSetting disabledSysParentPs = mSettings 1813 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1814 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1815 || !disabledSysParentPs.isPrivileged() 1816 || (disabledSysParentPs.childPackageNames != null 1817 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1818 return; 1819 } 1820 final int[] allUserIds = sUserManager.getUserIds(); 1821 final int permCount = pkg.requestedPermissions.size(); 1822 for (int i = 0; i < permCount; i++) { 1823 String permission = pkg.requestedPermissions.get(i); 1824 BasePermission bp = mSettings.mPermissions.get(permission); 1825 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1826 continue; 1827 } 1828 for (int userId : allUserIds) { 1829 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1830 permission, userId)) { 1831 grantRuntimePermission(pkg.packageName, permission, userId); 1832 } 1833 } 1834 } 1835 } 1836 1837 private StorageEventListener mStorageListener = new StorageEventListener() { 1838 @Override 1839 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1840 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1841 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1842 final String volumeUuid = vol.getFsUuid(); 1843 1844 // Clean up any users or apps that were removed or recreated 1845 // while this volume was missing 1846 reconcileUsers(volumeUuid); 1847 reconcileApps(volumeUuid); 1848 1849 // Clean up any install sessions that expired or were 1850 // cancelled while this volume was missing 1851 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1852 1853 loadPrivatePackages(vol); 1854 1855 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1856 unloadPrivatePackages(vol); 1857 } 1858 } 1859 1860 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1861 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1862 updateExternalMediaStatus(true, false); 1863 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1864 updateExternalMediaStatus(false, false); 1865 } 1866 } 1867 } 1868 1869 @Override 1870 public void onVolumeForgotten(String fsUuid) { 1871 if (TextUtils.isEmpty(fsUuid)) { 1872 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1873 return; 1874 } 1875 1876 // Remove any apps installed on the forgotten volume 1877 synchronized (mPackages) { 1878 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1879 for (PackageSetting ps : packages) { 1880 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1881 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1882 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1883 } 1884 1885 mSettings.onVolumeForgotten(fsUuid); 1886 mSettings.writeLPr(); 1887 } 1888 } 1889 }; 1890 1891 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1892 String[] grantedPermissions) { 1893 for (int userId : userIds) { 1894 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1895 } 1896 1897 // We could have touched GID membership, so flush out packages.list 1898 synchronized (mPackages) { 1899 mSettings.writePackageListLPr(); 1900 } 1901 } 1902 1903 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1904 String[] grantedPermissions) { 1905 SettingBase sb = (SettingBase) pkg.mExtras; 1906 if (sb == null) { 1907 return; 1908 } 1909 1910 PermissionsState permissionsState = sb.getPermissionsState(); 1911 1912 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1913 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1914 1915 for (String permission : pkg.requestedPermissions) { 1916 final BasePermission bp; 1917 synchronized (mPackages) { 1918 bp = mSettings.mPermissions.get(permission); 1919 } 1920 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1921 && (grantedPermissions == null 1922 || ArrayUtils.contains(grantedPermissions, permission))) { 1923 final int flags = permissionsState.getPermissionFlags(permission, userId); 1924 // Installer cannot change immutable permissions. 1925 if ((flags & immutableFlags) == 0) { 1926 grantRuntimePermission(pkg.packageName, permission, userId); 1927 } 1928 } 1929 } 1930 } 1931 1932 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1933 Bundle extras = null; 1934 switch (res.returnCode) { 1935 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1936 extras = new Bundle(); 1937 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1938 res.origPermission); 1939 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1940 res.origPackage); 1941 break; 1942 } 1943 case PackageManager.INSTALL_SUCCEEDED: { 1944 extras = new Bundle(); 1945 extras.putBoolean(Intent.EXTRA_REPLACING, 1946 res.removedInfo != null && res.removedInfo.removedPackage != null); 1947 break; 1948 } 1949 } 1950 return extras; 1951 } 1952 1953 void scheduleWriteSettingsLocked() { 1954 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1955 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1956 } 1957 } 1958 1959 void scheduleWritePackageListLocked(int userId) { 1960 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1961 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1962 msg.arg1 = userId; 1963 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1964 } 1965 } 1966 1967 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1968 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1969 scheduleWritePackageRestrictionsLocked(userId); 1970 } 1971 1972 void scheduleWritePackageRestrictionsLocked(int userId) { 1973 final int[] userIds = (userId == UserHandle.USER_ALL) 1974 ? sUserManager.getUserIds() : new int[]{userId}; 1975 for (int nextUserId : userIds) { 1976 if (!sUserManager.exists(nextUserId)) return; 1977 mDirtyUsers.add(nextUserId); 1978 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1979 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1980 } 1981 } 1982 } 1983 1984 public static PackageManagerService main(Context context, Installer installer, 1985 boolean factoryTest, boolean onlyCore) { 1986 // Self-check for initial settings. 1987 PackageManagerServiceCompilerMapping.checkProperties(); 1988 1989 PackageManagerService m = new PackageManagerService(context, installer, 1990 factoryTest, onlyCore); 1991 m.enableSystemUserPackages(); 1992 ServiceManager.addService("package", m); 1993 return m; 1994 } 1995 1996 private void enableSystemUserPackages() { 1997 if (!UserManager.isSplitSystemUser()) { 1998 return; 1999 } 2000 // For system user, enable apps based on the following conditions: 2001 // - app is whitelisted or belong to one of these groups: 2002 // -- system app which has no launcher icons 2003 // -- system app which has INTERACT_ACROSS_USERS permission 2004 // -- system IME app 2005 // - app is not in the blacklist 2006 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2007 Set<String> enableApps = new ArraySet<>(); 2008 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2009 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2010 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2011 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2012 enableApps.addAll(wlApps); 2013 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2014 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2015 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2016 enableApps.removeAll(blApps); 2017 Log.i(TAG, "Applications installed for system user: " + enableApps); 2018 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2019 UserHandle.SYSTEM); 2020 final int allAppsSize = allAps.size(); 2021 synchronized (mPackages) { 2022 for (int i = 0; i < allAppsSize; i++) { 2023 String pName = allAps.get(i); 2024 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2025 // Should not happen, but we shouldn't be failing if it does 2026 if (pkgSetting == null) { 2027 continue; 2028 } 2029 boolean install = enableApps.contains(pName); 2030 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2031 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2032 + " for system user"); 2033 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2034 } 2035 } 2036 } 2037 } 2038 2039 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2040 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2041 Context.DISPLAY_SERVICE); 2042 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2043 } 2044 2045 /** 2046 * Requests that files preopted on a secondary system partition be copied to the data partition 2047 * if possible. Note that the actual copying of the files is accomplished by init for security 2048 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2049 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2050 */ 2051 private static void requestCopyPreoptedFiles() { 2052 final int WAIT_TIME_MS = 100; 2053 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2054 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2055 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2056 // We will wait for up to 100 seconds. 2057 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2058 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2059 try { 2060 Thread.sleep(WAIT_TIME_MS); 2061 } catch (InterruptedException e) { 2062 // Do nothing 2063 } 2064 if (SystemClock.uptimeMillis() > timeEnd) { 2065 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2066 Slog.wtf(TAG, "cppreopt did not finish!"); 2067 break; 2068 } 2069 } 2070 } 2071 } 2072 2073 public PackageManagerService(Context context, Installer installer, 2074 boolean factoryTest, boolean onlyCore) { 2075 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2076 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2077 SystemClock.uptimeMillis()); 2078 2079 if (mSdkVersion <= 0) { 2080 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2081 } 2082 2083 mContext = context; 2084 2085 mPermissionReviewRequired = context.getResources().getBoolean( 2086 R.bool.config_permissionReviewRequired); 2087 2088 mFactoryTest = factoryTest; 2089 mOnlyCore = onlyCore; 2090 mMetrics = new DisplayMetrics(); 2091 mSettings = new Settings(mPackages); 2092 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2093 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2094 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2095 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2096 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2097 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2098 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2099 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2100 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2101 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2102 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2103 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2104 2105 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2106 if (separateProcesses != null && separateProcesses.length() > 0) { 2107 if ("*".equals(separateProcesses)) { 2108 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2109 mSeparateProcesses = null; 2110 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2111 } else { 2112 mDefParseFlags = 0; 2113 mSeparateProcesses = separateProcesses.split(","); 2114 Slog.w(TAG, "Running with debug.separate_processes: " 2115 + separateProcesses); 2116 } 2117 } else { 2118 mDefParseFlags = 0; 2119 mSeparateProcesses = null; 2120 } 2121 2122 mInstaller = installer; 2123 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2124 "*dexopt*"); 2125 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2126 2127 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2128 FgThread.get().getLooper()); 2129 2130 getDefaultDisplayMetrics(context, mMetrics); 2131 2132 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2133 SystemConfig systemConfig = SystemConfig.getInstance(); 2134 mGlobalGids = systemConfig.getGlobalGids(); 2135 mSystemPermissions = systemConfig.getSystemPermissions(); 2136 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2137 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2138 2139 mProtectedPackages = new ProtectedPackages(mContext); 2140 2141 synchronized (mInstallLock) { 2142 // writer 2143 synchronized (mPackages) { 2144 mHandlerThread = new ServiceThread(TAG, 2145 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2146 mHandlerThread.start(); 2147 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2148 mProcessLoggingHandler = new ProcessLoggingHandler(); 2149 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2150 2151 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2152 2153 File dataDir = Environment.getDataDirectory(); 2154 mAppInstallDir = new File(dataDir, "app"); 2155 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2156 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2157 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2158 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2159 2160 sUserManager = new UserManagerService(context, this, mPackages); 2161 2162 // Propagate permission configuration in to package manager. 2163 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2164 = systemConfig.getPermissions(); 2165 for (int i=0; i<permConfig.size(); i++) { 2166 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2167 BasePermission bp = mSettings.mPermissions.get(perm.name); 2168 if (bp == null) { 2169 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2170 mSettings.mPermissions.put(perm.name, bp); 2171 } 2172 if (perm.gids != null) { 2173 bp.setGids(perm.gids, perm.perUser); 2174 } 2175 } 2176 2177 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2178 for (int i=0; i<libConfig.size(); i++) { 2179 mSharedLibraries.put(libConfig.keyAt(i), 2180 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2181 } 2182 2183 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2184 2185 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2186 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2187 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2188 2189 if (mFirstBoot) { 2190 requestCopyPreoptedFiles(); 2191 } 2192 2193 String customResolverActivity = Resources.getSystem().getString( 2194 R.string.config_customResolverActivity); 2195 if (TextUtils.isEmpty(customResolverActivity)) { 2196 customResolverActivity = null; 2197 } else { 2198 mCustomResolverComponentName = ComponentName.unflattenFromString( 2199 customResolverActivity); 2200 } 2201 2202 long startTime = SystemClock.uptimeMillis(); 2203 2204 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2205 startTime); 2206 2207 // Set flag to monitor and not change apk file paths when 2208 // scanning install directories. 2209 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2210 2211 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2212 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2213 2214 if (bootClassPath == null) { 2215 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2216 } 2217 2218 if (systemServerClassPath == null) { 2219 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2220 } 2221 2222 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2223 final String[] dexCodeInstructionSets = 2224 getDexCodeInstructionSets( 2225 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2226 2227 /** 2228 * Ensure all external libraries have had dexopt run on them. 2229 */ 2230 if (mSharedLibraries.size() > 0) { 2231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2232 // NOTE: For now, we're compiling these system "shared libraries" 2233 // (and framework jars) into all available architectures. It's possible 2234 // to compile them only when we come across an app that uses them (there's 2235 // already logic for that in scanPackageLI) but that adds some complexity. 2236 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2237 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2238 final String lib = libEntry.path; 2239 if (lib == null) { 2240 continue; 2241 } 2242 2243 try { 2244 // Shared libraries do not have profiles so we perform a full 2245 // AOT compilation (if needed). 2246 int dexoptNeeded = DexFile.getDexOptNeeded( 2247 lib, dexCodeInstructionSet, 2248 getCompilerFilterForReason(REASON_SHARED_APK), 2249 false /* newProfile */); 2250 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2251 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2252 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2253 getCompilerFilterForReason(REASON_SHARED_APK), 2254 StorageManager.UUID_PRIVATE_INTERNAL, 2255 SKIP_SHARED_LIBRARY_CHECK); 2256 } 2257 } catch (FileNotFoundException e) { 2258 Slog.w(TAG, "Library not found: " + lib); 2259 } catch (IOException | InstallerException e) { 2260 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2261 + e.getMessage()); 2262 } 2263 } 2264 } 2265 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2266 } 2267 2268 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2269 2270 final VersionInfo ver = mSettings.getInternalVersion(); 2271 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2272 2273 // when upgrading from pre-M, promote system app permissions from install to runtime 2274 mPromoteSystemApps = 2275 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2276 2277 // When upgrading from pre-N, we need to handle package extraction like first boot, 2278 // as there is no profiling data available. 2279 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2280 2281 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2282 2283 // save off the names of pre-existing system packages prior to scanning; we don't 2284 // want to automatically grant runtime permissions for new system apps 2285 if (mPromoteSystemApps) { 2286 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2287 while (pkgSettingIter.hasNext()) { 2288 PackageSetting ps = pkgSettingIter.next(); 2289 if (isSystemApp(ps)) { 2290 mExistingSystemPackages.add(ps.name); 2291 } 2292 } 2293 } 2294 2295 // Collect vendor overlay packages. (Do this before scanning any apps.) 2296 // For security and version matching reason, only consider 2297 // overlay packages if they reside in the right directory. 2298 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2299 if (overlayThemeDir.isEmpty()) { 2300 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2301 } 2302 if (!overlayThemeDir.isEmpty()) { 2303 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2304 | PackageParser.PARSE_IS_SYSTEM 2305 | PackageParser.PARSE_IS_SYSTEM_DIR 2306 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2307 } 2308 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2309 | PackageParser.PARSE_IS_SYSTEM 2310 | PackageParser.PARSE_IS_SYSTEM_DIR 2311 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2312 2313 // Find base frameworks (resource packages without code). 2314 scanDirTracedLI(frameworkDir, mDefParseFlags 2315 | PackageParser.PARSE_IS_SYSTEM 2316 | PackageParser.PARSE_IS_SYSTEM_DIR 2317 | PackageParser.PARSE_IS_PRIVILEGED, 2318 scanFlags | SCAN_NO_DEX, 0); 2319 2320 // Collected privileged system packages. 2321 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2322 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2323 | PackageParser.PARSE_IS_SYSTEM 2324 | PackageParser.PARSE_IS_SYSTEM_DIR 2325 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2326 2327 // Collect ordinary system packages. 2328 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2329 scanDirTracedLI(systemAppDir, mDefParseFlags 2330 | PackageParser.PARSE_IS_SYSTEM 2331 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2332 2333 // Collect all vendor packages. 2334 File vendorAppDir = new File("/vendor/app"); 2335 try { 2336 vendorAppDir = vendorAppDir.getCanonicalFile(); 2337 } catch (IOException e) { 2338 // failed to look up canonical path, continue with original one 2339 } 2340 scanDirTracedLI(vendorAppDir, mDefParseFlags 2341 | PackageParser.PARSE_IS_SYSTEM 2342 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2343 2344 // Collect all OEM packages. 2345 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2346 scanDirTracedLI(oemAppDir, mDefParseFlags 2347 | PackageParser.PARSE_IS_SYSTEM 2348 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2349 2350 // Prune any system packages that no longer exist. 2351 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2352 if (!mOnlyCore) { 2353 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2354 while (psit.hasNext()) { 2355 PackageSetting ps = psit.next(); 2356 2357 /* 2358 * If this is not a system app, it can't be a 2359 * disable system app. 2360 */ 2361 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2362 continue; 2363 } 2364 2365 /* 2366 * If the package is scanned, it's not erased. 2367 */ 2368 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2369 if (scannedPkg != null) { 2370 /* 2371 * If the system app is both scanned and in the 2372 * disabled packages list, then it must have been 2373 * added via OTA. Remove it from the currently 2374 * scanned package so the previously user-installed 2375 * application can be scanned. 2376 */ 2377 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2378 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2379 + ps.name + "; removing system app. Last known codePath=" 2380 + ps.codePathString + ", installStatus=" + ps.installStatus 2381 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2382 + scannedPkg.mVersionCode); 2383 removePackageLI(scannedPkg, true); 2384 mExpectingBetter.put(ps.name, ps.codePath); 2385 } 2386 2387 continue; 2388 } 2389 2390 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2391 psit.remove(); 2392 logCriticalInfo(Log.WARN, "System package " + ps.name 2393 + " no longer exists; it's data will be wiped"); 2394 // Actual deletion of code and data will be handled by later 2395 // reconciliation step 2396 } else { 2397 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2398 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2399 possiblyDeletedUpdatedSystemApps.add(ps.name); 2400 } 2401 } 2402 } 2403 } 2404 2405 //look for any incomplete package installations 2406 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2407 for (int i = 0; i < deletePkgsList.size(); i++) { 2408 // Actual deletion of code and data will be handled by later 2409 // reconciliation step 2410 final String packageName = deletePkgsList.get(i).name; 2411 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2412 synchronized (mPackages) { 2413 mSettings.removePackageLPw(packageName); 2414 } 2415 } 2416 2417 //delete tmp files 2418 deleteTempPackageFiles(); 2419 2420 // Remove any shared userIDs that have no associated packages 2421 mSettings.pruneSharedUsersLPw(); 2422 2423 if (!mOnlyCore) { 2424 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2425 SystemClock.uptimeMillis()); 2426 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2427 2428 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2429 | PackageParser.PARSE_FORWARD_LOCK, 2430 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2431 2432 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2433 | PackageParser.PARSE_IS_EPHEMERAL, 2434 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2435 2436 /** 2437 * Remove disable package settings for any updated system 2438 * apps that were removed via an OTA. If they're not a 2439 * previously-updated app, remove them completely. 2440 * Otherwise, just revoke their system-level permissions. 2441 */ 2442 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2443 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2444 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2445 2446 String msg; 2447 if (deletedPkg == null) { 2448 msg = "Updated system package " + deletedAppName 2449 + " no longer exists; it's data will be wiped"; 2450 // Actual deletion of code and data will be handled by later 2451 // reconciliation step 2452 } else { 2453 msg = "Updated system app + " + deletedAppName 2454 + " no longer present; removing system privileges for " 2455 + deletedAppName; 2456 2457 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2458 2459 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2460 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2461 } 2462 logCriticalInfo(Log.WARN, msg); 2463 } 2464 2465 /** 2466 * Make sure all system apps that we expected to appear on 2467 * the userdata partition actually showed up. If they never 2468 * appeared, crawl back and revive the system version. 2469 */ 2470 for (int i = 0; i < mExpectingBetter.size(); i++) { 2471 final String packageName = mExpectingBetter.keyAt(i); 2472 if (!mPackages.containsKey(packageName)) { 2473 final File scanFile = mExpectingBetter.valueAt(i); 2474 2475 logCriticalInfo(Log.WARN, "Expected better " + packageName 2476 + " but never showed up; reverting to system"); 2477 2478 int reparseFlags = mDefParseFlags; 2479 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2480 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR 2482 | PackageParser.PARSE_IS_PRIVILEGED; 2483 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2484 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2485 | PackageParser.PARSE_IS_SYSTEM_DIR; 2486 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2487 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR; 2489 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2490 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2491 | PackageParser.PARSE_IS_SYSTEM_DIR; 2492 } else { 2493 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2494 continue; 2495 } 2496 2497 mSettings.enableSystemPackageLPw(packageName); 2498 2499 try { 2500 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2501 } catch (PackageManagerException e) { 2502 Slog.e(TAG, "Failed to parse original system package: " 2503 + e.getMessage()); 2504 } 2505 } 2506 } 2507 } 2508 mExpectingBetter.clear(); 2509 2510 // Resolve the storage manager. 2511 mStorageManagerPackage = getStorageManagerPackageName(); 2512 2513 // Resolve protected action filters. Only the setup wizard is allowed to 2514 // have a high priority filter for these actions. 2515 mSetupWizardPackage = getSetupWizardPackageName(); 2516 if (mProtectedFilters.size() > 0) { 2517 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2518 Slog.i(TAG, "No setup wizard;" 2519 + " All protected intents capped to priority 0"); 2520 } 2521 for (ActivityIntentInfo filter : mProtectedFilters) { 2522 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2523 if (DEBUG_FILTERS) { 2524 Slog.i(TAG, "Found setup wizard;" 2525 + " allow priority " + filter.getPriority() + ";" 2526 + " package: " + filter.activity.info.packageName 2527 + " activity: " + filter.activity.className 2528 + " priority: " + filter.getPriority()); 2529 } 2530 // skip setup wizard; allow it to keep the high priority filter 2531 continue; 2532 } 2533 Slog.w(TAG, "Protected action; cap priority to 0;" 2534 + " package: " + filter.activity.info.packageName 2535 + " activity: " + filter.activity.className 2536 + " origPrio: " + filter.getPriority()); 2537 filter.setPriority(0); 2538 } 2539 } 2540 mDeferProtectedFilters = false; 2541 mProtectedFilters.clear(); 2542 2543 // Now that we know all of the shared libraries, update all clients to have 2544 // the correct library paths. 2545 updateAllSharedLibrariesLPw(); 2546 2547 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2548 // NOTE: We ignore potential failures here during a system scan (like 2549 // the rest of the commands above) because there's precious little we 2550 // can do about it. A settings error is reported, though. 2551 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2552 } 2553 2554 // Now that we know all the packages we are keeping, 2555 // read and update their last usage times. 2556 mPackageUsage.read(mPackages); 2557 mCompilerStats.read(); 2558 2559 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2560 SystemClock.uptimeMillis()); 2561 Slog.i(TAG, "Time to scan packages: " 2562 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2563 + " seconds"); 2564 2565 // If the platform SDK has changed since the last time we booted, 2566 // we need to re-grant app permission to catch any new ones that 2567 // appear. This is really a hack, and means that apps can in some 2568 // cases get permissions that the user didn't initially explicitly 2569 // allow... it would be nice to have some better way to handle 2570 // this situation. 2571 int updateFlags = UPDATE_PERMISSIONS_ALL; 2572 if (ver.sdkVersion != mSdkVersion) { 2573 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2574 + mSdkVersion + "; regranting permissions for internal storage"); 2575 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2576 } 2577 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2578 ver.sdkVersion = mSdkVersion; 2579 2580 // If this is the first boot or an update from pre-M, and it is a normal 2581 // boot, then we need to initialize the default preferred apps across 2582 // all defined users. 2583 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2584 for (UserInfo user : sUserManager.getUsers(true)) { 2585 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2586 applyFactoryDefaultBrowserLPw(user.id); 2587 primeDomainVerificationsLPw(user.id); 2588 } 2589 } 2590 2591 // Prepare storage for system user really early during boot, 2592 // since core system apps like SettingsProvider and SystemUI 2593 // can't wait for user to start 2594 final int storageFlags; 2595 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2596 storageFlags = StorageManager.FLAG_STORAGE_DE; 2597 } else { 2598 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2599 } 2600 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2601 storageFlags, true /* migrateAppData */); 2602 2603 // If this is first boot after an OTA, and a normal boot, then 2604 // we need to clear code cache directories. 2605 // Note that we do *not* clear the application profiles. These remain valid 2606 // across OTAs and are used to drive profile verification (post OTA) and 2607 // profile compilation (without waiting to collect a fresh set of profiles). 2608 if (mIsUpgrade && !onlyCore) { 2609 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2610 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2611 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2612 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2613 // No apps are running this early, so no need to freeze 2614 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2615 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2616 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2617 } 2618 } 2619 ver.fingerprint = Build.FINGERPRINT; 2620 } 2621 2622 checkDefaultBrowser(); 2623 2624 // clear only after permissions and other defaults have been updated 2625 mExistingSystemPackages.clear(); 2626 mPromoteSystemApps = false; 2627 2628 // All the changes are done during package scanning. 2629 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2630 2631 // can downgrade to reader 2632 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2633 mSettings.writeLPr(); 2634 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2635 2636 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2637 // early on (before the package manager declares itself as early) because other 2638 // components in the system server might ask for package contexts for these apps. 2639 // 2640 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2641 // (i.e, that the data partition is unavailable). 2642 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2643 long start = System.nanoTime(); 2644 List<PackageParser.Package> coreApps = new ArrayList<>(); 2645 for (PackageParser.Package pkg : mPackages.values()) { 2646 if (pkg.coreApp) { 2647 coreApps.add(pkg); 2648 } 2649 } 2650 2651 int[] stats = performDexOptUpgrade(coreApps, false, 2652 getCompilerFilterForReason(REASON_CORE_APP)); 2653 2654 final int elapsedTimeSeconds = 2655 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2656 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2657 2658 if (DEBUG_DEXOPT) { 2659 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2660 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2661 } 2662 2663 2664 // TODO: Should we log these stats to tron too ? 2665 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2666 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2667 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2668 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2669 } 2670 2671 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2672 SystemClock.uptimeMillis()); 2673 2674 if (!mOnlyCore) { 2675 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2676 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2677 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2678 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2679 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2680 mIntentFilterVerifierComponent); 2681 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2682 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2683 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2684 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2685 } else { 2686 mRequiredVerifierPackage = null; 2687 mRequiredInstallerPackage = null; 2688 mRequiredUninstallerPackage = null; 2689 mIntentFilterVerifierComponent = null; 2690 mIntentFilterVerifier = null; 2691 mServicesSystemSharedLibraryPackageName = null; 2692 mSharedSystemSharedLibraryPackageName = null; 2693 } 2694 2695 mInstallerService = new PackageInstallerService(context, this); 2696 2697 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2698 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2699 // both the installer and resolver must be present to enable ephemeral 2700 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2701 if (DEBUG_EPHEMERAL) { 2702 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2703 + " installer:" + ephemeralInstallerComponent); 2704 } 2705 mEphemeralResolverComponent = ephemeralResolverComponent; 2706 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2707 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2708 mEphemeralResolverConnection = 2709 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2710 } else { 2711 if (DEBUG_EPHEMERAL) { 2712 final String missingComponent = 2713 (ephemeralResolverComponent == null) 2714 ? (ephemeralInstallerComponent == null) 2715 ? "resolver and installer" 2716 : "resolver" 2717 : "installer"; 2718 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2719 } 2720 mEphemeralResolverComponent = null; 2721 mEphemeralInstallerComponent = null; 2722 mEphemeralResolverConnection = null; 2723 } 2724 2725 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2726 } // synchronized (mPackages) 2727 } // synchronized (mInstallLock) 2728 2729 // Now after opening every single application zip, make sure they 2730 // are all flushed. Not really needed, but keeps things nice and 2731 // tidy. 2732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2733 Runtime.getRuntime().gc(); 2734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2735 2736 // The initial scanning above does many calls into installd while 2737 // holding the mPackages lock, but we're mostly interested in yelling 2738 // once we have a booted system. 2739 mInstaller.setWarnIfHeld(mPackages); 2740 2741 // Expose private service for system components to use. 2742 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2743 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2744 } 2745 2746 @Override 2747 public boolean isFirstBoot() { 2748 return mFirstBoot; 2749 } 2750 2751 @Override 2752 public boolean isOnlyCoreApps() { 2753 return mOnlyCore; 2754 } 2755 2756 @Override 2757 public boolean isUpgrade() { 2758 return mIsUpgrade; 2759 } 2760 2761 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2762 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2763 2764 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2765 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2766 UserHandle.USER_SYSTEM); 2767 if (matches.size() == 1) { 2768 return matches.get(0).getComponentInfo().packageName; 2769 } else if (matches.size() == 0) { 2770 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2771 return null; 2772 } 2773 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2774 } 2775 2776 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2777 synchronized (mPackages) { 2778 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2779 if (libraryEntry == null) { 2780 throw new IllegalStateException("Missing required shared library:" + libraryName); 2781 } 2782 return libraryEntry.apk; 2783 } 2784 } 2785 2786 private @NonNull String getRequiredInstallerLPr() { 2787 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2788 intent.addCategory(Intent.CATEGORY_DEFAULT); 2789 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2790 2791 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2792 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2793 UserHandle.USER_SYSTEM); 2794 if (matches.size() == 1) { 2795 ResolveInfo resolveInfo = matches.get(0); 2796 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2797 throw new RuntimeException("The installer must be a privileged app"); 2798 } 2799 return matches.get(0).getComponentInfo().packageName; 2800 } else { 2801 throw new RuntimeException("There must be exactly one installer; found " + matches); 2802 } 2803 } 2804 2805 private @NonNull String getRequiredUninstallerLPr() { 2806 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2807 intent.addCategory(Intent.CATEGORY_DEFAULT); 2808 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2809 2810 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2811 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2812 UserHandle.USER_SYSTEM); 2813 if (resolveInfo == null || 2814 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2815 throw new RuntimeException("There must be exactly one uninstaller; found " 2816 + resolveInfo); 2817 } 2818 return resolveInfo.getComponentInfo().packageName; 2819 } 2820 2821 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2822 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2823 2824 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2825 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2826 UserHandle.USER_SYSTEM); 2827 ResolveInfo best = null; 2828 final int N = matches.size(); 2829 for (int i = 0; i < N; i++) { 2830 final ResolveInfo cur = matches.get(i); 2831 final String packageName = cur.getComponentInfo().packageName; 2832 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2833 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2834 continue; 2835 } 2836 2837 if (best == null || cur.priority > best.priority) { 2838 best = cur; 2839 } 2840 } 2841 2842 if (best != null) { 2843 return best.getComponentInfo().getComponentName(); 2844 } else { 2845 throw new RuntimeException("There must be at least one intent filter verifier"); 2846 } 2847 } 2848 2849 private @Nullable ComponentName getEphemeralResolverLPr() { 2850 final String[] packageArray = 2851 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2852 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2853 if (DEBUG_EPHEMERAL) { 2854 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2855 } 2856 return null; 2857 } 2858 2859 final int resolveFlags = 2860 MATCH_DIRECT_BOOT_AWARE 2861 | MATCH_DIRECT_BOOT_UNAWARE 2862 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2863 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2864 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2865 resolveFlags, UserHandle.USER_SYSTEM); 2866 2867 final int N = resolvers.size(); 2868 if (N == 0) { 2869 if (DEBUG_EPHEMERAL) { 2870 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2871 } 2872 return null; 2873 } 2874 2875 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2876 for (int i = 0; i < N; i++) { 2877 final ResolveInfo info = resolvers.get(i); 2878 2879 if (info.serviceInfo == null) { 2880 continue; 2881 } 2882 2883 final String packageName = info.serviceInfo.packageName; 2884 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2887 + " pkg: " + packageName + ", info:" + info); 2888 } 2889 continue; 2890 } 2891 2892 if (DEBUG_EPHEMERAL) { 2893 Slog.v(TAG, "Ephemeral resolver found;" 2894 + " pkg: " + packageName + ", info:" + info); 2895 } 2896 return new ComponentName(packageName, info.serviceInfo.name); 2897 } 2898 if (DEBUG_EPHEMERAL) { 2899 Slog.v(TAG, "Ephemeral resolver NOT found"); 2900 } 2901 return null; 2902 } 2903 2904 private @Nullable ComponentName getEphemeralInstallerLPr() { 2905 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2906 intent.addCategory(Intent.CATEGORY_DEFAULT); 2907 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2908 2909 final int resolveFlags = 2910 MATCH_DIRECT_BOOT_AWARE 2911 | MATCH_DIRECT_BOOT_UNAWARE 2912 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2913 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2914 resolveFlags, UserHandle.USER_SYSTEM); 2915 if (matches.size() == 0) { 2916 return null; 2917 } else if (matches.size() == 1) { 2918 return matches.get(0).getComponentInfo().getComponentName(); 2919 } else { 2920 throw new RuntimeException( 2921 "There must be at most one ephemeral installer; found " + matches); 2922 } 2923 } 2924 2925 private void primeDomainVerificationsLPw(int userId) { 2926 if (DEBUG_DOMAIN_VERIFICATION) { 2927 Slog.d(TAG, "Priming domain verifications in user " + userId); 2928 } 2929 2930 SystemConfig systemConfig = SystemConfig.getInstance(); 2931 ArraySet<String> packages = systemConfig.getLinkedApps(); 2932 2933 for (String packageName : packages) { 2934 PackageParser.Package pkg = mPackages.get(packageName); 2935 if (pkg != null) { 2936 if (!pkg.isSystemApp()) { 2937 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2938 continue; 2939 } 2940 2941 ArraySet<String> domains = null; 2942 for (PackageParser.Activity a : pkg.activities) { 2943 for (ActivityIntentInfo filter : a.intents) { 2944 if (hasValidDomains(filter)) { 2945 if (domains == null) { 2946 domains = new ArraySet<String>(); 2947 } 2948 domains.addAll(filter.getHostsList()); 2949 } 2950 } 2951 } 2952 2953 if (domains != null && domains.size() > 0) { 2954 if (DEBUG_DOMAIN_VERIFICATION) { 2955 Slog.v(TAG, " + " + packageName); 2956 } 2957 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2958 // state w.r.t. the formal app-linkage "no verification attempted" state; 2959 // and then 'always' in the per-user state actually used for intent resolution. 2960 final IntentFilterVerificationInfo ivi; 2961 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 2962 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2963 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2964 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2965 } else { 2966 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2967 + "' does not handle web links"); 2968 } 2969 } else { 2970 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2971 } 2972 } 2973 2974 scheduleWritePackageRestrictionsLocked(userId); 2975 scheduleWriteSettingsLocked(); 2976 } 2977 2978 private void applyFactoryDefaultBrowserLPw(int userId) { 2979 // The default browser app's package name is stored in a string resource, 2980 // with a product-specific overlay used for vendor customization. 2981 String browserPkg = mContext.getResources().getString( 2982 com.android.internal.R.string.default_browser); 2983 if (!TextUtils.isEmpty(browserPkg)) { 2984 // non-empty string => required to be a known package 2985 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2986 if (ps == null) { 2987 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2988 browserPkg = null; 2989 } else { 2990 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2991 } 2992 } 2993 2994 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2995 // default. If there's more than one, just leave everything alone. 2996 if (browserPkg == null) { 2997 calculateDefaultBrowserLPw(userId); 2998 } 2999 } 3000 3001 private void calculateDefaultBrowserLPw(int userId) { 3002 List<String> allBrowsers = resolveAllBrowserApps(userId); 3003 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3004 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3005 } 3006 3007 private List<String> resolveAllBrowserApps(int userId) { 3008 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3009 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3010 PackageManager.MATCH_ALL, userId); 3011 3012 final int count = list.size(); 3013 List<String> result = new ArrayList<String>(count); 3014 for (int i=0; i<count; i++) { 3015 ResolveInfo info = list.get(i); 3016 if (info.activityInfo == null 3017 || !info.handleAllWebDataURI 3018 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3019 || result.contains(info.activityInfo.packageName)) { 3020 continue; 3021 } 3022 result.add(info.activityInfo.packageName); 3023 } 3024 3025 return result; 3026 } 3027 3028 private boolean packageIsBrowser(String packageName, int userId) { 3029 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3030 PackageManager.MATCH_ALL, userId); 3031 final int N = list.size(); 3032 for (int i = 0; i < N; i++) { 3033 ResolveInfo info = list.get(i); 3034 if (packageName.equals(info.activityInfo.packageName)) { 3035 return true; 3036 } 3037 } 3038 return false; 3039 } 3040 3041 private void checkDefaultBrowser() { 3042 final int myUserId = UserHandle.myUserId(); 3043 final String packageName = getDefaultBrowserPackageName(myUserId); 3044 if (packageName != null) { 3045 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3046 if (info == null) { 3047 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3048 synchronized (mPackages) { 3049 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3050 } 3051 } 3052 } 3053 } 3054 3055 @Override 3056 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3057 throws RemoteException { 3058 try { 3059 return super.onTransact(code, data, reply, flags); 3060 } catch (RuntimeException e) { 3061 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3062 Slog.wtf(TAG, "Package Manager Crash", e); 3063 } 3064 throw e; 3065 } 3066 } 3067 3068 static int[] appendInts(int[] cur, int[] add) { 3069 if (add == null) return cur; 3070 if (cur == null) return add; 3071 final int N = add.length; 3072 for (int i=0; i<N; i++) { 3073 cur = appendInt(cur, add[i]); 3074 } 3075 return cur; 3076 } 3077 3078 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3079 if (!sUserManager.exists(userId)) return null; 3080 if (ps == null) { 3081 return null; 3082 } 3083 final PackageParser.Package p = ps.pkg; 3084 if (p == null) { 3085 return null; 3086 } 3087 3088 final PermissionsState permissionsState = ps.getPermissionsState(); 3089 3090 // Compute GIDs only if requested 3091 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3092 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3093 // Compute granted permissions only if package has requested permissions 3094 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3095 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3096 final PackageUserState state = ps.readUserState(userId); 3097 3098 return PackageParser.generatePackageInfo(p, gids, flags, 3099 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3100 } 3101 3102 @Override 3103 public void checkPackageStartable(String packageName, int userId) { 3104 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3105 3106 synchronized (mPackages) { 3107 final PackageSetting ps = mSettings.mPackages.get(packageName); 3108 if (ps == null) { 3109 throw new SecurityException("Package " + packageName + " was not found!"); 3110 } 3111 3112 if (!ps.getInstalled(userId)) { 3113 throw new SecurityException( 3114 "Package " + packageName + " was not installed for user " + userId + "!"); 3115 } 3116 3117 if (mSafeMode && !ps.isSystem()) { 3118 throw new SecurityException("Package " + packageName + " not a system app!"); 3119 } 3120 3121 if (mFrozenPackages.contains(packageName)) { 3122 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3123 } 3124 3125 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3126 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3127 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3128 } 3129 } 3130 } 3131 3132 @Override 3133 public boolean isPackageAvailable(String packageName, int userId) { 3134 if (!sUserManager.exists(userId)) return false; 3135 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3136 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3137 synchronized (mPackages) { 3138 PackageParser.Package p = mPackages.get(packageName); 3139 if (p != null) { 3140 final PackageSetting ps = (PackageSetting) p.mExtras; 3141 if (ps != null) { 3142 final PackageUserState state = ps.readUserState(userId); 3143 if (state != null) { 3144 return PackageParser.isAvailable(state); 3145 } 3146 } 3147 } 3148 } 3149 return false; 3150 } 3151 3152 @Override 3153 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3154 if (!sUserManager.exists(userId)) return null; 3155 flags = updateFlagsForPackage(flags, userId, packageName); 3156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3157 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3158 // reader 3159 synchronized (mPackages) { 3160 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3161 PackageParser.Package p = null; 3162 if (matchFactoryOnly) { 3163 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3164 if (ps != null) { 3165 return generatePackageInfo(ps, flags, userId); 3166 } 3167 } 3168 if (p == null) { 3169 p = mPackages.get(packageName); 3170 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3171 return null; 3172 } 3173 } 3174 if (DEBUG_PACKAGE_INFO) 3175 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3176 if (p != null) { 3177 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3178 } 3179 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3180 final PackageSetting ps = mSettings.mPackages.get(packageName); 3181 return generatePackageInfo(ps, flags, userId); 3182 } 3183 } 3184 return null; 3185 } 3186 3187 @Override 3188 public String[] currentToCanonicalPackageNames(String[] names) { 3189 String[] out = new String[names.length]; 3190 // reader 3191 synchronized (mPackages) { 3192 for (int i=names.length-1; i>=0; i--) { 3193 PackageSetting ps = mSettings.mPackages.get(names[i]); 3194 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3195 } 3196 } 3197 return out; 3198 } 3199 3200 @Override 3201 public String[] canonicalToCurrentPackageNames(String[] names) { 3202 String[] out = new String[names.length]; 3203 // reader 3204 synchronized (mPackages) { 3205 for (int i=names.length-1; i>=0; i--) { 3206 String cur = mSettings.getRenamedPackageLPr(names[i]); 3207 out[i] = cur != null ? cur : names[i]; 3208 } 3209 } 3210 return out; 3211 } 3212 3213 @Override 3214 public int getPackageUid(String packageName, int flags, int userId) { 3215 if (!sUserManager.exists(userId)) return -1; 3216 flags = updateFlagsForPackage(flags, userId, packageName); 3217 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3218 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3219 3220 // reader 3221 synchronized (mPackages) { 3222 final PackageParser.Package p = mPackages.get(packageName); 3223 if (p != null && p.isMatch(flags)) { 3224 return UserHandle.getUid(userId, p.applicationInfo.uid); 3225 } 3226 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3227 final PackageSetting ps = mSettings.mPackages.get(packageName); 3228 if (ps != null && ps.isMatch(flags)) { 3229 return UserHandle.getUid(userId, ps.appId); 3230 } 3231 } 3232 } 3233 3234 return -1; 3235 } 3236 3237 @Override 3238 public int[] getPackageGids(String packageName, int flags, int userId) { 3239 if (!sUserManager.exists(userId)) return null; 3240 flags = updateFlagsForPackage(flags, userId, packageName); 3241 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3242 false /* requireFullPermission */, false /* checkShell */, 3243 "getPackageGids"); 3244 3245 // reader 3246 synchronized (mPackages) { 3247 final PackageParser.Package p = mPackages.get(packageName); 3248 if (p != null && p.isMatch(flags)) { 3249 PackageSetting ps = (PackageSetting) p.mExtras; 3250 return ps.getPermissionsState().computeGids(userId); 3251 } 3252 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3253 final PackageSetting ps = mSettings.mPackages.get(packageName); 3254 if (ps != null && ps.isMatch(flags)) { 3255 return ps.getPermissionsState().computeGids(userId); 3256 } 3257 } 3258 } 3259 3260 return null; 3261 } 3262 3263 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3264 if (bp.perm != null) { 3265 return PackageParser.generatePermissionInfo(bp.perm, flags); 3266 } 3267 PermissionInfo pi = new PermissionInfo(); 3268 pi.name = bp.name; 3269 pi.packageName = bp.sourcePackage; 3270 pi.nonLocalizedLabel = bp.name; 3271 pi.protectionLevel = bp.protectionLevel; 3272 return pi; 3273 } 3274 3275 @Override 3276 public PermissionInfo getPermissionInfo(String name, int flags) { 3277 // reader 3278 synchronized (mPackages) { 3279 final BasePermission p = mSettings.mPermissions.get(name); 3280 if (p != null) { 3281 return generatePermissionInfo(p, flags); 3282 } 3283 return null; 3284 } 3285 } 3286 3287 @Override 3288 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3289 int flags) { 3290 // reader 3291 synchronized (mPackages) { 3292 if (group != null && !mPermissionGroups.containsKey(group)) { 3293 // This is thrown as NameNotFoundException 3294 return null; 3295 } 3296 3297 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3298 for (BasePermission p : mSettings.mPermissions.values()) { 3299 if (group == null) { 3300 if (p.perm == null || p.perm.info.group == null) { 3301 out.add(generatePermissionInfo(p, flags)); 3302 } 3303 } else { 3304 if (p.perm != null && group.equals(p.perm.info.group)) { 3305 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3306 } 3307 } 3308 } 3309 return new ParceledListSlice<>(out); 3310 } 3311 } 3312 3313 @Override 3314 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3315 // reader 3316 synchronized (mPackages) { 3317 return PackageParser.generatePermissionGroupInfo( 3318 mPermissionGroups.get(name), flags); 3319 } 3320 } 3321 3322 @Override 3323 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3324 // reader 3325 synchronized (mPackages) { 3326 final int N = mPermissionGroups.size(); 3327 ArrayList<PermissionGroupInfo> out 3328 = new ArrayList<PermissionGroupInfo>(N); 3329 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3330 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3331 } 3332 return new ParceledListSlice<>(out); 3333 } 3334 } 3335 3336 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3337 int userId) { 3338 if (!sUserManager.exists(userId)) return null; 3339 PackageSetting ps = mSettings.mPackages.get(packageName); 3340 if (ps != null) { 3341 if (ps.pkg == null) { 3342 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3343 if (pInfo != null) { 3344 return pInfo.applicationInfo; 3345 } 3346 return null; 3347 } 3348 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3349 ps.readUserState(userId), userId); 3350 } 3351 return null; 3352 } 3353 3354 @Override 3355 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3356 if (!sUserManager.exists(userId)) return null; 3357 flags = updateFlagsForApplication(flags, userId, packageName); 3358 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3359 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3360 // writer 3361 synchronized (mPackages) { 3362 PackageParser.Package p = mPackages.get(packageName); 3363 if (DEBUG_PACKAGE_INFO) Log.v( 3364 TAG, "getApplicationInfo " + packageName 3365 + ": " + p); 3366 if (p != null) { 3367 PackageSetting ps = mSettings.mPackages.get(packageName); 3368 if (ps == null) return null; 3369 // Note: isEnabledLP() does not apply here - always return info 3370 return PackageParser.generateApplicationInfo( 3371 p, flags, ps.readUserState(userId), userId); 3372 } 3373 if ("android".equals(packageName)||"system".equals(packageName)) { 3374 return mAndroidApplication; 3375 } 3376 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3377 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3378 } 3379 } 3380 return null; 3381 } 3382 3383 @Override 3384 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3385 final IPackageDataObserver observer) { 3386 mContext.enforceCallingOrSelfPermission( 3387 android.Manifest.permission.CLEAR_APP_CACHE, null); 3388 // Queue up an async operation since clearing cache may take a little while. 3389 mHandler.post(new Runnable() { 3390 public void run() { 3391 mHandler.removeCallbacks(this); 3392 boolean success = true; 3393 synchronized (mInstallLock) { 3394 try { 3395 mInstaller.freeCache(volumeUuid, freeStorageSize); 3396 } catch (InstallerException e) { 3397 Slog.w(TAG, "Couldn't clear application caches: " + e); 3398 success = false; 3399 } 3400 } 3401 if (observer != null) { 3402 try { 3403 observer.onRemoveCompleted(null, success); 3404 } catch (RemoteException e) { 3405 Slog.w(TAG, "RemoveException when invoking call back"); 3406 } 3407 } 3408 } 3409 }); 3410 } 3411 3412 @Override 3413 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3414 final IntentSender pi) { 3415 mContext.enforceCallingOrSelfPermission( 3416 android.Manifest.permission.CLEAR_APP_CACHE, null); 3417 // Queue up an async operation since clearing cache may take a little while. 3418 mHandler.post(new Runnable() { 3419 public void run() { 3420 mHandler.removeCallbacks(this); 3421 boolean success = true; 3422 synchronized (mInstallLock) { 3423 try { 3424 mInstaller.freeCache(volumeUuid, freeStorageSize); 3425 } catch (InstallerException e) { 3426 Slog.w(TAG, "Couldn't clear application caches: " + e); 3427 success = false; 3428 } 3429 } 3430 if(pi != null) { 3431 try { 3432 // Callback via pending intent 3433 int code = success ? 1 : 0; 3434 pi.sendIntent(null, code, null, 3435 null, null); 3436 } catch (SendIntentException e1) { 3437 Slog.i(TAG, "Failed to send pending intent"); 3438 } 3439 } 3440 } 3441 }); 3442 } 3443 3444 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3445 synchronized (mInstallLock) { 3446 try { 3447 mInstaller.freeCache(volumeUuid, freeStorageSize); 3448 } catch (InstallerException e) { 3449 throw new IOException("Failed to free enough space", e); 3450 } 3451 } 3452 } 3453 3454 /** 3455 * Update given flags based on encryption status of current user. 3456 */ 3457 private int updateFlags(int flags, int userId) { 3458 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3459 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3460 // Caller expressed an explicit opinion about what encryption 3461 // aware/unaware components they want to see, so fall through and 3462 // give them what they want 3463 } else { 3464 // Caller expressed no opinion, so match based on user state 3465 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3466 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3467 } else { 3468 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3469 } 3470 } 3471 return flags; 3472 } 3473 3474 private UserManagerInternal getUserManagerInternal() { 3475 if (mUserManagerInternal == null) { 3476 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3477 } 3478 return mUserManagerInternal; 3479 } 3480 3481 /** 3482 * Update given flags when being used to request {@link PackageInfo}. 3483 */ 3484 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3485 boolean triaged = true; 3486 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3487 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3488 // Caller is asking for component details, so they'd better be 3489 // asking for specific encryption matching behavior, or be triaged 3490 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3491 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3492 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3493 triaged = false; 3494 } 3495 } 3496 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3497 | PackageManager.MATCH_SYSTEM_ONLY 3498 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3499 triaged = false; 3500 } 3501 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3502 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3503 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3504 } 3505 return updateFlags(flags, userId); 3506 } 3507 3508 /** 3509 * Update given flags when being used to request {@link ApplicationInfo}. 3510 */ 3511 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3512 return updateFlagsForPackage(flags, userId, cookie); 3513 } 3514 3515 /** 3516 * Update given flags when being used to request {@link ComponentInfo}. 3517 */ 3518 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3519 if (cookie instanceof Intent) { 3520 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3521 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3522 } 3523 } 3524 3525 boolean triaged = true; 3526 // Caller is asking for component details, so they'd better be 3527 // asking for specific encryption matching behavior, or be triaged 3528 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3529 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3530 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3531 triaged = false; 3532 } 3533 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3534 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3535 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3536 } 3537 3538 return updateFlags(flags, userId); 3539 } 3540 3541 /** 3542 * Update given flags when being used to request {@link ResolveInfo}. 3543 */ 3544 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3545 // Safe mode means we shouldn't match any third-party components 3546 if (mSafeMode) { 3547 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3548 } 3549 3550 return updateFlagsForComponent(flags, userId, cookie); 3551 } 3552 3553 @Override 3554 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3555 if (!sUserManager.exists(userId)) return null; 3556 flags = updateFlagsForComponent(flags, userId, component); 3557 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3558 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3559 synchronized (mPackages) { 3560 PackageParser.Activity a = mActivities.mActivities.get(component); 3561 3562 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3563 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3564 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3565 if (ps == null) return null; 3566 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3567 userId); 3568 } 3569 if (mResolveComponentName.equals(component)) { 3570 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3571 new PackageUserState(), userId); 3572 } 3573 } 3574 return null; 3575 } 3576 3577 @Override 3578 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3579 String resolvedType) { 3580 synchronized (mPackages) { 3581 if (component.equals(mResolveComponentName)) { 3582 // The resolver supports EVERYTHING! 3583 return true; 3584 } 3585 PackageParser.Activity a = mActivities.mActivities.get(component); 3586 if (a == null) { 3587 return false; 3588 } 3589 for (int i=0; i<a.intents.size(); i++) { 3590 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3591 intent.getData(), intent.getCategories(), TAG) >= 0) { 3592 return true; 3593 } 3594 } 3595 return false; 3596 } 3597 } 3598 3599 @Override 3600 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3601 if (!sUserManager.exists(userId)) return null; 3602 flags = updateFlagsForComponent(flags, userId, component); 3603 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3604 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3605 synchronized (mPackages) { 3606 PackageParser.Activity a = mReceivers.mActivities.get(component); 3607 if (DEBUG_PACKAGE_INFO) Log.v( 3608 TAG, "getReceiverInfo " + component + ": " + a); 3609 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3610 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3611 if (ps == null) return null; 3612 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3613 userId); 3614 } 3615 } 3616 return null; 3617 } 3618 3619 @Override 3620 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3621 if (!sUserManager.exists(userId)) return null; 3622 flags = updateFlagsForComponent(flags, userId, component); 3623 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3624 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3625 synchronized (mPackages) { 3626 PackageParser.Service s = mServices.mServices.get(component); 3627 if (DEBUG_PACKAGE_INFO) Log.v( 3628 TAG, "getServiceInfo " + component + ": " + s); 3629 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3630 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3631 if (ps == null) return null; 3632 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3633 userId); 3634 } 3635 } 3636 return null; 3637 } 3638 3639 @Override 3640 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3641 if (!sUserManager.exists(userId)) return null; 3642 flags = updateFlagsForComponent(flags, userId, component); 3643 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3644 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3645 synchronized (mPackages) { 3646 PackageParser.Provider p = mProviders.mProviders.get(component); 3647 if (DEBUG_PACKAGE_INFO) Log.v( 3648 TAG, "getProviderInfo " + component + ": " + p); 3649 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3650 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3651 if (ps == null) return null; 3652 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3653 userId); 3654 } 3655 } 3656 return null; 3657 } 3658 3659 @Override 3660 public String[] getSystemSharedLibraryNames() { 3661 Set<String> libSet; 3662 synchronized (mPackages) { 3663 libSet = mSharedLibraries.keySet(); 3664 int size = libSet.size(); 3665 if (size > 0) { 3666 String[] libs = new String[size]; 3667 libSet.toArray(libs); 3668 return libs; 3669 } 3670 } 3671 return null; 3672 } 3673 3674 @Override 3675 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3676 synchronized (mPackages) { 3677 return mServicesSystemSharedLibraryPackageName; 3678 } 3679 } 3680 3681 @Override 3682 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3683 synchronized (mPackages) { 3684 return mSharedSystemSharedLibraryPackageName; 3685 } 3686 } 3687 3688 @Override 3689 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3690 synchronized (mPackages) { 3691 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3692 3693 final FeatureInfo fi = new FeatureInfo(); 3694 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3695 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3696 res.add(fi); 3697 3698 return new ParceledListSlice<>(res); 3699 } 3700 } 3701 3702 @Override 3703 public boolean hasSystemFeature(String name, int version) { 3704 synchronized (mPackages) { 3705 final FeatureInfo feat = mAvailableFeatures.get(name); 3706 if (feat == null) { 3707 return false; 3708 } else { 3709 return feat.version >= version; 3710 } 3711 } 3712 } 3713 3714 @Override 3715 public int checkPermission(String permName, String pkgName, int userId) { 3716 if (!sUserManager.exists(userId)) { 3717 return PackageManager.PERMISSION_DENIED; 3718 } 3719 3720 synchronized (mPackages) { 3721 final PackageParser.Package p = mPackages.get(pkgName); 3722 if (p != null && p.mExtras != null) { 3723 final PackageSetting ps = (PackageSetting) p.mExtras; 3724 final PermissionsState permissionsState = ps.getPermissionsState(); 3725 if (permissionsState.hasPermission(permName, userId)) { 3726 return PackageManager.PERMISSION_GRANTED; 3727 } 3728 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3729 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3730 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3731 return PackageManager.PERMISSION_GRANTED; 3732 } 3733 } 3734 } 3735 3736 return PackageManager.PERMISSION_DENIED; 3737 } 3738 3739 @Override 3740 public int checkUidPermission(String permName, int uid) { 3741 final int userId = UserHandle.getUserId(uid); 3742 3743 if (!sUserManager.exists(userId)) { 3744 return PackageManager.PERMISSION_DENIED; 3745 } 3746 3747 synchronized (mPackages) { 3748 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3749 if (obj != null) { 3750 final SettingBase ps = (SettingBase) obj; 3751 final PermissionsState permissionsState = ps.getPermissionsState(); 3752 if (permissionsState.hasPermission(permName, userId)) { 3753 return PackageManager.PERMISSION_GRANTED; 3754 } 3755 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3756 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3757 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3758 return PackageManager.PERMISSION_GRANTED; 3759 } 3760 } else { 3761 ArraySet<String> perms = mSystemPermissions.get(uid); 3762 if (perms != null) { 3763 if (perms.contains(permName)) { 3764 return PackageManager.PERMISSION_GRANTED; 3765 } 3766 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3767 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 } 3771 } 3772 } 3773 3774 return PackageManager.PERMISSION_DENIED; 3775 } 3776 3777 @Override 3778 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3779 if (UserHandle.getCallingUserId() != userId) { 3780 mContext.enforceCallingPermission( 3781 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3782 "isPermissionRevokedByPolicy for user " + userId); 3783 } 3784 3785 if (checkPermission(permission, packageName, userId) 3786 == PackageManager.PERMISSION_GRANTED) { 3787 return false; 3788 } 3789 3790 final long identity = Binder.clearCallingIdentity(); 3791 try { 3792 final int flags = getPermissionFlags(permission, packageName, userId); 3793 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3794 } finally { 3795 Binder.restoreCallingIdentity(identity); 3796 } 3797 } 3798 3799 @Override 3800 public String getPermissionControllerPackageName() { 3801 synchronized (mPackages) { 3802 return mRequiredInstallerPackage; 3803 } 3804 } 3805 3806 /** 3807 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3808 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3809 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3810 * @param message the message to log on security exception 3811 */ 3812 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3813 boolean checkShell, String message) { 3814 if (userId < 0) { 3815 throw new IllegalArgumentException("Invalid userId " + userId); 3816 } 3817 if (checkShell) { 3818 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3819 } 3820 if (userId == UserHandle.getUserId(callingUid)) return; 3821 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3822 if (requireFullPermission) { 3823 mContext.enforceCallingOrSelfPermission( 3824 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3825 } else { 3826 try { 3827 mContext.enforceCallingOrSelfPermission( 3828 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3829 } catch (SecurityException se) { 3830 mContext.enforceCallingOrSelfPermission( 3831 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3832 } 3833 } 3834 } 3835 } 3836 3837 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3838 if (callingUid == Process.SHELL_UID) { 3839 if (userHandle >= 0 3840 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3841 throw new SecurityException("Shell does not have permission to access user " 3842 + userHandle); 3843 } else if (userHandle < 0) { 3844 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3845 + Debug.getCallers(3)); 3846 } 3847 } 3848 } 3849 3850 private BasePermission findPermissionTreeLP(String permName) { 3851 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3852 if (permName.startsWith(bp.name) && 3853 permName.length() > bp.name.length() && 3854 permName.charAt(bp.name.length()) == '.') { 3855 return bp; 3856 } 3857 } 3858 return null; 3859 } 3860 3861 private BasePermission checkPermissionTreeLP(String permName) { 3862 if (permName != null) { 3863 BasePermission bp = findPermissionTreeLP(permName); 3864 if (bp != null) { 3865 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3866 return bp; 3867 } 3868 throw new SecurityException("Calling uid " 3869 + Binder.getCallingUid() 3870 + " is not allowed to add to permission tree " 3871 + bp.name + " owned by uid " + bp.uid); 3872 } 3873 } 3874 throw new SecurityException("No permission tree found for " + permName); 3875 } 3876 3877 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3878 if (s1 == null) { 3879 return s2 == null; 3880 } 3881 if (s2 == null) { 3882 return false; 3883 } 3884 if (s1.getClass() != s2.getClass()) { 3885 return false; 3886 } 3887 return s1.equals(s2); 3888 } 3889 3890 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3891 if (pi1.icon != pi2.icon) return false; 3892 if (pi1.logo != pi2.logo) return false; 3893 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3894 if (!compareStrings(pi1.name, pi2.name)) return false; 3895 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3896 // We'll take care of setting this one. 3897 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3898 // These are not currently stored in settings. 3899 //if (!compareStrings(pi1.group, pi2.group)) return false; 3900 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3901 //if (pi1.labelRes != pi2.labelRes) return false; 3902 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3903 return true; 3904 } 3905 3906 int permissionInfoFootprint(PermissionInfo info) { 3907 int size = info.name.length(); 3908 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3909 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3910 return size; 3911 } 3912 3913 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3914 int size = 0; 3915 for (BasePermission perm : mSettings.mPermissions.values()) { 3916 if (perm.uid == tree.uid) { 3917 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3918 } 3919 } 3920 return size; 3921 } 3922 3923 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3924 // We calculate the max size of permissions defined by this uid and throw 3925 // if that plus the size of 'info' would exceed our stated maximum. 3926 if (tree.uid != Process.SYSTEM_UID) { 3927 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3928 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3929 throw new SecurityException("Permission tree size cap exceeded"); 3930 } 3931 } 3932 } 3933 3934 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3935 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3936 throw new SecurityException("Label must be specified in permission"); 3937 } 3938 BasePermission tree = checkPermissionTreeLP(info.name); 3939 BasePermission bp = mSettings.mPermissions.get(info.name); 3940 boolean added = bp == null; 3941 boolean changed = true; 3942 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3943 if (added) { 3944 enforcePermissionCapLocked(info, tree); 3945 bp = new BasePermission(info.name, tree.sourcePackage, 3946 BasePermission.TYPE_DYNAMIC); 3947 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3948 throw new SecurityException( 3949 "Not allowed to modify non-dynamic permission " 3950 + info.name); 3951 } else { 3952 if (bp.protectionLevel == fixedLevel 3953 && bp.perm.owner.equals(tree.perm.owner) 3954 && bp.uid == tree.uid 3955 && comparePermissionInfos(bp.perm.info, info)) { 3956 changed = false; 3957 } 3958 } 3959 bp.protectionLevel = fixedLevel; 3960 info = new PermissionInfo(info); 3961 info.protectionLevel = fixedLevel; 3962 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3963 bp.perm.info.packageName = tree.perm.info.packageName; 3964 bp.uid = tree.uid; 3965 if (added) { 3966 mSettings.mPermissions.put(info.name, bp); 3967 } 3968 if (changed) { 3969 if (!async) { 3970 mSettings.writeLPr(); 3971 } else { 3972 scheduleWriteSettingsLocked(); 3973 } 3974 } 3975 return added; 3976 } 3977 3978 @Override 3979 public boolean addPermission(PermissionInfo info) { 3980 synchronized (mPackages) { 3981 return addPermissionLocked(info, false); 3982 } 3983 } 3984 3985 @Override 3986 public boolean addPermissionAsync(PermissionInfo info) { 3987 synchronized (mPackages) { 3988 return addPermissionLocked(info, true); 3989 } 3990 } 3991 3992 @Override 3993 public void removePermission(String name) { 3994 synchronized (mPackages) { 3995 checkPermissionTreeLP(name); 3996 BasePermission bp = mSettings.mPermissions.get(name); 3997 if (bp != null) { 3998 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3999 throw new SecurityException( 4000 "Not allowed to modify non-dynamic permission " 4001 + name); 4002 } 4003 mSettings.mPermissions.remove(name); 4004 mSettings.writeLPr(); 4005 } 4006 } 4007 } 4008 4009 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4010 BasePermission bp) { 4011 int index = pkg.requestedPermissions.indexOf(bp.name); 4012 if (index == -1) { 4013 throw new SecurityException("Package " + pkg.packageName 4014 + " has not requested permission " + bp.name); 4015 } 4016 if (!bp.isRuntime() && !bp.isDevelopment()) { 4017 throw new SecurityException("Permission " + bp.name 4018 + " is not a changeable permission type"); 4019 } 4020 } 4021 4022 @Override 4023 public void grantRuntimePermission(String packageName, String name, final int userId) { 4024 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4025 } 4026 4027 private void grantRuntimePermission(String packageName, String name, final int userId, 4028 boolean overridePolicy) { 4029 if (!sUserManager.exists(userId)) { 4030 Log.e(TAG, "No such user:" + userId); 4031 return; 4032 } 4033 4034 mContext.enforceCallingOrSelfPermission( 4035 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4036 "grantRuntimePermission"); 4037 4038 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4039 true /* requireFullPermission */, true /* checkShell */, 4040 "grantRuntimePermission"); 4041 4042 final int uid; 4043 final SettingBase sb; 4044 4045 synchronized (mPackages) { 4046 final PackageParser.Package pkg = mPackages.get(packageName); 4047 if (pkg == null) { 4048 throw new IllegalArgumentException("Unknown package: " + packageName); 4049 } 4050 4051 final BasePermission bp = mSettings.mPermissions.get(name); 4052 if (bp == null) { 4053 throw new IllegalArgumentException("Unknown permission: " + name); 4054 } 4055 4056 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4057 4058 // If a permission review is required for legacy apps we represent 4059 // their permissions as always granted runtime ones since we need 4060 // to keep the review required permission flag per user while an 4061 // install permission's state is shared across all users. 4062 if (mPermissionReviewRequired 4063 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4064 && bp.isRuntime()) { 4065 return; 4066 } 4067 4068 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4069 sb = (SettingBase) pkg.mExtras; 4070 if (sb == null) { 4071 throw new IllegalArgumentException("Unknown package: " + packageName); 4072 } 4073 4074 final PermissionsState permissionsState = sb.getPermissionsState(); 4075 4076 final int flags = permissionsState.getPermissionFlags(name, userId); 4077 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4078 throw new SecurityException("Cannot grant system fixed permission " 4079 + name + " for package " + packageName); 4080 } 4081 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4082 throw new SecurityException("Cannot grant policy fixed permission " 4083 + name + " for package " + packageName); 4084 } 4085 4086 if (bp.isDevelopment()) { 4087 // Development permissions must be handled specially, since they are not 4088 // normal runtime permissions. For now they apply to all users. 4089 if (permissionsState.grantInstallPermission(bp) != 4090 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4091 scheduleWriteSettingsLocked(); 4092 } 4093 return; 4094 } 4095 4096 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4097 throw new SecurityException("Cannot grant non-ephemeral permission" 4098 + name + " for package " + packageName); 4099 } 4100 4101 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4102 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4103 return; 4104 } 4105 4106 final int result = permissionsState.grantRuntimePermission(bp, userId); 4107 switch (result) { 4108 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4109 return; 4110 } 4111 4112 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4113 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4114 mHandler.post(new Runnable() { 4115 @Override 4116 public void run() { 4117 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4118 } 4119 }); 4120 } 4121 break; 4122 } 4123 4124 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4125 4126 // Not critical if that is lost - app has to request again. 4127 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4128 } 4129 4130 // Only need to do this if user is initialized. Otherwise it's a new user 4131 // and there are no processes running as the user yet and there's no need 4132 // to make an expensive call to remount processes for the changed permissions. 4133 if (READ_EXTERNAL_STORAGE.equals(name) 4134 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4135 final long token = Binder.clearCallingIdentity(); 4136 try { 4137 if (sUserManager.isInitialized(userId)) { 4138 MountServiceInternal mountServiceInternal = LocalServices.getService( 4139 MountServiceInternal.class); 4140 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4141 } 4142 } finally { 4143 Binder.restoreCallingIdentity(token); 4144 } 4145 } 4146 } 4147 4148 @Override 4149 public void revokeRuntimePermission(String packageName, String name, int userId) { 4150 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4151 } 4152 4153 private void revokeRuntimePermission(String packageName, String name, int userId, 4154 boolean overridePolicy) { 4155 if (!sUserManager.exists(userId)) { 4156 Log.e(TAG, "No such user:" + userId); 4157 return; 4158 } 4159 4160 mContext.enforceCallingOrSelfPermission( 4161 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4162 "revokeRuntimePermission"); 4163 4164 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4165 true /* requireFullPermission */, true /* checkShell */, 4166 "revokeRuntimePermission"); 4167 4168 final int appId; 4169 4170 synchronized (mPackages) { 4171 final PackageParser.Package pkg = mPackages.get(packageName); 4172 if (pkg == null) { 4173 throw new IllegalArgumentException("Unknown package: " + packageName); 4174 } 4175 4176 final BasePermission bp = mSettings.mPermissions.get(name); 4177 if (bp == null) { 4178 throw new IllegalArgumentException("Unknown permission: " + name); 4179 } 4180 4181 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4182 4183 // If a permission review is required for legacy apps we represent 4184 // their permissions as always granted runtime ones since we need 4185 // to keep the review required permission flag per user while an 4186 // install permission's state is shared across all users. 4187 if (mPermissionReviewRequired 4188 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4189 && bp.isRuntime()) { 4190 return; 4191 } 4192 4193 SettingBase sb = (SettingBase) pkg.mExtras; 4194 if (sb == null) { 4195 throw new IllegalArgumentException("Unknown package: " + packageName); 4196 } 4197 4198 final PermissionsState permissionsState = sb.getPermissionsState(); 4199 4200 final int flags = permissionsState.getPermissionFlags(name, userId); 4201 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4202 throw new SecurityException("Cannot revoke system fixed permission " 4203 + name + " for package " + packageName); 4204 } 4205 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4206 throw new SecurityException("Cannot revoke policy fixed permission " 4207 + name + " for package " + packageName); 4208 } 4209 4210 if (bp.isDevelopment()) { 4211 // Development permissions must be handled specially, since they are not 4212 // normal runtime permissions. For now they apply to all users. 4213 if (permissionsState.revokeInstallPermission(bp) != 4214 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4215 scheduleWriteSettingsLocked(); 4216 } 4217 return; 4218 } 4219 4220 if (permissionsState.revokeRuntimePermission(bp, userId) == 4221 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4222 return; 4223 } 4224 4225 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4226 4227 // Critical, after this call app should never have the permission. 4228 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4229 4230 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4231 } 4232 4233 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4234 } 4235 4236 @Override 4237 public void resetRuntimePermissions() { 4238 mContext.enforceCallingOrSelfPermission( 4239 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4240 "revokeRuntimePermission"); 4241 4242 int callingUid = Binder.getCallingUid(); 4243 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4244 mContext.enforceCallingOrSelfPermission( 4245 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4246 "resetRuntimePermissions"); 4247 } 4248 4249 synchronized (mPackages) { 4250 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4251 for (int userId : UserManagerService.getInstance().getUserIds()) { 4252 final int packageCount = mPackages.size(); 4253 for (int i = 0; i < packageCount; i++) { 4254 PackageParser.Package pkg = mPackages.valueAt(i); 4255 if (!(pkg.mExtras instanceof PackageSetting)) { 4256 continue; 4257 } 4258 PackageSetting ps = (PackageSetting) pkg.mExtras; 4259 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4260 } 4261 } 4262 } 4263 } 4264 4265 @Override 4266 public int getPermissionFlags(String name, String packageName, int userId) { 4267 if (!sUserManager.exists(userId)) { 4268 return 0; 4269 } 4270 4271 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4272 4273 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4274 true /* requireFullPermission */, false /* checkShell */, 4275 "getPermissionFlags"); 4276 4277 synchronized (mPackages) { 4278 final PackageParser.Package pkg = mPackages.get(packageName); 4279 if (pkg == null) { 4280 return 0; 4281 } 4282 4283 final BasePermission bp = mSettings.mPermissions.get(name); 4284 if (bp == null) { 4285 return 0; 4286 } 4287 4288 SettingBase sb = (SettingBase) pkg.mExtras; 4289 if (sb == null) { 4290 return 0; 4291 } 4292 4293 PermissionsState permissionsState = sb.getPermissionsState(); 4294 return permissionsState.getPermissionFlags(name, userId); 4295 } 4296 } 4297 4298 @Override 4299 public void updatePermissionFlags(String name, String packageName, int flagMask, 4300 int flagValues, int userId) { 4301 if (!sUserManager.exists(userId)) { 4302 return; 4303 } 4304 4305 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4306 4307 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4308 true /* requireFullPermission */, true /* checkShell */, 4309 "updatePermissionFlags"); 4310 4311 // Only the system can change these flags and nothing else. 4312 if (getCallingUid() != Process.SYSTEM_UID) { 4313 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4314 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4315 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4316 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4317 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4318 } 4319 4320 synchronized (mPackages) { 4321 final PackageParser.Package pkg = mPackages.get(packageName); 4322 if (pkg == null) { 4323 throw new IllegalArgumentException("Unknown package: " + packageName); 4324 } 4325 4326 final BasePermission bp = mSettings.mPermissions.get(name); 4327 if (bp == null) { 4328 throw new IllegalArgumentException("Unknown permission: " + name); 4329 } 4330 4331 SettingBase sb = (SettingBase) pkg.mExtras; 4332 if (sb == null) { 4333 throw new IllegalArgumentException("Unknown package: " + packageName); 4334 } 4335 4336 PermissionsState permissionsState = sb.getPermissionsState(); 4337 4338 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4339 4340 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4341 // Install and runtime permissions are stored in different places, 4342 // so figure out what permission changed and persist the change. 4343 if (permissionsState.getInstallPermissionState(name) != null) { 4344 scheduleWriteSettingsLocked(); 4345 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4346 || hadState) { 4347 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4348 } 4349 } 4350 } 4351 } 4352 4353 /** 4354 * Update the permission flags for all packages and runtime permissions of a user in order 4355 * to allow device or profile owner to remove POLICY_FIXED. 4356 */ 4357 @Override 4358 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4359 if (!sUserManager.exists(userId)) { 4360 return; 4361 } 4362 4363 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4364 4365 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4366 true /* requireFullPermission */, true /* checkShell */, 4367 "updatePermissionFlagsForAllApps"); 4368 4369 // Only the system can change system fixed flags. 4370 if (getCallingUid() != Process.SYSTEM_UID) { 4371 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4372 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4373 } 4374 4375 synchronized (mPackages) { 4376 boolean changed = false; 4377 final int packageCount = mPackages.size(); 4378 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4379 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4380 SettingBase sb = (SettingBase) pkg.mExtras; 4381 if (sb == null) { 4382 continue; 4383 } 4384 PermissionsState permissionsState = sb.getPermissionsState(); 4385 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4386 userId, flagMask, flagValues); 4387 } 4388 if (changed) { 4389 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4390 } 4391 } 4392 } 4393 4394 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4395 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4396 != PackageManager.PERMISSION_GRANTED 4397 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4398 != PackageManager.PERMISSION_GRANTED) { 4399 throw new SecurityException(message + " requires " 4400 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4401 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4402 } 4403 } 4404 4405 @Override 4406 public boolean shouldShowRequestPermissionRationale(String permissionName, 4407 String packageName, int userId) { 4408 if (UserHandle.getCallingUserId() != userId) { 4409 mContext.enforceCallingPermission( 4410 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4411 "canShowRequestPermissionRationale for user " + userId); 4412 } 4413 4414 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4415 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4416 return false; 4417 } 4418 4419 if (checkPermission(permissionName, packageName, userId) 4420 == PackageManager.PERMISSION_GRANTED) { 4421 return false; 4422 } 4423 4424 final int flags; 4425 4426 final long identity = Binder.clearCallingIdentity(); 4427 try { 4428 flags = getPermissionFlags(permissionName, 4429 packageName, userId); 4430 } finally { 4431 Binder.restoreCallingIdentity(identity); 4432 } 4433 4434 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4435 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4436 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4437 4438 if ((flags & fixedFlags) != 0) { 4439 return false; 4440 } 4441 4442 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4443 } 4444 4445 @Override 4446 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4447 mContext.enforceCallingOrSelfPermission( 4448 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4449 "addOnPermissionsChangeListener"); 4450 4451 synchronized (mPackages) { 4452 mOnPermissionChangeListeners.addListenerLocked(listener); 4453 } 4454 } 4455 4456 @Override 4457 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4458 synchronized (mPackages) { 4459 mOnPermissionChangeListeners.removeListenerLocked(listener); 4460 } 4461 } 4462 4463 @Override 4464 public boolean isProtectedBroadcast(String actionName) { 4465 synchronized (mPackages) { 4466 if (mProtectedBroadcasts.contains(actionName)) { 4467 return true; 4468 } else if (actionName != null) { 4469 // TODO: remove these terrible hacks 4470 if (actionName.startsWith("android.net.netmon.lingerExpired") 4471 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4472 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4473 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4474 return true; 4475 } 4476 } 4477 } 4478 return false; 4479 } 4480 4481 @Override 4482 public int checkSignatures(String pkg1, String pkg2) { 4483 synchronized (mPackages) { 4484 final PackageParser.Package p1 = mPackages.get(pkg1); 4485 final PackageParser.Package p2 = mPackages.get(pkg2); 4486 if (p1 == null || p1.mExtras == null 4487 || p2 == null || p2.mExtras == null) { 4488 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4489 } 4490 return compareSignatures(p1.mSignatures, p2.mSignatures); 4491 } 4492 } 4493 4494 @Override 4495 public int checkUidSignatures(int uid1, int uid2) { 4496 // Map to base uids. 4497 uid1 = UserHandle.getAppId(uid1); 4498 uid2 = UserHandle.getAppId(uid2); 4499 // reader 4500 synchronized (mPackages) { 4501 Signature[] s1; 4502 Signature[] s2; 4503 Object obj = mSettings.getUserIdLPr(uid1); 4504 if (obj != null) { 4505 if (obj instanceof SharedUserSetting) { 4506 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4507 } else if (obj instanceof PackageSetting) { 4508 s1 = ((PackageSetting)obj).signatures.mSignatures; 4509 } else { 4510 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4511 } 4512 } else { 4513 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4514 } 4515 obj = mSettings.getUserIdLPr(uid2); 4516 if (obj != null) { 4517 if (obj instanceof SharedUserSetting) { 4518 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4519 } else if (obj instanceof PackageSetting) { 4520 s2 = ((PackageSetting)obj).signatures.mSignatures; 4521 } else { 4522 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4523 } 4524 } else { 4525 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4526 } 4527 return compareSignatures(s1, s2); 4528 } 4529 } 4530 4531 /** 4532 * This method should typically only be used when granting or revoking 4533 * permissions, since the app may immediately restart after this call. 4534 * <p> 4535 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4536 * guard your work against the app being relaunched. 4537 */ 4538 private void killUid(int appId, int userId, String reason) { 4539 final long identity = Binder.clearCallingIdentity(); 4540 try { 4541 IActivityManager am = ActivityManagerNative.getDefault(); 4542 if (am != null) { 4543 try { 4544 am.killUid(appId, userId, reason); 4545 } catch (RemoteException e) { 4546 /* ignore - same process */ 4547 } 4548 } 4549 } finally { 4550 Binder.restoreCallingIdentity(identity); 4551 } 4552 } 4553 4554 /** 4555 * Compares two sets of signatures. Returns: 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4558 * <br /> 4559 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4560 * <br /> 4561 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4562 * <br /> 4563 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4564 * <br /> 4565 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4566 */ 4567 static int compareSignatures(Signature[] s1, Signature[] s2) { 4568 if (s1 == null) { 4569 return s2 == null 4570 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4571 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4572 } 4573 4574 if (s2 == null) { 4575 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4576 } 4577 4578 if (s1.length != s2.length) { 4579 return PackageManager.SIGNATURE_NO_MATCH; 4580 } 4581 4582 // Since both signature sets are of size 1, we can compare without HashSets. 4583 if (s1.length == 1) { 4584 return s1[0].equals(s2[0]) ? 4585 PackageManager.SIGNATURE_MATCH : 4586 PackageManager.SIGNATURE_NO_MATCH; 4587 } 4588 4589 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4590 for (Signature sig : s1) { 4591 set1.add(sig); 4592 } 4593 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4594 for (Signature sig : s2) { 4595 set2.add(sig); 4596 } 4597 // Make sure s2 contains all signatures in s1. 4598 if (set1.equals(set2)) { 4599 return PackageManager.SIGNATURE_MATCH; 4600 } 4601 return PackageManager.SIGNATURE_NO_MATCH; 4602 } 4603 4604 /** 4605 * If the database version for this type of package (internal storage or 4606 * external storage) is less than the version where package signatures 4607 * were updated, return true. 4608 */ 4609 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4610 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4611 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4612 } 4613 4614 /** 4615 * Used for backward compatibility to make sure any packages with 4616 * certificate chains get upgraded to the new style. {@code existingSigs} 4617 * will be in the old format (since they were stored on disk from before the 4618 * system upgrade) and {@code scannedSigs} will be in the newer format. 4619 */ 4620 private int compareSignaturesCompat(PackageSignatures existingSigs, 4621 PackageParser.Package scannedPkg) { 4622 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4623 return PackageManager.SIGNATURE_NO_MATCH; 4624 } 4625 4626 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4627 for (Signature sig : existingSigs.mSignatures) { 4628 existingSet.add(sig); 4629 } 4630 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4631 for (Signature sig : scannedPkg.mSignatures) { 4632 try { 4633 Signature[] chainSignatures = sig.getChainSignatures(); 4634 for (Signature chainSig : chainSignatures) { 4635 scannedCompatSet.add(chainSig); 4636 } 4637 } catch (CertificateEncodingException e) { 4638 scannedCompatSet.add(sig); 4639 } 4640 } 4641 /* 4642 * Make sure the expanded scanned set contains all signatures in the 4643 * existing one. 4644 */ 4645 if (scannedCompatSet.equals(existingSet)) { 4646 // Migrate the old signatures to the new scheme. 4647 existingSigs.assignSignatures(scannedPkg.mSignatures); 4648 // The new KeySets will be re-added later in the scanning process. 4649 synchronized (mPackages) { 4650 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4651 } 4652 return PackageManager.SIGNATURE_MATCH; 4653 } 4654 return PackageManager.SIGNATURE_NO_MATCH; 4655 } 4656 4657 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4658 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4659 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4660 } 4661 4662 private int compareSignaturesRecover(PackageSignatures existingSigs, 4663 PackageParser.Package scannedPkg) { 4664 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4665 return PackageManager.SIGNATURE_NO_MATCH; 4666 } 4667 4668 String msg = null; 4669 try { 4670 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4671 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4672 + scannedPkg.packageName); 4673 return PackageManager.SIGNATURE_MATCH; 4674 } 4675 } catch (CertificateException e) { 4676 msg = e.getMessage(); 4677 } 4678 4679 logCriticalInfo(Log.INFO, 4680 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4681 return PackageManager.SIGNATURE_NO_MATCH; 4682 } 4683 4684 @Override 4685 public List<String> getAllPackages() { 4686 synchronized (mPackages) { 4687 return new ArrayList<String>(mPackages.keySet()); 4688 } 4689 } 4690 4691 @Override 4692 public String[] getPackagesForUid(int uid) { 4693 final int userId = UserHandle.getUserId(uid); 4694 uid = UserHandle.getAppId(uid); 4695 // reader 4696 synchronized (mPackages) { 4697 Object obj = mSettings.getUserIdLPr(uid); 4698 if (obj instanceof SharedUserSetting) { 4699 final SharedUserSetting sus = (SharedUserSetting) obj; 4700 final int N = sus.packages.size(); 4701 String[] res = new String[N]; 4702 final Iterator<PackageSetting> it = sus.packages.iterator(); 4703 int i = 0; 4704 while (it.hasNext()) { 4705 PackageSetting ps = it.next(); 4706 if (ps.getInstalled(userId)) { 4707 res[i++] = ps.name; 4708 } else { 4709 res = ArrayUtils.removeElement(String.class, res, res[i]); 4710 } 4711 } 4712 return res; 4713 } else if (obj instanceof PackageSetting) { 4714 final PackageSetting ps = (PackageSetting) obj; 4715 return new String[] { ps.name }; 4716 } 4717 } 4718 return null; 4719 } 4720 4721 @Override 4722 public String getNameForUid(int uid) { 4723 // reader 4724 synchronized (mPackages) { 4725 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4726 if (obj instanceof SharedUserSetting) { 4727 final SharedUserSetting sus = (SharedUserSetting) obj; 4728 return sus.name + ":" + sus.userId; 4729 } else if (obj instanceof PackageSetting) { 4730 final PackageSetting ps = (PackageSetting) obj; 4731 return ps.name; 4732 } 4733 } 4734 return null; 4735 } 4736 4737 @Override 4738 public int getUidForSharedUser(String sharedUserName) { 4739 if(sharedUserName == null) { 4740 return -1; 4741 } 4742 // reader 4743 synchronized (mPackages) { 4744 SharedUserSetting suid; 4745 try { 4746 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4747 if (suid != null) { 4748 return suid.userId; 4749 } 4750 } catch (PackageManagerException ignore) { 4751 // can't happen, but, still need to catch it 4752 } 4753 return -1; 4754 } 4755 } 4756 4757 @Override 4758 public int getFlagsForUid(int uid) { 4759 synchronized (mPackages) { 4760 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4761 if (obj instanceof SharedUserSetting) { 4762 final SharedUserSetting sus = (SharedUserSetting) obj; 4763 return sus.pkgFlags; 4764 } else if (obj instanceof PackageSetting) { 4765 final PackageSetting ps = (PackageSetting) obj; 4766 return ps.pkgFlags; 4767 } 4768 } 4769 return 0; 4770 } 4771 4772 @Override 4773 public int getPrivateFlagsForUid(int uid) { 4774 synchronized (mPackages) { 4775 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4776 if (obj instanceof SharedUserSetting) { 4777 final SharedUserSetting sus = (SharedUserSetting) obj; 4778 return sus.pkgPrivateFlags; 4779 } else if (obj instanceof PackageSetting) { 4780 final PackageSetting ps = (PackageSetting) obj; 4781 return ps.pkgPrivateFlags; 4782 } 4783 } 4784 return 0; 4785 } 4786 4787 @Override 4788 public boolean isUidPrivileged(int uid) { 4789 uid = UserHandle.getAppId(uid); 4790 // reader 4791 synchronized (mPackages) { 4792 Object obj = mSettings.getUserIdLPr(uid); 4793 if (obj instanceof SharedUserSetting) { 4794 final SharedUserSetting sus = (SharedUserSetting) obj; 4795 final Iterator<PackageSetting> it = sus.packages.iterator(); 4796 while (it.hasNext()) { 4797 if (it.next().isPrivileged()) { 4798 return true; 4799 } 4800 } 4801 } else if (obj instanceof PackageSetting) { 4802 final PackageSetting ps = (PackageSetting) obj; 4803 return ps.isPrivileged(); 4804 } 4805 } 4806 return false; 4807 } 4808 4809 @Override 4810 public String[] getAppOpPermissionPackages(String permissionName) { 4811 synchronized (mPackages) { 4812 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4813 if (pkgs == null) { 4814 return null; 4815 } 4816 return pkgs.toArray(new String[pkgs.size()]); 4817 } 4818 } 4819 4820 @Override 4821 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4822 int flags, int userId) { 4823 try { 4824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4825 4826 if (!sUserManager.exists(userId)) return null; 4827 flags = updateFlagsForResolve(flags, userId, intent); 4828 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4829 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4830 4831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4832 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4833 flags, userId); 4834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4835 4836 final ResolveInfo bestChoice = 4837 chooseBestActivity(intent, resolvedType, flags, query, userId); 4838 return bestChoice; 4839 } finally { 4840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4841 } 4842 } 4843 4844 @Override 4845 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4846 IntentFilter filter, int match, ComponentName activity) { 4847 final int userId = UserHandle.getCallingUserId(); 4848 if (DEBUG_PREFERRED) { 4849 Log.v(TAG, "setLastChosenActivity intent=" + intent 4850 + " resolvedType=" + resolvedType 4851 + " flags=" + flags 4852 + " filter=" + filter 4853 + " match=" + match 4854 + " activity=" + activity); 4855 filter.dump(new PrintStreamPrinter(System.out), " "); 4856 } 4857 intent.setComponent(null); 4858 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4859 userId); 4860 // Find any earlier preferred or last chosen entries and nuke them 4861 findPreferredActivity(intent, resolvedType, 4862 flags, query, 0, false, true, false, userId); 4863 // Add the new activity as the last chosen for this filter 4864 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4865 "Setting last chosen"); 4866 } 4867 4868 @Override 4869 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4870 final int userId = UserHandle.getCallingUserId(); 4871 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4872 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4873 userId); 4874 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4875 false, false, false, userId); 4876 } 4877 4878 private boolean isEphemeralDisabled() { 4879 // ephemeral apps have been disabled across the board 4880 if (DISABLE_EPHEMERAL_APPS) { 4881 return true; 4882 } 4883 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4884 if (!mSystemReady) { 4885 return true; 4886 } 4887 // we can't get a content resolver until the system is ready; these checks must happen last 4888 final ContentResolver resolver = mContext.getContentResolver(); 4889 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4890 return true; 4891 } 4892 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4893 } 4894 4895 private boolean isEphemeralAllowed( 4896 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4897 boolean skipPackageCheck) { 4898 // Short circuit and return early if possible. 4899 if (isEphemeralDisabled()) { 4900 return false; 4901 } 4902 final int callingUser = UserHandle.getCallingUserId(); 4903 if (callingUser != UserHandle.USER_SYSTEM) { 4904 return false; 4905 } 4906 if (mEphemeralResolverConnection == null) { 4907 return false; 4908 } 4909 if (intent.getComponent() != null) { 4910 return false; 4911 } 4912 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4913 return false; 4914 } 4915 if (!skipPackageCheck && intent.getPackage() != null) { 4916 return false; 4917 } 4918 final boolean isWebUri = hasWebURI(intent); 4919 if (!isWebUri || intent.getData().getHost() == null) { 4920 return false; 4921 } 4922 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4923 synchronized (mPackages) { 4924 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4925 for (int n = 0; n < count; n++) { 4926 ResolveInfo info = resolvedActivities.get(n); 4927 String packageName = info.activityInfo.packageName; 4928 PackageSetting ps = mSettings.mPackages.get(packageName); 4929 if (ps != null) { 4930 // Try to get the status from User settings first 4931 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4932 int status = (int) (packedStatus >> 32); 4933 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4934 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4935 if (DEBUG_EPHEMERAL) { 4936 Slog.v(TAG, "DENY ephemeral apps;" 4937 + " pkg: " + packageName + ", status: " + status); 4938 } 4939 return false; 4940 } 4941 } 4942 } 4943 } 4944 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4945 return true; 4946 } 4947 4948 private static EphemeralResolveInfo getEphemeralResolveInfo( 4949 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4950 String resolvedType, int userId, String packageName) { 4951 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4952 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4953 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4954 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4955 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4956 ephemeralPrefixCount); 4957 final int[] shaPrefix = digest.getDigestPrefix(); 4958 final byte[][] digestBytes = digest.getDigestBytes(); 4959 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4960 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4961 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4962 // No hash prefix match; there are no ephemeral apps for this domain. 4963 return null; 4964 } 4965 4966 // Go in reverse order so we match the narrowest scope first. 4967 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4968 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4969 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4970 continue; 4971 } 4972 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4973 // No filters; this should never happen. 4974 if (filters.isEmpty()) { 4975 continue; 4976 } 4977 if (packageName != null 4978 && !packageName.equals(ephemeralApplication.getPackageName())) { 4979 continue; 4980 } 4981 // We have a domain match; resolve the filters to see if anything matches. 4982 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4983 for (int j = filters.size() - 1; j >= 0; --j) { 4984 final EphemeralResolveIntentInfo intentInfo = 4985 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4986 ephemeralResolver.addFilter(intentInfo); 4987 } 4988 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4989 intent, resolvedType, false /*defaultOnly*/, userId); 4990 if (!matchedResolveInfoList.isEmpty()) { 4991 return matchedResolveInfoList.get(0); 4992 } 4993 } 4994 } 4995 // Hash or filter mis-match; no ephemeral apps for this domain. 4996 return null; 4997 } 4998 4999 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5000 int flags, List<ResolveInfo> query, int userId) { 5001 if (query != null) { 5002 final int N = query.size(); 5003 if (N == 1) { 5004 return query.get(0); 5005 } else if (N > 1) { 5006 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5007 // If there is more than one activity with the same priority, 5008 // then let the user decide between them. 5009 ResolveInfo r0 = query.get(0); 5010 ResolveInfo r1 = query.get(1); 5011 if (DEBUG_INTENT_MATCHING || debug) { 5012 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5013 + r1.activityInfo.name + "=" + r1.priority); 5014 } 5015 // If the first activity has a higher priority, or a different 5016 // default, then it is always desirable to pick it. 5017 if (r0.priority != r1.priority 5018 || r0.preferredOrder != r1.preferredOrder 5019 || r0.isDefault != r1.isDefault) { 5020 return query.get(0); 5021 } 5022 // If we have saved a preference for a preferred activity for 5023 // this Intent, use that. 5024 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5025 flags, query, r0.priority, true, false, debug, userId); 5026 if (ri != null) { 5027 return ri; 5028 } 5029 ri = new ResolveInfo(mResolveInfo); 5030 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5031 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5032 // If all of the options come from the same package, show the application's 5033 // label and icon instead of the generic resolver's. 5034 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5035 // and then throw away the ResolveInfo itself, meaning that the caller loses 5036 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5037 // a fallback for this case; we only set the target package's resources on 5038 // the ResolveInfo, not the ActivityInfo. 5039 final String intentPackage = intent.getPackage(); 5040 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5041 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5042 ri.resolvePackageName = intentPackage; 5043 if (userNeedsBadging(userId)) { 5044 ri.noResourceId = true; 5045 } else { 5046 ri.icon = appi.icon; 5047 } 5048 ri.iconResourceId = appi.icon; 5049 ri.labelRes = appi.labelRes; 5050 } 5051 ri.activityInfo.applicationInfo = new ApplicationInfo( 5052 ri.activityInfo.applicationInfo); 5053 if (userId != 0) { 5054 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5055 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5056 } 5057 // Make sure that the resolver is displayable in car mode 5058 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5059 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5060 return ri; 5061 } 5062 } 5063 return null; 5064 } 5065 5066 /** 5067 * Return true if the given list is not empty and all of its contents have 5068 * an activityInfo with the given package name. 5069 */ 5070 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5071 if (ArrayUtils.isEmpty(list)) { 5072 return false; 5073 } 5074 for (int i = 0, N = list.size(); i < N; i++) { 5075 final ResolveInfo ri = list.get(i); 5076 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5077 if (ai == null || !packageName.equals(ai.packageName)) { 5078 return false; 5079 } 5080 } 5081 return true; 5082 } 5083 5084 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5085 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5086 final int N = query.size(); 5087 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5088 .get(userId); 5089 // Get the list of persistent preferred activities that handle the intent 5090 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5091 List<PersistentPreferredActivity> pprefs = ppir != null 5092 ? ppir.queryIntent(intent, resolvedType, 5093 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5094 : null; 5095 if (pprefs != null && pprefs.size() > 0) { 5096 final int M = pprefs.size(); 5097 for (int i=0; i<M; i++) { 5098 final PersistentPreferredActivity ppa = pprefs.get(i); 5099 if (DEBUG_PREFERRED || debug) { 5100 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5101 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5102 + "\n component=" + ppa.mComponent); 5103 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5104 } 5105 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5106 flags | MATCH_DISABLED_COMPONENTS, userId); 5107 if (DEBUG_PREFERRED || debug) { 5108 Slog.v(TAG, "Found persistent preferred activity:"); 5109 if (ai != null) { 5110 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5111 } else { 5112 Slog.v(TAG, " null"); 5113 } 5114 } 5115 if (ai == null) { 5116 // This previously registered persistent preferred activity 5117 // component is no longer known. Ignore it and do NOT remove it. 5118 continue; 5119 } 5120 for (int j=0; j<N; j++) { 5121 final ResolveInfo ri = query.get(j); 5122 if (!ri.activityInfo.applicationInfo.packageName 5123 .equals(ai.applicationInfo.packageName)) { 5124 continue; 5125 } 5126 if (!ri.activityInfo.name.equals(ai.name)) { 5127 continue; 5128 } 5129 // Found a persistent preference that can handle the intent. 5130 if (DEBUG_PREFERRED || debug) { 5131 Slog.v(TAG, "Returning persistent preferred activity: " + 5132 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5133 } 5134 return ri; 5135 } 5136 } 5137 } 5138 return null; 5139 } 5140 5141 // TODO: handle preferred activities missing while user has amnesia 5142 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5143 List<ResolveInfo> query, int priority, boolean always, 5144 boolean removeMatches, boolean debug, int userId) { 5145 if (!sUserManager.exists(userId)) return null; 5146 flags = updateFlagsForResolve(flags, userId, intent); 5147 // writer 5148 synchronized (mPackages) { 5149 if (intent.getSelector() != null) { 5150 intent = intent.getSelector(); 5151 } 5152 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5153 5154 // Try to find a matching persistent preferred activity. 5155 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5156 debug, userId); 5157 5158 // If a persistent preferred activity matched, use it. 5159 if (pri != null) { 5160 return pri; 5161 } 5162 5163 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5164 // Get the list of preferred activities that handle the intent 5165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5166 List<PreferredActivity> prefs = pir != null 5167 ? pir.queryIntent(intent, resolvedType, 5168 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5169 : null; 5170 if (prefs != null && prefs.size() > 0) { 5171 boolean changed = false; 5172 try { 5173 // First figure out how good the original match set is. 5174 // We will only allow preferred activities that came 5175 // from the same match quality. 5176 int match = 0; 5177 5178 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5179 5180 final int N = query.size(); 5181 for (int j=0; j<N; j++) { 5182 final ResolveInfo ri = query.get(j); 5183 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5184 + ": 0x" + Integer.toHexString(match)); 5185 if (ri.match > match) { 5186 match = ri.match; 5187 } 5188 } 5189 5190 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5191 + Integer.toHexString(match)); 5192 5193 match &= IntentFilter.MATCH_CATEGORY_MASK; 5194 final int M = prefs.size(); 5195 for (int i=0; i<M; i++) { 5196 final PreferredActivity pa = prefs.get(i); 5197 if (DEBUG_PREFERRED || debug) { 5198 Slog.v(TAG, "Checking PreferredActivity ds=" 5199 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5200 + "\n component=" + pa.mPref.mComponent); 5201 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5202 } 5203 if (pa.mPref.mMatch != match) { 5204 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5205 + Integer.toHexString(pa.mPref.mMatch)); 5206 continue; 5207 } 5208 // If it's not an "always" type preferred activity and that's what we're 5209 // looking for, skip it. 5210 if (always && !pa.mPref.mAlways) { 5211 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5212 continue; 5213 } 5214 final ActivityInfo ai = getActivityInfo( 5215 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5216 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5217 userId); 5218 if (DEBUG_PREFERRED || debug) { 5219 Slog.v(TAG, "Found preferred activity:"); 5220 if (ai != null) { 5221 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5222 } else { 5223 Slog.v(TAG, " null"); 5224 } 5225 } 5226 if (ai == null) { 5227 // This previously registered preferred activity 5228 // component is no longer known. Most likely an update 5229 // to the app was installed and in the new version this 5230 // component no longer exists. Clean it up by removing 5231 // it from the preferred activities list, and skip it. 5232 Slog.w(TAG, "Removing dangling preferred activity: " 5233 + pa.mPref.mComponent); 5234 pir.removeFilter(pa); 5235 changed = true; 5236 continue; 5237 } 5238 for (int j=0; j<N; j++) { 5239 final ResolveInfo ri = query.get(j); 5240 if (!ri.activityInfo.applicationInfo.packageName 5241 .equals(ai.applicationInfo.packageName)) { 5242 continue; 5243 } 5244 if (!ri.activityInfo.name.equals(ai.name)) { 5245 continue; 5246 } 5247 5248 if (removeMatches) { 5249 pir.removeFilter(pa); 5250 changed = true; 5251 if (DEBUG_PREFERRED) { 5252 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5253 } 5254 break; 5255 } 5256 5257 // Okay we found a previously set preferred or last chosen app. 5258 // If the result set is different from when this 5259 // was created, we need to clear it and re-ask the 5260 // user their preference, if we're looking for an "always" type entry. 5261 if (always && !pa.mPref.sameSet(query)) { 5262 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5263 + intent + " type " + resolvedType); 5264 if (DEBUG_PREFERRED) { 5265 Slog.v(TAG, "Removing preferred activity since set changed " 5266 + pa.mPref.mComponent); 5267 } 5268 pir.removeFilter(pa); 5269 // Re-add the filter as a "last chosen" entry (!always) 5270 PreferredActivity lastChosen = new PreferredActivity( 5271 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5272 pir.addFilter(lastChosen); 5273 changed = true; 5274 return null; 5275 } 5276 5277 // Yay! Either the set matched or we're looking for the last chosen 5278 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5279 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5280 return ri; 5281 } 5282 } 5283 } finally { 5284 if (changed) { 5285 if (DEBUG_PREFERRED) { 5286 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5287 } 5288 scheduleWritePackageRestrictionsLocked(userId); 5289 } 5290 } 5291 } 5292 } 5293 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5294 return null; 5295 } 5296 5297 /* 5298 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5299 */ 5300 @Override 5301 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5302 int targetUserId) { 5303 mContext.enforceCallingOrSelfPermission( 5304 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5305 List<CrossProfileIntentFilter> matches = 5306 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5307 if (matches != null) { 5308 int size = matches.size(); 5309 for (int i = 0; i < size; i++) { 5310 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5311 } 5312 } 5313 if (hasWebURI(intent)) { 5314 // cross-profile app linking works only towards the parent. 5315 final UserInfo parent = getProfileParent(sourceUserId); 5316 synchronized(mPackages) { 5317 int flags = updateFlagsForResolve(0, parent.id, intent); 5318 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5319 intent, resolvedType, flags, sourceUserId, parent.id); 5320 return xpDomainInfo != null; 5321 } 5322 } 5323 return false; 5324 } 5325 5326 private UserInfo getProfileParent(int userId) { 5327 final long identity = Binder.clearCallingIdentity(); 5328 try { 5329 return sUserManager.getProfileParent(userId); 5330 } finally { 5331 Binder.restoreCallingIdentity(identity); 5332 } 5333 } 5334 5335 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5336 String resolvedType, int userId) { 5337 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5338 if (resolver != null) { 5339 return resolver.queryIntent(intent, resolvedType, false, userId); 5340 } 5341 return null; 5342 } 5343 5344 @Override 5345 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5346 String resolvedType, int flags, int userId) { 5347 try { 5348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5349 5350 return new ParceledListSlice<>( 5351 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5352 } finally { 5353 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5354 } 5355 } 5356 5357 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5358 String resolvedType, int flags, int userId) { 5359 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5360 flags = updateFlagsForResolve(flags, userId, intent); 5361 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5362 false /* requireFullPermission */, false /* checkShell */, 5363 "query intent activities"); 5364 ComponentName comp = intent.getComponent(); 5365 if (comp == null) { 5366 if (intent.getSelector() != null) { 5367 intent = intent.getSelector(); 5368 comp = intent.getComponent(); 5369 } 5370 } 5371 5372 if (comp != null) { 5373 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5374 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5375 if (ai != null) { 5376 final ResolveInfo ri = new ResolveInfo(); 5377 ri.activityInfo = ai; 5378 list.add(ri); 5379 } 5380 return list; 5381 } 5382 5383 // reader 5384 boolean sortResult = false; 5385 boolean addEphemeral = false; 5386 boolean matchEphemeralPackage = false; 5387 List<ResolveInfo> result; 5388 final String pkgName = intent.getPackage(); 5389 synchronized (mPackages) { 5390 if (pkgName == null) { 5391 List<CrossProfileIntentFilter> matchingFilters = 5392 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5393 // Check for results that need to skip the current profile. 5394 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5395 resolvedType, flags, userId); 5396 if (xpResolveInfo != null) { 5397 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5398 xpResult.add(xpResolveInfo); 5399 return filterIfNotSystemUser(xpResult, userId); 5400 } 5401 5402 // Check for results in the current profile. 5403 result = filterIfNotSystemUser(mActivities.queryIntent( 5404 intent, resolvedType, flags, userId), userId); 5405 addEphemeral = 5406 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5407 5408 // Check for cross profile results. 5409 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5410 xpResolveInfo = queryCrossProfileIntents( 5411 matchingFilters, intent, resolvedType, flags, userId, 5412 hasNonNegativePriorityResult); 5413 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5414 boolean isVisibleToUser = filterIfNotSystemUser( 5415 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5416 if (isVisibleToUser) { 5417 result.add(xpResolveInfo); 5418 sortResult = true; 5419 } 5420 } 5421 if (hasWebURI(intent)) { 5422 CrossProfileDomainInfo xpDomainInfo = null; 5423 final UserInfo parent = getProfileParent(userId); 5424 if (parent != null) { 5425 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5426 flags, userId, parent.id); 5427 } 5428 if (xpDomainInfo != null) { 5429 if (xpResolveInfo != null) { 5430 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5431 // in the result. 5432 result.remove(xpResolveInfo); 5433 } 5434 if (result.size() == 0 && !addEphemeral) { 5435 // No result in current profile, but found candidate in parent user. 5436 // And we are not going to add emphemeral app, so we can return the 5437 // result straight away. 5438 result.add(xpDomainInfo.resolveInfo); 5439 return result; 5440 } 5441 } else if (result.size() <= 1 && !addEphemeral) { 5442 // No result in parent user and <= 1 result in current profile, and we 5443 // are not going to add emphemeral app, so we can return the result without 5444 // further processing. 5445 return result; 5446 } 5447 // We have more than one candidate (combining results from current and parent 5448 // profile), so we need filtering and sorting. 5449 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5450 intent, flags, result, xpDomainInfo, userId); 5451 sortResult = true; 5452 } 5453 } else { 5454 final PackageParser.Package pkg = mPackages.get(pkgName); 5455 if (pkg != null) { 5456 result = filterIfNotSystemUser( 5457 mActivities.queryIntentForPackage( 5458 intent, resolvedType, flags, pkg.activities, userId), 5459 userId); 5460 } else { 5461 // the caller wants to resolve for a particular package; however, there 5462 // were no installed results, so, try to find an ephemeral result 5463 addEphemeral = isEphemeralAllowed( 5464 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5465 matchEphemeralPackage = true; 5466 result = new ArrayList<ResolveInfo>(); 5467 } 5468 } 5469 } 5470 if (addEphemeral) { 5471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5472 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5473 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5474 matchEphemeralPackage ? pkgName : null); 5475 if (ai != null) { 5476 if (DEBUG_EPHEMERAL) { 5477 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5478 } 5479 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5480 ephemeralInstaller.ephemeralResolveInfo = ai; 5481 // make sure this resolver is the default 5482 ephemeralInstaller.isDefault = true; 5483 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5484 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5485 // add a non-generic filter 5486 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5487 ephemeralInstaller.filter.addDataPath( 5488 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5489 result.add(ephemeralInstaller); 5490 } 5491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5492 } 5493 if (sortResult) { 5494 Collections.sort(result, mResolvePrioritySorter); 5495 } 5496 return result; 5497 } 5498 5499 private static class CrossProfileDomainInfo { 5500 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5501 ResolveInfo resolveInfo; 5502 /* Best domain verification status of the activities found in the other profile */ 5503 int bestDomainVerificationStatus; 5504 } 5505 5506 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5507 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5508 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5509 sourceUserId)) { 5510 return null; 5511 } 5512 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5513 resolvedType, flags, parentUserId); 5514 5515 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5516 return null; 5517 } 5518 CrossProfileDomainInfo result = null; 5519 int size = resultTargetUser.size(); 5520 for (int i = 0; i < size; i++) { 5521 ResolveInfo riTargetUser = resultTargetUser.get(i); 5522 // Intent filter verification is only for filters that specify a host. So don't return 5523 // those that handle all web uris. 5524 if (riTargetUser.handleAllWebDataURI) { 5525 continue; 5526 } 5527 String packageName = riTargetUser.activityInfo.packageName; 5528 PackageSetting ps = mSettings.mPackages.get(packageName); 5529 if (ps == null) { 5530 continue; 5531 } 5532 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5533 int status = (int)(verificationState >> 32); 5534 if (result == null) { 5535 result = new CrossProfileDomainInfo(); 5536 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5537 sourceUserId, parentUserId); 5538 result.bestDomainVerificationStatus = status; 5539 } else { 5540 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5541 result.bestDomainVerificationStatus); 5542 } 5543 } 5544 // Don't consider matches with status NEVER across profiles. 5545 if (result != null && result.bestDomainVerificationStatus 5546 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5547 return null; 5548 } 5549 return result; 5550 } 5551 5552 /** 5553 * Verification statuses are ordered from the worse to the best, except for 5554 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5555 */ 5556 private int bestDomainVerificationStatus(int status1, int status2) { 5557 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5558 return status2; 5559 } 5560 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5561 return status1; 5562 } 5563 return (int) MathUtils.max(status1, status2); 5564 } 5565 5566 private boolean isUserEnabled(int userId) { 5567 long callingId = Binder.clearCallingIdentity(); 5568 try { 5569 UserInfo userInfo = sUserManager.getUserInfo(userId); 5570 return userInfo != null && userInfo.isEnabled(); 5571 } finally { 5572 Binder.restoreCallingIdentity(callingId); 5573 } 5574 } 5575 5576 /** 5577 * Filter out activities with systemUserOnly flag set, when current user is not System. 5578 * 5579 * @return filtered list 5580 */ 5581 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5582 if (userId == UserHandle.USER_SYSTEM) { 5583 return resolveInfos; 5584 } 5585 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5586 ResolveInfo info = resolveInfos.get(i); 5587 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5588 resolveInfos.remove(i); 5589 } 5590 } 5591 return resolveInfos; 5592 } 5593 5594 /** 5595 * @param resolveInfos list of resolve infos in descending priority order 5596 * @return if the list contains a resolve info with non-negative priority 5597 */ 5598 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5599 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5600 } 5601 5602 private static boolean hasWebURI(Intent intent) { 5603 if (intent.getData() == null) { 5604 return false; 5605 } 5606 final String scheme = intent.getScheme(); 5607 if (TextUtils.isEmpty(scheme)) { 5608 return false; 5609 } 5610 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5611 } 5612 5613 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5614 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5615 int userId) { 5616 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5617 5618 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5619 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5620 candidates.size()); 5621 } 5622 5623 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5624 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5625 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5626 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5627 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5628 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5629 5630 synchronized (mPackages) { 5631 final int count = candidates.size(); 5632 // First, try to use linked apps. Partition the candidates into four lists: 5633 // one for the final results, one for the "do not use ever", one for "undefined status" 5634 // and finally one for "browser app type". 5635 for (int n=0; n<count; n++) { 5636 ResolveInfo info = candidates.get(n); 5637 String packageName = info.activityInfo.packageName; 5638 PackageSetting ps = mSettings.mPackages.get(packageName); 5639 if (ps != null) { 5640 // Add to the special match all list (Browser use case) 5641 if (info.handleAllWebDataURI) { 5642 matchAllList.add(info); 5643 continue; 5644 } 5645 // Try to get the status from User settings first 5646 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5647 int status = (int)(packedStatus >> 32); 5648 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5649 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5650 if (DEBUG_DOMAIN_VERIFICATION) { 5651 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5652 + " : linkgen=" + linkGeneration); 5653 } 5654 // Use link-enabled generation as preferredOrder, i.e. 5655 // prefer newly-enabled over earlier-enabled. 5656 info.preferredOrder = linkGeneration; 5657 alwaysList.add(info); 5658 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5659 if (DEBUG_DOMAIN_VERIFICATION) { 5660 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5661 } 5662 neverList.add(info); 5663 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5664 if (DEBUG_DOMAIN_VERIFICATION) { 5665 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5666 } 5667 alwaysAskList.add(info); 5668 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5669 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5670 if (DEBUG_DOMAIN_VERIFICATION) { 5671 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5672 } 5673 undefinedList.add(info); 5674 } 5675 } 5676 } 5677 5678 // We'll want to include browser possibilities in a few cases 5679 boolean includeBrowser = false; 5680 5681 // First try to add the "always" resolution(s) for the current user, if any 5682 if (alwaysList.size() > 0) { 5683 result.addAll(alwaysList); 5684 } else { 5685 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5686 result.addAll(undefinedList); 5687 // Maybe add one for the other profile. 5688 if (xpDomainInfo != null && ( 5689 xpDomainInfo.bestDomainVerificationStatus 5690 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5691 result.add(xpDomainInfo.resolveInfo); 5692 } 5693 includeBrowser = true; 5694 } 5695 5696 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5697 // If there were 'always' entries their preferred order has been set, so we also 5698 // back that off to make the alternatives equivalent 5699 if (alwaysAskList.size() > 0) { 5700 for (ResolveInfo i : result) { 5701 i.preferredOrder = 0; 5702 } 5703 result.addAll(alwaysAskList); 5704 includeBrowser = true; 5705 } 5706 5707 if (includeBrowser) { 5708 // Also add browsers (all of them or only the default one) 5709 if (DEBUG_DOMAIN_VERIFICATION) { 5710 Slog.v(TAG, " ...including browsers in candidate set"); 5711 } 5712 if ((matchFlags & MATCH_ALL) != 0) { 5713 result.addAll(matchAllList); 5714 } else { 5715 // Browser/generic handling case. If there's a default browser, go straight 5716 // to that (but only if there is no other higher-priority match). 5717 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5718 int maxMatchPrio = 0; 5719 ResolveInfo defaultBrowserMatch = null; 5720 final int numCandidates = matchAllList.size(); 5721 for (int n = 0; n < numCandidates; n++) { 5722 ResolveInfo info = matchAllList.get(n); 5723 // track the highest overall match priority... 5724 if (info.priority > maxMatchPrio) { 5725 maxMatchPrio = info.priority; 5726 } 5727 // ...and the highest-priority default browser match 5728 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5729 if (defaultBrowserMatch == null 5730 || (defaultBrowserMatch.priority < info.priority)) { 5731 if (debug) { 5732 Slog.v(TAG, "Considering default browser match " + info); 5733 } 5734 defaultBrowserMatch = info; 5735 } 5736 } 5737 } 5738 if (defaultBrowserMatch != null 5739 && defaultBrowserMatch.priority >= maxMatchPrio 5740 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5741 { 5742 if (debug) { 5743 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5744 } 5745 result.add(defaultBrowserMatch); 5746 } else { 5747 result.addAll(matchAllList); 5748 } 5749 } 5750 5751 // If there is nothing selected, add all candidates and remove the ones that the user 5752 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5753 if (result.size() == 0) { 5754 result.addAll(candidates); 5755 result.removeAll(neverList); 5756 } 5757 } 5758 } 5759 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5760 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5761 result.size()); 5762 for (ResolveInfo info : result) { 5763 Slog.v(TAG, " + " + info.activityInfo); 5764 } 5765 } 5766 return result; 5767 } 5768 5769 // Returns a packed value as a long: 5770 // 5771 // high 'int'-sized word: link status: undefined/ask/never/always. 5772 // low 'int'-sized word: relative priority among 'always' results. 5773 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5774 long result = ps.getDomainVerificationStatusForUser(userId); 5775 // if none available, get the master status 5776 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5777 if (ps.getIntentFilterVerificationInfo() != null) { 5778 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5779 } 5780 } 5781 return result; 5782 } 5783 5784 private ResolveInfo querySkipCurrentProfileIntents( 5785 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5786 int flags, int sourceUserId) { 5787 if (matchingFilters != null) { 5788 int size = matchingFilters.size(); 5789 for (int i = 0; i < size; i ++) { 5790 CrossProfileIntentFilter filter = matchingFilters.get(i); 5791 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5792 // Checking if there are activities in the target user that can handle the 5793 // intent. 5794 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5795 resolvedType, flags, sourceUserId); 5796 if (resolveInfo != null) { 5797 return resolveInfo; 5798 } 5799 } 5800 } 5801 } 5802 return null; 5803 } 5804 5805 // Return matching ResolveInfo in target user if any. 5806 private ResolveInfo queryCrossProfileIntents( 5807 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5808 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5809 if (matchingFilters != null) { 5810 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5811 // match the same intent. For performance reasons, it is better not to 5812 // run queryIntent twice for the same userId 5813 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5814 int size = matchingFilters.size(); 5815 for (int i = 0; i < size; i++) { 5816 CrossProfileIntentFilter filter = matchingFilters.get(i); 5817 int targetUserId = filter.getTargetUserId(); 5818 boolean skipCurrentProfile = 5819 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5820 boolean skipCurrentProfileIfNoMatchFound = 5821 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5822 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5823 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5824 // Checking if there are activities in the target user that can handle the 5825 // intent. 5826 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5827 resolvedType, flags, sourceUserId); 5828 if (resolveInfo != null) return resolveInfo; 5829 alreadyTriedUserIds.put(targetUserId, true); 5830 } 5831 } 5832 } 5833 return null; 5834 } 5835 5836 /** 5837 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5838 * will forward the intent to the filter's target user. 5839 * Otherwise, returns null. 5840 */ 5841 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5842 String resolvedType, int flags, int sourceUserId) { 5843 int targetUserId = filter.getTargetUserId(); 5844 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5845 resolvedType, flags, targetUserId); 5846 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5847 // If all the matches in the target profile are suspended, return null. 5848 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5849 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5850 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5851 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5852 targetUserId); 5853 } 5854 } 5855 } 5856 return null; 5857 } 5858 5859 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5860 int sourceUserId, int targetUserId) { 5861 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5862 long ident = Binder.clearCallingIdentity(); 5863 boolean targetIsProfile; 5864 try { 5865 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5866 } finally { 5867 Binder.restoreCallingIdentity(ident); 5868 } 5869 String className; 5870 if (targetIsProfile) { 5871 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5872 } else { 5873 className = FORWARD_INTENT_TO_PARENT; 5874 } 5875 ComponentName forwardingActivityComponentName = new ComponentName( 5876 mAndroidApplication.packageName, className); 5877 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5878 sourceUserId); 5879 if (!targetIsProfile) { 5880 forwardingActivityInfo.showUserIcon = targetUserId; 5881 forwardingResolveInfo.noResourceId = true; 5882 } 5883 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5884 forwardingResolveInfo.priority = 0; 5885 forwardingResolveInfo.preferredOrder = 0; 5886 forwardingResolveInfo.match = 0; 5887 forwardingResolveInfo.isDefault = true; 5888 forwardingResolveInfo.filter = filter; 5889 forwardingResolveInfo.targetUserId = targetUserId; 5890 return forwardingResolveInfo; 5891 } 5892 5893 @Override 5894 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5895 Intent[] specifics, String[] specificTypes, Intent intent, 5896 String resolvedType, int flags, int userId) { 5897 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5898 specificTypes, intent, resolvedType, flags, userId)); 5899 } 5900 5901 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5902 Intent[] specifics, String[] specificTypes, Intent intent, 5903 String resolvedType, int flags, int userId) { 5904 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5905 flags = updateFlagsForResolve(flags, userId, intent); 5906 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5907 false /* requireFullPermission */, false /* checkShell */, 5908 "query intent activity options"); 5909 final String resultsAction = intent.getAction(); 5910 5911 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5912 | PackageManager.GET_RESOLVED_FILTER, userId); 5913 5914 if (DEBUG_INTENT_MATCHING) { 5915 Log.v(TAG, "Query " + intent + ": " + results); 5916 } 5917 5918 int specificsPos = 0; 5919 int N; 5920 5921 // todo: note that the algorithm used here is O(N^2). This 5922 // isn't a problem in our current environment, but if we start running 5923 // into situations where we have more than 5 or 10 matches then this 5924 // should probably be changed to something smarter... 5925 5926 // First we go through and resolve each of the specific items 5927 // that were supplied, taking care of removing any corresponding 5928 // duplicate items in the generic resolve list. 5929 if (specifics != null) { 5930 for (int i=0; i<specifics.length; i++) { 5931 final Intent sintent = specifics[i]; 5932 if (sintent == null) { 5933 continue; 5934 } 5935 5936 if (DEBUG_INTENT_MATCHING) { 5937 Log.v(TAG, "Specific #" + i + ": " + sintent); 5938 } 5939 5940 String action = sintent.getAction(); 5941 if (resultsAction != null && resultsAction.equals(action)) { 5942 // If this action was explicitly requested, then don't 5943 // remove things that have it. 5944 action = null; 5945 } 5946 5947 ResolveInfo ri = null; 5948 ActivityInfo ai = null; 5949 5950 ComponentName comp = sintent.getComponent(); 5951 if (comp == null) { 5952 ri = resolveIntent( 5953 sintent, 5954 specificTypes != null ? specificTypes[i] : null, 5955 flags, userId); 5956 if (ri == null) { 5957 continue; 5958 } 5959 if (ri == mResolveInfo) { 5960 // ACK! Must do something better with this. 5961 } 5962 ai = ri.activityInfo; 5963 comp = new ComponentName(ai.applicationInfo.packageName, 5964 ai.name); 5965 } else { 5966 ai = getActivityInfo(comp, flags, userId); 5967 if (ai == null) { 5968 continue; 5969 } 5970 } 5971 5972 // Look for any generic query activities that are duplicates 5973 // of this specific one, and remove them from the results. 5974 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5975 N = results.size(); 5976 int j; 5977 for (j=specificsPos; j<N; j++) { 5978 ResolveInfo sri = results.get(j); 5979 if ((sri.activityInfo.name.equals(comp.getClassName()) 5980 && sri.activityInfo.applicationInfo.packageName.equals( 5981 comp.getPackageName())) 5982 || (action != null && sri.filter.matchAction(action))) { 5983 results.remove(j); 5984 if (DEBUG_INTENT_MATCHING) Log.v( 5985 TAG, "Removing duplicate item from " + j 5986 + " due to specific " + specificsPos); 5987 if (ri == null) { 5988 ri = sri; 5989 } 5990 j--; 5991 N--; 5992 } 5993 } 5994 5995 // Add this specific item to its proper place. 5996 if (ri == null) { 5997 ri = new ResolveInfo(); 5998 ri.activityInfo = ai; 5999 } 6000 results.add(specificsPos, ri); 6001 ri.specificIndex = i; 6002 specificsPos++; 6003 } 6004 } 6005 6006 // Now we go through the remaining generic results and remove any 6007 // duplicate actions that are found here. 6008 N = results.size(); 6009 for (int i=specificsPos; i<N-1; i++) { 6010 final ResolveInfo rii = results.get(i); 6011 if (rii.filter == null) { 6012 continue; 6013 } 6014 6015 // Iterate over all of the actions of this result's intent 6016 // filter... typically this should be just one. 6017 final Iterator<String> it = rii.filter.actionsIterator(); 6018 if (it == null) { 6019 continue; 6020 } 6021 while (it.hasNext()) { 6022 final String action = it.next(); 6023 if (resultsAction != null && resultsAction.equals(action)) { 6024 // If this action was explicitly requested, then don't 6025 // remove things that have it. 6026 continue; 6027 } 6028 for (int j=i+1; j<N; j++) { 6029 final ResolveInfo rij = results.get(j); 6030 if (rij.filter != null && rij.filter.hasAction(action)) { 6031 results.remove(j); 6032 if (DEBUG_INTENT_MATCHING) Log.v( 6033 TAG, "Removing duplicate item from " + j 6034 + " due to action " + action + " at " + i); 6035 j--; 6036 N--; 6037 } 6038 } 6039 } 6040 6041 // If the caller didn't request filter information, drop it now 6042 // so we don't have to marshall/unmarshall it. 6043 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6044 rii.filter = null; 6045 } 6046 } 6047 6048 // Filter out the caller activity if so requested. 6049 if (caller != null) { 6050 N = results.size(); 6051 for (int i=0; i<N; i++) { 6052 ActivityInfo ainfo = results.get(i).activityInfo; 6053 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6054 && caller.getClassName().equals(ainfo.name)) { 6055 results.remove(i); 6056 break; 6057 } 6058 } 6059 } 6060 6061 // If the caller didn't request filter information, 6062 // drop them now so we don't have to 6063 // marshall/unmarshall it. 6064 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6065 N = results.size(); 6066 for (int i=0; i<N; i++) { 6067 results.get(i).filter = null; 6068 } 6069 } 6070 6071 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6072 return results; 6073 } 6074 6075 @Override 6076 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6077 String resolvedType, int flags, int userId) { 6078 return new ParceledListSlice<>( 6079 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6080 } 6081 6082 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6083 String resolvedType, int flags, int userId) { 6084 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6085 flags = updateFlagsForResolve(flags, userId, intent); 6086 ComponentName comp = intent.getComponent(); 6087 if (comp == null) { 6088 if (intent.getSelector() != null) { 6089 intent = intent.getSelector(); 6090 comp = intent.getComponent(); 6091 } 6092 } 6093 if (comp != null) { 6094 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6095 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6096 if (ai != null) { 6097 ResolveInfo ri = new ResolveInfo(); 6098 ri.activityInfo = ai; 6099 list.add(ri); 6100 } 6101 return list; 6102 } 6103 6104 // reader 6105 synchronized (mPackages) { 6106 String pkgName = intent.getPackage(); 6107 if (pkgName == null) { 6108 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6109 } 6110 final PackageParser.Package pkg = mPackages.get(pkgName); 6111 if (pkg != null) { 6112 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6113 userId); 6114 } 6115 return Collections.emptyList(); 6116 } 6117 } 6118 6119 @Override 6120 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6121 if (!sUserManager.exists(userId)) return null; 6122 flags = updateFlagsForResolve(flags, userId, intent); 6123 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6124 if (query != null) { 6125 if (query.size() >= 1) { 6126 // If there is more than one service with the same priority, 6127 // just arbitrarily pick the first one. 6128 return query.get(0); 6129 } 6130 } 6131 return null; 6132 } 6133 6134 @Override 6135 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6136 String resolvedType, int flags, int userId) { 6137 return new ParceledListSlice<>( 6138 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6139 } 6140 6141 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6142 String resolvedType, int flags, int userId) { 6143 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6144 flags = updateFlagsForResolve(flags, userId, intent); 6145 ComponentName comp = intent.getComponent(); 6146 if (comp == null) { 6147 if (intent.getSelector() != null) { 6148 intent = intent.getSelector(); 6149 comp = intent.getComponent(); 6150 } 6151 } 6152 if (comp != null) { 6153 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6154 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6155 if (si != null) { 6156 final ResolveInfo ri = new ResolveInfo(); 6157 ri.serviceInfo = si; 6158 list.add(ri); 6159 } 6160 return list; 6161 } 6162 6163 // reader 6164 synchronized (mPackages) { 6165 String pkgName = intent.getPackage(); 6166 if (pkgName == null) { 6167 return mServices.queryIntent(intent, resolvedType, flags, userId); 6168 } 6169 final PackageParser.Package pkg = mPackages.get(pkgName); 6170 if (pkg != null) { 6171 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6172 userId); 6173 } 6174 return Collections.emptyList(); 6175 } 6176 } 6177 6178 @Override 6179 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6180 String resolvedType, int flags, int userId) { 6181 return new ParceledListSlice<>( 6182 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6183 } 6184 6185 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6186 Intent intent, String resolvedType, int flags, int userId) { 6187 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6188 flags = updateFlagsForResolve(flags, userId, intent); 6189 ComponentName comp = intent.getComponent(); 6190 if (comp == null) { 6191 if (intent.getSelector() != null) { 6192 intent = intent.getSelector(); 6193 comp = intent.getComponent(); 6194 } 6195 } 6196 if (comp != null) { 6197 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6198 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6199 if (pi != null) { 6200 final ResolveInfo ri = new ResolveInfo(); 6201 ri.providerInfo = pi; 6202 list.add(ri); 6203 } 6204 return list; 6205 } 6206 6207 // reader 6208 synchronized (mPackages) { 6209 String pkgName = intent.getPackage(); 6210 if (pkgName == null) { 6211 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6212 } 6213 final PackageParser.Package pkg = mPackages.get(pkgName); 6214 if (pkg != null) { 6215 return mProviders.queryIntentForPackage( 6216 intent, resolvedType, flags, pkg.providers, userId); 6217 } 6218 return Collections.emptyList(); 6219 } 6220 } 6221 6222 @Override 6223 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6224 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6225 flags = updateFlagsForPackage(flags, userId, null); 6226 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6228 true /* requireFullPermission */, false /* checkShell */, 6229 "get installed packages"); 6230 6231 // writer 6232 synchronized (mPackages) { 6233 ArrayList<PackageInfo> list; 6234 if (listUninstalled) { 6235 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6236 for (PackageSetting ps : mSettings.mPackages.values()) { 6237 final PackageInfo pi; 6238 if (ps.pkg != null) { 6239 pi = generatePackageInfo(ps, flags, userId); 6240 } else { 6241 pi = generatePackageInfo(ps, flags, userId); 6242 } 6243 if (pi != null) { 6244 list.add(pi); 6245 } 6246 } 6247 } else { 6248 list = new ArrayList<PackageInfo>(mPackages.size()); 6249 for (PackageParser.Package p : mPackages.values()) { 6250 final PackageInfo pi = 6251 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6252 if (pi != null) { 6253 list.add(pi); 6254 } 6255 } 6256 } 6257 6258 return new ParceledListSlice<PackageInfo>(list); 6259 } 6260 } 6261 6262 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6263 String[] permissions, boolean[] tmp, int flags, int userId) { 6264 int numMatch = 0; 6265 final PermissionsState permissionsState = ps.getPermissionsState(); 6266 for (int i=0; i<permissions.length; i++) { 6267 final String permission = permissions[i]; 6268 if (permissionsState.hasPermission(permission, userId)) { 6269 tmp[i] = true; 6270 numMatch++; 6271 } else { 6272 tmp[i] = false; 6273 } 6274 } 6275 if (numMatch == 0) { 6276 return; 6277 } 6278 final PackageInfo pi; 6279 if (ps.pkg != null) { 6280 pi = generatePackageInfo(ps, flags, userId); 6281 } else { 6282 pi = generatePackageInfo(ps, flags, userId); 6283 } 6284 // The above might return null in cases of uninstalled apps or install-state 6285 // skew across users/profiles. 6286 if (pi != null) { 6287 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6288 if (numMatch == permissions.length) { 6289 pi.requestedPermissions = permissions; 6290 } else { 6291 pi.requestedPermissions = new String[numMatch]; 6292 numMatch = 0; 6293 for (int i=0; i<permissions.length; i++) { 6294 if (tmp[i]) { 6295 pi.requestedPermissions[numMatch] = permissions[i]; 6296 numMatch++; 6297 } 6298 } 6299 } 6300 } 6301 list.add(pi); 6302 } 6303 } 6304 6305 @Override 6306 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6307 String[] permissions, int flags, int userId) { 6308 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6309 flags = updateFlagsForPackage(flags, userId, permissions); 6310 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6311 6312 // writer 6313 synchronized (mPackages) { 6314 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6315 boolean[] tmpBools = new boolean[permissions.length]; 6316 if (listUninstalled) { 6317 for (PackageSetting ps : mSettings.mPackages.values()) { 6318 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6319 } 6320 } else { 6321 for (PackageParser.Package pkg : mPackages.values()) { 6322 PackageSetting ps = (PackageSetting)pkg.mExtras; 6323 if (ps != null) { 6324 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6325 userId); 6326 } 6327 } 6328 } 6329 6330 return new ParceledListSlice<PackageInfo>(list); 6331 } 6332 } 6333 6334 @Override 6335 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6336 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6337 flags = updateFlagsForApplication(flags, userId, null); 6338 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6339 6340 // writer 6341 synchronized (mPackages) { 6342 ArrayList<ApplicationInfo> list; 6343 if (listUninstalled) { 6344 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6345 for (PackageSetting ps : mSettings.mPackages.values()) { 6346 ApplicationInfo ai; 6347 if (ps.pkg != null) { 6348 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6349 ps.readUserState(userId), userId); 6350 } else { 6351 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6352 } 6353 if (ai != null) { 6354 list.add(ai); 6355 } 6356 } 6357 } else { 6358 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6359 for (PackageParser.Package p : mPackages.values()) { 6360 if (p.mExtras != null) { 6361 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6362 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6363 if (ai != null) { 6364 list.add(ai); 6365 } 6366 } 6367 } 6368 } 6369 6370 return new ParceledListSlice<ApplicationInfo>(list); 6371 } 6372 } 6373 6374 @Override 6375 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6376 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6377 return null; 6378 } 6379 6380 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6381 "getEphemeralApplications"); 6382 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6383 true /* requireFullPermission */, false /* checkShell */, 6384 "getEphemeralApplications"); 6385 synchronized (mPackages) { 6386 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6387 .getEphemeralApplicationsLPw(userId); 6388 if (ephemeralApps != null) { 6389 return new ParceledListSlice<>(ephemeralApps); 6390 } 6391 } 6392 return null; 6393 } 6394 6395 @Override 6396 public boolean isEphemeralApplication(String packageName, int userId) { 6397 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6398 true /* requireFullPermission */, false /* checkShell */, 6399 "isEphemeral"); 6400 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6401 return false; 6402 } 6403 6404 if (!isCallerSameApp(packageName)) { 6405 return false; 6406 } 6407 synchronized (mPackages) { 6408 PackageParser.Package pkg = mPackages.get(packageName); 6409 if (pkg != null) { 6410 return pkg.applicationInfo.isEphemeralApp(); 6411 } 6412 } 6413 return false; 6414 } 6415 6416 @Override 6417 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6418 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6419 return null; 6420 } 6421 6422 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6423 true /* requireFullPermission */, false /* checkShell */, 6424 "getCookie"); 6425 if (!isCallerSameApp(packageName)) { 6426 return null; 6427 } 6428 synchronized (mPackages) { 6429 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6430 packageName, userId); 6431 } 6432 } 6433 6434 @Override 6435 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6436 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6437 return true; 6438 } 6439 6440 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6441 true /* requireFullPermission */, true /* checkShell */, 6442 "setCookie"); 6443 if (!isCallerSameApp(packageName)) { 6444 return false; 6445 } 6446 synchronized (mPackages) { 6447 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6448 packageName, cookie, userId); 6449 } 6450 } 6451 6452 @Override 6453 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6454 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6455 return null; 6456 } 6457 6458 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6459 "getEphemeralApplicationIcon"); 6460 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6461 true /* requireFullPermission */, false /* checkShell */, 6462 "getEphemeralApplicationIcon"); 6463 synchronized (mPackages) { 6464 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6465 packageName, userId); 6466 } 6467 } 6468 6469 private boolean isCallerSameApp(String packageName) { 6470 PackageParser.Package pkg = mPackages.get(packageName); 6471 return pkg != null 6472 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6473 } 6474 6475 @Override 6476 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6477 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6478 } 6479 6480 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6481 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6482 6483 // reader 6484 synchronized (mPackages) { 6485 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6486 final int userId = UserHandle.getCallingUserId(); 6487 while (i.hasNext()) { 6488 final PackageParser.Package p = i.next(); 6489 if (p.applicationInfo == null) continue; 6490 6491 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6492 && !p.applicationInfo.isDirectBootAware(); 6493 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6494 && p.applicationInfo.isDirectBootAware(); 6495 6496 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6497 && (!mSafeMode || isSystemApp(p)) 6498 && (matchesUnaware || matchesAware)) { 6499 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6500 if (ps != null) { 6501 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6502 ps.readUserState(userId), userId); 6503 if (ai != null) { 6504 finalList.add(ai); 6505 } 6506 } 6507 } 6508 } 6509 } 6510 6511 return finalList; 6512 } 6513 6514 @Override 6515 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6516 if (!sUserManager.exists(userId)) return null; 6517 flags = updateFlagsForComponent(flags, userId, name); 6518 // reader 6519 synchronized (mPackages) { 6520 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6521 PackageSetting ps = provider != null 6522 ? mSettings.mPackages.get(provider.owner.packageName) 6523 : null; 6524 return ps != null 6525 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6526 ? PackageParser.generateProviderInfo(provider, flags, 6527 ps.readUserState(userId), userId) 6528 : null; 6529 } 6530 } 6531 6532 /** 6533 * @deprecated 6534 */ 6535 @Deprecated 6536 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6537 // reader 6538 synchronized (mPackages) { 6539 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6540 .entrySet().iterator(); 6541 final int userId = UserHandle.getCallingUserId(); 6542 while (i.hasNext()) { 6543 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6544 PackageParser.Provider p = entry.getValue(); 6545 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6546 6547 if (ps != null && p.syncable 6548 && (!mSafeMode || (p.info.applicationInfo.flags 6549 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6550 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6551 ps.readUserState(userId), userId); 6552 if (info != null) { 6553 outNames.add(entry.getKey()); 6554 outInfo.add(info); 6555 } 6556 } 6557 } 6558 } 6559 } 6560 6561 @Override 6562 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6563 int uid, int flags) { 6564 final int userId = processName != null ? UserHandle.getUserId(uid) 6565 : UserHandle.getCallingUserId(); 6566 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6567 flags = updateFlagsForComponent(flags, userId, processName); 6568 6569 ArrayList<ProviderInfo> finalList = null; 6570 // reader 6571 synchronized (mPackages) { 6572 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6573 while (i.hasNext()) { 6574 final PackageParser.Provider p = i.next(); 6575 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6576 if (ps != null && p.info.authority != null 6577 && (processName == null 6578 || (p.info.processName.equals(processName) 6579 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6580 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6581 if (finalList == null) { 6582 finalList = new ArrayList<ProviderInfo>(3); 6583 } 6584 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6585 ps.readUserState(userId), userId); 6586 if (info != null) { 6587 finalList.add(info); 6588 } 6589 } 6590 } 6591 } 6592 6593 if (finalList != null) { 6594 Collections.sort(finalList, mProviderInitOrderSorter); 6595 return new ParceledListSlice<ProviderInfo>(finalList); 6596 } 6597 6598 return ParceledListSlice.emptyList(); 6599 } 6600 6601 @Override 6602 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6603 // reader 6604 synchronized (mPackages) { 6605 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6606 return PackageParser.generateInstrumentationInfo(i, flags); 6607 } 6608 } 6609 6610 @Override 6611 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6612 String targetPackage, int flags) { 6613 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6614 } 6615 6616 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6617 int flags) { 6618 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6619 6620 // reader 6621 synchronized (mPackages) { 6622 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6623 while (i.hasNext()) { 6624 final PackageParser.Instrumentation p = i.next(); 6625 if (targetPackage == null 6626 || targetPackage.equals(p.info.targetPackage)) { 6627 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6628 flags); 6629 if (ii != null) { 6630 finalList.add(ii); 6631 } 6632 } 6633 } 6634 } 6635 6636 return finalList; 6637 } 6638 6639 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6640 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6641 if (overlays == null) { 6642 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6643 return; 6644 } 6645 for (PackageParser.Package opkg : overlays.values()) { 6646 // Not much to do if idmap fails: we already logged the error 6647 // and we certainly don't want to abort installation of pkg simply 6648 // because an overlay didn't fit properly. For these reasons, 6649 // ignore the return value of createIdmapForPackagePairLI. 6650 createIdmapForPackagePairLI(pkg, opkg); 6651 } 6652 } 6653 6654 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6655 PackageParser.Package opkg) { 6656 if (!opkg.mTrustedOverlay) { 6657 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6658 opkg.baseCodePath + ": overlay not trusted"); 6659 return false; 6660 } 6661 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6662 if (overlaySet == null) { 6663 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6664 opkg.baseCodePath + " but target package has no known overlays"); 6665 return false; 6666 } 6667 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6668 // TODO: generate idmap for split APKs 6669 try { 6670 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6671 } catch (InstallerException e) { 6672 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6673 + opkg.baseCodePath); 6674 return false; 6675 } 6676 PackageParser.Package[] overlayArray = 6677 overlaySet.values().toArray(new PackageParser.Package[0]); 6678 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6679 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6680 return p1.mOverlayPriority - p2.mOverlayPriority; 6681 } 6682 }; 6683 Arrays.sort(overlayArray, cmp); 6684 6685 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6686 int i = 0; 6687 for (PackageParser.Package p : overlayArray) { 6688 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6689 } 6690 return true; 6691 } 6692 6693 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6694 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6695 try { 6696 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6697 } finally { 6698 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6699 } 6700 } 6701 6702 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6703 final File[] files = dir.listFiles(); 6704 if (ArrayUtils.isEmpty(files)) { 6705 Log.d(TAG, "No files in app dir " + dir); 6706 return; 6707 } 6708 6709 if (DEBUG_PACKAGE_SCANNING) { 6710 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6711 + " flags=0x" + Integer.toHexString(parseFlags)); 6712 } 6713 6714 for (File file : files) { 6715 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6716 && !PackageInstallerService.isStageName(file.getName()); 6717 if (!isPackage) { 6718 // Ignore entries which are not packages 6719 continue; 6720 } 6721 try { 6722 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6723 scanFlags, currentTime, null); 6724 } catch (PackageManagerException e) { 6725 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6726 6727 // Delete invalid userdata apps 6728 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6729 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6730 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6731 removeCodePathLI(file); 6732 } 6733 } 6734 } 6735 } 6736 6737 private static File getSettingsProblemFile() { 6738 File dataDir = Environment.getDataDirectory(); 6739 File systemDir = new File(dataDir, "system"); 6740 File fname = new File(systemDir, "uiderrors.txt"); 6741 return fname; 6742 } 6743 6744 static void reportSettingsProblem(int priority, String msg) { 6745 logCriticalInfo(priority, msg); 6746 } 6747 6748 static void logCriticalInfo(int priority, String msg) { 6749 Slog.println(priority, TAG, msg); 6750 EventLogTags.writePmCriticalInfo(msg); 6751 try { 6752 File fname = getSettingsProblemFile(); 6753 FileOutputStream out = new FileOutputStream(fname, true); 6754 PrintWriter pw = new FastPrintWriter(out); 6755 SimpleDateFormat formatter = new SimpleDateFormat(); 6756 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6757 pw.println(dateString + ": " + msg); 6758 pw.close(); 6759 FileUtils.setPermissions( 6760 fname.toString(), 6761 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6762 -1, -1); 6763 } catch (java.io.IOException e) { 6764 } 6765 } 6766 6767 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6768 if (srcFile.isDirectory()) { 6769 final File baseFile = new File(pkg.baseCodePath); 6770 long maxModifiedTime = baseFile.lastModified(); 6771 if (pkg.splitCodePaths != null) { 6772 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6773 final File splitFile = new File(pkg.splitCodePaths[i]); 6774 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6775 } 6776 } 6777 return maxModifiedTime; 6778 } 6779 return srcFile.lastModified(); 6780 } 6781 6782 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6783 final int policyFlags) throws PackageManagerException { 6784 // When upgrading from pre-N MR1, verify the package time stamp using the package 6785 // directory and not the APK file. 6786 final long lastModifiedTime = mIsPreNMR1Upgrade 6787 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6788 if (ps != null 6789 && ps.codePath.equals(srcFile) 6790 && ps.timeStamp == lastModifiedTime 6791 && !isCompatSignatureUpdateNeeded(pkg) 6792 && !isRecoverSignatureUpdateNeeded(pkg)) { 6793 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6794 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6795 ArraySet<PublicKey> signingKs; 6796 synchronized (mPackages) { 6797 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6798 } 6799 if (ps.signatures.mSignatures != null 6800 && ps.signatures.mSignatures.length != 0 6801 && signingKs != null) { 6802 // Optimization: reuse the existing cached certificates 6803 // if the package appears to be unchanged. 6804 pkg.mSignatures = ps.signatures.mSignatures; 6805 pkg.mSigningKeys = signingKs; 6806 return; 6807 } 6808 6809 Slog.w(TAG, "PackageSetting for " + ps.name 6810 + " is missing signatures. Collecting certs again to recover them."); 6811 } else { 6812 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6813 } 6814 6815 try { 6816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 6817 PackageParser.collectCertificates(pkg, policyFlags); 6818 } catch (PackageParserException e) { 6819 throw PackageManagerException.from(e); 6820 } finally { 6821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6822 } 6823 } 6824 6825 /** 6826 * Traces a package scan. 6827 * @see #scanPackageLI(File, int, int, long, UserHandle) 6828 */ 6829 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6830 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 6832 try { 6833 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6834 } finally { 6835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6836 } 6837 } 6838 6839 /** 6840 * Scans a package and returns the newly parsed package. 6841 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6842 */ 6843 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6844 long currentTime, UserHandle user) throws PackageManagerException { 6845 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6846 PackageParser pp = new PackageParser(); 6847 pp.setSeparateProcesses(mSeparateProcesses); 6848 pp.setOnlyCoreApps(mOnlyCore); 6849 pp.setDisplayMetrics(mMetrics); 6850 6851 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6852 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6853 } 6854 6855 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6856 final PackageParser.Package pkg; 6857 try { 6858 pkg = pp.parsePackage(scanFile, parseFlags); 6859 } catch (PackageParserException e) { 6860 throw PackageManagerException.from(e); 6861 } finally { 6862 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6863 } 6864 6865 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6866 } 6867 6868 /** 6869 * Scans a package and returns the newly parsed package. 6870 * @throws PackageManagerException on a parse error. 6871 */ 6872 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6873 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6874 throws PackageManagerException { 6875 // If the package has children and this is the first dive in the function 6876 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6877 // packages (parent and children) would be successfully scanned before the 6878 // actual scan since scanning mutates internal state and we want to atomically 6879 // install the package and its children. 6880 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6881 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6882 scanFlags |= SCAN_CHECK_ONLY; 6883 } 6884 } else { 6885 scanFlags &= ~SCAN_CHECK_ONLY; 6886 } 6887 6888 // Scan the parent 6889 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6890 scanFlags, currentTime, user); 6891 6892 // Scan the children 6893 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6894 for (int i = 0; i < childCount; i++) { 6895 PackageParser.Package childPackage = pkg.childPackages.get(i); 6896 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6897 currentTime, user); 6898 } 6899 6900 6901 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6902 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6903 } 6904 6905 return scannedPkg; 6906 } 6907 6908 /** 6909 * Scans a package and returns the newly parsed package. 6910 * @throws PackageManagerException on a parse error. 6911 */ 6912 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6913 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6914 throws PackageManagerException { 6915 PackageSetting ps = null; 6916 PackageSetting updatedPkg; 6917 // reader 6918 synchronized (mPackages) { 6919 // Look to see if we already know about this package. 6920 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 6921 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6922 // This package has been renamed to its original name. Let's 6923 // use that. 6924 ps = mSettings.getPackageLPr(oldName); 6925 } 6926 // If there was no original package, see one for the real package name. 6927 if (ps == null) { 6928 ps = mSettings.getPackageLPr(pkg.packageName); 6929 } 6930 // Check to see if this package could be hiding/updating a system 6931 // package. Must look for it either under the original or real 6932 // package name depending on our state. 6933 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6934 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6935 6936 // If this is a package we don't know about on the system partition, we 6937 // may need to remove disabled child packages on the system partition 6938 // or may need to not add child packages if the parent apk is updated 6939 // on the data partition and no longer defines this child package. 6940 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6941 // If this is a parent package for an updated system app and this system 6942 // app got an OTA update which no longer defines some of the child packages 6943 // we have to prune them from the disabled system packages. 6944 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6945 if (disabledPs != null) { 6946 final int scannedChildCount = (pkg.childPackages != null) 6947 ? pkg.childPackages.size() : 0; 6948 final int disabledChildCount = disabledPs.childPackageNames != null 6949 ? disabledPs.childPackageNames.size() : 0; 6950 for (int i = 0; i < disabledChildCount; i++) { 6951 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6952 boolean disabledPackageAvailable = false; 6953 for (int j = 0; j < scannedChildCount; j++) { 6954 PackageParser.Package childPkg = pkg.childPackages.get(j); 6955 if (childPkg.packageName.equals(disabledChildPackageName)) { 6956 disabledPackageAvailable = true; 6957 break; 6958 } 6959 } 6960 if (!disabledPackageAvailable) { 6961 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6962 } 6963 } 6964 } 6965 } 6966 } 6967 6968 boolean updatedPkgBetter = false; 6969 // First check if this is a system package that may involve an update 6970 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6971 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6972 // it needs to drop FLAG_PRIVILEGED. 6973 if (locationIsPrivileged(scanFile)) { 6974 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6975 } else { 6976 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6977 } 6978 6979 if (ps != null && !ps.codePath.equals(scanFile)) { 6980 // The path has changed from what was last scanned... check the 6981 // version of the new path against what we have stored to determine 6982 // what to do. 6983 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6984 if (pkg.mVersionCode <= ps.versionCode) { 6985 // The system package has been updated and the code path does not match 6986 // Ignore entry. Skip it. 6987 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6988 + " ignored: updated version " + ps.versionCode 6989 + " better than this " + pkg.mVersionCode); 6990 if (!updatedPkg.codePath.equals(scanFile)) { 6991 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6992 + ps.name + " changing from " + updatedPkg.codePathString 6993 + " to " + scanFile); 6994 updatedPkg.codePath = scanFile; 6995 updatedPkg.codePathString = scanFile.toString(); 6996 updatedPkg.resourcePath = scanFile; 6997 updatedPkg.resourcePathString = scanFile.toString(); 6998 } 6999 updatedPkg.pkg = pkg; 7000 updatedPkg.versionCode = pkg.mVersionCode; 7001 7002 // Update the disabled system child packages to point to the package too. 7003 final int childCount = updatedPkg.childPackageNames != null 7004 ? updatedPkg.childPackageNames.size() : 0; 7005 for (int i = 0; i < childCount; i++) { 7006 String childPackageName = updatedPkg.childPackageNames.get(i); 7007 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7008 childPackageName); 7009 if (updatedChildPkg != null) { 7010 updatedChildPkg.pkg = pkg; 7011 updatedChildPkg.versionCode = pkg.mVersionCode; 7012 } 7013 } 7014 7015 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7016 + scanFile + " ignored: updated version " + ps.versionCode 7017 + " better than this " + pkg.mVersionCode); 7018 } else { 7019 // The current app on the system partition is better than 7020 // what we have updated to on the data partition; switch 7021 // back to the system partition version. 7022 // At this point, its safely assumed that package installation for 7023 // apps in system partition will go through. If not there won't be a working 7024 // version of the app 7025 // writer 7026 synchronized (mPackages) { 7027 // Just remove the loaded entries from package lists. 7028 mPackages.remove(ps.name); 7029 } 7030 7031 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7032 + " reverting from " + ps.codePathString 7033 + ": new version " + pkg.mVersionCode 7034 + " better than installed " + ps.versionCode); 7035 7036 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7037 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7038 synchronized (mInstallLock) { 7039 args.cleanUpResourcesLI(); 7040 } 7041 synchronized (mPackages) { 7042 mSettings.enableSystemPackageLPw(ps.name); 7043 } 7044 updatedPkgBetter = true; 7045 } 7046 } 7047 } 7048 7049 if (updatedPkg != null) { 7050 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7051 // initially 7052 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7053 7054 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7055 // flag set initially 7056 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7057 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7058 } 7059 } 7060 7061 // Verify certificates against what was last scanned 7062 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7063 7064 /* 7065 * A new system app appeared, but we already had a non-system one of the 7066 * same name installed earlier. 7067 */ 7068 boolean shouldHideSystemApp = false; 7069 if (updatedPkg == null && ps != null 7070 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7071 /* 7072 * Check to make sure the signatures match first. If they don't, 7073 * wipe the installed application and its data. 7074 */ 7075 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7076 != PackageManager.SIGNATURE_MATCH) { 7077 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7078 + " signatures don't match existing userdata copy; removing"); 7079 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7080 "scanPackageInternalLI")) { 7081 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7082 } 7083 ps = null; 7084 } else { 7085 /* 7086 * If the newly-added system app is an older version than the 7087 * already installed version, hide it. It will be scanned later 7088 * and re-added like an update. 7089 */ 7090 if (pkg.mVersionCode <= ps.versionCode) { 7091 shouldHideSystemApp = true; 7092 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7093 + " but new version " + pkg.mVersionCode + " better than installed " 7094 + ps.versionCode + "; hiding system"); 7095 } else { 7096 /* 7097 * The newly found system app is a newer version that the 7098 * one previously installed. Simply remove the 7099 * already-installed application and replace it with our own 7100 * while keeping the application data. 7101 */ 7102 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7103 + " reverting from " + ps.codePathString + ": new version " 7104 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7105 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7106 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7107 synchronized (mInstallLock) { 7108 args.cleanUpResourcesLI(); 7109 } 7110 } 7111 } 7112 } 7113 7114 // The apk is forward locked (not public) if its code and resources 7115 // are kept in different files. (except for app in either system or 7116 // vendor path). 7117 // TODO grab this value from PackageSettings 7118 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7119 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7120 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7121 } 7122 } 7123 7124 // TODO: extend to support forward-locked splits 7125 String resourcePath = null; 7126 String baseResourcePath = null; 7127 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7128 if (ps != null && ps.resourcePathString != null) { 7129 resourcePath = ps.resourcePathString; 7130 baseResourcePath = ps.resourcePathString; 7131 } else { 7132 // Should not happen at all. Just log an error. 7133 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7134 } 7135 } else { 7136 resourcePath = pkg.codePath; 7137 baseResourcePath = pkg.baseCodePath; 7138 } 7139 7140 // Set application objects path explicitly. 7141 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7142 pkg.setApplicationInfoCodePath(pkg.codePath); 7143 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7144 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7145 pkg.setApplicationInfoResourcePath(resourcePath); 7146 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7147 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7148 7149 // Note that we invoke the following method only if we are about to unpack an application 7150 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7151 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7152 7153 /* 7154 * If the system app should be overridden by a previously installed 7155 * data, hide the system app now and let the /data/app scan pick it up 7156 * again. 7157 */ 7158 if (shouldHideSystemApp) { 7159 synchronized (mPackages) { 7160 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7161 } 7162 } 7163 7164 return scannedPkg; 7165 } 7166 7167 private static String fixProcessName(String defProcessName, 7168 String processName) { 7169 if (processName == null) { 7170 return defProcessName; 7171 } 7172 return processName; 7173 } 7174 7175 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7176 throws PackageManagerException { 7177 if (pkgSetting.signatures.mSignatures != null) { 7178 // Already existing package. Make sure signatures match 7179 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7180 == PackageManager.SIGNATURE_MATCH; 7181 if (!match) { 7182 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7183 == PackageManager.SIGNATURE_MATCH; 7184 } 7185 if (!match) { 7186 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7187 == PackageManager.SIGNATURE_MATCH; 7188 } 7189 if (!match) { 7190 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7191 + pkg.packageName + " signatures do not match the " 7192 + "previously installed version; ignoring!"); 7193 } 7194 } 7195 7196 // Check for shared user signatures 7197 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7198 // Already existing package. Make sure signatures match 7199 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7200 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7201 if (!match) { 7202 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7203 == PackageManager.SIGNATURE_MATCH; 7204 } 7205 if (!match) { 7206 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7207 == PackageManager.SIGNATURE_MATCH; 7208 } 7209 if (!match) { 7210 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7211 "Package " + pkg.packageName 7212 + " has no signatures that match those in shared user " 7213 + pkgSetting.sharedUser.name + "; ignoring!"); 7214 } 7215 } 7216 } 7217 7218 /** 7219 * Enforces that only the system UID or root's UID can call a method exposed 7220 * via Binder. 7221 * 7222 * @param message used as message if SecurityException is thrown 7223 * @throws SecurityException if the caller is not system or root 7224 */ 7225 private static final void enforceSystemOrRoot(String message) { 7226 final int uid = Binder.getCallingUid(); 7227 if (uid != Process.SYSTEM_UID && uid != 0) { 7228 throw new SecurityException(message); 7229 } 7230 } 7231 7232 @Override 7233 public void performFstrimIfNeeded() { 7234 enforceSystemOrRoot("Only the system can request fstrim"); 7235 7236 // Before everything else, see whether we need to fstrim. 7237 try { 7238 IMountService ms = PackageHelper.getMountService(); 7239 if (ms != null) { 7240 boolean doTrim = false; 7241 final long interval = android.provider.Settings.Global.getLong( 7242 mContext.getContentResolver(), 7243 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7244 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7245 if (interval > 0) { 7246 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7247 if (timeSinceLast > interval) { 7248 doTrim = true; 7249 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7250 + "; running immediately"); 7251 } 7252 } 7253 if (doTrim) { 7254 final boolean dexOptDialogShown; 7255 synchronized (mPackages) { 7256 dexOptDialogShown = mDexOptDialogShown; 7257 } 7258 if (!isFirstBoot() && dexOptDialogShown) { 7259 try { 7260 ActivityManagerNative.getDefault().showBootMessage( 7261 mContext.getResources().getString( 7262 R.string.android_upgrading_fstrim), true); 7263 } catch (RemoteException e) { 7264 } 7265 } 7266 ms.runMaintenance(); 7267 } 7268 } else { 7269 Slog.e(TAG, "Mount service unavailable!"); 7270 } 7271 } catch (RemoteException e) { 7272 // Can't happen; MountService is local 7273 } 7274 } 7275 7276 @Override 7277 public void updatePackagesIfNeeded() { 7278 enforceSystemOrRoot("Only the system can request package update"); 7279 7280 // We need to re-extract after an OTA. 7281 boolean causeUpgrade = isUpgrade(); 7282 7283 // First boot or factory reset. 7284 // Note: we also handle devices that are upgrading to N right now as if it is their 7285 // first boot, as they do not have profile data. 7286 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7287 7288 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7289 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7290 7291 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7292 return; 7293 } 7294 7295 List<PackageParser.Package> pkgs; 7296 synchronized (mPackages) { 7297 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7298 } 7299 7300 final long startTime = System.nanoTime(); 7301 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7302 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7303 7304 final int elapsedTimeSeconds = 7305 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7306 7307 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7308 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7309 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7310 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7311 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7312 } 7313 7314 /** 7315 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7316 * containing statistics about the invocation. The array consists of three elements, 7317 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7318 * and {@code numberOfPackagesFailed}. 7319 */ 7320 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7321 String compilerFilter) { 7322 7323 int numberOfPackagesVisited = 0; 7324 int numberOfPackagesOptimized = 0; 7325 int numberOfPackagesSkipped = 0; 7326 int numberOfPackagesFailed = 0; 7327 final int numberOfPackagesToDexopt = pkgs.size(); 7328 7329 for (PackageParser.Package pkg : pkgs) { 7330 numberOfPackagesVisited++; 7331 7332 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7333 if (DEBUG_DEXOPT) { 7334 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7335 } 7336 numberOfPackagesSkipped++; 7337 continue; 7338 } 7339 7340 if (DEBUG_DEXOPT) { 7341 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7342 numberOfPackagesToDexopt + ": " + pkg.packageName); 7343 } 7344 7345 if (showDialog) { 7346 try { 7347 ActivityManagerNative.getDefault().showBootMessage( 7348 mContext.getResources().getString(R.string.android_upgrading_apk, 7349 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7350 } catch (RemoteException e) { 7351 } 7352 synchronized (mPackages) { 7353 mDexOptDialogShown = true; 7354 } 7355 } 7356 7357 // If the OTA updates a system app which was previously preopted to a non-preopted state 7358 // the app might end up being verified at runtime. That's because by default the apps 7359 // are verify-profile but for preopted apps there's no profile. 7360 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7361 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7362 // filter (by default interpret-only). 7363 // Note that at this stage unused apps are already filtered. 7364 if (isSystemApp(pkg) && 7365 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7366 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7367 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7368 } 7369 7370 // If the OTA updates a system app which was previously preopted to a non-preopted state 7371 // the app might end up being verified at runtime. That's because by default the apps 7372 // are verify-profile but for preopted apps there's no profile. 7373 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7374 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7375 // filter (by default interpret-only). 7376 // Note that at this stage unused apps are already filtered. 7377 if (isSystemApp(pkg) && 7378 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7379 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7380 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7381 } 7382 7383 // checkProfiles is false to avoid merging profiles during boot which 7384 // might interfere with background compilation (b/28612421). 7385 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7386 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7387 // trade-off worth doing to save boot time work. 7388 int dexOptStatus = performDexOptTraced(pkg.packageName, 7389 false /* checkProfiles */, 7390 compilerFilter, 7391 false /* force */); 7392 switch (dexOptStatus) { 7393 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7394 numberOfPackagesOptimized++; 7395 break; 7396 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7397 numberOfPackagesSkipped++; 7398 break; 7399 case PackageDexOptimizer.DEX_OPT_FAILED: 7400 numberOfPackagesFailed++; 7401 break; 7402 default: 7403 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7404 break; 7405 } 7406 } 7407 7408 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7409 numberOfPackagesFailed }; 7410 } 7411 7412 @Override 7413 public void notifyPackageUse(String packageName, int reason) { 7414 synchronized (mPackages) { 7415 PackageParser.Package p = mPackages.get(packageName); 7416 if (p == null) { 7417 return; 7418 } 7419 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7420 } 7421 } 7422 7423 // TODO: this is not used nor needed. Delete it. 7424 @Override 7425 public boolean performDexOptIfNeeded(String packageName) { 7426 int dexOptStatus = performDexOptTraced(packageName, 7427 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7428 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7429 } 7430 7431 @Override 7432 public boolean performDexOpt(String packageName, 7433 boolean checkProfiles, int compileReason, boolean force) { 7434 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7435 getCompilerFilterForReason(compileReason), force); 7436 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7437 } 7438 7439 @Override 7440 public boolean performDexOptMode(String packageName, 7441 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7442 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7443 targetCompilerFilter, force); 7444 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7445 } 7446 7447 private int performDexOptTraced(String packageName, 7448 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7450 try { 7451 return performDexOptInternal(packageName, checkProfiles, 7452 targetCompilerFilter, force); 7453 } finally { 7454 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7455 } 7456 } 7457 7458 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7459 // if the package can now be considered up to date for the given filter. 7460 private int performDexOptInternal(String packageName, 7461 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7462 PackageParser.Package p; 7463 synchronized (mPackages) { 7464 p = mPackages.get(packageName); 7465 if (p == null) { 7466 // Package could not be found. Report failure. 7467 return PackageDexOptimizer.DEX_OPT_FAILED; 7468 } 7469 mPackageUsage.maybeWriteAsync(mPackages); 7470 mCompilerStats.maybeWriteAsync(); 7471 } 7472 long callingId = Binder.clearCallingIdentity(); 7473 try { 7474 synchronized (mInstallLock) { 7475 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7476 targetCompilerFilter, force); 7477 } 7478 } finally { 7479 Binder.restoreCallingIdentity(callingId); 7480 } 7481 } 7482 7483 public ArraySet<String> getOptimizablePackages() { 7484 ArraySet<String> pkgs = new ArraySet<String>(); 7485 synchronized (mPackages) { 7486 for (PackageParser.Package p : mPackages.values()) { 7487 if (PackageDexOptimizer.canOptimizePackage(p)) { 7488 pkgs.add(p.packageName); 7489 } 7490 } 7491 } 7492 return pkgs; 7493 } 7494 7495 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7496 boolean checkProfiles, String targetCompilerFilter, 7497 boolean force) { 7498 // Select the dex optimizer based on the force parameter. 7499 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7500 // allocate an object here. 7501 PackageDexOptimizer pdo = force 7502 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7503 : mPackageDexOptimizer; 7504 7505 // Optimize all dependencies first. Note: we ignore the return value and march on 7506 // on errors. 7507 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7508 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7509 if (!deps.isEmpty()) { 7510 for (PackageParser.Package depPackage : deps) { 7511 // TODO: Analyze and investigate if we (should) profile libraries. 7512 // Currently this will do a full compilation of the library by default. 7513 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7514 false /* checkProfiles */, 7515 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7516 getOrCreateCompilerPackageStats(depPackage)); 7517 } 7518 } 7519 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7520 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7521 } 7522 7523 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7524 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7525 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7526 Set<String> collectedNames = new HashSet<>(); 7527 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7528 7529 retValue.remove(p); 7530 7531 return retValue; 7532 } else { 7533 return Collections.emptyList(); 7534 } 7535 } 7536 7537 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7538 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7539 if (!collectedNames.contains(p.packageName)) { 7540 collectedNames.add(p.packageName); 7541 collected.add(p); 7542 7543 if (p.usesLibraries != null) { 7544 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7545 } 7546 if (p.usesOptionalLibraries != null) { 7547 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7548 collectedNames); 7549 } 7550 } 7551 } 7552 7553 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7554 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7555 for (String libName : libs) { 7556 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7557 if (libPkg != null) { 7558 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7559 } 7560 } 7561 } 7562 7563 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7564 synchronized (mPackages) { 7565 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7566 if (lib != null && lib.apk != null) { 7567 return mPackages.get(lib.apk); 7568 } 7569 } 7570 return null; 7571 } 7572 7573 public void shutdown() { 7574 mPackageUsage.writeNow(mPackages); 7575 mCompilerStats.writeNow(); 7576 } 7577 7578 @Override 7579 public void dumpProfiles(String packageName) { 7580 PackageParser.Package pkg; 7581 synchronized (mPackages) { 7582 pkg = mPackages.get(packageName); 7583 if (pkg == null) { 7584 throw new IllegalArgumentException("Unknown package: " + packageName); 7585 } 7586 } 7587 /* Only the shell, root, or the app user should be able to dump profiles. */ 7588 int callingUid = Binder.getCallingUid(); 7589 if (callingUid != Process.SHELL_UID && 7590 callingUid != Process.ROOT_UID && 7591 callingUid != pkg.applicationInfo.uid) { 7592 throw new SecurityException("dumpProfiles"); 7593 } 7594 7595 synchronized (mInstallLock) { 7596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7597 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7598 try { 7599 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7600 String gid = Integer.toString(sharedGid); 7601 String codePaths = TextUtils.join(";", allCodePaths); 7602 mInstaller.dumpProfiles(gid, packageName, codePaths); 7603 } catch (InstallerException e) { 7604 Slog.w(TAG, "Failed to dump profiles", e); 7605 } 7606 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7607 } 7608 } 7609 7610 @Override 7611 public void forceDexOpt(String packageName) { 7612 enforceSystemOrRoot("forceDexOpt"); 7613 7614 PackageParser.Package pkg; 7615 synchronized (mPackages) { 7616 pkg = mPackages.get(packageName); 7617 if (pkg == null) { 7618 throw new IllegalArgumentException("Unknown package: " + packageName); 7619 } 7620 } 7621 7622 synchronized (mInstallLock) { 7623 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7624 7625 // Whoever is calling forceDexOpt wants a fully compiled package. 7626 // Don't use profiles since that may cause compilation to be skipped. 7627 final int res = performDexOptInternalWithDependenciesLI(pkg, 7628 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7629 true /* force */); 7630 7631 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7632 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7633 throw new IllegalStateException("Failed to dexopt: " + res); 7634 } 7635 } 7636 } 7637 7638 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7639 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7640 Slog.w(TAG, "Unable to update from " + oldPkg.name 7641 + " to " + newPkg.packageName 7642 + ": old package not in system partition"); 7643 return false; 7644 } else if (mPackages.get(oldPkg.name) != null) { 7645 Slog.w(TAG, "Unable to update from " + oldPkg.name 7646 + " to " + newPkg.packageName 7647 + ": old package still exists"); 7648 return false; 7649 } 7650 return true; 7651 } 7652 7653 void removeCodePathLI(File codePath) { 7654 if (codePath.isDirectory()) { 7655 try { 7656 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7657 } catch (InstallerException e) { 7658 Slog.w(TAG, "Failed to remove code path", e); 7659 } 7660 } else { 7661 codePath.delete(); 7662 } 7663 } 7664 7665 private int[] resolveUserIds(int userId) { 7666 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7667 } 7668 7669 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7670 if (pkg == null) { 7671 Slog.wtf(TAG, "Package was null!", new Throwable()); 7672 return; 7673 } 7674 clearAppDataLeafLIF(pkg, userId, flags); 7675 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7676 for (int i = 0; i < childCount; i++) { 7677 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7678 } 7679 } 7680 7681 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7682 final PackageSetting ps; 7683 synchronized (mPackages) { 7684 ps = mSettings.mPackages.get(pkg.packageName); 7685 } 7686 for (int realUserId : resolveUserIds(userId)) { 7687 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7688 try { 7689 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7690 ceDataInode); 7691 } catch (InstallerException e) { 7692 Slog.w(TAG, String.valueOf(e)); 7693 } 7694 } 7695 } 7696 7697 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7698 if (pkg == null) { 7699 Slog.wtf(TAG, "Package was null!", new Throwable()); 7700 return; 7701 } 7702 destroyAppDataLeafLIF(pkg, userId, flags); 7703 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7704 for (int i = 0; i < childCount; i++) { 7705 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7706 } 7707 } 7708 7709 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7710 final PackageSetting ps; 7711 synchronized (mPackages) { 7712 ps = mSettings.mPackages.get(pkg.packageName); 7713 } 7714 for (int realUserId : resolveUserIds(userId)) { 7715 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7716 try { 7717 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7718 ceDataInode); 7719 } catch (InstallerException e) { 7720 Slog.w(TAG, String.valueOf(e)); 7721 } 7722 } 7723 } 7724 7725 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7726 if (pkg == null) { 7727 Slog.wtf(TAG, "Package was null!", new Throwable()); 7728 return; 7729 } 7730 destroyAppProfilesLeafLIF(pkg); 7731 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7732 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7733 for (int i = 0; i < childCount; i++) { 7734 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7735 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7736 true /* removeBaseMarker */); 7737 } 7738 } 7739 7740 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7741 boolean removeBaseMarker) { 7742 if (pkg.isForwardLocked()) { 7743 return; 7744 } 7745 7746 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7747 try { 7748 path = PackageManagerServiceUtils.realpath(new File(path)); 7749 } catch (IOException e) { 7750 // TODO: Should we return early here ? 7751 Slog.w(TAG, "Failed to get canonical path", e); 7752 continue; 7753 } 7754 7755 final String useMarker = path.replace('/', '@'); 7756 for (int realUserId : resolveUserIds(userId)) { 7757 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7758 if (removeBaseMarker) { 7759 File foreignUseMark = new File(profileDir, useMarker); 7760 if (foreignUseMark.exists()) { 7761 if (!foreignUseMark.delete()) { 7762 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7763 + pkg.packageName); 7764 } 7765 } 7766 } 7767 7768 File[] markers = profileDir.listFiles(); 7769 if (markers != null) { 7770 final String searchString = "@" + pkg.packageName + "@"; 7771 // We also delete all markers that contain the package name we're 7772 // uninstalling. These are associated with secondary dex-files belonging 7773 // to the package. Reconstructing the path of these dex files is messy 7774 // in general. 7775 for (File marker : markers) { 7776 if (marker.getName().indexOf(searchString) > 0) { 7777 if (!marker.delete()) { 7778 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7779 + pkg.packageName); 7780 } 7781 } 7782 } 7783 } 7784 } 7785 } 7786 } 7787 7788 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7789 try { 7790 mInstaller.destroyAppProfiles(pkg.packageName); 7791 } catch (InstallerException e) { 7792 Slog.w(TAG, String.valueOf(e)); 7793 } 7794 } 7795 7796 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7797 if (pkg == null) { 7798 Slog.wtf(TAG, "Package was null!", new Throwable()); 7799 return; 7800 } 7801 clearAppProfilesLeafLIF(pkg); 7802 // We don't remove the base foreign use marker when clearing profiles because 7803 // we will rename it when the app is updated. Unlike the actual profile contents, 7804 // the foreign use marker is good across installs. 7805 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7806 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7807 for (int i = 0; i < childCount; i++) { 7808 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7809 } 7810 } 7811 7812 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7813 try { 7814 mInstaller.clearAppProfiles(pkg.packageName); 7815 } catch (InstallerException e) { 7816 Slog.w(TAG, String.valueOf(e)); 7817 } 7818 } 7819 7820 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7821 long lastUpdateTime) { 7822 // Set parent install/update time 7823 PackageSetting ps = (PackageSetting) pkg.mExtras; 7824 if (ps != null) { 7825 ps.firstInstallTime = firstInstallTime; 7826 ps.lastUpdateTime = lastUpdateTime; 7827 } 7828 // Set children install/update time 7829 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7830 for (int i = 0; i < childCount; i++) { 7831 PackageParser.Package childPkg = pkg.childPackages.get(i); 7832 ps = (PackageSetting) childPkg.mExtras; 7833 if (ps != null) { 7834 ps.firstInstallTime = firstInstallTime; 7835 ps.lastUpdateTime = lastUpdateTime; 7836 } 7837 } 7838 } 7839 7840 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7841 PackageParser.Package changingLib) { 7842 if (file.path != null) { 7843 usesLibraryFiles.add(file.path); 7844 return; 7845 } 7846 PackageParser.Package p = mPackages.get(file.apk); 7847 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7848 // If we are doing this while in the middle of updating a library apk, 7849 // then we need to make sure to use that new apk for determining the 7850 // dependencies here. (We haven't yet finished committing the new apk 7851 // to the package manager state.) 7852 if (p == null || p.packageName.equals(changingLib.packageName)) { 7853 p = changingLib; 7854 } 7855 } 7856 if (p != null) { 7857 usesLibraryFiles.addAll(p.getAllCodePaths()); 7858 } 7859 } 7860 7861 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 7862 PackageParser.Package changingLib) throws PackageManagerException { 7863 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7864 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7865 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7866 for (int i=0; i<N; i++) { 7867 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7868 if (file == null) { 7869 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7870 "Package " + pkg.packageName + " requires unavailable shared library " 7871 + pkg.usesLibraries.get(i) + "; failing!"); 7872 } 7873 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7874 } 7875 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7876 for (int i=0; i<N; i++) { 7877 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7878 if (file == null) { 7879 Slog.w(TAG, "Package " + pkg.packageName 7880 + " desires unavailable shared library " 7881 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7882 } else { 7883 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7884 } 7885 } 7886 N = usesLibraryFiles.size(); 7887 if (N > 0) { 7888 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7889 } else { 7890 pkg.usesLibraryFiles = null; 7891 } 7892 } 7893 } 7894 7895 private static boolean hasString(List<String> list, List<String> which) { 7896 if (list == null) { 7897 return false; 7898 } 7899 for (int i=list.size()-1; i>=0; i--) { 7900 for (int j=which.size()-1; j>=0; j--) { 7901 if (which.get(j).equals(list.get(i))) { 7902 return true; 7903 } 7904 } 7905 } 7906 return false; 7907 } 7908 7909 private void updateAllSharedLibrariesLPw() { 7910 for (PackageParser.Package pkg : mPackages.values()) { 7911 try { 7912 updateSharedLibrariesLPr(pkg, null); 7913 } catch (PackageManagerException e) { 7914 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7915 } 7916 } 7917 } 7918 7919 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7920 PackageParser.Package changingPkg) { 7921 ArrayList<PackageParser.Package> res = null; 7922 for (PackageParser.Package pkg : mPackages.values()) { 7923 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7924 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7925 if (res == null) { 7926 res = new ArrayList<PackageParser.Package>(); 7927 } 7928 res.add(pkg); 7929 try { 7930 updateSharedLibrariesLPr(pkg, changingPkg); 7931 } catch (PackageManagerException e) { 7932 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7933 } 7934 } 7935 } 7936 return res; 7937 } 7938 7939 /** 7940 * Derive the value of the {@code cpuAbiOverride} based on the provided 7941 * value and an optional stored value from the package settings. 7942 */ 7943 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7944 String cpuAbiOverride = null; 7945 7946 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7947 cpuAbiOverride = null; 7948 } else if (abiOverride != null) { 7949 cpuAbiOverride = abiOverride; 7950 } else if (settings != null) { 7951 cpuAbiOverride = settings.cpuAbiOverrideString; 7952 } 7953 7954 return cpuAbiOverride; 7955 } 7956 7957 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7958 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7959 throws PackageManagerException { 7960 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7961 // If the package has children and this is the first dive in the function 7962 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7963 // whether all packages (parent and children) would be successfully scanned 7964 // before the actual scan since scanning mutates internal state and we want 7965 // to atomically install the package and its children. 7966 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7967 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7968 scanFlags |= SCAN_CHECK_ONLY; 7969 } 7970 } else { 7971 scanFlags &= ~SCAN_CHECK_ONLY; 7972 } 7973 7974 final PackageParser.Package scannedPkg; 7975 try { 7976 // Scan the parent 7977 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7978 // Scan the children 7979 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7980 for (int i = 0; i < childCount; i++) { 7981 PackageParser.Package childPkg = pkg.childPackages.get(i); 7982 scanPackageLI(childPkg, policyFlags, 7983 scanFlags, currentTime, user); 7984 } 7985 } finally { 7986 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7987 } 7988 7989 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7990 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7991 } 7992 7993 return scannedPkg; 7994 } 7995 7996 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7997 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7998 boolean success = false; 7999 try { 8000 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8001 currentTime, user); 8002 success = true; 8003 return res; 8004 } finally { 8005 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8006 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8007 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8008 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8009 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8010 } 8011 } 8012 } 8013 8014 /** 8015 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8016 */ 8017 private static boolean apkHasCode(String fileName) { 8018 StrictJarFile jarFile = null; 8019 try { 8020 jarFile = new StrictJarFile(fileName, 8021 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8022 return jarFile.findEntry("classes.dex") != null; 8023 } catch (IOException ignore) { 8024 } finally { 8025 try { 8026 if (jarFile != null) { 8027 jarFile.close(); 8028 } 8029 } catch (IOException ignore) {} 8030 } 8031 return false; 8032 } 8033 8034 /** 8035 * Enforces code policy for the package. This ensures that if an APK has 8036 * declared hasCode="true" in its manifest that the APK actually contains 8037 * code. 8038 * 8039 * @throws PackageManagerException If bytecode could not be found when it should exist 8040 */ 8041 private static void assertCodePolicy(PackageParser.Package pkg) 8042 throws PackageManagerException { 8043 final boolean shouldHaveCode = 8044 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8045 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8046 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8047 "Package " + pkg.baseCodePath + " code is missing"); 8048 } 8049 8050 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8051 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8052 final boolean splitShouldHaveCode = 8053 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8054 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8055 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8056 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8057 } 8058 } 8059 } 8060 } 8061 8062 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8063 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8064 throws PackageManagerException { 8065 if (DEBUG_PACKAGE_SCANNING) { 8066 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8067 Log.d(TAG, "Scanning package " + pkg.packageName); 8068 } 8069 8070 applyPolicy(pkg, policyFlags); 8071 8072 assertPackageIsValid(pkg, policyFlags); 8073 8074 // Initialize package source and resource directories 8075 final File scanFile = new File(pkg.codePath); 8076 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8077 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8078 8079 SharedUserSetting suid = null; 8080 PackageSetting pkgSetting = null; 8081 8082 // Getting the package setting may have a side-effect, so if we 8083 // are only checking if scan would succeed, stash a copy of the 8084 // old setting to restore at the end. 8085 PackageSetting nonMutatedPs = null; 8086 8087 // writer 8088 synchronized (mPackages) { 8089 if (pkg.mSharedUserId != null) { 8090 // SIDE EFFECTS; may potentially allocate a new shared user 8091 suid = mSettings.getSharedUserLPw( 8092 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8093 if (DEBUG_PACKAGE_SCANNING) { 8094 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8095 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8096 + "): packages=" + suid.packages); 8097 } 8098 } 8099 8100 // Check if we are renaming from an original package name. 8101 PackageSetting origPackage = null; 8102 String realName = null; 8103 if (pkg.mOriginalPackages != null) { 8104 // This package may need to be renamed to a previously 8105 // installed name. Let's check on that... 8106 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8107 if (pkg.mOriginalPackages.contains(renamed)) { 8108 // This package had originally been installed as the 8109 // original name, and we have already taken care of 8110 // transitioning to the new one. Just update the new 8111 // one to continue using the old name. 8112 realName = pkg.mRealPackage; 8113 if (!pkg.packageName.equals(renamed)) { 8114 // Callers into this function may have already taken 8115 // care of renaming the package; only do it here if 8116 // it is not already done. 8117 pkg.setPackageName(renamed); 8118 } 8119 } else { 8120 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8121 if ((origPackage = mSettings.getPackageLPr( 8122 pkg.mOriginalPackages.get(i))) != null) { 8123 // We do have the package already installed under its 8124 // original name... should we use it? 8125 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8126 // New package is not compatible with original. 8127 origPackage = null; 8128 continue; 8129 } else if (origPackage.sharedUser != null) { 8130 // Make sure uid is compatible between packages. 8131 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8132 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8133 + " to " + pkg.packageName + ": old uid " 8134 + origPackage.sharedUser.name 8135 + " differs from " + pkg.mSharedUserId); 8136 origPackage = null; 8137 continue; 8138 } 8139 // TODO: Add case when shared user id is added [b/28144775] 8140 } else { 8141 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8142 + pkg.packageName + " to old name " + origPackage.name); 8143 } 8144 break; 8145 } 8146 } 8147 } 8148 } 8149 8150 if (mTransferedPackages.contains(pkg.packageName)) { 8151 Slog.w(TAG, "Package " + pkg.packageName 8152 + " was transferred to another, but its .apk remains"); 8153 } 8154 8155 // See comments in nonMutatedPs declaration 8156 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8157 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8158 if (foundPs != null) { 8159 nonMutatedPs = new PackageSetting(foundPs); 8160 } 8161 } 8162 8163 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8164 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8165 PackageManagerService.reportSettingsProblem(Log.WARN, 8166 "Package " + pkg.packageName + " shared user changed from " 8167 + (pkgSetting.sharedUser != null 8168 ? pkgSetting.sharedUser.name : "<nothing>") 8169 + " to " 8170 + (suid != null ? suid.name : "<nothing>") 8171 + "; replacing with new"); 8172 pkgSetting = null; 8173 } 8174 final PackageSetting oldPkgSetting = 8175 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8176 final PackageSetting disabledPkgSetting = 8177 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8178 if (pkgSetting == null) { 8179 final String parentPackageName = (pkg.parentPackage != null) 8180 ? pkg.parentPackage.packageName : null; 8181 // REMOVE SharedUserSetting from method; update in a separate call 8182 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8183 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8184 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8185 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8186 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8187 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8188 UserManagerService.getInstance()); 8189 // SIDE EFFECTS; updates system state; move elsewhere 8190 if (origPackage != null) { 8191 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8192 } 8193 mSettings.addUserToSettingLPw(pkgSetting); 8194 } else { 8195 // REMOVE SharedUserSetting from method; update in a separate call 8196 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8197 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8198 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8199 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8200 UserManagerService.getInstance()); 8201 } 8202 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8203 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8204 8205 // SIDE EFFECTS; modifies system state; move elsewhere 8206 if (pkgSetting.origPackage != null) { 8207 // If we are first transitioning from an original package, 8208 // fix up the new package's name now. We need to do this after 8209 // looking up the package under its new name, so getPackageLP 8210 // can take care of fiddling things correctly. 8211 pkg.setPackageName(origPackage.name); 8212 8213 // File a report about this. 8214 String msg = "New package " + pkgSetting.realName 8215 + " renamed to replace old package " + pkgSetting.name; 8216 reportSettingsProblem(Log.WARN, msg); 8217 8218 // Make a note of it. 8219 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8220 mTransferedPackages.add(origPackage.name); 8221 } 8222 8223 // No longer need to retain this. 8224 pkgSetting.origPackage = null; 8225 } 8226 8227 // SIDE EFFECTS; modifies system state; move elsewhere 8228 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8229 // Make a note of it. 8230 mTransferedPackages.add(pkg.packageName); 8231 } 8232 8233 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8234 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8235 } 8236 8237 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8238 // Check all shared libraries and map to their actual file path. 8239 // We only do this here for apps not on a system dir, because those 8240 // are the only ones that can fail an install due to this. We 8241 // will take care of the system apps by updating all of their 8242 // library paths after the scan is done. 8243 updateSharedLibrariesLPr(pkg, null); 8244 } 8245 8246 if (mFoundPolicyFile) { 8247 SELinuxMMAC.assignSeinfoValue(pkg); 8248 } 8249 8250 pkg.applicationInfo.uid = pkgSetting.appId; 8251 pkg.mExtras = pkgSetting; 8252 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8253 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8254 // We just determined the app is signed correctly, so bring 8255 // over the latest parsed certs. 8256 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8257 } else { 8258 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8259 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8260 "Package " + pkg.packageName + " upgrade keys do not match the " 8261 + "previously installed version"); 8262 } else { 8263 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8264 String msg = "System package " + pkg.packageName 8265 + " signature changed; retaining data."; 8266 reportSettingsProblem(Log.WARN, msg); 8267 } 8268 } 8269 } else { 8270 try { 8271 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8272 verifySignaturesLP(pkgSetting, pkg); 8273 // We just determined the app is signed correctly, so bring 8274 // over the latest parsed certs. 8275 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8276 } catch (PackageManagerException e) { 8277 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8278 throw e; 8279 } 8280 // The signature has changed, but this package is in the system 8281 // image... let's recover! 8282 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8283 // However... if this package is part of a shared user, but it 8284 // doesn't match the signature of the shared user, let's fail. 8285 // What this means is that you can't change the signatures 8286 // associated with an overall shared user, which doesn't seem all 8287 // that unreasonable. 8288 if (pkgSetting.sharedUser != null) { 8289 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8290 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8291 throw new PackageManagerException( 8292 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8293 "Signature mismatch for shared user: " 8294 + pkgSetting.sharedUser); 8295 } 8296 } 8297 // File a report about this. 8298 String msg = "System package " + pkg.packageName 8299 + " signature changed; retaining data."; 8300 reportSettingsProblem(Log.WARN, msg); 8301 } 8302 } 8303 8304 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8305 // This package wants to adopt ownership of permissions from 8306 // another package. 8307 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8308 final String origName = pkg.mAdoptPermissions.get(i); 8309 final PackageSetting orig = mSettings.getPackageLPr(origName); 8310 if (orig != null) { 8311 if (verifyPackageUpdateLPr(orig, pkg)) { 8312 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8313 + pkg.packageName); 8314 // SIDE EFFECTS; updates permissions system state; move elsewhere 8315 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8316 } 8317 } 8318 } 8319 } 8320 } 8321 8322 pkg.applicationInfo.processName = fixProcessName( 8323 pkg.applicationInfo.packageName, 8324 pkg.applicationInfo.processName); 8325 8326 if (pkg != mPlatformPackage) { 8327 // Get all of our default paths setup 8328 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8329 } 8330 8331 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8332 8333 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8335 derivePackageAbi( 8336 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8337 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8338 8339 // Some system apps still use directory structure for native libraries 8340 // in which case we might end up not detecting abi solely based on apk 8341 // structure. Try to detect abi based on directory structure. 8342 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8343 pkg.applicationInfo.primaryCpuAbi == null) { 8344 setBundledAppAbisAndRoots(pkg, pkgSetting); 8345 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8346 } 8347 } else { 8348 if ((scanFlags & SCAN_MOVE) != 0) { 8349 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8350 // but we already have this packages package info in the PackageSetting. We just 8351 // use that and derive the native library path based on the new codepath. 8352 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8353 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8354 } 8355 8356 // Set native library paths again. For moves, the path will be updated based on the 8357 // ABIs we've determined above. For non-moves, the path will be updated based on the 8358 // ABIs we determined during compilation, but the path will depend on the final 8359 // package path (after the rename away from the stage path). 8360 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8361 } 8362 8363 // This is a special case for the "system" package, where the ABI is 8364 // dictated by the zygote configuration (and init.rc). We should keep track 8365 // of this ABI so that we can deal with "normal" applications that run under 8366 // the same UID correctly. 8367 if (mPlatformPackage == pkg) { 8368 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8369 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8370 } 8371 8372 // If there's a mismatch between the abi-override in the package setting 8373 // and the abiOverride specified for the install. Warn about this because we 8374 // would've already compiled the app without taking the package setting into 8375 // account. 8376 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8377 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8378 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8379 " for package " + pkg.packageName); 8380 } 8381 } 8382 8383 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8384 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8385 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8386 8387 // Copy the derived override back to the parsed package, so that we can 8388 // update the package settings accordingly. 8389 pkg.cpuAbiOverride = cpuAbiOverride; 8390 8391 if (DEBUG_ABI_SELECTION) { 8392 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8393 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8394 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8395 } 8396 8397 // Push the derived path down into PackageSettings so we know what to 8398 // clean up at uninstall time. 8399 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8400 8401 if (DEBUG_ABI_SELECTION) { 8402 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8403 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8404 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8405 } 8406 8407 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8408 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8409 // We don't do this here during boot because we can do it all 8410 // at once after scanning all existing packages. 8411 // 8412 // We also do this *before* we perform dexopt on this package, so that 8413 // we can avoid redundant dexopts, and also to make sure we've got the 8414 // code and package path correct. 8415 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8416 } 8417 8418 if (mFactoryTest && pkg.requestedPermissions.contains( 8419 android.Manifest.permission.FACTORY_TEST)) { 8420 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8421 } 8422 8423 if (isSystemApp(pkg)) { 8424 pkgSetting.isOrphaned = true; 8425 } 8426 8427 // Take care of first install / last update times. 8428 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8429 if (currentTime != 0) { 8430 if (pkgSetting.firstInstallTime == 0) { 8431 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8432 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8433 pkgSetting.lastUpdateTime = currentTime; 8434 } 8435 } else if (pkgSetting.firstInstallTime == 0) { 8436 // We need *something*. Take time time stamp of the file. 8437 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8438 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8439 if (scanFileTime != pkgSetting.timeStamp) { 8440 // A package on the system image has changed; consider this 8441 // to be an update. 8442 pkgSetting.lastUpdateTime = scanFileTime; 8443 } 8444 } 8445 pkgSetting.setTimeStamp(scanFileTime); 8446 8447 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8448 if (nonMutatedPs != null) { 8449 synchronized (mPackages) { 8450 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8451 } 8452 } 8453 } else { 8454 // Modify state for the given package setting 8455 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8456 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8457 } 8458 return pkg; 8459 } 8460 8461 /** 8462 * Applies policy to the parsed package based upon the given policy flags. 8463 * Ensures the package is in a good state. 8464 * <p> 8465 * Implementation detail: This method must NOT have any side effect. It would 8466 * ideally be static, but, it requires locks to read system state. 8467 */ 8468 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8469 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8470 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8471 if (pkg.applicationInfo.isDirectBootAware()) { 8472 // we're direct boot aware; set for all components 8473 for (PackageParser.Service s : pkg.services) { 8474 s.info.encryptionAware = s.info.directBootAware = true; 8475 } 8476 for (PackageParser.Provider p : pkg.providers) { 8477 p.info.encryptionAware = p.info.directBootAware = true; 8478 } 8479 for (PackageParser.Activity a : pkg.activities) { 8480 a.info.encryptionAware = a.info.directBootAware = true; 8481 } 8482 for (PackageParser.Activity r : pkg.receivers) { 8483 r.info.encryptionAware = r.info.directBootAware = true; 8484 } 8485 } 8486 } else { 8487 // Only allow system apps to be flagged as core apps. 8488 pkg.coreApp = false; 8489 // clear flags not applicable to regular apps 8490 pkg.applicationInfo.privateFlags &= 8491 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8492 pkg.applicationInfo.privateFlags &= 8493 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8494 } 8495 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8496 8497 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8498 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8499 } 8500 8501 if (!isSystemApp(pkg)) { 8502 // Only system apps can use these features. 8503 pkg.mOriginalPackages = null; 8504 pkg.mRealPackage = null; 8505 pkg.mAdoptPermissions = null; 8506 } 8507 } 8508 8509 /** 8510 * Asserts the parsed package is valid according to teh given policy. If the 8511 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8512 * <p> 8513 * Implementation detail: This method must NOT have any side effects. It would 8514 * ideally be static, but, it requires locks to read system state. 8515 * 8516 * @throws PackageManagerException If the package fails any of the validation checks 8517 */ 8518 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags) 8519 throws PackageManagerException { 8520 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8521 assertCodePolicy(pkg); 8522 } 8523 8524 if (pkg.applicationInfo.getCodePath() == null || 8525 pkg.applicationInfo.getResourcePath() == null) { 8526 // Bail out. The resource and code paths haven't been set. 8527 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8528 "Code and resource paths haven't been set correctly"); 8529 } 8530 8531 // Make sure we're not adding any bogus keyset info 8532 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8533 ksms.assertScannedPackageValid(pkg); 8534 8535 synchronized (mPackages) { 8536 // The special "android" package can only be defined once 8537 if (pkg.packageName.equals("android")) { 8538 if (mAndroidApplication != null) { 8539 Slog.w(TAG, "*************************************************"); 8540 Slog.w(TAG, "Core android package being redefined. Skipping."); 8541 Slog.w(TAG, " codePath=" + pkg.codePath); 8542 Slog.w(TAG, "*************************************************"); 8543 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8544 "Core android package being redefined. Skipping."); 8545 } 8546 } 8547 8548 // A package name must be unique; don't allow duplicates 8549 if (mPackages.containsKey(pkg.packageName) 8550 || mSharedLibraries.containsKey(pkg.packageName)) { 8551 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8552 "Application package " + pkg.packageName 8553 + " already installed. Skipping duplicate."); 8554 } 8555 8556 // Only privileged apps and updated privileged apps can add child packages. 8557 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8558 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8559 throw new PackageManagerException("Only privileged apps can add child " 8560 + "packages. Ignoring package " + pkg.packageName); 8561 } 8562 final int childCount = pkg.childPackages.size(); 8563 for (int i = 0; i < childCount; i++) { 8564 PackageParser.Package childPkg = pkg.childPackages.get(i); 8565 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8566 childPkg.packageName)) { 8567 throw new PackageManagerException("Can't override child of " 8568 + "another disabled app. Ignoring package " + pkg.packageName); 8569 } 8570 } 8571 } 8572 8573 // If we're only installing presumed-existing packages, require that the 8574 // scanned APK is both already known and at the path previously established 8575 // for it. Previously unknown packages we pick up normally, but if we have an 8576 // a priori expectation about this package's install presence, enforce it. 8577 // With a singular exception for new system packages. When an OTA contains 8578 // a new system package, we allow the codepath to change from a system location 8579 // to the user-installed location. If we don't allow this change, any newer, 8580 // user-installed version of the application will be ignored. 8581 if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) { 8582 if (mExpectingBetter.containsKey(pkg.packageName)) { 8583 logCriticalInfo(Log.WARN, 8584 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8585 } else { 8586 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8587 if (known != null) { 8588 if (DEBUG_PACKAGE_SCANNING) { 8589 Log.d(TAG, "Examining " + pkg.codePath 8590 + " and requiring known paths " + known.codePathString 8591 + " & " + known.resourcePathString); 8592 } 8593 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8594 || !pkg.applicationInfo.getResourcePath().equals( 8595 known.resourcePathString)) { 8596 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8597 "Application package " + pkg.packageName 8598 + " found at " + pkg.applicationInfo.getCodePath() 8599 + " but expected at " + known.codePathString 8600 + "; ignoring."); 8601 } 8602 } 8603 } 8604 } 8605 8606 // Verify that this new package doesn't have any content providers 8607 // that conflict with existing packages. Only do this if the 8608 // package isn't already installed, since we don't want to break 8609 // things that are installed. 8610 if ((policyFlags & SCAN_NEW_INSTALL) != 0) { 8611 final int N = pkg.providers.size(); 8612 int i; 8613 for (i=0; i<N; i++) { 8614 PackageParser.Provider p = pkg.providers.get(i); 8615 if (p.info.authority != null) { 8616 String names[] = p.info.authority.split(";"); 8617 for (int j = 0; j < names.length; j++) { 8618 if (mProvidersByAuthority.containsKey(names[j])) { 8619 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8620 final String otherPackageName = 8621 ((other != null && other.getComponentName() != null) ? 8622 other.getComponentName().getPackageName() : "?"); 8623 throw new PackageManagerException( 8624 INSTALL_FAILED_CONFLICTING_PROVIDER, 8625 "Can't install because provider name " + names[j] 8626 + " (in package " + pkg.applicationInfo.packageName 8627 + ") is already used by " + otherPackageName); 8628 } 8629 } 8630 } 8631 } 8632 } 8633 } 8634 } 8635 8636 /** 8637 * Adds a scanned package to the system. When this method is finished, the package will 8638 * be available for query, resolution, etc... 8639 */ 8640 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8641 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8642 final String pkgName = pkg.packageName; 8643 if (mCustomResolverComponentName != null && 8644 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8645 setUpCustomResolverActivity(pkg); 8646 } 8647 8648 if (pkg.packageName.equals("android")) { 8649 synchronized (mPackages) { 8650 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8651 // Set up information for our fall-back user intent resolution activity. 8652 mPlatformPackage = pkg; 8653 pkg.mVersionCode = mSdkVersion; 8654 mAndroidApplication = pkg.applicationInfo; 8655 8656 if (!mResolverReplaced) { 8657 mResolveActivity.applicationInfo = mAndroidApplication; 8658 mResolveActivity.name = ResolverActivity.class.getName(); 8659 mResolveActivity.packageName = mAndroidApplication.packageName; 8660 mResolveActivity.processName = "system:ui"; 8661 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8662 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8663 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8664 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8665 mResolveActivity.exported = true; 8666 mResolveActivity.enabled = true; 8667 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8668 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8669 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8670 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8671 | ActivityInfo.CONFIG_ORIENTATION 8672 | ActivityInfo.CONFIG_KEYBOARD 8673 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8674 mResolveInfo.activityInfo = mResolveActivity; 8675 mResolveInfo.priority = 0; 8676 mResolveInfo.preferredOrder = 0; 8677 mResolveInfo.match = 0; 8678 mResolveComponentName = new ComponentName( 8679 mAndroidApplication.packageName, mResolveActivity.name); 8680 } 8681 } 8682 } 8683 } 8684 8685 ArrayList<PackageParser.Package> clientLibPkgs = null; 8686 // writer 8687 synchronized (mPackages) { 8688 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8689 // Only system apps can add new shared libraries. 8690 if (pkg.libraryNames != null) { 8691 for (int i=0; i<pkg.libraryNames.size(); i++) { 8692 String name = pkg.libraryNames.get(i); 8693 boolean allowed = false; 8694 if (pkg.isUpdatedSystemApp()) { 8695 // New library entries can only be added through the 8696 // system image. This is important to get rid of a lot 8697 // of nasty edge cases: for example if we allowed a non- 8698 // system update of the app to add a library, then uninstalling 8699 // the update would make the library go away, and assumptions 8700 // we made such as through app install filtering would now 8701 // have allowed apps on the device which aren't compatible 8702 // with it. Better to just have the restriction here, be 8703 // conservative, and create many fewer cases that can negatively 8704 // impact the user experience. 8705 final PackageSetting sysPs = mSettings 8706 .getDisabledSystemPkgLPr(pkg.packageName); 8707 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8708 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8709 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8710 allowed = true; 8711 break; 8712 } 8713 } 8714 } 8715 } else { 8716 allowed = true; 8717 } 8718 if (allowed) { 8719 if (!mSharedLibraries.containsKey(name)) { 8720 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8721 } else if (!name.equals(pkg.packageName)) { 8722 Slog.w(TAG, "Package " + pkg.packageName + " library " 8723 + name + " already exists; skipping"); 8724 } 8725 } else { 8726 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8727 + name + " that is not declared on system image; skipping"); 8728 } 8729 } 8730 if ((scanFlags & SCAN_BOOTING) == 0) { 8731 // If we are not booting, we need to update any applications 8732 // that are clients of our shared library. If we are booting, 8733 // this will all be done once the scan is complete. 8734 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8735 } 8736 } 8737 } 8738 } 8739 8740 if ((scanFlags & SCAN_BOOTING) != 0) { 8741 // No apps can run during boot scan, so they don't need to be frozen 8742 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8743 // Caller asked to not kill app, so it's probably not frozen 8744 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8745 // Caller asked us to ignore frozen check for some reason; they 8746 // probably didn't know the package name 8747 } else { 8748 // We're doing major surgery on this package, so it better be frozen 8749 // right now to keep it from launching 8750 checkPackageFrozen(pkgName); 8751 } 8752 8753 // Also need to kill any apps that are dependent on the library. 8754 if (clientLibPkgs != null) { 8755 for (int i=0; i<clientLibPkgs.size(); i++) { 8756 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8757 killApplication(clientPkg.applicationInfo.packageName, 8758 clientPkg.applicationInfo.uid, "update lib"); 8759 } 8760 } 8761 8762 // writer 8763 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8764 8765 boolean createIdmapFailed = false; 8766 synchronized (mPackages) { 8767 // We don't expect installation to fail beyond this point 8768 8769 if (pkgSetting.pkg != null) { 8770 // Note that |user| might be null during the initial boot scan. If a codePath 8771 // for an app has changed during a boot scan, it's due to an app update that's 8772 // part of the system partition and marker changes must be applied to all users. 8773 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 8774 final int[] userIds = resolveUserIds(userId); 8775 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 8776 } 8777 8778 // Add the new setting to mSettings 8779 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8780 // Add the new setting to mPackages 8781 mPackages.put(pkg.applicationInfo.packageName, pkg); 8782 // Make sure we don't accidentally delete its data. 8783 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8784 while (iter.hasNext()) { 8785 PackageCleanItem item = iter.next(); 8786 if (pkgName.equals(item.packageName)) { 8787 iter.remove(); 8788 } 8789 } 8790 8791 // Add the package's KeySets to the global KeySetManagerService 8792 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8793 ksms.addScannedPackageLPw(pkg); 8794 8795 int N = pkg.providers.size(); 8796 StringBuilder r = null; 8797 int i; 8798 for (i=0; i<N; i++) { 8799 PackageParser.Provider p = pkg.providers.get(i); 8800 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8801 p.info.processName); 8802 mProviders.addProvider(p); 8803 p.syncable = p.info.isSyncable; 8804 if (p.info.authority != null) { 8805 String names[] = p.info.authority.split(";"); 8806 p.info.authority = null; 8807 for (int j = 0; j < names.length; j++) { 8808 if (j == 1 && p.syncable) { 8809 // We only want the first authority for a provider to possibly be 8810 // syncable, so if we already added this provider using a different 8811 // authority clear the syncable flag. We copy the provider before 8812 // changing it because the mProviders object contains a reference 8813 // to a provider that we don't want to change. 8814 // Only do this for the second authority since the resulting provider 8815 // object can be the same for all future authorities for this provider. 8816 p = new PackageParser.Provider(p); 8817 p.syncable = false; 8818 } 8819 if (!mProvidersByAuthority.containsKey(names[j])) { 8820 mProvidersByAuthority.put(names[j], p); 8821 if (p.info.authority == null) { 8822 p.info.authority = names[j]; 8823 } else { 8824 p.info.authority = p.info.authority + ";" + names[j]; 8825 } 8826 if (DEBUG_PACKAGE_SCANNING) { 8827 if (chatty) 8828 Log.d(TAG, "Registered content provider: " + names[j] 8829 + ", className = " + p.info.name + ", isSyncable = " 8830 + p.info.isSyncable); 8831 } 8832 } else { 8833 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8834 Slog.w(TAG, "Skipping provider name " + names[j] + 8835 " (in package " + pkg.applicationInfo.packageName + 8836 "): name already used by " 8837 + ((other != null && other.getComponentName() != null) 8838 ? other.getComponentName().getPackageName() : "?")); 8839 } 8840 } 8841 } 8842 if (chatty) { 8843 if (r == null) { 8844 r = new StringBuilder(256); 8845 } else { 8846 r.append(' '); 8847 } 8848 r.append(p.info.name); 8849 } 8850 } 8851 if (r != null) { 8852 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8853 } 8854 8855 N = pkg.services.size(); 8856 r = null; 8857 for (i=0; i<N; i++) { 8858 PackageParser.Service s = pkg.services.get(i); 8859 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8860 s.info.processName); 8861 mServices.addService(s); 8862 if (chatty) { 8863 if (r == null) { 8864 r = new StringBuilder(256); 8865 } else { 8866 r.append(' '); 8867 } 8868 r.append(s.info.name); 8869 } 8870 } 8871 if (r != null) { 8872 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8873 } 8874 8875 N = pkg.receivers.size(); 8876 r = null; 8877 for (i=0; i<N; i++) { 8878 PackageParser.Activity a = pkg.receivers.get(i); 8879 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8880 a.info.processName); 8881 mReceivers.addActivity(a, "receiver"); 8882 if (chatty) { 8883 if (r == null) { 8884 r = new StringBuilder(256); 8885 } else { 8886 r.append(' '); 8887 } 8888 r.append(a.info.name); 8889 } 8890 } 8891 if (r != null) { 8892 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8893 } 8894 8895 N = pkg.activities.size(); 8896 r = null; 8897 for (i=0; i<N; i++) { 8898 PackageParser.Activity a = pkg.activities.get(i); 8899 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8900 a.info.processName); 8901 mActivities.addActivity(a, "activity"); 8902 if (chatty) { 8903 if (r == null) { 8904 r = new StringBuilder(256); 8905 } else { 8906 r.append(' '); 8907 } 8908 r.append(a.info.name); 8909 } 8910 } 8911 if (r != null) { 8912 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8913 } 8914 8915 N = pkg.permissionGroups.size(); 8916 r = null; 8917 for (i=0; i<N; i++) { 8918 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8919 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8920 final String curPackageName = cur == null ? null : cur.info.packageName; 8921 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8922 if (cur == null || isPackageUpdate) { 8923 mPermissionGroups.put(pg.info.name, pg); 8924 if (chatty) { 8925 if (r == null) { 8926 r = new StringBuilder(256); 8927 } else { 8928 r.append(' '); 8929 } 8930 if (isPackageUpdate) { 8931 r.append("UPD:"); 8932 } 8933 r.append(pg.info.name); 8934 } 8935 } else { 8936 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8937 + pg.info.packageName + " ignored: original from " 8938 + cur.info.packageName); 8939 if (chatty) { 8940 if (r == null) { 8941 r = new StringBuilder(256); 8942 } else { 8943 r.append(' '); 8944 } 8945 r.append("DUP:"); 8946 r.append(pg.info.name); 8947 } 8948 } 8949 } 8950 if (r != null) { 8951 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8952 } 8953 8954 N = pkg.permissions.size(); 8955 r = null; 8956 for (i=0; i<N; i++) { 8957 PackageParser.Permission p = pkg.permissions.get(i); 8958 8959 // Assume by default that we did not install this permission into the system. 8960 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8961 8962 // Now that permission groups have a special meaning, we ignore permission 8963 // groups for legacy apps to prevent unexpected behavior. In particular, 8964 // permissions for one app being granted to someone just becase they happen 8965 // to be in a group defined by another app (before this had no implications). 8966 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8967 p.group = mPermissionGroups.get(p.info.group); 8968 // Warn for a permission in an unknown group. 8969 if (p.info.group != null && p.group == null) { 8970 Slog.w(TAG, "Permission " + p.info.name + " from package " 8971 + p.info.packageName + " in an unknown group " + p.info.group); 8972 } 8973 } 8974 8975 ArrayMap<String, BasePermission> permissionMap = 8976 p.tree ? mSettings.mPermissionTrees 8977 : mSettings.mPermissions; 8978 BasePermission bp = permissionMap.get(p.info.name); 8979 8980 // Allow system apps to redefine non-system permissions 8981 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8982 final boolean currentOwnerIsSystem = (bp.perm != null 8983 && isSystemApp(bp.perm.owner)); 8984 if (isSystemApp(p.owner)) { 8985 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8986 // It's a built-in permission and no owner, take ownership now 8987 bp.packageSetting = pkgSetting; 8988 bp.perm = p; 8989 bp.uid = pkg.applicationInfo.uid; 8990 bp.sourcePackage = p.info.packageName; 8991 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8992 } else if (!currentOwnerIsSystem) { 8993 String msg = "New decl " + p.owner + " of permission " 8994 + p.info.name + " is system; overriding " + bp.sourcePackage; 8995 reportSettingsProblem(Log.WARN, msg); 8996 bp = null; 8997 } 8998 } 8999 } 9000 9001 if (bp == null) { 9002 bp = new BasePermission(p.info.name, p.info.packageName, 9003 BasePermission.TYPE_NORMAL); 9004 permissionMap.put(p.info.name, bp); 9005 } 9006 9007 if (bp.perm == null) { 9008 if (bp.sourcePackage == null 9009 || bp.sourcePackage.equals(p.info.packageName)) { 9010 BasePermission tree = findPermissionTreeLP(p.info.name); 9011 if (tree == null 9012 || tree.sourcePackage.equals(p.info.packageName)) { 9013 bp.packageSetting = pkgSetting; 9014 bp.perm = p; 9015 bp.uid = pkg.applicationInfo.uid; 9016 bp.sourcePackage = p.info.packageName; 9017 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9018 if (chatty) { 9019 if (r == null) { 9020 r = new StringBuilder(256); 9021 } else { 9022 r.append(' '); 9023 } 9024 r.append(p.info.name); 9025 } 9026 } else { 9027 Slog.w(TAG, "Permission " + p.info.name + " from package " 9028 + p.info.packageName + " ignored: base tree " 9029 + tree.name + " is from package " 9030 + tree.sourcePackage); 9031 } 9032 } else { 9033 Slog.w(TAG, "Permission " + p.info.name + " from package " 9034 + p.info.packageName + " ignored: original from " 9035 + bp.sourcePackage); 9036 } 9037 } else if (chatty) { 9038 if (r == null) { 9039 r = new StringBuilder(256); 9040 } else { 9041 r.append(' '); 9042 } 9043 r.append("DUP:"); 9044 r.append(p.info.name); 9045 } 9046 if (bp.perm == p) { 9047 bp.protectionLevel = p.info.protectionLevel; 9048 } 9049 } 9050 9051 if (r != null) { 9052 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9053 } 9054 9055 N = pkg.instrumentation.size(); 9056 r = null; 9057 for (i=0; i<N; i++) { 9058 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9059 a.info.packageName = pkg.applicationInfo.packageName; 9060 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9061 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9062 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9063 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9064 a.info.dataDir = pkg.applicationInfo.dataDir; 9065 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9066 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9067 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9068 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9069 mInstrumentation.put(a.getComponentName(), a); 9070 if (chatty) { 9071 if (r == null) { 9072 r = new StringBuilder(256); 9073 } else { 9074 r.append(' '); 9075 } 9076 r.append(a.info.name); 9077 } 9078 } 9079 if (r != null) { 9080 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9081 } 9082 9083 if (pkg.protectedBroadcasts != null) { 9084 N = pkg.protectedBroadcasts.size(); 9085 for (i=0; i<N; i++) { 9086 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9087 } 9088 } 9089 9090 // Create idmap files for pairs of (packages, overlay packages). 9091 // Note: "android", ie framework-res.apk, is handled by native layers. 9092 if (pkg.mOverlayTarget != null) { 9093 // This is an overlay package. 9094 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9095 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9096 mOverlays.put(pkg.mOverlayTarget, 9097 new ArrayMap<String, PackageParser.Package>()); 9098 } 9099 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9100 map.put(pkg.packageName, pkg); 9101 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9102 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9103 createIdmapFailed = true; 9104 } 9105 } 9106 } else if (mOverlays.containsKey(pkg.packageName) && 9107 !pkg.packageName.equals("android")) { 9108 // This is a regular package, with one or more known overlay packages. 9109 createIdmapsForPackageLI(pkg); 9110 } 9111 } 9112 9113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9114 9115 if (createIdmapFailed) { 9116 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9117 "scanPackageLI failed to createIdmap"); 9118 } 9119 } 9120 9121 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9122 PackageParser.Package update, int[] userIds) { 9123 if (existing.applicationInfo == null || update.applicationInfo == null) { 9124 // This isn't due to an app installation. 9125 return; 9126 } 9127 9128 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9129 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9130 9131 // The codePath hasn't changed, so there's nothing for us to do. 9132 if (Objects.equals(oldCodePath, newCodePath)) { 9133 return; 9134 } 9135 9136 File canonicalNewCodePath; 9137 try { 9138 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9139 } catch (IOException e) { 9140 Slog.w(TAG, "Failed to get canonical path.", e); 9141 return; 9142 } 9143 9144 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9145 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9146 // that the last component of the path (i.e, the name) doesn't need canonicalization 9147 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9148 // but may change in the future. Hopefully this function won't exist at that point. 9149 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9150 oldCodePath.getName()); 9151 9152 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9153 // with "@". 9154 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9155 if (!oldMarkerPrefix.endsWith("@")) { 9156 oldMarkerPrefix += "@"; 9157 } 9158 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9159 if (!newMarkerPrefix.endsWith("@")) { 9160 newMarkerPrefix += "@"; 9161 } 9162 9163 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9164 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9165 for (String updatedPath : updatedPaths) { 9166 String updatedPathName = new File(updatedPath).getName(); 9167 markerSuffixes.add(updatedPathName.replace('/', '@')); 9168 } 9169 9170 for (int userId : userIds) { 9171 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9172 9173 for (String markerSuffix : markerSuffixes) { 9174 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9175 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9176 if (oldForeignUseMark.exists()) { 9177 try { 9178 Os.rename(oldForeignUseMark.getAbsolutePath(), 9179 newForeignUseMark.getAbsolutePath()); 9180 } catch (ErrnoException e) { 9181 Slog.w(TAG, "Failed to rename foreign use marker", e); 9182 oldForeignUseMark.delete(); 9183 } 9184 } 9185 } 9186 } 9187 } 9188 9189 /** 9190 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9191 * is derived purely on the basis of the contents of {@code scanFile} and 9192 * {@code cpuAbiOverride}. 9193 * 9194 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9195 */ 9196 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9197 String cpuAbiOverride, boolean extractLibs, 9198 File appLib32InstallDir) 9199 throws PackageManagerException { 9200 // TODO: We can probably be smarter about this stuff. For installed apps, 9201 // we can calculate this information at install time once and for all. For 9202 // system apps, we can probably assume that this information doesn't change 9203 // after the first boot scan. As things stand, we do lots of unnecessary work. 9204 9205 // Give ourselves some initial paths; we'll come back for another 9206 // pass once we've determined ABI below. 9207 setNativeLibraryPaths(pkg, appLib32InstallDir); 9208 9209 // We would never need to extract libs for forward-locked and external packages, 9210 // since the container service will do it for us. We shouldn't attempt to 9211 // extract libs from system app when it was not updated. 9212 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9213 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9214 extractLibs = false; 9215 } 9216 9217 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9218 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9219 9220 NativeLibraryHelper.Handle handle = null; 9221 try { 9222 handle = NativeLibraryHelper.Handle.create(pkg); 9223 // TODO(multiArch): This can be null for apps that didn't go through the 9224 // usual installation process. We can calculate it again, like we 9225 // do during install time. 9226 // 9227 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9228 // unnecessary. 9229 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9230 9231 // Null out the abis so that they can be recalculated. 9232 pkg.applicationInfo.primaryCpuAbi = null; 9233 pkg.applicationInfo.secondaryCpuAbi = null; 9234 if (isMultiArch(pkg.applicationInfo)) { 9235 // Warn if we've set an abiOverride for multi-lib packages.. 9236 // By definition, we need to copy both 32 and 64 bit libraries for 9237 // such packages. 9238 if (pkg.cpuAbiOverride != null 9239 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9240 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9241 } 9242 9243 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9244 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9245 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9246 if (extractLibs) { 9247 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9248 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9249 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9250 useIsaSpecificSubdirs); 9251 } else { 9252 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9253 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9254 } 9255 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9256 } 9257 9258 maybeThrowExceptionForMultiArchCopy( 9259 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9260 9261 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9262 if (extractLibs) { 9263 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9264 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9265 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9266 useIsaSpecificSubdirs); 9267 } else { 9268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9269 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9270 } 9271 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9272 } 9273 9274 maybeThrowExceptionForMultiArchCopy( 9275 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9276 9277 if (abi64 >= 0) { 9278 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9279 } 9280 9281 if (abi32 >= 0) { 9282 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9283 if (abi64 >= 0) { 9284 if (pkg.use32bitAbi) { 9285 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9286 pkg.applicationInfo.primaryCpuAbi = abi; 9287 } else { 9288 pkg.applicationInfo.secondaryCpuAbi = abi; 9289 } 9290 } else { 9291 pkg.applicationInfo.primaryCpuAbi = abi; 9292 } 9293 } 9294 9295 } else { 9296 String[] abiList = (cpuAbiOverride != null) ? 9297 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9298 9299 // Enable gross and lame hacks for apps that are built with old 9300 // SDK tools. We must scan their APKs for renderscript bitcode and 9301 // not launch them if it's present. Don't bother checking on devices 9302 // that don't have 64 bit support. 9303 boolean needsRenderScriptOverride = false; 9304 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9305 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9306 abiList = Build.SUPPORTED_32_BIT_ABIS; 9307 needsRenderScriptOverride = true; 9308 } 9309 9310 final int copyRet; 9311 if (extractLibs) { 9312 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9313 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9314 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9315 } else { 9316 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9317 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9318 } 9319 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9320 9321 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9322 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9323 "Error unpackaging native libs for app, errorCode=" + copyRet); 9324 } 9325 9326 if (copyRet >= 0) { 9327 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9328 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9329 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9330 } else if (needsRenderScriptOverride) { 9331 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9332 } 9333 } 9334 } catch (IOException ioe) { 9335 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9336 } finally { 9337 IoUtils.closeQuietly(handle); 9338 } 9339 9340 // Now that we've calculated the ABIs and determined if it's an internal app, 9341 // we will go ahead and populate the nativeLibraryPath. 9342 setNativeLibraryPaths(pkg, appLib32InstallDir); 9343 } 9344 9345 /** 9346 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9347 * i.e, so that all packages can be run inside a single process if required. 9348 * 9349 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9350 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9351 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9352 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9353 * updating a package that belongs to a shared user. 9354 * 9355 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9356 * adds unnecessary complexity. 9357 */ 9358 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9359 PackageParser.Package scannedPackage) { 9360 String requiredInstructionSet = null; 9361 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9362 requiredInstructionSet = VMRuntime.getInstructionSet( 9363 scannedPackage.applicationInfo.primaryCpuAbi); 9364 } 9365 9366 PackageSetting requirer = null; 9367 for (PackageSetting ps : packagesForUser) { 9368 // If packagesForUser contains scannedPackage, we skip it. This will happen 9369 // when scannedPackage is an update of an existing package. Without this check, 9370 // we will never be able to change the ABI of any package belonging to a shared 9371 // user, even if it's compatible with other packages. 9372 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9373 if (ps.primaryCpuAbiString == null) { 9374 continue; 9375 } 9376 9377 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9378 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9379 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9380 // this but there's not much we can do. 9381 String errorMessage = "Instruction set mismatch, " 9382 + ((requirer == null) ? "[caller]" : requirer) 9383 + " requires " + requiredInstructionSet + " whereas " + ps 9384 + " requires " + instructionSet; 9385 Slog.w(TAG, errorMessage); 9386 } 9387 9388 if (requiredInstructionSet == null) { 9389 requiredInstructionSet = instructionSet; 9390 requirer = ps; 9391 } 9392 } 9393 } 9394 9395 if (requiredInstructionSet != null) { 9396 String adjustedAbi; 9397 if (requirer != null) { 9398 // requirer != null implies that either scannedPackage was null or that scannedPackage 9399 // did not require an ABI, in which case we have to adjust scannedPackage to match 9400 // the ABI of the set (which is the same as requirer's ABI) 9401 adjustedAbi = requirer.primaryCpuAbiString; 9402 if (scannedPackage != null) { 9403 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9404 } 9405 } else { 9406 // requirer == null implies that we're updating all ABIs in the set to 9407 // match scannedPackage. 9408 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9409 } 9410 9411 for (PackageSetting ps : packagesForUser) { 9412 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9413 if (ps.primaryCpuAbiString != null) { 9414 continue; 9415 } 9416 9417 ps.primaryCpuAbiString = adjustedAbi; 9418 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9419 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9420 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9421 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9422 + " (requirer=" 9423 + (requirer == null ? "null" : requirer.pkg.packageName) 9424 + ", scannedPackage=" 9425 + (scannedPackage != null ? scannedPackage.packageName : "null") 9426 + ")"); 9427 try { 9428 mInstaller.rmdex(ps.codePathString, 9429 getDexCodeInstructionSet(getPreferredInstructionSet())); 9430 } catch (InstallerException ignored) { 9431 } 9432 } 9433 } 9434 } 9435 } 9436 } 9437 9438 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9439 synchronized (mPackages) { 9440 mResolverReplaced = true; 9441 // Set up information for custom user intent resolution activity. 9442 mResolveActivity.applicationInfo = pkg.applicationInfo; 9443 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9444 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9445 mResolveActivity.processName = pkg.applicationInfo.packageName; 9446 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9447 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9448 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9449 mResolveActivity.theme = 0; 9450 mResolveActivity.exported = true; 9451 mResolveActivity.enabled = true; 9452 mResolveInfo.activityInfo = mResolveActivity; 9453 mResolveInfo.priority = 0; 9454 mResolveInfo.preferredOrder = 0; 9455 mResolveInfo.match = 0; 9456 mResolveComponentName = mCustomResolverComponentName; 9457 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9458 mResolveComponentName); 9459 } 9460 } 9461 9462 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9463 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9464 9465 // Set up information for ephemeral installer activity 9466 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9467 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9468 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9469 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9470 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9471 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9472 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9473 mEphemeralInstallerActivity.theme = 0; 9474 mEphemeralInstallerActivity.exported = true; 9475 mEphemeralInstallerActivity.enabled = true; 9476 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9477 mEphemeralInstallerInfo.priority = 0; 9478 mEphemeralInstallerInfo.preferredOrder = 1; 9479 mEphemeralInstallerInfo.isDefault = true; 9480 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9481 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9482 9483 if (DEBUG_EPHEMERAL) { 9484 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9485 } 9486 } 9487 9488 private static String calculateBundledApkRoot(final String codePathString) { 9489 final File codePath = new File(codePathString); 9490 final File codeRoot; 9491 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9492 codeRoot = Environment.getRootDirectory(); 9493 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9494 codeRoot = Environment.getOemDirectory(); 9495 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9496 codeRoot = Environment.getVendorDirectory(); 9497 } else { 9498 // Unrecognized code path; take its top real segment as the apk root: 9499 // e.g. /something/app/blah.apk => /something 9500 try { 9501 File f = codePath.getCanonicalFile(); 9502 File parent = f.getParentFile(); // non-null because codePath is a file 9503 File tmp; 9504 while ((tmp = parent.getParentFile()) != null) { 9505 f = parent; 9506 parent = tmp; 9507 } 9508 codeRoot = f; 9509 Slog.w(TAG, "Unrecognized code path " 9510 + codePath + " - using " + codeRoot); 9511 } catch (IOException e) { 9512 // Can't canonicalize the code path -- shenanigans? 9513 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9514 return Environment.getRootDirectory().getPath(); 9515 } 9516 } 9517 return codeRoot.getPath(); 9518 } 9519 9520 /** 9521 * Derive and set the location of native libraries for the given package, 9522 * which varies depending on where and how the package was installed. 9523 */ 9524 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9525 final ApplicationInfo info = pkg.applicationInfo; 9526 final String codePath = pkg.codePath; 9527 final File codeFile = new File(codePath); 9528 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9529 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9530 9531 info.nativeLibraryRootDir = null; 9532 info.nativeLibraryRootRequiresIsa = false; 9533 info.nativeLibraryDir = null; 9534 info.secondaryNativeLibraryDir = null; 9535 9536 if (isApkFile(codeFile)) { 9537 // Monolithic install 9538 if (bundledApp) { 9539 // If "/system/lib64/apkname" exists, assume that is the per-package 9540 // native library directory to use; otherwise use "/system/lib/apkname". 9541 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9542 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9543 getPrimaryInstructionSet(info)); 9544 9545 // This is a bundled system app so choose the path based on the ABI. 9546 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9547 // is just the default path. 9548 final String apkName = deriveCodePathName(codePath); 9549 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9550 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9551 apkName).getAbsolutePath(); 9552 9553 if (info.secondaryCpuAbi != null) { 9554 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9555 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9556 secondaryLibDir, apkName).getAbsolutePath(); 9557 } 9558 } else if (asecApp) { 9559 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9560 .getAbsolutePath(); 9561 } else { 9562 final String apkName = deriveCodePathName(codePath); 9563 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9564 .getAbsolutePath(); 9565 } 9566 9567 info.nativeLibraryRootRequiresIsa = false; 9568 info.nativeLibraryDir = info.nativeLibraryRootDir; 9569 } else { 9570 // Cluster install 9571 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9572 info.nativeLibraryRootRequiresIsa = true; 9573 9574 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9575 getPrimaryInstructionSet(info)).getAbsolutePath(); 9576 9577 if (info.secondaryCpuAbi != null) { 9578 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9579 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9580 } 9581 } 9582 } 9583 9584 /** 9585 * Calculate the abis and roots for a bundled app. These can uniquely 9586 * be determined from the contents of the system partition, i.e whether 9587 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9588 * of this information, and instead assume that the system was built 9589 * sensibly. 9590 */ 9591 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9592 PackageSetting pkgSetting) { 9593 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9594 9595 // If "/system/lib64/apkname" exists, assume that is the per-package 9596 // native library directory to use; otherwise use "/system/lib/apkname". 9597 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9598 setBundledAppAbi(pkg, apkRoot, apkName); 9599 // pkgSetting might be null during rescan following uninstall of updates 9600 // to a bundled app, so accommodate that possibility. The settings in 9601 // that case will be established later from the parsed package. 9602 // 9603 // If the settings aren't null, sync them up with what we've just derived. 9604 // note that apkRoot isn't stored in the package settings. 9605 if (pkgSetting != null) { 9606 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9607 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9608 } 9609 } 9610 9611 /** 9612 * Deduces the ABI of a bundled app and sets the relevant fields on the 9613 * parsed pkg object. 9614 * 9615 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9616 * under which system libraries are installed. 9617 * @param apkName the name of the installed package. 9618 */ 9619 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9620 final File codeFile = new File(pkg.codePath); 9621 9622 final boolean has64BitLibs; 9623 final boolean has32BitLibs; 9624 if (isApkFile(codeFile)) { 9625 // Monolithic install 9626 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9627 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9628 } else { 9629 // Cluster install 9630 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9631 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9632 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9633 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9634 has64BitLibs = (new File(rootDir, isa)).exists(); 9635 } else { 9636 has64BitLibs = false; 9637 } 9638 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9639 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9640 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9641 has32BitLibs = (new File(rootDir, isa)).exists(); 9642 } else { 9643 has32BitLibs = false; 9644 } 9645 } 9646 9647 if (has64BitLibs && !has32BitLibs) { 9648 // The package has 64 bit libs, but not 32 bit libs. Its primary 9649 // ABI should be 64 bit. We can safely assume here that the bundled 9650 // native libraries correspond to the most preferred ABI in the list. 9651 9652 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9653 pkg.applicationInfo.secondaryCpuAbi = null; 9654 } else if (has32BitLibs && !has64BitLibs) { 9655 // The package has 32 bit libs but not 64 bit libs. Its primary 9656 // ABI should be 32 bit. 9657 9658 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9659 pkg.applicationInfo.secondaryCpuAbi = null; 9660 } else if (has32BitLibs && has64BitLibs) { 9661 // The application has both 64 and 32 bit bundled libraries. We check 9662 // here that the app declares multiArch support, and warn if it doesn't. 9663 // 9664 // We will be lenient here and record both ABIs. The primary will be the 9665 // ABI that's higher on the list, i.e, a device that's configured to prefer 9666 // 64 bit apps will see a 64 bit primary ABI, 9667 9668 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9669 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9670 } 9671 9672 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9673 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9674 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9675 } else { 9676 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9677 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9678 } 9679 } else { 9680 pkg.applicationInfo.primaryCpuAbi = null; 9681 pkg.applicationInfo.secondaryCpuAbi = null; 9682 } 9683 } 9684 9685 private void killApplication(String pkgName, int appId, String reason) { 9686 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9687 } 9688 9689 private void killApplication(String pkgName, int appId, int userId, String reason) { 9690 // Request the ActivityManager to kill the process(only for existing packages) 9691 // so that we do not end up in a confused state while the user is still using the older 9692 // version of the application while the new one gets installed. 9693 final long token = Binder.clearCallingIdentity(); 9694 try { 9695 IActivityManager am = ActivityManagerNative.getDefault(); 9696 if (am != null) { 9697 try { 9698 am.killApplication(pkgName, appId, userId, reason); 9699 } catch (RemoteException e) { 9700 } 9701 } 9702 } finally { 9703 Binder.restoreCallingIdentity(token); 9704 } 9705 } 9706 9707 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9708 // Remove the parent package setting 9709 PackageSetting ps = (PackageSetting) pkg.mExtras; 9710 if (ps != null) { 9711 removePackageLI(ps, chatty); 9712 } 9713 // Remove the child package setting 9714 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9715 for (int i = 0; i < childCount; i++) { 9716 PackageParser.Package childPkg = pkg.childPackages.get(i); 9717 ps = (PackageSetting) childPkg.mExtras; 9718 if (ps != null) { 9719 removePackageLI(ps, chatty); 9720 } 9721 } 9722 } 9723 9724 void removePackageLI(PackageSetting ps, boolean chatty) { 9725 if (DEBUG_INSTALL) { 9726 if (chatty) 9727 Log.d(TAG, "Removing package " + ps.name); 9728 } 9729 9730 // writer 9731 synchronized (mPackages) { 9732 mPackages.remove(ps.name); 9733 final PackageParser.Package pkg = ps.pkg; 9734 if (pkg != null) { 9735 cleanPackageDataStructuresLILPw(pkg, chatty); 9736 } 9737 } 9738 } 9739 9740 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9741 if (DEBUG_INSTALL) { 9742 if (chatty) 9743 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9744 } 9745 9746 // writer 9747 synchronized (mPackages) { 9748 // Remove the parent package 9749 mPackages.remove(pkg.applicationInfo.packageName); 9750 cleanPackageDataStructuresLILPw(pkg, chatty); 9751 9752 // Remove the child packages 9753 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9754 for (int i = 0; i < childCount; i++) { 9755 PackageParser.Package childPkg = pkg.childPackages.get(i); 9756 mPackages.remove(childPkg.applicationInfo.packageName); 9757 cleanPackageDataStructuresLILPw(childPkg, chatty); 9758 } 9759 } 9760 } 9761 9762 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9763 int N = pkg.providers.size(); 9764 StringBuilder r = null; 9765 int i; 9766 for (i=0; i<N; i++) { 9767 PackageParser.Provider p = pkg.providers.get(i); 9768 mProviders.removeProvider(p); 9769 if (p.info.authority == null) { 9770 9771 /* There was another ContentProvider with this authority when 9772 * this app was installed so this authority is null, 9773 * Ignore it as we don't have to unregister the provider. 9774 */ 9775 continue; 9776 } 9777 String names[] = p.info.authority.split(";"); 9778 for (int j = 0; j < names.length; j++) { 9779 if (mProvidersByAuthority.get(names[j]) == p) { 9780 mProvidersByAuthority.remove(names[j]); 9781 if (DEBUG_REMOVE) { 9782 if (chatty) 9783 Log.d(TAG, "Unregistered content provider: " + names[j] 9784 + ", className = " + p.info.name + ", isSyncable = " 9785 + p.info.isSyncable); 9786 } 9787 } 9788 } 9789 if (DEBUG_REMOVE && chatty) { 9790 if (r == null) { 9791 r = new StringBuilder(256); 9792 } else { 9793 r.append(' '); 9794 } 9795 r.append(p.info.name); 9796 } 9797 } 9798 if (r != null) { 9799 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9800 } 9801 9802 N = pkg.services.size(); 9803 r = null; 9804 for (i=0; i<N; i++) { 9805 PackageParser.Service s = pkg.services.get(i); 9806 mServices.removeService(s); 9807 if (chatty) { 9808 if (r == null) { 9809 r = new StringBuilder(256); 9810 } else { 9811 r.append(' '); 9812 } 9813 r.append(s.info.name); 9814 } 9815 } 9816 if (r != null) { 9817 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9818 } 9819 9820 N = pkg.receivers.size(); 9821 r = null; 9822 for (i=0; i<N; i++) { 9823 PackageParser.Activity a = pkg.receivers.get(i); 9824 mReceivers.removeActivity(a, "receiver"); 9825 if (DEBUG_REMOVE && chatty) { 9826 if (r == null) { 9827 r = new StringBuilder(256); 9828 } else { 9829 r.append(' '); 9830 } 9831 r.append(a.info.name); 9832 } 9833 } 9834 if (r != null) { 9835 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9836 } 9837 9838 N = pkg.activities.size(); 9839 r = null; 9840 for (i=0; i<N; i++) { 9841 PackageParser.Activity a = pkg.activities.get(i); 9842 mActivities.removeActivity(a, "activity"); 9843 if (DEBUG_REMOVE && chatty) { 9844 if (r == null) { 9845 r = new StringBuilder(256); 9846 } else { 9847 r.append(' '); 9848 } 9849 r.append(a.info.name); 9850 } 9851 } 9852 if (r != null) { 9853 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9854 } 9855 9856 N = pkg.permissions.size(); 9857 r = null; 9858 for (i=0; i<N; i++) { 9859 PackageParser.Permission p = pkg.permissions.get(i); 9860 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9861 if (bp == null) { 9862 bp = mSettings.mPermissionTrees.get(p.info.name); 9863 } 9864 if (bp != null && bp.perm == p) { 9865 bp.perm = null; 9866 if (DEBUG_REMOVE && chatty) { 9867 if (r == null) { 9868 r = new StringBuilder(256); 9869 } else { 9870 r.append(' '); 9871 } 9872 r.append(p.info.name); 9873 } 9874 } 9875 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9876 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9877 if (appOpPkgs != null) { 9878 appOpPkgs.remove(pkg.packageName); 9879 } 9880 } 9881 } 9882 if (r != null) { 9883 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9884 } 9885 9886 N = pkg.requestedPermissions.size(); 9887 r = null; 9888 for (i=0; i<N; i++) { 9889 String perm = pkg.requestedPermissions.get(i); 9890 BasePermission bp = mSettings.mPermissions.get(perm); 9891 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9892 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9893 if (appOpPkgs != null) { 9894 appOpPkgs.remove(pkg.packageName); 9895 if (appOpPkgs.isEmpty()) { 9896 mAppOpPermissionPackages.remove(perm); 9897 } 9898 } 9899 } 9900 } 9901 if (r != null) { 9902 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9903 } 9904 9905 N = pkg.instrumentation.size(); 9906 r = null; 9907 for (i=0; i<N; i++) { 9908 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9909 mInstrumentation.remove(a.getComponentName()); 9910 if (DEBUG_REMOVE && chatty) { 9911 if (r == null) { 9912 r = new StringBuilder(256); 9913 } else { 9914 r.append(' '); 9915 } 9916 r.append(a.info.name); 9917 } 9918 } 9919 if (r != null) { 9920 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9921 } 9922 9923 r = null; 9924 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9925 // Only system apps can hold shared libraries. 9926 if (pkg.libraryNames != null) { 9927 for (i=0; i<pkg.libraryNames.size(); i++) { 9928 String name = pkg.libraryNames.get(i); 9929 SharedLibraryEntry cur = mSharedLibraries.get(name); 9930 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9931 mSharedLibraries.remove(name); 9932 if (DEBUG_REMOVE && chatty) { 9933 if (r == null) { 9934 r = new StringBuilder(256); 9935 } else { 9936 r.append(' '); 9937 } 9938 r.append(name); 9939 } 9940 } 9941 } 9942 } 9943 } 9944 if (r != null) { 9945 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9946 } 9947 } 9948 9949 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9950 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9951 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9952 return true; 9953 } 9954 } 9955 return false; 9956 } 9957 9958 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9959 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9960 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9961 9962 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9963 // Update the parent permissions 9964 updatePermissionsLPw(pkg.packageName, pkg, flags); 9965 // Update the child permissions 9966 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9967 for (int i = 0; i < childCount; i++) { 9968 PackageParser.Package childPkg = pkg.childPackages.get(i); 9969 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9970 } 9971 } 9972 9973 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9974 int flags) { 9975 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9976 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9977 } 9978 9979 private void updatePermissionsLPw(String changingPkg, 9980 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9981 // Make sure there are no dangling permission trees. 9982 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9983 while (it.hasNext()) { 9984 final BasePermission bp = it.next(); 9985 if (bp.packageSetting == null) { 9986 // We may not yet have parsed the package, so just see if 9987 // we still know about its settings. 9988 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9989 } 9990 if (bp.packageSetting == null) { 9991 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9992 + " from package " + bp.sourcePackage); 9993 it.remove(); 9994 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9995 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9996 Slog.i(TAG, "Removing old permission tree: " + bp.name 9997 + " from package " + bp.sourcePackage); 9998 flags |= UPDATE_PERMISSIONS_ALL; 9999 it.remove(); 10000 } 10001 } 10002 } 10003 10004 // Make sure all dynamic permissions have been assigned to a package, 10005 // and make sure there are no dangling permissions. 10006 it = mSettings.mPermissions.values().iterator(); 10007 while (it.hasNext()) { 10008 final BasePermission bp = it.next(); 10009 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10010 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10011 + bp.name + " pkg=" + bp.sourcePackage 10012 + " info=" + bp.pendingInfo); 10013 if (bp.packageSetting == null && bp.pendingInfo != null) { 10014 final BasePermission tree = findPermissionTreeLP(bp.name); 10015 if (tree != null && tree.perm != null) { 10016 bp.packageSetting = tree.packageSetting; 10017 bp.perm = new PackageParser.Permission(tree.perm.owner, 10018 new PermissionInfo(bp.pendingInfo)); 10019 bp.perm.info.packageName = tree.perm.info.packageName; 10020 bp.perm.info.name = bp.name; 10021 bp.uid = tree.uid; 10022 } 10023 } 10024 } 10025 if (bp.packageSetting == null) { 10026 // We may not yet have parsed the package, so just see if 10027 // we still know about its settings. 10028 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10029 } 10030 if (bp.packageSetting == null) { 10031 Slog.w(TAG, "Removing dangling permission: " + bp.name 10032 + " from package " + bp.sourcePackage); 10033 it.remove(); 10034 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10035 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10036 Slog.i(TAG, "Removing old permission: " + bp.name 10037 + " from package " + bp.sourcePackage); 10038 flags |= UPDATE_PERMISSIONS_ALL; 10039 it.remove(); 10040 } 10041 } 10042 } 10043 10044 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10045 // Now update the permissions for all packages, in particular 10046 // replace the granted permissions of the system packages. 10047 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10048 for (PackageParser.Package pkg : mPackages.values()) { 10049 if (pkg != pkgInfo) { 10050 // Only replace for packages on requested volume 10051 final String volumeUuid = getVolumeUuidForPackage(pkg); 10052 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10053 && Objects.equals(replaceVolumeUuid, volumeUuid); 10054 grantPermissionsLPw(pkg, replace, changingPkg); 10055 } 10056 } 10057 } 10058 10059 if (pkgInfo != null) { 10060 // Only replace for packages on requested volume 10061 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10062 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10063 && Objects.equals(replaceVolumeUuid, volumeUuid); 10064 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10065 } 10066 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10067 } 10068 10069 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10070 String packageOfInterest) { 10071 // IMPORTANT: There are two types of permissions: install and runtime. 10072 // Install time permissions are granted when the app is installed to 10073 // all device users and users added in the future. Runtime permissions 10074 // are granted at runtime explicitly to specific users. Normal and signature 10075 // protected permissions are install time permissions. Dangerous permissions 10076 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10077 // otherwise they are runtime permissions. This function does not manage 10078 // runtime permissions except for the case an app targeting Lollipop MR1 10079 // being upgraded to target a newer SDK, in which case dangerous permissions 10080 // are transformed from install time to runtime ones. 10081 10082 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10083 if (ps == null) { 10084 return; 10085 } 10086 10087 PermissionsState permissionsState = ps.getPermissionsState(); 10088 PermissionsState origPermissions = permissionsState; 10089 10090 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10091 10092 boolean runtimePermissionsRevoked = false; 10093 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10094 10095 boolean changedInstallPermission = false; 10096 10097 if (replace) { 10098 ps.installPermissionsFixed = false; 10099 if (!ps.isSharedUser()) { 10100 origPermissions = new PermissionsState(permissionsState); 10101 permissionsState.reset(); 10102 } else { 10103 // We need to know only about runtime permission changes since the 10104 // calling code always writes the install permissions state but 10105 // the runtime ones are written only if changed. The only cases of 10106 // changed runtime permissions here are promotion of an install to 10107 // runtime and revocation of a runtime from a shared user. 10108 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10109 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10110 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10111 runtimePermissionsRevoked = true; 10112 } 10113 } 10114 } 10115 10116 permissionsState.setGlobalGids(mGlobalGids); 10117 10118 final int N = pkg.requestedPermissions.size(); 10119 for (int i=0; i<N; i++) { 10120 final String name = pkg.requestedPermissions.get(i); 10121 final BasePermission bp = mSettings.mPermissions.get(name); 10122 10123 if (DEBUG_INSTALL) { 10124 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10125 } 10126 10127 if (bp == null || bp.packageSetting == null) { 10128 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10129 Slog.w(TAG, "Unknown permission " + name 10130 + " in package " + pkg.packageName); 10131 } 10132 continue; 10133 } 10134 10135 10136 // Limit ephemeral apps to ephemeral allowed permissions. 10137 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10138 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10139 + pkg.packageName); 10140 continue; 10141 } 10142 10143 final String perm = bp.name; 10144 boolean allowedSig = false; 10145 int grant = GRANT_DENIED; 10146 10147 // Keep track of app op permissions. 10148 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10149 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10150 if (pkgs == null) { 10151 pkgs = new ArraySet<>(); 10152 mAppOpPermissionPackages.put(bp.name, pkgs); 10153 } 10154 pkgs.add(pkg.packageName); 10155 } 10156 10157 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10158 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10159 >= Build.VERSION_CODES.M; 10160 switch (level) { 10161 case PermissionInfo.PROTECTION_NORMAL: { 10162 // For all apps normal permissions are install time ones. 10163 grant = GRANT_INSTALL; 10164 } break; 10165 10166 case PermissionInfo.PROTECTION_DANGEROUS: { 10167 // If a permission review is required for legacy apps we represent 10168 // their permissions as always granted runtime ones since we need 10169 // to keep the review required permission flag per user while an 10170 // install permission's state is shared across all users. 10171 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10172 // For legacy apps dangerous permissions are install time ones. 10173 grant = GRANT_INSTALL; 10174 } else if (origPermissions.hasInstallPermission(bp.name)) { 10175 // For legacy apps that became modern, install becomes runtime. 10176 grant = GRANT_UPGRADE; 10177 } else if (mPromoteSystemApps 10178 && isSystemApp(ps) 10179 && mExistingSystemPackages.contains(ps.name)) { 10180 // For legacy system apps, install becomes runtime. 10181 // We cannot check hasInstallPermission() for system apps since those 10182 // permissions were granted implicitly and not persisted pre-M. 10183 grant = GRANT_UPGRADE; 10184 } else { 10185 // For modern apps keep runtime permissions unchanged. 10186 grant = GRANT_RUNTIME; 10187 } 10188 } break; 10189 10190 case PermissionInfo.PROTECTION_SIGNATURE: { 10191 // For all apps signature permissions are install time ones. 10192 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10193 if (allowedSig) { 10194 grant = GRANT_INSTALL; 10195 } 10196 } break; 10197 } 10198 10199 if (DEBUG_INSTALL) { 10200 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10201 } 10202 10203 if (grant != GRANT_DENIED) { 10204 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10205 // If this is an existing, non-system package, then 10206 // we can't add any new permissions to it. 10207 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10208 // Except... if this is a permission that was added 10209 // to the platform (note: need to only do this when 10210 // updating the platform). 10211 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10212 grant = GRANT_DENIED; 10213 } 10214 } 10215 } 10216 10217 switch (grant) { 10218 case GRANT_INSTALL: { 10219 // Revoke this as runtime permission to handle the case of 10220 // a runtime permission being downgraded to an install one. 10221 // Also in permission review mode we keep dangerous permissions 10222 // for legacy apps 10223 for (int userId : UserManagerService.getInstance().getUserIds()) { 10224 if (origPermissions.getRuntimePermissionState( 10225 bp.name, userId) != null) { 10226 // Revoke the runtime permission and clear the flags. 10227 origPermissions.revokeRuntimePermission(bp, userId); 10228 origPermissions.updatePermissionFlags(bp, userId, 10229 PackageManager.MASK_PERMISSION_FLAGS, 0); 10230 // If we revoked a permission permission, we have to write. 10231 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10232 changedRuntimePermissionUserIds, userId); 10233 } 10234 } 10235 // Grant an install permission. 10236 if (permissionsState.grantInstallPermission(bp) != 10237 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10238 changedInstallPermission = true; 10239 } 10240 } break; 10241 10242 case GRANT_RUNTIME: { 10243 // Grant previously granted runtime permissions. 10244 for (int userId : UserManagerService.getInstance().getUserIds()) { 10245 PermissionState permissionState = origPermissions 10246 .getRuntimePermissionState(bp.name, userId); 10247 int flags = permissionState != null 10248 ? permissionState.getFlags() : 0; 10249 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10250 if (permissionsState.grantRuntimePermission(bp, userId) == 10251 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10252 // If we cannot put the permission as it was, we have to write. 10253 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10254 changedRuntimePermissionUserIds, userId); 10255 } 10256 // If the app supports runtime permissions no need for a review. 10257 if (mPermissionReviewRequired 10258 && appSupportsRuntimePermissions 10259 && (flags & PackageManager 10260 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10261 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10262 // Since we changed the flags, we have to write. 10263 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10264 changedRuntimePermissionUserIds, userId); 10265 } 10266 } else if (mPermissionReviewRequired 10267 && !appSupportsRuntimePermissions) { 10268 // For legacy apps that need a permission review, every new 10269 // runtime permission is granted but it is pending a review. 10270 // We also need to review only platform defined runtime 10271 // permissions as these are the only ones the platform knows 10272 // how to disable the API to simulate revocation as legacy 10273 // apps don't expect to run with revoked permissions. 10274 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10275 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10276 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10277 // We changed the flags, hence have to write. 10278 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10279 changedRuntimePermissionUserIds, userId); 10280 } 10281 } 10282 if (permissionsState.grantRuntimePermission(bp, userId) 10283 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10284 // We changed the permission, hence have to write. 10285 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10286 changedRuntimePermissionUserIds, userId); 10287 } 10288 } 10289 // Propagate the permission flags. 10290 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10291 } 10292 } break; 10293 10294 case GRANT_UPGRADE: { 10295 // Grant runtime permissions for a previously held install permission. 10296 PermissionState permissionState = origPermissions 10297 .getInstallPermissionState(bp.name); 10298 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10299 10300 if (origPermissions.revokeInstallPermission(bp) 10301 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10302 // We will be transferring the permission flags, so clear them. 10303 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10304 PackageManager.MASK_PERMISSION_FLAGS, 0); 10305 changedInstallPermission = true; 10306 } 10307 10308 // If the permission is not to be promoted to runtime we ignore it and 10309 // also its other flags as they are not applicable to install permissions. 10310 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10311 for (int userId : currentUserIds) { 10312 if (permissionsState.grantRuntimePermission(bp, userId) != 10313 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10314 // Transfer the permission flags. 10315 permissionsState.updatePermissionFlags(bp, userId, 10316 flags, flags); 10317 // If we granted the permission, we have to write. 10318 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10319 changedRuntimePermissionUserIds, userId); 10320 } 10321 } 10322 } 10323 } break; 10324 10325 default: { 10326 if (packageOfInterest == null 10327 || packageOfInterest.equals(pkg.packageName)) { 10328 Slog.w(TAG, "Not granting permission " + perm 10329 + " to package " + pkg.packageName 10330 + " because it was previously installed without"); 10331 } 10332 } break; 10333 } 10334 } else { 10335 if (permissionsState.revokeInstallPermission(bp) != 10336 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10337 // Also drop the permission flags. 10338 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10339 PackageManager.MASK_PERMISSION_FLAGS, 0); 10340 changedInstallPermission = true; 10341 Slog.i(TAG, "Un-granting permission " + perm 10342 + " from package " + pkg.packageName 10343 + " (protectionLevel=" + bp.protectionLevel 10344 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10345 + ")"); 10346 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10347 // Don't print warning for app op permissions, since it is fine for them 10348 // not to be granted, there is a UI for the user to decide. 10349 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10350 Slog.w(TAG, "Not granting permission " + perm 10351 + " to package " + pkg.packageName 10352 + " (protectionLevel=" + bp.protectionLevel 10353 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10354 + ")"); 10355 } 10356 } 10357 } 10358 } 10359 10360 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10361 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10362 // This is the first that we have heard about this package, so the 10363 // permissions we have now selected are fixed until explicitly 10364 // changed. 10365 ps.installPermissionsFixed = true; 10366 } 10367 10368 // Persist the runtime permissions state for users with changes. If permissions 10369 // were revoked because no app in the shared user declares them we have to 10370 // write synchronously to avoid losing runtime permissions state. 10371 for (int userId : changedRuntimePermissionUserIds) { 10372 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10373 } 10374 } 10375 10376 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10377 boolean allowed = false; 10378 final int NP = PackageParser.NEW_PERMISSIONS.length; 10379 for (int ip=0; ip<NP; ip++) { 10380 final PackageParser.NewPermissionInfo npi 10381 = PackageParser.NEW_PERMISSIONS[ip]; 10382 if (npi.name.equals(perm) 10383 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10384 allowed = true; 10385 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10386 + pkg.packageName); 10387 break; 10388 } 10389 } 10390 return allowed; 10391 } 10392 10393 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10394 BasePermission bp, PermissionsState origPermissions) { 10395 boolean allowed; 10396 allowed = (compareSignatures( 10397 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10398 == PackageManager.SIGNATURE_MATCH) 10399 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10400 == PackageManager.SIGNATURE_MATCH); 10401 if (!allowed && (bp.protectionLevel 10402 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10403 if (isSystemApp(pkg)) { 10404 // For updated system applications, a system permission 10405 // is granted only if it had been defined by the original application. 10406 if (pkg.isUpdatedSystemApp()) { 10407 final PackageSetting sysPs = mSettings 10408 .getDisabledSystemPkgLPr(pkg.packageName); 10409 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10410 // If the original was granted this permission, we take 10411 // that grant decision as read and propagate it to the 10412 // update. 10413 if (sysPs.isPrivileged()) { 10414 allowed = true; 10415 } 10416 } else { 10417 // The system apk may have been updated with an older 10418 // version of the one on the data partition, but which 10419 // granted a new system permission that it didn't have 10420 // before. In this case we do want to allow the app to 10421 // now get the new permission if the ancestral apk is 10422 // privileged to get it. 10423 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10424 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10425 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10426 allowed = true; 10427 break; 10428 } 10429 } 10430 } 10431 // Also if a privileged parent package on the system image or any of 10432 // its children requested a privileged permission, the updated child 10433 // packages can also get the permission. 10434 if (pkg.parentPackage != null) { 10435 final PackageSetting disabledSysParentPs = mSettings 10436 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10437 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10438 && disabledSysParentPs.isPrivileged()) { 10439 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10440 allowed = true; 10441 } else if (disabledSysParentPs.pkg.childPackages != null) { 10442 final int count = disabledSysParentPs.pkg.childPackages.size(); 10443 for (int i = 0; i < count; i++) { 10444 PackageParser.Package disabledSysChildPkg = 10445 disabledSysParentPs.pkg.childPackages.get(i); 10446 if (isPackageRequestingPermission(disabledSysChildPkg, 10447 perm)) { 10448 allowed = true; 10449 break; 10450 } 10451 } 10452 } 10453 } 10454 } 10455 } 10456 } else { 10457 allowed = isPrivilegedApp(pkg); 10458 } 10459 } 10460 } 10461 if (!allowed) { 10462 if (!allowed && (bp.protectionLevel 10463 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10464 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10465 // If this was a previously normal/dangerous permission that got moved 10466 // to a system permission as part of the runtime permission redesign, then 10467 // we still want to blindly grant it to old apps. 10468 allowed = true; 10469 } 10470 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10471 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10472 // If this permission is to be granted to the system installer and 10473 // this app is an installer, then it gets the permission. 10474 allowed = true; 10475 } 10476 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10477 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10478 // If this permission is to be granted to the system verifier and 10479 // this app is a verifier, then it gets the permission. 10480 allowed = true; 10481 } 10482 if (!allowed && (bp.protectionLevel 10483 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10484 && isSystemApp(pkg)) { 10485 // Any pre-installed system app is allowed to get this permission. 10486 allowed = true; 10487 } 10488 if (!allowed && (bp.protectionLevel 10489 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10490 // For development permissions, a development permission 10491 // is granted only if it was already granted. 10492 allowed = origPermissions.hasInstallPermission(perm); 10493 } 10494 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10495 && pkg.packageName.equals(mSetupWizardPackage)) { 10496 // If this permission is to be granted to the system setup wizard and 10497 // this app is a setup wizard, then it gets the permission. 10498 allowed = true; 10499 } 10500 } 10501 return allowed; 10502 } 10503 10504 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10505 final int permCount = pkg.requestedPermissions.size(); 10506 for (int j = 0; j < permCount; j++) { 10507 String requestedPermission = pkg.requestedPermissions.get(j); 10508 if (permission.equals(requestedPermission)) { 10509 return true; 10510 } 10511 } 10512 return false; 10513 } 10514 10515 final class ActivityIntentResolver 10516 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10517 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10518 boolean defaultOnly, int userId) { 10519 if (!sUserManager.exists(userId)) return null; 10520 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10521 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10522 } 10523 10524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10525 int userId) { 10526 if (!sUserManager.exists(userId)) return null; 10527 mFlags = flags; 10528 return super.queryIntent(intent, resolvedType, 10529 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10530 } 10531 10532 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10533 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10534 if (!sUserManager.exists(userId)) return null; 10535 if (packageActivities == null) { 10536 return null; 10537 } 10538 mFlags = flags; 10539 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10540 final int N = packageActivities.size(); 10541 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10542 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10543 10544 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10545 for (int i = 0; i < N; ++i) { 10546 intentFilters = packageActivities.get(i).intents; 10547 if (intentFilters != null && intentFilters.size() > 0) { 10548 PackageParser.ActivityIntentInfo[] array = 10549 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10550 intentFilters.toArray(array); 10551 listCut.add(array); 10552 } 10553 } 10554 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10555 } 10556 10557 /** 10558 * Finds a privileged activity that matches the specified activity names. 10559 */ 10560 private PackageParser.Activity findMatchingActivity( 10561 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10562 for (PackageParser.Activity sysActivity : activityList) { 10563 if (sysActivity.info.name.equals(activityInfo.name)) { 10564 return sysActivity; 10565 } 10566 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10567 return sysActivity; 10568 } 10569 if (sysActivity.info.targetActivity != null) { 10570 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10571 return sysActivity; 10572 } 10573 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10574 return sysActivity; 10575 } 10576 } 10577 } 10578 return null; 10579 } 10580 10581 public class IterGenerator<E> { 10582 public Iterator<E> generate(ActivityIntentInfo info) { 10583 return null; 10584 } 10585 } 10586 10587 public class ActionIterGenerator extends IterGenerator<String> { 10588 @Override 10589 public Iterator<String> generate(ActivityIntentInfo info) { 10590 return info.actionsIterator(); 10591 } 10592 } 10593 10594 public class CategoriesIterGenerator extends IterGenerator<String> { 10595 @Override 10596 public Iterator<String> generate(ActivityIntentInfo info) { 10597 return info.categoriesIterator(); 10598 } 10599 } 10600 10601 public class SchemesIterGenerator extends IterGenerator<String> { 10602 @Override 10603 public Iterator<String> generate(ActivityIntentInfo info) { 10604 return info.schemesIterator(); 10605 } 10606 } 10607 10608 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10609 @Override 10610 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10611 return info.authoritiesIterator(); 10612 } 10613 } 10614 10615 /** 10616 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10617 * MODIFIED. Do not pass in a list that should not be changed. 10618 */ 10619 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10620 IterGenerator<T> generator, Iterator<T> searchIterator) { 10621 // loop through the set of actions; every one must be found in the intent filter 10622 while (searchIterator.hasNext()) { 10623 // we must have at least one filter in the list to consider a match 10624 if (intentList.size() == 0) { 10625 break; 10626 } 10627 10628 final T searchAction = searchIterator.next(); 10629 10630 // loop through the set of intent filters 10631 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10632 while (intentIter.hasNext()) { 10633 final ActivityIntentInfo intentInfo = intentIter.next(); 10634 boolean selectionFound = false; 10635 10636 // loop through the intent filter's selection criteria; at least one 10637 // of them must match the searched criteria 10638 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10639 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10640 final T intentSelection = intentSelectionIter.next(); 10641 if (intentSelection != null && intentSelection.equals(searchAction)) { 10642 selectionFound = true; 10643 break; 10644 } 10645 } 10646 10647 // the selection criteria wasn't found in this filter's set; this filter 10648 // is not a potential match 10649 if (!selectionFound) { 10650 intentIter.remove(); 10651 } 10652 } 10653 } 10654 } 10655 10656 private boolean isProtectedAction(ActivityIntentInfo filter) { 10657 final Iterator<String> actionsIter = filter.actionsIterator(); 10658 while (actionsIter != null && actionsIter.hasNext()) { 10659 final String filterAction = actionsIter.next(); 10660 if (PROTECTED_ACTIONS.contains(filterAction)) { 10661 return true; 10662 } 10663 } 10664 return false; 10665 } 10666 10667 /** 10668 * Adjusts the priority of the given intent filter according to policy. 10669 * <p> 10670 * <ul> 10671 * <li>The priority for non privileged applications is capped to '0'</li> 10672 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10673 * <li>The priority for unbundled updates to privileged applications is capped to the 10674 * priority defined on the system partition</li> 10675 * </ul> 10676 * <p> 10677 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10678 * allowed to obtain any priority on any action. 10679 */ 10680 private void adjustPriority( 10681 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10682 // nothing to do; priority is fine as-is 10683 if (intent.getPriority() <= 0) { 10684 return; 10685 } 10686 10687 final ActivityInfo activityInfo = intent.activity.info; 10688 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10689 10690 final boolean privilegedApp = 10691 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10692 if (!privilegedApp) { 10693 // non-privileged applications can never define a priority >0 10694 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10695 + " package: " + applicationInfo.packageName 10696 + " activity: " + intent.activity.className 10697 + " origPrio: " + intent.getPriority()); 10698 intent.setPriority(0); 10699 return; 10700 } 10701 10702 if (systemActivities == null) { 10703 // the system package is not disabled; we're parsing the system partition 10704 if (isProtectedAction(intent)) { 10705 if (mDeferProtectedFilters) { 10706 // We can't deal with these just yet. No component should ever obtain a 10707 // >0 priority for a protected actions, with ONE exception -- the setup 10708 // wizard. The setup wizard, however, cannot be known until we're able to 10709 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10710 // until all intent filters have been processed. Chicken, meet egg. 10711 // Let the filter temporarily have a high priority and rectify the 10712 // priorities after all system packages have been scanned. 10713 mProtectedFilters.add(intent); 10714 if (DEBUG_FILTERS) { 10715 Slog.i(TAG, "Protected action; save for later;" 10716 + " package: " + applicationInfo.packageName 10717 + " activity: " + intent.activity.className 10718 + " origPrio: " + intent.getPriority()); 10719 } 10720 return; 10721 } else { 10722 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10723 Slog.i(TAG, "No setup wizard;" 10724 + " All protected intents capped to priority 0"); 10725 } 10726 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10727 if (DEBUG_FILTERS) { 10728 Slog.i(TAG, "Found setup wizard;" 10729 + " allow priority " + intent.getPriority() + ";" 10730 + " package: " + intent.activity.info.packageName 10731 + " activity: " + intent.activity.className 10732 + " priority: " + intent.getPriority()); 10733 } 10734 // setup wizard gets whatever it wants 10735 return; 10736 } 10737 Slog.w(TAG, "Protected action; cap priority to 0;" 10738 + " package: " + intent.activity.info.packageName 10739 + " activity: " + intent.activity.className 10740 + " origPrio: " + intent.getPriority()); 10741 intent.setPriority(0); 10742 return; 10743 } 10744 } 10745 // privileged apps on the system image get whatever priority they request 10746 return; 10747 } 10748 10749 // privileged app unbundled update ... try to find the same activity 10750 final PackageParser.Activity foundActivity = 10751 findMatchingActivity(systemActivities, activityInfo); 10752 if (foundActivity == null) { 10753 // this is a new activity; it cannot obtain >0 priority 10754 if (DEBUG_FILTERS) { 10755 Slog.i(TAG, "New activity; cap priority to 0;" 10756 + " package: " + applicationInfo.packageName 10757 + " activity: " + intent.activity.className 10758 + " origPrio: " + intent.getPriority()); 10759 } 10760 intent.setPriority(0); 10761 return; 10762 } 10763 10764 // found activity, now check for filter equivalence 10765 10766 // a shallow copy is enough; we modify the list, not its contents 10767 final List<ActivityIntentInfo> intentListCopy = 10768 new ArrayList<>(foundActivity.intents); 10769 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10770 10771 // find matching action subsets 10772 final Iterator<String> actionsIterator = intent.actionsIterator(); 10773 if (actionsIterator != null) { 10774 getIntentListSubset( 10775 intentListCopy, new ActionIterGenerator(), actionsIterator); 10776 if (intentListCopy.size() == 0) { 10777 // no more intents to match; we're not equivalent 10778 if (DEBUG_FILTERS) { 10779 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10780 + " package: " + applicationInfo.packageName 10781 + " activity: " + intent.activity.className 10782 + " origPrio: " + intent.getPriority()); 10783 } 10784 intent.setPriority(0); 10785 return; 10786 } 10787 } 10788 10789 // find matching category subsets 10790 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10791 if (categoriesIterator != null) { 10792 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10793 categoriesIterator); 10794 if (intentListCopy.size() == 0) { 10795 // no more intents to match; we're not equivalent 10796 if (DEBUG_FILTERS) { 10797 Slog.i(TAG, "Mismatched category; 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 schemes subsets 10808 final Iterator<String> schemesIterator = intent.schemesIterator(); 10809 if (schemesIterator != null) { 10810 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10811 schemesIterator); 10812 if (intentListCopy.size() == 0) { 10813 // no more intents to match; we're not equivalent 10814 if (DEBUG_FILTERS) { 10815 Slog.i(TAG, "Mismatched scheme; 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 authorities subsets 10826 final Iterator<IntentFilter.AuthorityEntry> 10827 authoritiesIterator = intent.authoritiesIterator(); 10828 if (authoritiesIterator != null) { 10829 getIntentListSubset(intentListCopy, 10830 new AuthoritiesIterGenerator(), 10831 authoritiesIterator); 10832 if (intentListCopy.size() == 0) { 10833 // no more intents to match; we're not equivalent 10834 if (DEBUG_FILTERS) { 10835 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10836 + " package: " + applicationInfo.packageName 10837 + " activity: " + intent.activity.className 10838 + " origPrio: " + intent.getPriority()); 10839 } 10840 intent.setPriority(0); 10841 return; 10842 } 10843 } 10844 10845 // we found matching filter(s); app gets the max priority of all intents 10846 int cappedPriority = 0; 10847 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10848 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10849 } 10850 if (intent.getPriority() > cappedPriority) { 10851 if (DEBUG_FILTERS) { 10852 Slog.i(TAG, "Found matching filter(s);" 10853 + " cap priority to " + cappedPriority + ";" 10854 + " package: " + applicationInfo.packageName 10855 + " activity: " + intent.activity.className 10856 + " origPrio: " + intent.getPriority()); 10857 } 10858 intent.setPriority(cappedPriority); 10859 return; 10860 } 10861 // all this for nothing; the requested priority was <= what was on the system 10862 } 10863 10864 public final void addActivity(PackageParser.Activity a, String type) { 10865 mActivities.put(a.getComponentName(), a); 10866 if (DEBUG_SHOW_INFO) 10867 Log.v( 10868 TAG, " " + type + " " + 10869 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10870 if (DEBUG_SHOW_INFO) 10871 Log.v(TAG, " Class=" + a.info.name); 10872 final int NI = a.intents.size(); 10873 for (int j=0; j<NI; j++) { 10874 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10875 if ("activity".equals(type)) { 10876 final PackageSetting ps = 10877 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10878 final List<PackageParser.Activity> systemActivities = 10879 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10880 adjustPriority(systemActivities, intent); 10881 } 10882 if (DEBUG_SHOW_INFO) { 10883 Log.v(TAG, " IntentFilter:"); 10884 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10885 } 10886 if (!intent.debugCheck()) { 10887 Log.w(TAG, "==> For Activity " + a.info.name); 10888 } 10889 addFilter(intent); 10890 } 10891 } 10892 10893 public final void removeActivity(PackageParser.Activity a, String type) { 10894 mActivities.remove(a.getComponentName()); 10895 if (DEBUG_SHOW_INFO) { 10896 Log.v(TAG, " " + type + " " 10897 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10898 : a.info.name) + ":"); 10899 Log.v(TAG, " Class=" + a.info.name); 10900 } 10901 final int NI = a.intents.size(); 10902 for (int j=0; j<NI; j++) { 10903 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10904 if (DEBUG_SHOW_INFO) { 10905 Log.v(TAG, " IntentFilter:"); 10906 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10907 } 10908 removeFilter(intent); 10909 } 10910 } 10911 10912 @Override 10913 protected boolean allowFilterResult( 10914 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10915 ActivityInfo filterAi = filter.activity.info; 10916 for (int i=dest.size()-1; i>=0; i--) { 10917 ActivityInfo destAi = dest.get(i).activityInfo; 10918 if (destAi.name == filterAi.name 10919 && destAi.packageName == filterAi.packageName) { 10920 return false; 10921 } 10922 } 10923 return true; 10924 } 10925 10926 @Override 10927 protected ActivityIntentInfo[] newArray(int size) { 10928 return new ActivityIntentInfo[size]; 10929 } 10930 10931 @Override 10932 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10933 if (!sUserManager.exists(userId)) return true; 10934 PackageParser.Package p = filter.activity.owner; 10935 if (p != null) { 10936 PackageSetting ps = (PackageSetting)p.mExtras; 10937 if (ps != null) { 10938 // System apps are never considered stopped for purposes of 10939 // filtering, because there may be no way for the user to 10940 // actually re-launch them. 10941 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10942 && ps.getStopped(userId); 10943 } 10944 } 10945 return false; 10946 } 10947 10948 @Override 10949 protected boolean isPackageForFilter(String packageName, 10950 PackageParser.ActivityIntentInfo info) { 10951 return packageName.equals(info.activity.owner.packageName); 10952 } 10953 10954 @Override 10955 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10956 int match, int userId) { 10957 if (!sUserManager.exists(userId)) return null; 10958 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10959 return null; 10960 } 10961 final PackageParser.Activity activity = info.activity; 10962 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10963 if (ps == null) { 10964 return null; 10965 } 10966 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10967 ps.readUserState(userId), userId); 10968 if (ai == null) { 10969 return null; 10970 } 10971 final ResolveInfo res = new ResolveInfo(); 10972 res.activityInfo = ai; 10973 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10974 res.filter = info; 10975 } 10976 if (info != null) { 10977 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10978 } 10979 res.priority = info.getPriority(); 10980 res.preferredOrder = activity.owner.mPreferredOrder; 10981 //System.out.println("Result: " + res.activityInfo.className + 10982 // " = " + res.priority); 10983 res.match = match; 10984 res.isDefault = info.hasDefault; 10985 res.labelRes = info.labelRes; 10986 res.nonLocalizedLabel = info.nonLocalizedLabel; 10987 if (userNeedsBadging(userId)) { 10988 res.noResourceId = true; 10989 } else { 10990 res.icon = info.icon; 10991 } 10992 res.iconResourceId = info.icon; 10993 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10994 return res; 10995 } 10996 10997 @Override 10998 protected void sortResults(List<ResolveInfo> results) { 10999 Collections.sort(results, mResolvePrioritySorter); 11000 } 11001 11002 @Override 11003 protected void dumpFilter(PrintWriter out, String prefix, 11004 PackageParser.ActivityIntentInfo filter) { 11005 out.print(prefix); out.print( 11006 Integer.toHexString(System.identityHashCode(filter.activity))); 11007 out.print(' '); 11008 filter.activity.printComponentShortName(out); 11009 out.print(" filter "); 11010 out.println(Integer.toHexString(System.identityHashCode(filter))); 11011 } 11012 11013 @Override 11014 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11015 return filter.activity; 11016 } 11017 11018 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11019 PackageParser.Activity activity = (PackageParser.Activity)label; 11020 out.print(prefix); out.print( 11021 Integer.toHexString(System.identityHashCode(activity))); 11022 out.print(' '); 11023 activity.printComponentShortName(out); 11024 if (count > 1) { 11025 out.print(" ("); out.print(count); out.print(" filters)"); 11026 } 11027 out.println(); 11028 } 11029 11030 // Keys are String (activity class name), values are Activity. 11031 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11032 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11033 private int mFlags; 11034 } 11035 11036 private final class ServiceIntentResolver 11037 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11038 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11039 boolean defaultOnly, int userId) { 11040 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11041 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11042 } 11043 11044 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11045 int userId) { 11046 if (!sUserManager.exists(userId)) return null; 11047 mFlags = flags; 11048 return super.queryIntent(intent, resolvedType, 11049 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11050 } 11051 11052 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11053 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11054 if (!sUserManager.exists(userId)) return null; 11055 if (packageServices == null) { 11056 return null; 11057 } 11058 mFlags = flags; 11059 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11060 final int N = packageServices.size(); 11061 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11062 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11063 11064 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11065 for (int i = 0; i < N; ++i) { 11066 intentFilters = packageServices.get(i).intents; 11067 if (intentFilters != null && intentFilters.size() > 0) { 11068 PackageParser.ServiceIntentInfo[] array = 11069 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11070 intentFilters.toArray(array); 11071 listCut.add(array); 11072 } 11073 } 11074 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11075 } 11076 11077 public final void addService(PackageParser.Service s) { 11078 mServices.put(s.getComponentName(), s); 11079 if (DEBUG_SHOW_INFO) { 11080 Log.v(TAG, " " 11081 + (s.info.nonLocalizedLabel != null 11082 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11083 Log.v(TAG, " Class=" + s.info.name); 11084 } 11085 final int NI = s.intents.size(); 11086 int j; 11087 for (j=0; j<NI; j++) { 11088 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11089 if (DEBUG_SHOW_INFO) { 11090 Log.v(TAG, " IntentFilter:"); 11091 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11092 } 11093 if (!intent.debugCheck()) { 11094 Log.w(TAG, "==> For Service " + s.info.name); 11095 } 11096 addFilter(intent); 11097 } 11098 } 11099 11100 public final void removeService(PackageParser.Service s) { 11101 mServices.remove(s.getComponentName()); 11102 if (DEBUG_SHOW_INFO) { 11103 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11104 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11105 Log.v(TAG, " Class=" + s.info.name); 11106 } 11107 final int NI = s.intents.size(); 11108 int j; 11109 for (j=0; j<NI; j++) { 11110 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11111 if (DEBUG_SHOW_INFO) { 11112 Log.v(TAG, " IntentFilter:"); 11113 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11114 } 11115 removeFilter(intent); 11116 } 11117 } 11118 11119 @Override 11120 protected boolean allowFilterResult( 11121 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11122 ServiceInfo filterSi = filter.service.info; 11123 for (int i=dest.size()-1; i>=0; i--) { 11124 ServiceInfo destAi = dest.get(i).serviceInfo; 11125 if (destAi.name == filterSi.name 11126 && destAi.packageName == filterSi.packageName) { 11127 return false; 11128 } 11129 } 11130 return true; 11131 } 11132 11133 @Override 11134 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11135 return new PackageParser.ServiceIntentInfo[size]; 11136 } 11137 11138 @Override 11139 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11140 if (!sUserManager.exists(userId)) return true; 11141 PackageParser.Package p = filter.service.owner; 11142 if (p != null) { 11143 PackageSetting ps = (PackageSetting)p.mExtras; 11144 if (ps != null) { 11145 // System apps are never considered stopped for purposes of 11146 // filtering, because there may be no way for the user to 11147 // actually re-launch them. 11148 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11149 && ps.getStopped(userId); 11150 } 11151 } 11152 return false; 11153 } 11154 11155 @Override 11156 protected boolean isPackageForFilter(String packageName, 11157 PackageParser.ServiceIntentInfo info) { 11158 return packageName.equals(info.service.owner.packageName); 11159 } 11160 11161 @Override 11162 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11163 int match, int userId) { 11164 if (!sUserManager.exists(userId)) return null; 11165 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11166 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11167 return null; 11168 } 11169 final PackageParser.Service service = info.service; 11170 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11171 if (ps == null) { 11172 return null; 11173 } 11174 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11175 ps.readUserState(userId), userId); 11176 if (si == null) { 11177 return null; 11178 } 11179 final ResolveInfo res = new ResolveInfo(); 11180 res.serviceInfo = si; 11181 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11182 res.filter = filter; 11183 } 11184 res.priority = info.getPriority(); 11185 res.preferredOrder = service.owner.mPreferredOrder; 11186 res.match = match; 11187 res.isDefault = info.hasDefault; 11188 res.labelRes = info.labelRes; 11189 res.nonLocalizedLabel = info.nonLocalizedLabel; 11190 res.icon = info.icon; 11191 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11192 return res; 11193 } 11194 11195 @Override 11196 protected void sortResults(List<ResolveInfo> results) { 11197 Collections.sort(results, mResolvePrioritySorter); 11198 } 11199 11200 @Override 11201 protected void dumpFilter(PrintWriter out, String prefix, 11202 PackageParser.ServiceIntentInfo filter) { 11203 out.print(prefix); out.print( 11204 Integer.toHexString(System.identityHashCode(filter.service))); 11205 out.print(' '); 11206 filter.service.printComponentShortName(out); 11207 out.print(" filter "); 11208 out.println(Integer.toHexString(System.identityHashCode(filter))); 11209 } 11210 11211 @Override 11212 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11213 return filter.service; 11214 } 11215 11216 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11217 PackageParser.Service service = (PackageParser.Service)label; 11218 out.print(prefix); out.print( 11219 Integer.toHexString(System.identityHashCode(service))); 11220 out.print(' '); 11221 service.printComponentShortName(out); 11222 if (count > 1) { 11223 out.print(" ("); out.print(count); out.print(" filters)"); 11224 } 11225 out.println(); 11226 } 11227 11228// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11229// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11230// final List<ResolveInfo> retList = Lists.newArrayList(); 11231// while (i.hasNext()) { 11232// final ResolveInfo resolveInfo = (ResolveInfo) i; 11233// if (isEnabledLP(resolveInfo.serviceInfo)) { 11234// retList.add(resolveInfo); 11235// } 11236// } 11237// return retList; 11238// } 11239 11240 // Keys are String (activity class name), values are Activity. 11241 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11242 = new ArrayMap<ComponentName, PackageParser.Service>(); 11243 private int mFlags; 11244 }; 11245 11246 private final class ProviderIntentResolver 11247 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11248 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11249 boolean defaultOnly, int userId) { 11250 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11251 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11252 } 11253 11254 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11255 int userId) { 11256 if (!sUserManager.exists(userId)) 11257 return null; 11258 mFlags = flags; 11259 return super.queryIntent(intent, resolvedType, 11260 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11261 } 11262 11263 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11264 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11265 if (!sUserManager.exists(userId)) 11266 return null; 11267 if (packageProviders == null) { 11268 return null; 11269 } 11270 mFlags = flags; 11271 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11272 final int N = packageProviders.size(); 11273 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11274 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11275 11276 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11277 for (int i = 0; i < N; ++i) { 11278 intentFilters = packageProviders.get(i).intents; 11279 if (intentFilters != null && intentFilters.size() > 0) { 11280 PackageParser.ProviderIntentInfo[] array = 11281 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11282 intentFilters.toArray(array); 11283 listCut.add(array); 11284 } 11285 } 11286 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11287 } 11288 11289 public final void addProvider(PackageParser.Provider p) { 11290 if (mProviders.containsKey(p.getComponentName())) { 11291 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11292 return; 11293 } 11294 11295 mProviders.put(p.getComponentName(), p); 11296 if (DEBUG_SHOW_INFO) { 11297 Log.v(TAG, " " 11298 + (p.info.nonLocalizedLabel != null 11299 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11300 Log.v(TAG, " Class=" + p.info.name); 11301 } 11302 final int NI = p.intents.size(); 11303 int j; 11304 for (j = 0; j < NI; j++) { 11305 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11306 if (DEBUG_SHOW_INFO) { 11307 Log.v(TAG, " IntentFilter:"); 11308 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11309 } 11310 if (!intent.debugCheck()) { 11311 Log.w(TAG, "==> For Provider " + p.info.name); 11312 } 11313 addFilter(intent); 11314 } 11315 } 11316 11317 public final void removeProvider(PackageParser.Provider p) { 11318 mProviders.remove(p.getComponentName()); 11319 if (DEBUG_SHOW_INFO) { 11320 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11321 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11322 Log.v(TAG, " Class=" + p.info.name); 11323 } 11324 final int NI = p.intents.size(); 11325 int j; 11326 for (j = 0; j < NI; j++) { 11327 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11328 if (DEBUG_SHOW_INFO) { 11329 Log.v(TAG, " IntentFilter:"); 11330 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11331 } 11332 removeFilter(intent); 11333 } 11334 } 11335 11336 @Override 11337 protected boolean allowFilterResult( 11338 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11339 ProviderInfo filterPi = filter.provider.info; 11340 for (int i = dest.size() - 1; i >= 0; i--) { 11341 ProviderInfo destPi = dest.get(i).providerInfo; 11342 if (destPi.name == filterPi.name 11343 && destPi.packageName == filterPi.packageName) { 11344 return false; 11345 } 11346 } 11347 return true; 11348 } 11349 11350 @Override 11351 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11352 return new PackageParser.ProviderIntentInfo[size]; 11353 } 11354 11355 @Override 11356 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11357 if (!sUserManager.exists(userId)) 11358 return true; 11359 PackageParser.Package p = filter.provider.owner; 11360 if (p != null) { 11361 PackageSetting ps = (PackageSetting) p.mExtras; 11362 if (ps != null) { 11363 // System apps are never considered stopped for purposes of 11364 // filtering, because there may be no way for the user to 11365 // actually re-launch them. 11366 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11367 && ps.getStopped(userId); 11368 } 11369 } 11370 return false; 11371 } 11372 11373 @Override 11374 protected boolean isPackageForFilter(String packageName, 11375 PackageParser.ProviderIntentInfo info) { 11376 return packageName.equals(info.provider.owner.packageName); 11377 } 11378 11379 @Override 11380 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11381 int match, int userId) { 11382 if (!sUserManager.exists(userId)) 11383 return null; 11384 final PackageParser.ProviderIntentInfo info = filter; 11385 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11386 return null; 11387 } 11388 final PackageParser.Provider provider = info.provider; 11389 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11390 if (ps == null) { 11391 return null; 11392 } 11393 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11394 ps.readUserState(userId), userId); 11395 if (pi == null) { 11396 return null; 11397 } 11398 final ResolveInfo res = new ResolveInfo(); 11399 res.providerInfo = pi; 11400 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11401 res.filter = filter; 11402 } 11403 res.priority = info.getPriority(); 11404 res.preferredOrder = provider.owner.mPreferredOrder; 11405 res.match = match; 11406 res.isDefault = info.hasDefault; 11407 res.labelRes = info.labelRes; 11408 res.nonLocalizedLabel = info.nonLocalizedLabel; 11409 res.icon = info.icon; 11410 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11411 return res; 11412 } 11413 11414 @Override 11415 protected void sortResults(List<ResolveInfo> results) { 11416 Collections.sort(results, mResolvePrioritySorter); 11417 } 11418 11419 @Override 11420 protected void dumpFilter(PrintWriter out, String prefix, 11421 PackageParser.ProviderIntentInfo filter) { 11422 out.print(prefix); 11423 out.print( 11424 Integer.toHexString(System.identityHashCode(filter.provider))); 11425 out.print(' '); 11426 filter.provider.printComponentShortName(out); 11427 out.print(" filter "); 11428 out.println(Integer.toHexString(System.identityHashCode(filter))); 11429 } 11430 11431 @Override 11432 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11433 return filter.provider; 11434 } 11435 11436 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11437 PackageParser.Provider provider = (PackageParser.Provider)label; 11438 out.print(prefix); out.print( 11439 Integer.toHexString(System.identityHashCode(provider))); 11440 out.print(' '); 11441 provider.printComponentShortName(out); 11442 if (count > 1) { 11443 out.print(" ("); out.print(count); out.print(" filters)"); 11444 } 11445 out.println(); 11446 } 11447 11448 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11449 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11450 private int mFlags; 11451 } 11452 11453 private static final class EphemeralIntentResolver 11454 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11455 /** 11456 * The result that has the highest defined order. Ordering applies on a 11457 * per-package basis. Mapping is from package name to Pair of order and 11458 * EphemeralResolveInfo. 11459 * <p> 11460 * NOTE: This is implemented as a field variable for convenience and efficiency. 11461 * By having a field variable, we're able to track filter ordering as soon as 11462 * a non-zero order is defined. Otherwise, multiple loops across the result set 11463 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11464 * this needs to be contained entirely within {@link #filterResults()}. 11465 */ 11466 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11467 11468 @Override 11469 protected EphemeralResolveIntentInfo[] newArray(int size) { 11470 return new EphemeralResolveIntentInfo[size]; 11471 } 11472 11473 @Override 11474 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11475 return true; 11476 } 11477 11478 @Override 11479 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11480 int userId) { 11481 if (!sUserManager.exists(userId)) { 11482 return null; 11483 } 11484 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11485 final Integer order = info.getOrder(); 11486 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11487 mOrderResult.get(packageName); 11488 // ordering is enabled and this item's order isn't high enough 11489 if (lastOrderResult != null && lastOrderResult.first >= order) { 11490 return null; 11491 } 11492 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11493 if (order > 0) { 11494 // non-zero order, enable ordering 11495 mOrderResult.put(packageName, new Pair<>(order, res)); 11496 } 11497 return res; 11498 } 11499 11500 @Override 11501 protected void filterResults(List<EphemeralResolveInfo> results) { 11502 // only do work if ordering is enabled [most of the time it won't be] 11503 if (mOrderResult.size() == 0) { 11504 return; 11505 } 11506 int resultSize = results.size(); 11507 for (int i = 0; i < resultSize; i++) { 11508 final EphemeralResolveInfo info = results.get(i); 11509 final String packageName = info.getPackageName(); 11510 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11511 if (savedInfo == null) { 11512 // package doesn't having ordering 11513 continue; 11514 } 11515 if (savedInfo.second == info) { 11516 // circled back to the highest ordered item; remove from order list 11517 mOrderResult.remove(savedInfo); 11518 if (mOrderResult.size() == 0) { 11519 // no more ordered items 11520 break; 11521 } 11522 continue; 11523 } 11524 // item has a worse order, remove it from the result list 11525 results.remove(i); 11526 resultSize--; 11527 i--; 11528 } 11529 } 11530 } 11531 11532 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11533 new Comparator<ResolveInfo>() { 11534 public int compare(ResolveInfo r1, ResolveInfo r2) { 11535 int v1 = r1.priority; 11536 int v2 = r2.priority; 11537 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11538 if (v1 != v2) { 11539 return (v1 > v2) ? -1 : 1; 11540 } 11541 v1 = r1.preferredOrder; 11542 v2 = r2.preferredOrder; 11543 if (v1 != v2) { 11544 return (v1 > v2) ? -1 : 1; 11545 } 11546 if (r1.isDefault != r2.isDefault) { 11547 return r1.isDefault ? -1 : 1; 11548 } 11549 v1 = r1.match; 11550 v2 = r2.match; 11551 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11552 if (v1 != v2) { 11553 return (v1 > v2) ? -1 : 1; 11554 } 11555 if (r1.system != r2.system) { 11556 return r1.system ? -1 : 1; 11557 } 11558 if (r1.activityInfo != null) { 11559 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11560 } 11561 if (r1.serviceInfo != null) { 11562 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11563 } 11564 if (r1.providerInfo != null) { 11565 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11566 } 11567 return 0; 11568 } 11569 }; 11570 11571 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11572 new Comparator<ProviderInfo>() { 11573 public int compare(ProviderInfo p1, ProviderInfo p2) { 11574 final int v1 = p1.initOrder; 11575 final int v2 = p2.initOrder; 11576 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11577 } 11578 }; 11579 11580 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11581 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11582 final int[] userIds) { 11583 mHandler.post(new Runnable() { 11584 @Override 11585 public void run() { 11586 try { 11587 final IActivityManager am = ActivityManagerNative.getDefault(); 11588 if (am == null) return; 11589 final int[] resolvedUserIds; 11590 if (userIds == null) { 11591 resolvedUserIds = am.getRunningUserIds(); 11592 } else { 11593 resolvedUserIds = userIds; 11594 } 11595 for (int id : resolvedUserIds) { 11596 final Intent intent = new Intent(action, 11597 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11598 if (extras != null) { 11599 intent.putExtras(extras); 11600 } 11601 if (targetPkg != null) { 11602 intent.setPackage(targetPkg); 11603 } 11604 // Modify the UID when posting to other users 11605 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11606 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11607 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11608 intent.putExtra(Intent.EXTRA_UID, uid); 11609 } 11610 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11611 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11612 if (DEBUG_BROADCASTS) { 11613 RuntimeException here = new RuntimeException("here"); 11614 here.fillInStackTrace(); 11615 Slog.d(TAG, "Sending to user " + id + ": " 11616 + intent.toShortString(false, true, false, false) 11617 + " " + intent.getExtras(), here); 11618 } 11619 am.broadcastIntent(null, intent, null, finishedReceiver, 11620 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11621 null, finishedReceiver != null, false, id); 11622 } 11623 } catch (RemoteException ex) { 11624 } 11625 } 11626 }); 11627 } 11628 11629 /** 11630 * Check if the external storage media is available. This is true if there 11631 * is a mounted external storage medium or if the external storage is 11632 * emulated. 11633 */ 11634 private boolean isExternalMediaAvailable() { 11635 return mMediaMounted || Environment.isExternalStorageEmulated(); 11636 } 11637 11638 @Override 11639 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11640 // writer 11641 synchronized (mPackages) { 11642 if (!isExternalMediaAvailable()) { 11643 // If the external storage is no longer mounted at this point, 11644 // the caller may not have been able to delete all of this 11645 // packages files and can not delete any more. Bail. 11646 return null; 11647 } 11648 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11649 if (lastPackage != null) { 11650 pkgs.remove(lastPackage); 11651 } 11652 if (pkgs.size() > 0) { 11653 return pkgs.get(0); 11654 } 11655 } 11656 return null; 11657 } 11658 11659 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11660 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11661 userId, andCode ? 1 : 0, packageName); 11662 if (mSystemReady) { 11663 msg.sendToTarget(); 11664 } else { 11665 if (mPostSystemReadyMessages == null) { 11666 mPostSystemReadyMessages = new ArrayList<>(); 11667 } 11668 mPostSystemReadyMessages.add(msg); 11669 } 11670 } 11671 11672 void startCleaningPackages() { 11673 // reader 11674 if (!isExternalMediaAvailable()) { 11675 return; 11676 } 11677 synchronized (mPackages) { 11678 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11679 return; 11680 } 11681 } 11682 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11683 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11684 IActivityManager am = ActivityManagerNative.getDefault(); 11685 if (am != null) { 11686 try { 11687 am.startService(null, intent, null, mContext.getOpPackageName(), 11688 UserHandle.USER_SYSTEM); 11689 } catch (RemoteException e) { 11690 } 11691 } 11692 } 11693 11694 @Override 11695 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11696 int installFlags, String installerPackageName, int userId) { 11697 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11698 11699 final int callingUid = Binder.getCallingUid(); 11700 enforceCrossUserPermission(callingUid, userId, 11701 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11702 11703 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11704 try { 11705 if (observer != null) { 11706 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11707 } 11708 } catch (RemoteException re) { 11709 } 11710 return; 11711 } 11712 11713 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11714 installFlags |= PackageManager.INSTALL_FROM_ADB; 11715 11716 } else { 11717 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11718 // about installerPackageName. 11719 11720 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11721 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11722 } 11723 11724 UserHandle user; 11725 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11726 user = UserHandle.ALL; 11727 } else { 11728 user = new UserHandle(userId); 11729 } 11730 11731 // Only system components can circumvent runtime permissions when installing. 11732 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11733 && mContext.checkCallingOrSelfPermission(Manifest.permission 11734 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11735 throw new SecurityException("You need the " 11736 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11737 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11738 } 11739 11740 final File originFile = new File(originPath); 11741 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11742 11743 final Message msg = mHandler.obtainMessage(INIT_COPY); 11744 final VerificationInfo verificationInfo = new VerificationInfo( 11745 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11746 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11747 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11748 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11749 null /*certificates*/); 11750 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11751 msg.obj = params; 11752 11753 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11754 System.identityHashCode(msg.obj)); 11755 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11756 System.identityHashCode(msg.obj)); 11757 11758 mHandler.sendMessage(msg); 11759 } 11760 11761 void installStage(String packageName, File stagedDir, String stagedCid, 11762 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11763 String installerPackageName, int installerUid, UserHandle user, 11764 Certificate[][] certificates) { 11765 if (DEBUG_EPHEMERAL) { 11766 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11767 Slog.d(TAG, "Ephemeral install of " + packageName); 11768 } 11769 } 11770 final VerificationInfo verificationInfo = new VerificationInfo( 11771 sessionParams.originatingUri, sessionParams.referrerUri, 11772 sessionParams.originatingUid, installerUid); 11773 11774 final OriginInfo origin; 11775 if (stagedDir != null) { 11776 origin = OriginInfo.fromStagedFile(stagedDir); 11777 } else { 11778 origin = OriginInfo.fromStagedContainer(stagedCid); 11779 } 11780 11781 final Message msg = mHandler.obtainMessage(INIT_COPY); 11782 final InstallParams params = new InstallParams(origin, null, observer, 11783 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11784 verificationInfo, user, sessionParams.abiOverride, 11785 sessionParams.grantedRuntimePermissions, certificates); 11786 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11787 msg.obj = params; 11788 11789 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11790 System.identityHashCode(msg.obj)); 11791 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11792 System.identityHashCode(msg.obj)); 11793 11794 mHandler.sendMessage(msg); 11795 } 11796 11797 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11798 int userId) { 11799 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11800 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 11801 } 11802 11803 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 11804 int appId, int... userIds) { 11805 if (ArrayUtils.isEmpty(userIds)) { 11806 return; 11807 } 11808 Bundle extras = new Bundle(1); 11809 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 11810 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 11811 11812 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11813 packageName, extras, 0, null, null, userIds); 11814 if (isSystem) { 11815 mHandler.post(() -> { 11816 for (int userId : userIds) { 11817 sendBootCompletedBroadcastToSystemApp(packageName, userId); 11818 } 11819 } 11820 ); 11821 } 11822 } 11823 11824 /** 11825 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 11826 * automatically without needing an explicit launch. 11827 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 11828 */ 11829 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 11830 // If user is not running, the app didn't miss any broadcast 11831 if (!mUserManagerInternal.isUserRunning(userId)) { 11832 return; 11833 } 11834 final IActivityManager am = ActivityManagerNative.getDefault(); 11835 try { 11836 // Deliver LOCKED_BOOT_COMPLETED first 11837 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 11838 .setPackage(packageName); 11839 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 11840 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 11841 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11842 11843 // Deliver BOOT_COMPLETED only if user is unlocked 11844 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 11845 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 11846 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 11847 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11848 } 11849 } catch (RemoteException e) { 11850 throw e.rethrowFromSystemServer(); 11851 } 11852 } 11853 11854 @Override 11855 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11856 int userId) { 11857 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11858 PackageSetting pkgSetting; 11859 final int uid = Binder.getCallingUid(); 11860 enforceCrossUserPermission(uid, userId, 11861 true /* requireFullPermission */, true /* checkShell */, 11862 "setApplicationHiddenSetting for user " + userId); 11863 11864 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11865 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11866 return false; 11867 } 11868 11869 long callingId = Binder.clearCallingIdentity(); 11870 try { 11871 boolean sendAdded = false; 11872 boolean sendRemoved = false; 11873 // writer 11874 synchronized (mPackages) { 11875 pkgSetting = mSettings.mPackages.get(packageName); 11876 if (pkgSetting == null) { 11877 return false; 11878 } 11879 // Do not allow "android" is being disabled 11880 if ("android".equals(packageName)) { 11881 Slog.w(TAG, "Cannot hide package: android"); 11882 return false; 11883 } 11884 // Only allow protected packages to hide themselves. 11885 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11886 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11887 Slog.w(TAG, "Not hiding protected package: " + packageName); 11888 return false; 11889 } 11890 11891 if (pkgSetting.getHidden(userId) != hidden) { 11892 pkgSetting.setHidden(hidden, userId); 11893 mSettings.writePackageRestrictionsLPr(userId); 11894 if (hidden) { 11895 sendRemoved = true; 11896 } else { 11897 sendAdded = true; 11898 } 11899 } 11900 } 11901 if (sendAdded) { 11902 sendPackageAddedForUser(packageName, pkgSetting, userId); 11903 return true; 11904 } 11905 if (sendRemoved) { 11906 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11907 "hiding pkg"); 11908 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11909 return true; 11910 } 11911 } finally { 11912 Binder.restoreCallingIdentity(callingId); 11913 } 11914 return false; 11915 } 11916 11917 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11918 int userId) { 11919 final PackageRemovedInfo info = new PackageRemovedInfo(); 11920 info.removedPackage = packageName; 11921 info.removedUsers = new int[] {userId}; 11922 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11923 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11924 } 11925 11926 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11927 if (pkgList.length > 0) { 11928 Bundle extras = new Bundle(1); 11929 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11930 11931 sendPackageBroadcast( 11932 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11933 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11934 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11935 new int[] {userId}); 11936 } 11937 } 11938 11939 /** 11940 * Returns true if application is not found or there was an error. Otherwise it returns 11941 * the hidden state of the package for the given user. 11942 */ 11943 @Override 11944 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11946 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11947 true /* requireFullPermission */, false /* checkShell */, 11948 "getApplicationHidden for user " + userId); 11949 PackageSetting pkgSetting; 11950 long callingId = Binder.clearCallingIdentity(); 11951 try { 11952 // writer 11953 synchronized (mPackages) { 11954 pkgSetting = mSettings.mPackages.get(packageName); 11955 if (pkgSetting == null) { 11956 return true; 11957 } 11958 return pkgSetting.getHidden(userId); 11959 } 11960 } finally { 11961 Binder.restoreCallingIdentity(callingId); 11962 } 11963 } 11964 11965 /** 11966 * @hide 11967 */ 11968 @Override 11969 public int installExistingPackageAsUser(String packageName, int userId) { 11970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11971 null); 11972 PackageSetting pkgSetting; 11973 final int uid = Binder.getCallingUid(); 11974 enforceCrossUserPermission(uid, userId, 11975 true /* requireFullPermission */, true /* checkShell */, 11976 "installExistingPackage for user " + userId); 11977 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11978 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11979 } 11980 11981 long callingId = Binder.clearCallingIdentity(); 11982 try { 11983 boolean installed = false; 11984 11985 // writer 11986 synchronized (mPackages) { 11987 pkgSetting = mSettings.mPackages.get(packageName); 11988 if (pkgSetting == null) { 11989 return PackageManager.INSTALL_FAILED_INVALID_URI; 11990 } 11991 if (!pkgSetting.getInstalled(userId)) { 11992 pkgSetting.setInstalled(true, userId); 11993 pkgSetting.setHidden(false, userId); 11994 mSettings.writePackageRestrictionsLPr(userId); 11995 installed = true; 11996 } 11997 } 11998 11999 if (installed) { 12000 if (pkgSetting.pkg != null) { 12001 synchronized (mInstallLock) { 12002 // We don't need to freeze for a brand new install 12003 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12004 } 12005 } 12006 sendPackageAddedForUser(packageName, pkgSetting, userId); 12007 } 12008 } finally { 12009 Binder.restoreCallingIdentity(callingId); 12010 } 12011 12012 return PackageManager.INSTALL_SUCCEEDED; 12013 } 12014 12015 boolean isUserRestricted(int userId, String restrictionKey) { 12016 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12017 if (restrictions.getBoolean(restrictionKey, false)) { 12018 Log.w(TAG, "User is restricted: " + restrictionKey); 12019 return true; 12020 } 12021 return false; 12022 } 12023 12024 @Override 12025 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12026 int userId) { 12027 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12028 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12029 true /* requireFullPermission */, true /* checkShell */, 12030 "setPackagesSuspended for user " + userId); 12031 12032 if (ArrayUtils.isEmpty(packageNames)) { 12033 return packageNames; 12034 } 12035 12036 // List of package names for whom the suspended state has changed. 12037 List<String> changedPackages = new ArrayList<>(packageNames.length); 12038 // List of package names for whom the suspended state is not set as requested in this 12039 // method. 12040 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12041 long callingId = Binder.clearCallingIdentity(); 12042 try { 12043 for (int i = 0; i < packageNames.length; i++) { 12044 String packageName = packageNames[i]; 12045 boolean changed = false; 12046 final int appId; 12047 synchronized (mPackages) { 12048 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12049 if (pkgSetting == null) { 12050 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12051 + "\". Skipping suspending/un-suspending."); 12052 unactionedPackages.add(packageName); 12053 continue; 12054 } 12055 appId = pkgSetting.appId; 12056 if (pkgSetting.getSuspended(userId) != suspended) { 12057 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12058 unactionedPackages.add(packageName); 12059 continue; 12060 } 12061 pkgSetting.setSuspended(suspended, userId); 12062 mSettings.writePackageRestrictionsLPr(userId); 12063 changed = true; 12064 changedPackages.add(packageName); 12065 } 12066 } 12067 12068 if (changed && suspended) { 12069 killApplication(packageName, UserHandle.getUid(userId, appId), 12070 "suspending package"); 12071 } 12072 } 12073 } finally { 12074 Binder.restoreCallingIdentity(callingId); 12075 } 12076 12077 if (!changedPackages.isEmpty()) { 12078 sendPackagesSuspendedForUser(changedPackages.toArray( 12079 new String[changedPackages.size()]), userId, suspended); 12080 } 12081 12082 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12083 } 12084 12085 @Override 12086 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12087 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12088 true /* requireFullPermission */, false /* checkShell */, 12089 "isPackageSuspendedForUser for user " + userId); 12090 synchronized (mPackages) { 12091 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12092 if (pkgSetting == null) { 12093 throw new IllegalArgumentException("Unknown target package: " + packageName); 12094 } 12095 return pkgSetting.getSuspended(userId); 12096 } 12097 } 12098 12099 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12100 if (isPackageDeviceAdmin(packageName, userId)) { 12101 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12102 + "\": has an active device admin"); 12103 return false; 12104 } 12105 12106 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12107 if (packageName.equals(activeLauncherPackageName)) { 12108 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12109 + "\": contains the active launcher"); 12110 return false; 12111 } 12112 12113 if (packageName.equals(mRequiredInstallerPackage)) { 12114 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12115 + "\": required for package installation"); 12116 return false; 12117 } 12118 12119 if (packageName.equals(mRequiredUninstallerPackage)) { 12120 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12121 + "\": required for package uninstallation"); 12122 return false; 12123 } 12124 12125 if (packageName.equals(mRequiredVerifierPackage)) { 12126 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12127 + "\": required for package verification"); 12128 return false; 12129 } 12130 12131 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12132 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12133 + "\": is the default dialer"); 12134 return false; 12135 } 12136 12137 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12138 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12139 + "\": protected package"); 12140 return false; 12141 } 12142 12143 return true; 12144 } 12145 12146 private String getActiveLauncherPackageName(int userId) { 12147 Intent intent = new Intent(Intent.ACTION_MAIN); 12148 intent.addCategory(Intent.CATEGORY_HOME); 12149 ResolveInfo resolveInfo = resolveIntent( 12150 intent, 12151 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12152 PackageManager.MATCH_DEFAULT_ONLY, 12153 userId); 12154 12155 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12156 } 12157 12158 private String getDefaultDialerPackageName(int userId) { 12159 synchronized (mPackages) { 12160 return mSettings.getDefaultDialerPackageNameLPw(userId); 12161 } 12162 } 12163 12164 @Override 12165 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12166 mContext.enforceCallingOrSelfPermission( 12167 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12168 "Only package verification agents can verify applications"); 12169 12170 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12171 final PackageVerificationResponse response = new PackageVerificationResponse( 12172 verificationCode, Binder.getCallingUid()); 12173 msg.arg1 = id; 12174 msg.obj = response; 12175 mHandler.sendMessage(msg); 12176 } 12177 12178 @Override 12179 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12180 long millisecondsToDelay) { 12181 mContext.enforceCallingOrSelfPermission( 12182 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12183 "Only package verification agents can extend verification timeouts"); 12184 12185 final PackageVerificationState state = mPendingVerification.get(id); 12186 final PackageVerificationResponse response = new PackageVerificationResponse( 12187 verificationCodeAtTimeout, Binder.getCallingUid()); 12188 12189 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12190 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12191 } 12192 if (millisecondsToDelay < 0) { 12193 millisecondsToDelay = 0; 12194 } 12195 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12196 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12197 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12198 } 12199 12200 if ((state != null) && !state.timeoutExtended()) { 12201 state.extendTimeout(); 12202 12203 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12204 msg.arg1 = id; 12205 msg.obj = response; 12206 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12207 } 12208 } 12209 12210 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12211 int verificationCode, UserHandle user) { 12212 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12213 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12214 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12215 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12216 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12217 12218 mContext.sendBroadcastAsUser(intent, user, 12219 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12220 } 12221 12222 private ComponentName matchComponentForVerifier(String packageName, 12223 List<ResolveInfo> receivers) { 12224 ActivityInfo targetReceiver = null; 12225 12226 final int NR = receivers.size(); 12227 for (int i = 0; i < NR; i++) { 12228 final ResolveInfo info = receivers.get(i); 12229 if (info.activityInfo == null) { 12230 continue; 12231 } 12232 12233 if (packageName.equals(info.activityInfo.packageName)) { 12234 targetReceiver = info.activityInfo; 12235 break; 12236 } 12237 } 12238 12239 if (targetReceiver == null) { 12240 return null; 12241 } 12242 12243 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12244 } 12245 12246 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12247 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12248 if (pkgInfo.verifiers.length == 0) { 12249 return null; 12250 } 12251 12252 final int N = pkgInfo.verifiers.length; 12253 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12254 for (int i = 0; i < N; i++) { 12255 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12256 12257 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12258 receivers); 12259 if (comp == null) { 12260 continue; 12261 } 12262 12263 final int verifierUid = getUidForVerifier(verifierInfo); 12264 if (verifierUid == -1) { 12265 continue; 12266 } 12267 12268 if (DEBUG_VERIFY) { 12269 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12270 + " with the correct signature"); 12271 } 12272 sufficientVerifiers.add(comp); 12273 verificationState.addSufficientVerifier(verifierUid); 12274 } 12275 12276 return sufficientVerifiers; 12277 } 12278 12279 private int getUidForVerifier(VerifierInfo verifierInfo) { 12280 synchronized (mPackages) { 12281 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12282 if (pkg == null) { 12283 return -1; 12284 } else if (pkg.mSignatures.length != 1) { 12285 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12286 + " has more than one signature; ignoring"); 12287 return -1; 12288 } 12289 12290 /* 12291 * If the public key of the package's signature does not match 12292 * our expected public key, then this is a different package and 12293 * we should skip. 12294 */ 12295 12296 final byte[] expectedPublicKey; 12297 try { 12298 final Signature verifierSig = pkg.mSignatures[0]; 12299 final PublicKey publicKey = verifierSig.getPublicKey(); 12300 expectedPublicKey = publicKey.getEncoded(); 12301 } catch (CertificateException e) { 12302 return -1; 12303 } 12304 12305 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12306 12307 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12308 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12309 + " does not have the expected public key; ignoring"); 12310 return -1; 12311 } 12312 12313 return pkg.applicationInfo.uid; 12314 } 12315 } 12316 12317 @Override 12318 public void finishPackageInstall(int token, boolean didLaunch) { 12319 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12320 12321 if (DEBUG_INSTALL) { 12322 Slog.v(TAG, "BM finishing package install for " + token); 12323 } 12324 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12325 12326 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12327 mHandler.sendMessage(msg); 12328 } 12329 12330 /** 12331 * Get the verification agent timeout. 12332 * 12333 * @return verification timeout in milliseconds 12334 */ 12335 private long getVerificationTimeout() { 12336 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12337 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12338 DEFAULT_VERIFICATION_TIMEOUT); 12339 } 12340 12341 /** 12342 * Get the default verification agent response code. 12343 * 12344 * @return default verification response code 12345 */ 12346 private int getDefaultVerificationResponse() { 12347 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12348 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12349 DEFAULT_VERIFICATION_RESPONSE); 12350 } 12351 12352 /** 12353 * Check whether or not package verification has been enabled. 12354 * 12355 * @return true if verification should be performed 12356 */ 12357 private boolean isVerificationEnabled(int userId, int installFlags) { 12358 if (!DEFAULT_VERIFY_ENABLE) { 12359 return false; 12360 } 12361 // Ephemeral apps don't get the full verification treatment 12362 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12363 if (DEBUG_EPHEMERAL) { 12364 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12365 } 12366 return false; 12367 } 12368 12369 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12370 12371 // Check if installing from ADB 12372 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12373 // Do not run verification in a test harness environment 12374 if (ActivityManager.isRunningInTestHarness()) { 12375 return false; 12376 } 12377 if (ensureVerifyAppsEnabled) { 12378 return true; 12379 } 12380 // Check if the developer does not want package verification for ADB installs 12381 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12382 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12383 return false; 12384 } 12385 } 12386 12387 if (ensureVerifyAppsEnabled) { 12388 return true; 12389 } 12390 12391 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12392 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12393 } 12394 12395 @Override 12396 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12397 throws RemoteException { 12398 mContext.enforceCallingOrSelfPermission( 12399 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12400 "Only intentfilter verification agents can verify applications"); 12401 12402 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12403 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12404 Binder.getCallingUid(), verificationCode, failedDomains); 12405 msg.arg1 = id; 12406 msg.obj = response; 12407 mHandler.sendMessage(msg); 12408 } 12409 12410 @Override 12411 public int getIntentVerificationStatus(String packageName, int userId) { 12412 synchronized (mPackages) { 12413 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12414 } 12415 } 12416 12417 @Override 12418 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12419 mContext.enforceCallingOrSelfPermission( 12420 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12421 12422 boolean result = false; 12423 synchronized (mPackages) { 12424 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12425 } 12426 if (result) { 12427 scheduleWritePackageRestrictionsLocked(userId); 12428 } 12429 return result; 12430 } 12431 12432 @Override 12433 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12434 String packageName) { 12435 synchronized (mPackages) { 12436 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12437 } 12438 } 12439 12440 @Override 12441 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12442 if (TextUtils.isEmpty(packageName)) { 12443 return ParceledListSlice.emptyList(); 12444 } 12445 synchronized (mPackages) { 12446 PackageParser.Package pkg = mPackages.get(packageName); 12447 if (pkg == null || pkg.activities == null) { 12448 return ParceledListSlice.emptyList(); 12449 } 12450 final int count = pkg.activities.size(); 12451 ArrayList<IntentFilter> result = new ArrayList<>(); 12452 for (int n=0; n<count; n++) { 12453 PackageParser.Activity activity = pkg.activities.get(n); 12454 if (activity.intents != null && activity.intents.size() > 0) { 12455 result.addAll(activity.intents); 12456 } 12457 } 12458 return new ParceledListSlice<>(result); 12459 } 12460 } 12461 12462 @Override 12463 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12464 mContext.enforceCallingOrSelfPermission( 12465 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12466 12467 synchronized (mPackages) { 12468 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12469 if (packageName != null) { 12470 result |= updateIntentVerificationStatus(packageName, 12471 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12472 userId); 12473 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12474 packageName, userId); 12475 } 12476 return result; 12477 } 12478 } 12479 12480 @Override 12481 public String getDefaultBrowserPackageName(int userId) { 12482 synchronized (mPackages) { 12483 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12484 } 12485 } 12486 12487 /** 12488 * Get the "allow unknown sources" setting. 12489 * 12490 * @return the current "allow unknown sources" setting 12491 */ 12492 private int getUnknownSourcesSettings() { 12493 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12494 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12495 -1); 12496 } 12497 12498 @Override 12499 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12500 final int uid = Binder.getCallingUid(); 12501 // writer 12502 synchronized (mPackages) { 12503 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12504 if (targetPackageSetting == null) { 12505 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12506 } 12507 12508 PackageSetting installerPackageSetting; 12509 if (installerPackageName != null) { 12510 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12511 if (installerPackageSetting == null) { 12512 throw new IllegalArgumentException("Unknown installer package: " 12513 + installerPackageName); 12514 } 12515 } else { 12516 installerPackageSetting = null; 12517 } 12518 12519 Signature[] callerSignature; 12520 Object obj = mSettings.getUserIdLPr(uid); 12521 if (obj != null) { 12522 if (obj instanceof SharedUserSetting) { 12523 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12524 } else if (obj instanceof PackageSetting) { 12525 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12526 } else { 12527 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12528 } 12529 } else { 12530 throw new SecurityException("Unknown calling UID: " + uid); 12531 } 12532 12533 // Verify: can't set installerPackageName to a package that is 12534 // not signed with the same cert as the caller. 12535 if (installerPackageSetting != null) { 12536 if (compareSignatures(callerSignature, 12537 installerPackageSetting.signatures.mSignatures) 12538 != PackageManager.SIGNATURE_MATCH) { 12539 throw new SecurityException( 12540 "Caller does not have same cert as new installer package " 12541 + installerPackageName); 12542 } 12543 } 12544 12545 // Verify: if target already has an installer package, it must 12546 // be signed with the same cert as the caller. 12547 if (targetPackageSetting.installerPackageName != null) { 12548 PackageSetting setting = mSettings.mPackages.get( 12549 targetPackageSetting.installerPackageName); 12550 // If the currently set package isn't valid, then it's always 12551 // okay to change it. 12552 if (setting != null) { 12553 if (compareSignatures(callerSignature, 12554 setting.signatures.mSignatures) 12555 != PackageManager.SIGNATURE_MATCH) { 12556 throw new SecurityException( 12557 "Caller does not have same cert as old installer package " 12558 + targetPackageSetting.installerPackageName); 12559 } 12560 } 12561 } 12562 12563 // Okay! 12564 targetPackageSetting.installerPackageName = installerPackageName; 12565 if (installerPackageName != null) { 12566 mSettings.mInstallerPackages.add(installerPackageName); 12567 } 12568 scheduleWriteSettingsLocked(); 12569 } 12570 } 12571 12572 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12573 // Queue up an async operation since the package installation may take a little while. 12574 mHandler.post(new Runnable() { 12575 public void run() { 12576 mHandler.removeCallbacks(this); 12577 // Result object to be returned 12578 PackageInstalledInfo res = new PackageInstalledInfo(); 12579 res.setReturnCode(currentStatus); 12580 res.uid = -1; 12581 res.pkg = null; 12582 res.removedInfo = null; 12583 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12584 args.doPreInstall(res.returnCode); 12585 synchronized (mInstallLock) { 12586 installPackageTracedLI(args, res); 12587 } 12588 args.doPostInstall(res.returnCode, res.uid); 12589 } 12590 12591 // A restore should be performed at this point if (a) the install 12592 // succeeded, (b) the operation is not an update, and (c) the new 12593 // package has not opted out of backup participation. 12594 final boolean update = res.removedInfo != null 12595 && res.removedInfo.removedPackage != null; 12596 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12597 boolean doRestore = !update 12598 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12599 12600 // Set up the post-install work request bookkeeping. This will be used 12601 // and cleaned up by the post-install event handling regardless of whether 12602 // there's a restore pass performed. Token values are >= 1. 12603 int token; 12604 if (mNextInstallToken < 0) mNextInstallToken = 1; 12605 token = mNextInstallToken++; 12606 12607 PostInstallData data = new PostInstallData(args, res); 12608 mRunningInstalls.put(token, data); 12609 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12610 12611 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12612 // Pass responsibility to the Backup Manager. It will perform a 12613 // restore if appropriate, then pass responsibility back to the 12614 // Package Manager to run the post-install observer callbacks 12615 // and broadcasts. 12616 IBackupManager bm = IBackupManager.Stub.asInterface( 12617 ServiceManager.getService(Context.BACKUP_SERVICE)); 12618 if (bm != null) { 12619 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12620 + " to BM for possible restore"); 12621 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12622 try { 12623 // TODO: http://b/22388012 12624 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12625 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12626 } else { 12627 doRestore = false; 12628 } 12629 } catch (RemoteException e) { 12630 // can't happen; the backup manager is local 12631 } catch (Exception e) { 12632 Slog.e(TAG, "Exception trying to enqueue restore", e); 12633 doRestore = false; 12634 } 12635 } else { 12636 Slog.e(TAG, "Backup Manager not found!"); 12637 doRestore = false; 12638 } 12639 } 12640 12641 if (!doRestore) { 12642 // No restore possible, or the Backup Manager was mysteriously not 12643 // available -- just fire the post-install work request directly. 12644 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12645 12646 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12647 12648 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12649 mHandler.sendMessage(msg); 12650 } 12651 } 12652 }); 12653 } 12654 12655 /** 12656 * Callback from PackageSettings whenever an app is first transitioned out of the 12657 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12658 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12659 * here whether the app is the target of an ongoing install, and only send the 12660 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12661 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12662 * handling. 12663 */ 12664 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12665 // Serialize this with the rest of the install-process message chain. In the 12666 // restore-at-install case, this Runnable will necessarily run before the 12667 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12668 // are coherent. In the non-restore case, the app has already completed install 12669 // and been launched through some other means, so it is not in a problematic 12670 // state for observers to see the FIRST_LAUNCH signal. 12671 mHandler.post(new Runnable() { 12672 @Override 12673 public void run() { 12674 for (int i = 0; i < mRunningInstalls.size(); i++) { 12675 final PostInstallData data = mRunningInstalls.valueAt(i); 12676 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12677 continue; 12678 } 12679 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12680 // right package; but is it for the right user? 12681 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12682 if (userId == data.res.newUsers[uIndex]) { 12683 if (DEBUG_BACKUP) { 12684 Slog.i(TAG, "Package " + pkgName 12685 + " being restored so deferring FIRST_LAUNCH"); 12686 } 12687 return; 12688 } 12689 } 12690 } 12691 } 12692 // didn't find it, so not being restored 12693 if (DEBUG_BACKUP) { 12694 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12695 } 12696 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12697 } 12698 }); 12699 } 12700 12701 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12702 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12703 installerPkg, null, userIds); 12704 } 12705 12706 private abstract class HandlerParams { 12707 private static final int MAX_RETRIES = 4; 12708 12709 /** 12710 * Number of times startCopy() has been attempted and had a non-fatal 12711 * error. 12712 */ 12713 private int mRetries = 0; 12714 12715 /** User handle for the user requesting the information or installation. */ 12716 private final UserHandle mUser; 12717 String traceMethod; 12718 int traceCookie; 12719 12720 HandlerParams(UserHandle user) { 12721 mUser = user; 12722 } 12723 12724 UserHandle getUser() { 12725 return mUser; 12726 } 12727 12728 HandlerParams setTraceMethod(String traceMethod) { 12729 this.traceMethod = traceMethod; 12730 return this; 12731 } 12732 12733 HandlerParams setTraceCookie(int traceCookie) { 12734 this.traceCookie = traceCookie; 12735 return this; 12736 } 12737 12738 final boolean startCopy() { 12739 boolean res; 12740 try { 12741 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12742 12743 if (++mRetries > MAX_RETRIES) { 12744 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12745 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12746 handleServiceError(); 12747 return false; 12748 } else { 12749 handleStartCopy(); 12750 res = true; 12751 } 12752 } catch (RemoteException e) { 12753 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12754 mHandler.sendEmptyMessage(MCS_RECONNECT); 12755 res = false; 12756 } 12757 handleReturnCode(); 12758 return res; 12759 } 12760 12761 final void serviceError() { 12762 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12763 handleServiceError(); 12764 handleReturnCode(); 12765 } 12766 12767 abstract void handleStartCopy() throws RemoteException; 12768 abstract void handleServiceError(); 12769 abstract void handleReturnCode(); 12770 } 12771 12772 class MeasureParams extends HandlerParams { 12773 private final PackageStats mStats; 12774 private boolean mSuccess; 12775 12776 private final IPackageStatsObserver mObserver; 12777 12778 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12779 super(new UserHandle(stats.userHandle)); 12780 mObserver = observer; 12781 mStats = stats; 12782 } 12783 12784 @Override 12785 public String toString() { 12786 return "MeasureParams{" 12787 + Integer.toHexString(System.identityHashCode(this)) 12788 + " " + mStats.packageName + "}"; 12789 } 12790 12791 @Override 12792 void handleStartCopy() throws RemoteException { 12793 synchronized (mInstallLock) { 12794 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12795 } 12796 12797 if (mSuccess) { 12798 boolean mounted = false; 12799 try { 12800 final String status = Environment.getExternalStorageState(); 12801 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12802 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12803 } catch (Exception e) { 12804 } 12805 12806 if (mounted) { 12807 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12808 12809 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12810 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12811 12812 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12813 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12814 12815 // Always subtract cache size, since it's a subdirectory 12816 mStats.externalDataSize -= mStats.externalCacheSize; 12817 12818 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12819 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12820 12821 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12822 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12823 } 12824 } 12825 } 12826 12827 @Override 12828 void handleReturnCode() { 12829 if (mObserver != null) { 12830 try { 12831 mObserver.onGetStatsCompleted(mStats, mSuccess); 12832 } catch (RemoteException e) { 12833 Slog.i(TAG, "Observer no longer exists."); 12834 } 12835 } 12836 } 12837 12838 @Override 12839 void handleServiceError() { 12840 Slog.e(TAG, "Could not measure application " + mStats.packageName 12841 + " external storage"); 12842 } 12843 } 12844 12845 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12846 throws RemoteException { 12847 long result = 0; 12848 for (File path : paths) { 12849 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12850 } 12851 return result; 12852 } 12853 12854 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12855 for (File path : paths) { 12856 try { 12857 mcs.clearDirectory(path.getAbsolutePath()); 12858 } catch (RemoteException e) { 12859 } 12860 } 12861 } 12862 12863 static class OriginInfo { 12864 /** 12865 * Location where install is coming from, before it has been 12866 * copied/renamed into place. This could be a single monolithic APK 12867 * file, or a cluster directory. This location may be untrusted. 12868 */ 12869 final File file; 12870 final String cid; 12871 12872 /** 12873 * Flag indicating that {@link #file} or {@link #cid} has already been 12874 * staged, meaning downstream users don't need to defensively copy the 12875 * contents. 12876 */ 12877 final boolean staged; 12878 12879 /** 12880 * Flag indicating that {@link #file} or {@link #cid} is an already 12881 * installed app that is being moved. 12882 */ 12883 final boolean existing; 12884 12885 final String resolvedPath; 12886 final File resolvedFile; 12887 12888 static OriginInfo fromNothing() { 12889 return new OriginInfo(null, null, false, false); 12890 } 12891 12892 static OriginInfo fromUntrustedFile(File file) { 12893 return new OriginInfo(file, null, false, false); 12894 } 12895 12896 static OriginInfo fromExistingFile(File file) { 12897 return new OriginInfo(file, null, false, true); 12898 } 12899 12900 static OriginInfo fromStagedFile(File file) { 12901 return new OriginInfo(file, null, true, false); 12902 } 12903 12904 static OriginInfo fromStagedContainer(String cid) { 12905 return new OriginInfo(null, cid, true, false); 12906 } 12907 12908 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12909 this.file = file; 12910 this.cid = cid; 12911 this.staged = staged; 12912 this.existing = existing; 12913 12914 if (cid != null) { 12915 resolvedPath = PackageHelper.getSdDir(cid); 12916 resolvedFile = new File(resolvedPath); 12917 } else if (file != null) { 12918 resolvedPath = file.getAbsolutePath(); 12919 resolvedFile = file; 12920 } else { 12921 resolvedPath = null; 12922 resolvedFile = null; 12923 } 12924 } 12925 } 12926 12927 static class MoveInfo { 12928 final int moveId; 12929 final String fromUuid; 12930 final String toUuid; 12931 final String packageName; 12932 final String dataAppName; 12933 final int appId; 12934 final String seinfo; 12935 final int targetSdkVersion; 12936 12937 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12938 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12939 this.moveId = moveId; 12940 this.fromUuid = fromUuid; 12941 this.toUuid = toUuid; 12942 this.packageName = packageName; 12943 this.dataAppName = dataAppName; 12944 this.appId = appId; 12945 this.seinfo = seinfo; 12946 this.targetSdkVersion = targetSdkVersion; 12947 } 12948 } 12949 12950 static class VerificationInfo { 12951 /** A constant used to indicate that a uid value is not present. */ 12952 public static final int NO_UID = -1; 12953 12954 /** URI referencing where the package was downloaded from. */ 12955 final Uri originatingUri; 12956 12957 /** HTTP referrer URI associated with the originatingURI. */ 12958 final Uri referrer; 12959 12960 /** UID of the application that the install request originated from. */ 12961 final int originatingUid; 12962 12963 /** UID of application requesting the install */ 12964 final int installerUid; 12965 12966 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12967 this.originatingUri = originatingUri; 12968 this.referrer = referrer; 12969 this.originatingUid = originatingUid; 12970 this.installerUid = installerUid; 12971 } 12972 } 12973 12974 class InstallParams extends HandlerParams { 12975 final OriginInfo origin; 12976 final MoveInfo move; 12977 final IPackageInstallObserver2 observer; 12978 int installFlags; 12979 final String installerPackageName; 12980 final String volumeUuid; 12981 private InstallArgs mArgs; 12982 private int mRet; 12983 final String packageAbiOverride; 12984 final String[] grantedRuntimePermissions; 12985 final VerificationInfo verificationInfo; 12986 final Certificate[][] certificates; 12987 12988 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12989 int installFlags, String installerPackageName, String volumeUuid, 12990 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12991 String[] grantedPermissions, Certificate[][] certificates) { 12992 super(user); 12993 this.origin = origin; 12994 this.move = move; 12995 this.observer = observer; 12996 this.installFlags = installFlags; 12997 this.installerPackageName = installerPackageName; 12998 this.volumeUuid = volumeUuid; 12999 this.verificationInfo = verificationInfo; 13000 this.packageAbiOverride = packageAbiOverride; 13001 this.grantedRuntimePermissions = grantedPermissions; 13002 this.certificates = certificates; 13003 } 13004 13005 @Override 13006 public String toString() { 13007 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13008 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13009 } 13010 13011 private int installLocationPolicy(PackageInfoLite pkgLite) { 13012 String packageName = pkgLite.packageName; 13013 int installLocation = pkgLite.installLocation; 13014 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13015 // reader 13016 synchronized (mPackages) { 13017 // Currently installed package which the new package is attempting to replace or 13018 // null if no such package is installed. 13019 PackageParser.Package installedPkg = mPackages.get(packageName); 13020 // Package which currently owns the data which the new package will own if installed. 13021 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13022 // will be null whereas dataOwnerPkg will contain information about the package 13023 // which was uninstalled while keeping its data. 13024 PackageParser.Package dataOwnerPkg = installedPkg; 13025 if (dataOwnerPkg == null) { 13026 PackageSetting ps = mSettings.mPackages.get(packageName); 13027 if (ps != null) { 13028 dataOwnerPkg = ps.pkg; 13029 } 13030 } 13031 13032 if (dataOwnerPkg != null) { 13033 // If installed, the package will get access to data left on the device by its 13034 // predecessor. As a security measure, this is permited only if this is not a 13035 // version downgrade or if the predecessor package is marked as debuggable and 13036 // a downgrade is explicitly requested. 13037 // 13038 // On debuggable platform builds, downgrades are permitted even for 13039 // non-debuggable packages to make testing easier. Debuggable platform builds do 13040 // not offer security guarantees and thus it's OK to disable some security 13041 // mechanisms to make debugging/testing easier on those builds. However, even on 13042 // debuggable builds downgrades of packages are permitted only if requested via 13043 // installFlags. This is because we aim to keep the behavior of debuggable 13044 // platform builds as close as possible to the behavior of non-debuggable 13045 // platform builds. 13046 final boolean downgradeRequested = 13047 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13048 final boolean packageDebuggable = 13049 (dataOwnerPkg.applicationInfo.flags 13050 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13051 final boolean downgradePermitted = 13052 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13053 if (!downgradePermitted) { 13054 try { 13055 checkDowngrade(dataOwnerPkg, pkgLite); 13056 } catch (PackageManagerException e) { 13057 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13058 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13059 } 13060 } 13061 } 13062 13063 if (installedPkg != null) { 13064 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13065 // Check for updated system application. 13066 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13067 if (onSd) { 13068 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13069 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13070 } 13071 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13072 } else { 13073 if (onSd) { 13074 // Install flag overrides everything. 13075 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13076 } 13077 // If current upgrade specifies particular preference 13078 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13079 // Application explicitly specified internal. 13080 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13081 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13082 // App explictly prefers external. Let policy decide 13083 } else { 13084 // Prefer previous location 13085 if (isExternal(installedPkg)) { 13086 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13087 } 13088 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13089 } 13090 } 13091 } else { 13092 // Invalid install. Return error code 13093 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13094 } 13095 } 13096 } 13097 // All the special cases have been taken care of. 13098 // Return result based on recommended install location. 13099 if (onSd) { 13100 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13101 } 13102 return pkgLite.recommendedInstallLocation; 13103 } 13104 13105 /* 13106 * Invoke remote method to get package information and install 13107 * location values. Override install location based on default 13108 * policy if needed and then create install arguments based 13109 * on the install location. 13110 */ 13111 public void handleStartCopy() throws RemoteException { 13112 int ret = PackageManager.INSTALL_SUCCEEDED; 13113 13114 // If we're already staged, we've firmly committed to an install location 13115 if (origin.staged) { 13116 if (origin.file != null) { 13117 installFlags |= PackageManager.INSTALL_INTERNAL; 13118 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13119 } else if (origin.cid != null) { 13120 installFlags |= PackageManager.INSTALL_EXTERNAL; 13121 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13122 } else { 13123 throw new IllegalStateException("Invalid stage location"); 13124 } 13125 } 13126 13127 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13128 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13129 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13130 PackageInfoLite pkgLite = null; 13131 13132 if (onInt && onSd) { 13133 // Check if both bits are set. 13134 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13135 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13136 } else if (onSd && ephemeral) { 13137 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13138 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13139 } else { 13140 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13141 packageAbiOverride); 13142 13143 if (DEBUG_EPHEMERAL && ephemeral) { 13144 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13145 } 13146 13147 /* 13148 * If we have too little free space, try to free cache 13149 * before giving up. 13150 */ 13151 if (!origin.staged && pkgLite.recommendedInstallLocation 13152 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13153 // TODO: focus freeing disk space on the target device 13154 final StorageManager storage = StorageManager.from(mContext); 13155 final long lowThreshold = storage.getStorageLowBytes( 13156 Environment.getDataDirectory()); 13157 13158 final long sizeBytes = mContainerService.calculateInstalledSize( 13159 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13160 13161 try { 13162 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13163 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13164 installFlags, packageAbiOverride); 13165 } catch (InstallerException e) { 13166 Slog.w(TAG, "Failed to free cache", e); 13167 } 13168 13169 /* 13170 * The cache free must have deleted the file we 13171 * downloaded to install. 13172 * 13173 * TODO: fix the "freeCache" call to not delete 13174 * the file we care about. 13175 */ 13176 if (pkgLite.recommendedInstallLocation 13177 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13178 pkgLite.recommendedInstallLocation 13179 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13180 } 13181 } 13182 } 13183 13184 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13185 int loc = pkgLite.recommendedInstallLocation; 13186 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13187 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13188 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13189 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13190 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13191 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13192 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13193 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13194 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13195 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13196 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13197 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13198 } else { 13199 // Override with defaults if needed. 13200 loc = installLocationPolicy(pkgLite); 13201 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13202 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13203 } else if (!onSd && !onInt) { 13204 // Override install location with flags 13205 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13206 // Set the flag to install on external media. 13207 installFlags |= PackageManager.INSTALL_EXTERNAL; 13208 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13209 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13210 if (DEBUG_EPHEMERAL) { 13211 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13212 } 13213 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13214 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13215 |PackageManager.INSTALL_INTERNAL); 13216 } else { 13217 // Make sure the flag for installing on external 13218 // media is unset 13219 installFlags |= PackageManager.INSTALL_INTERNAL; 13220 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13221 } 13222 } 13223 } 13224 } 13225 13226 final InstallArgs args = createInstallArgs(this); 13227 mArgs = args; 13228 13229 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13230 // TODO: http://b/22976637 13231 // Apps installed for "all" users use the device owner to verify the app 13232 UserHandle verifierUser = getUser(); 13233 if (verifierUser == UserHandle.ALL) { 13234 verifierUser = UserHandle.SYSTEM; 13235 } 13236 13237 /* 13238 * Determine if we have any installed package verifiers. If we 13239 * do, then we'll defer to them to verify the packages. 13240 */ 13241 final int requiredUid = mRequiredVerifierPackage == null ? -1 13242 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13243 verifierUser.getIdentifier()); 13244 if (!origin.existing && requiredUid != -1 13245 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13246 final Intent verification = new Intent( 13247 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13248 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13249 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13250 PACKAGE_MIME_TYPE); 13251 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13252 13253 // Query all live verifiers based on current user state 13254 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13255 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13256 13257 if (DEBUG_VERIFY) { 13258 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13259 + verification.toString() + " with " + pkgLite.verifiers.length 13260 + " optional verifiers"); 13261 } 13262 13263 final int verificationId = mPendingVerificationToken++; 13264 13265 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13266 13267 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13268 installerPackageName); 13269 13270 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13271 installFlags); 13272 13273 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13274 pkgLite.packageName); 13275 13276 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13277 pkgLite.versionCode); 13278 13279 if (verificationInfo != null) { 13280 if (verificationInfo.originatingUri != null) { 13281 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13282 verificationInfo.originatingUri); 13283 } 13284 if (verificationInfo.referrer != null) { 13285 verification.putExtra(Intent.EXTRA_REFERRER, 13286 verificationInfo.referrer); 13287 } 13288 if (verificationInfo.originatingUid >= 0) { 13289 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13290 verificationInfo.originatingUid); 13291 } 13292 if (verificationInfo.installerUid >= 0) { 13293 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13294 verificationInfo.installerUid); 13295 } 13296 } 13297 13298 final PackageVerificationState verificationState = new PackageVerificationState( 13299 requiredUid, args); 13300 13301 mPendingVerification.append(verificationId, verificationState); 13302 13303 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13304 receivers, verificationState); 13305 13306 /* 13307 * If any sufficient verifiers were listed in the package 13308 * manifest, attempt to ask them. 13309 */ 13310 if (sufficientVerifiers != null) { 13311 final int N = sufficientVerifiers.size(); 13312 if (N == 0) { 13313 Slog.i(TAG, "Additional verifiers required, but none installed."); 13314 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13315 } else { 13316 for (int i = 0; i < N; i++) { 13317 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13318 13319 final Intent sufficientIntent = new Intent(verification); 13320 sufficientIntent.setComponent(verifierComponent); 13321 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13322 } 13323 } 13324 } 13325 13326 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13327 mRequiredVerifierPackage, receivers); 13328 if (ret == PackageManager.INSTALL_SUCCEEDED 13329 && mRequiredVerifierPackage != null) { 13330 Trace.asyncTraceBegin( 13331 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13332 /* 13333 * Send the intent to the required verification agent, 13334 * but only start the verification timeout after the 13335 * target BroadcastReceivers have run. 13336 */ 13337 verification.setComponent(requiredVerifierComponent); 13338 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13339 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13340 new BroadcastReceiver() { 13341 @Override 13342 public void onReceive(Context context, Intent intent) { 13343 final Message msg = mHandler 13344 .obtainMessage(CHECK_PENDING_VERIFICATION); 13345 msg.arg1 = verificationId; 13346 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13347 } 13348 }, null, 0, null, null); 13349 13350 /* 13351 * We don't want the copy to proceed until verification 13352 * succeeds, so null out this field. 13353 */ 13354 mArgs = null; 13355 } 13356 } else { 13357 /* 13358 * No package verification is enabled, so immediately start 13359 * the remote call to initiate copy using temporary file. 13360 */ 13361 ret = args.copyApk(mContainerService, true); 13362 } 13363 } 13364 13365 mRet = ret; 13366 } 13367 13368 @Override 13369 void handleReturnCode() { 13370 // If mArgs is null, then MCS couldn't be reached. When it 13371 // reconnects, it will try again to install. At that point, this 13372 // will succeed. 13373 if (mArgs != null) { 13374 processPendingInstall(mArgs, mRet); 13375 } 13376 } 13377 13378 @Override 13379 void handleServiceError() { 13380 mArgs = createInstallArgs(this); 13381 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13382 } 13383 13384 public boolean isForwardLocked() { 13385 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13386 } 13387 } 13388 13389 /** 13390 * Used during creation of InstallArgs 13391 * 13392 * @param installFlags package installation flags 13393 * @return true if should be installed on external storage 13394 */ 13395 private static boolean installOnExternalAsec(int installFlags) { 13396 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13397 return false; 13398 } 13399 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13400 return true; 13401 } 13402 return false; 13403 } 13404 13405 /** 13406 * Used during creation of InstallArgs 13407 * 13408 * @param installFlags package installation flags 13409 * @return true if should be installed as forward locked 13410 */ 13411 private static boolean installForwardLocked(int installFlags) { 13412 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13413 } 13414 13415 private InstallArgs createInstallArgs(InstallParams params) { 13416 if (params.move != null) { 13417 return new MoveInstallArgs(params); 13418 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13419 return new AsecInstallArgs(params); 13420 } else { 13421 return new FileInstallArgs(params); 13422 } 13423 } 13424 13425 /** 13426 * Create args that describe an existing installed package. Typically used 13427 * when cleaning up old installs, or used as a move source. 13428 */ 13429 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13430 String resourcePath, String[] instructionSets) { 13431 final boolean isInAsec; 13432 if (installOnExternalAsec(installFlags)) { 13433 /* Apps on SD card are always in ASEC containers. */ 13434 isInAsec = true; 13435 } else if (installForwardLocked(installFlags) 13436 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13437 /* 13438 * Forward-locked apps are only in ASEC containers if they're the 13439 * new style 13440 */ 13441 isInAsec = true; 13442 } else { 13443 isInAsec = false; 13444 } 13445 13446 if (isInAsec) { 13447 return new AsecInstallArgs(codePath, instructionSets, 13448 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13449 } else { 13450 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13451 } 13452 } 13453 13454 static abstract class InstallArgs { 13455 /** @see InstallParams#origin */ 13456 final OriginInfo origin; 13457 /** @see InstallParams#move */ 13458 final MoveInfo move; 13459 13460 final IPackageInstallObserver2 observer; 13461 // Always refers to PackageManager flags only 13462 final int installFlags; 13463 final String installerPackageName; 13464 final String volumeUuid; 13465 final UserHandle user; 13466 final String abiOverride; 13467 final String[] installGrantPermissions; 13468 /** If non-null, drop an async trace when the install completes */ 13469 final String traceMethod; 13470 final int traceCookie; 13471 final Certificate[][] certificates; 13472 13473 // The list of instruction sets supported by this app. This is currently 13474 // only used during the rmdex() phase to clean up resources. We can get rid of this 13475 // if we move dex files under the common app path. 13476 /* nullable */ String[] instructionSets; 13477 13478 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13479 int installFlags, String installerPackageName, String volumeUuid, 13480 UserHandle user, String[] instructionSets, 13481 String abiOverride, String[] installGrantPermissions, 13482 String traceMethod, int traceCookie, Certificate[][] certificates) { 13483 this.origin = origin; 13484 this.move = move; 13485 this.installFlags = installFlags; 13486 this.observer = observer; 13487 this.installerPackageName = installerPackageName; 13488 this.volumeUuid = volumeUuid; 13489 this.user = user; 13490 this.instructionSets = instructionSets; 13491 this.abiOverride = abiOverride; 13492 this.installGrantPermissions = installGrantPermissions; 13493 this.traceMethod = traceMethod; 13494 this.traceCookie = traceCookie; 13495 this.certificates = certificates; 13496 } 13497 13498 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13499 abstract int doPreInstall(int status); 13500 13501 /** 13502 * Rename package into final resting place. All paths on the given 13503 * scanned package should be updated to reflect the rename. 13504 */ 13505 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13506 abstract int doPostInstall(int status, int uid); 13507 13508 /** @see PackageSettingBase#codePathString */ 13509 abstract String getCodePath(); 13510 /** @see PackageSettingBase#resourcePathString */ 13511 abstract String getResourcePath(); 13512 13513 // Need installer lock especially for dex file removal. 13514 abstract void cleanUpResourcesLI(); 13515 abstract boolean doPostDeleteLI(boolean delete); 13516 13517 /** 13518 * Called before the source arguments are copied. This is used mostly 13519 * for MoveParams when it needs to read the source file to put it in the 13520 * destination. 13521 */ 13522 int doPreCopy() { 13523 return PackageManager.INSTALL_SUCCEEDED; 13524 } 13525 13526 /** 13527 * Called after the source arguments are copied. This is used mostly for 13528 * MoveParams when it needs to read the source file to put it in the 13529 * destination. 13530 */ 13531 int doPostCopy(int uid) { 13532 return PackageManager.INSTALL_SUCCEEDED; 13533 } 13534 13535 protected boolean isFwdLocked() { 13536 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13537 } 13538 13539 protected boolean isExternalAsec() { 13540 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13541 } 13542 13543 protected boolean isEphemeral() { 13544 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13545 } 13546 13547 UserHandle getUser() { 13548 return user; 13549 } 13550 } 13551 13552 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13553 if (!allCodePaths.isEmpty()) { 13554 if (instructionSets == null) { 13555 throw new IllegalStateException("instructionSet == null"); 13556 } 13557 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13558 for (String codePath : allCodePaths) { 13559 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13560 try { 13561 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13562 } catch (InstallerException ignored) { 13563 } 13564 } 13565 } 13566 } 13567 } 13568 13569 /** 13570 * Logic to handle installation of non-ASEC applications, including copying 13571 * and renaming logic. 13572 */ 13573 class FileInstallArgs extends InstallArgs { 13574 private File codeFile; 13575 private File resourceFile; 13576 13577 // Example topology: 13578 // /data/app/com.example/base.apk 13579 // /data/app/com.example/split_foo.apk 13580 // /data/app/com.example/lib/arm/libfoo.so 13581 // /data/app/com.example/lib/arm64/libfoo.so 13582 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13583 13584 /** New install */ 13585 FileInstallArgs(InstallParams params) { 13586 super(params.origin, params.move, params.observer, params.installFlags, 13587 params.installerPackageName, params.volumeUuid, 13588 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13589 params.grantedRuntimePermissions, 13590 params.traceMethod, params.traceCookie, params.certificates); 13591 if (isFwdLocked()) { 13592 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13593 } 13594 } 13595 13596 /** Existing install */ 13597 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13598 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13599 null, null, null, 0, null /*certificates*/); 13600 this.codeFile = (codePath != null) ? new File(codePath) : null; 13601 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13602 } 13603 13604 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13605 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13606 try { 13607 return doCopyApk(imcs, temp); 13608 } finally { 13609 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13610 } 13611 } 13612 13613 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13614 if (origin.staged) { 13615 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13616 codeFile = origin.file; 13617 resourceFile = origin.file; 13618 return PackageManager.INSTALL_SUCCEEDED; 13619 } 13620 13621 try { 13622 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13623 final File tempDir = 13624 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13625 codeFile = tempDir; 13626 resourceFile = tempDir; 13627 } catch (IOException e) { 13628 Slog.w(TAG, "Failed to create copy file: " + e); 13629 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13630 } 13631 13632 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13633 @Override 13634 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13635 if (!FileUtils.isValidExtFilename(name)) { 13636 throw new IllegalArgumentException("Invalid filename: " + name); 13637 } 13638 try { 13639 final File file = new File(codeFile, name); 13640 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13641 O_RDWR | O_CREAT, 0644); 13642 Os.chmod(file.getAbsolutePath(), 0644); 13643 return new ParcelFileDescriptor(fd); 13644 } catch (ErrnoException e) { 13645 throw new RemoteException("Failed to open: " + e.getMessage()); 13646 } 13647 } 13648 }; 13649 13650 int ret = PackageManager.INSTALL_SUCCEEDED; 13651 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13652 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13653 Slog.e(TAG, "Failed to copy package"); 13654 return ret; 13655 } 13656 13657 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13658 NativeLibraryHelper.Handle handle = null; 13659 try { 13660 handle = NativeLibraryHelper.Handle.create(codeFile); 13661 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13662 abiOverride); 13663 } catch (IOException e) { 13664 Slog.e(TAG, "Copying native libraries failed", e); 13665 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13666 } finally { 13667 IoUtils.closeQuietly(handle); 13668 } 13669 13670 return ret; 13671 } 13672 13673 int doPreInstall(int status) { 13674 if (status != PackageManager.INSTALL_SUCCEEDED) { 13675 cleanUp(); 13676 } 13677 return status; 13678 } 13679 13680 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13681 if (status != PackageManager.INSTALL_SUCCEEDED) { 13682 cleanUp(); 13683 return false; 13684 } 13685 13686 final File targetDir = codeFile.getParentFile(); 13687 final File beforeCodeFile = codeFile; 13688 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13689 13690 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13691 try { 13692 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13693 } catch (ErrnoException e) { 13694 Slog.w(TAG, "Failed to rename", e); 13695 return false; 13696 } 13697 13698 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13699 Slog.w(TAG, "Failed to restorecon"); 13700 return false; 13701 } 13702 13703 // Reflect the rename internally 13704 codeFile = afterCodeFile; 13705 resourceFile = afterCodeFile; 13706 13707 // Reflect the rename in scanned details 13708 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13709 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13710 afterCodeFile, pkg.baseCodePath)); 13711 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13712 afterCodeFile, pkg.splitCodePaths)); 13713 13714 // Reflect the rename in app info 13715 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13716 pkg.setApplicationInfoCodePath(pkg.codePath); 13717 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13718 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13719 pkg.setApplicationInfoResourcePath(pkg.codePath); 13720 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13721 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13722 13723 return true; 13724 } 13725 13726 int doPostInstall(int status, int uid) { 13727 if (status != PackageManager.INSTALL_SUCCEEDED) { 13728 cleanUp(); 13729 } 13730 return status; 13731 } 13732 13733 @Override 13734 String getCodePath() { 13735 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13736 } 13737 13738 @Override 13739 String getResourcePath() { 13740 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13741 } 13742 13743 private boolean cleanUp() { 13744 if (codeFile == null || !codeFile.exists()) { 13745 return false; 13746 } 13747 13748 removeCodePathLI(codeFile); 13749 13750 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13751 resourceFile.delete(); 13752 } 13753 13754 return true; 13755 } 13756 13757 void cleanUpResourcesLI() { 13758 // Try enumerating all code paths before deleting 13759 List<String> allCodePaths = Collections.EMPTY_LIST; 13760 if (codeFile != null && codeFile.exists()) { 13761 try { 13762 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13763 allCodePaths = pkg.getAllCodePaths(); 13764 } catch (PackageParserException e) { 13765 // Ignored; we tried our best 13766 } 13767 } 13768 13769 cleanUp(); 13770 removeDexFiles(allCodePaths, instructionSets); 13771 } 13772 13773 boolean doPostDeleteLI(boolean delete) { 13774 // XXX err, shouldn't we respect the delete flag? 13775 cleanUpResourcesLI(); 13776 return true; 13777 } 13778 } 13779 13780 private boolean isAsecExternal(String cid) { 13781 final String asecPath = PackageHelper.getSdFilesystem(cid); 13782 return !asecPath.startsWith(mAsecInternalPath); 13783 } 13784 13785 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13786 PackageManagerException { 13787 if (copyRet < 0) { 13788 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13789 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13790 throw new PackageManagerException(copyRet, message); 13791 } 13792 } 13793 } 13794 13795 /** 13796 * Extract the MountService "container ID" from the full code path of an 13797 * .apk. 13798 */ 13799 static String cidFromCodePath(String fullCodePath) { 13800 int eidx = fullCodePath.lastIndexOf("/"); 13801 String subStr1 = fullCodePath.substring(0, eidx); 13802 int sidx = subStr1.lastIndexOf("/"); 13803 return subStr1.substring(sidx+1, eidx); 13804 } 13805 13806 /** 13807 * Logic to handle installation of ASEC applications, including copying and 13808 * renaming logic. 13809 */ 13810 class AsecInstallArgs extends InstallArgs { 13811 static final String RES_FILE_NAME = "pkg.apk"; 13812 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13813 13814 String cid; 13815 String packagePath; 13816 String resourcePath; 13817 13818 /** New install */ 13819 AsecInstallArgs(InstallParams params) { 13820 super(params.origin, params.move, params.observer, params.installFlags, 13821 params.installerPackageName, params.volumeUuid, 13822 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13823 params.grantedRuntimePermissions, 13824 params.traceMethod, params.traceCookie, params.certificates); 13825 } 13826 13827 /** Existing install */ 13828 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13829 boolean isExternal, boolean isForwardLocked) { 13830 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13831 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13832 instructionSets, null, null, null, 0, null /*certificates*/); 13833 // Hackily pretend we're still looking at a full code path 13834 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13835 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13836 } 13837 13838 // Extract cid from fullCodePath 13839 int eidx = fullCodePath.lastIndexOf("/"); 13840 String subStr1 = fullCodePath.substring(0, eidx); 13841 int sidx = subStr1.lastIndexOf("/"); 13842 cid = subStr1.substring(sidx+1, eidx); 13843 setMountPath(subStr1); 13844 } 13845 13846 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13847 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13848 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13849 instructionSets, null, null, null, 0, null /*certificates*/); 13850 this.cid = cid; 13851 setMountPath(PackageHelper.getSdDir(cid)); 13852 } 13853 13854 void createCopyFile() { 13855 cid = mInstallerService.allocateExternalStageCidLegacy(); 13856 } 13857 13858 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13859 if (origin.staged && origin.cid != null) { 13860 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13861 cid = origin.cid; 13862 setMountPath(PackageHelper.getSdDir(cid)); 13863 return PackageManager.INSTALL_SUCCEEDED; 13864 } 13865 13866 if (temp) { 13867 createCopyFile(); 13868 } else { 13869 /* 13870 * Pre-emptively destroy the container since it's destroyed if 13871 * copying fails due to it existing anyway. 13872 */ 13873 PackageHelper.destroySdDir(cid); 13874 } 13875 13876 final String newMountPath = imcs.copyPackageToContainer( 13877 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13878 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13879 13880 if (newMountPath != null) { 13881 setMountPath(newMountPath); 13882 return PackageManager.INSTALL_SUCCEEDED; 13883 } else { 13884 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13885 } 13886 } 13887 13888 @Override 13889 String getCodePath() { 13890 return packagePath; 13891 } 13892 13893 @Override 13894 String getResourcePath() { 13895 return resourcePath; 13896 } 13897 13898 int doPreInstall(int status) { 13899 if (status != PackageManager.INSTALL_SUCCEEDED) { 13900 // Destroy container 13901 PackageHelper.destroySdDir(cid); 13902 } else { 13903 boolean mounted = PackageHelper.isContainerMounted(cid); 13904 if (!mounted) { 13905 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13906 Process.SYSTEM_UID); 13907 if (newMountPath != null) { 13908 setMountPath(newMountPath); 13909 } else { 13910 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13911 } 13912 } 13913 } 13914 return status; 13915 } 13916 13917 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13918 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13919 String newMountPath = null; 13920 if (PackageHelper.isContainerMounted(cid)) { 13921 // Unmount the container 13922 if (!PackageHelper.unMountSdDir(cid)) { 13923 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13924 return false; 13925 } 13926 } 13927 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13928 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13929 " which might be stale. Will try to clean up."); 13930 // Clean up the stale container and proceed to recreate. 13931 if (!PackageHelper.destroySdDir(newCacheId)) { 13932 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13933 return false; 13934 } 13935 // Successfully cleaned up stale container. Try to rename again. 13936 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13937 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13938 + " inspite of cleaning it up."); 13939 return false; 13940 } 13941 } 13942 if (!PackageHelper.isContainerMounted(newCacheId)) { 13943 Slog.w(TAG, "Mounting container " + newCacheId); 13944 newMountPath = PackageHelper.mountSdDir(newCacheId, 13945 getEncryptKey(), Process.SYSTEM_UID); 13946 } else { 13947 newMountPath = PackageHelper.getSdDir(newCacheId); 13948 } 13949 if (newMountPath == null) { 13950 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13951 return false; 13952 } 13953 Log.i(TAG, "Succesfully renamed " + cid + 13954 " to " + newCacheId + 13955 " at new path: " + newMountPath); 13956 cid = newCacheId; 13957 13958 final File beforeCodeFile = new File(packagePath); 13959 setMountPath(newMountPath); 13960 final File afterCodeFile = new File(packagePath); 13961 13962 // Reflect the rename in scanned details 13963 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13964 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13965 afterCodeFile, pkg.baseCodePath)); 13966 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13967 afterCodeFile, pkg.splitCodePaths)); 13968 13969 // Reflect the rename in app info 13970 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13971 pkg.setApplicationInfoCodePath(pkg.codePath); 13972 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13973 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13974 pkg.setApplicationInfoResourcePath(pkg.codePath); 13975 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13976 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13977 13978 return true; 13979 } 13980 13981 private void setMountPath(String mountPath) { 13982 final File mountFile = new File(mountPath); 13983 13984 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13985 if (monolithicFile.exists()) { 13986 packagePath = monolithicFile.getAbsolutePath(); 13987 if (isFwdLocked()) { 13988 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13989 } else { 13990 resourcePath = packagePath; 13991 } 13992 } else { 13993 packagePath = mountFile.getAbsolutePath(); 13994 resourcePath = packagePath; 13995 } 13996 } 13997 13998 int doPostInstall(int status, int uid) { 13999 if (status != PackageManager.INSTALL_SUCCEEDED) { 14000 cleanUp(); 14001 } else { 14002 final int groupOwner; 14003 final String protectedFile; 14004 if (isFwdLocked()) { 14005 groupOwner = UserHandle.getSharedAppGid(uid); 14006 protectedFile = RES_FILE_NAME; 14007 } else { 14008 groupOwner = -1; 14009 protectedFile = null; 14010 } 14011 14012 if (uid < Process.FIRST_APPLICATION_UID 14013 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14014 Slog.e(TAG, "Failed to finalize " + cid); 14015 PackageHelper.destroySdDir(cid); 14016 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14017 } 14018 14019 boolean mounted = PackageHelper.isContainerMounted(cid); 14020 if (!mounted) { 14021 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14022 } 14023 } 14024 return status; 14025 } 14026 14027 private void cleanUp() { 14028 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14029 14030 // Destroy secure container 14031 PackageHelper.destroySdDir(cid); 14032 } 14033 14034 private List<String> getAllCodePaths() { 14035 final File codeFile = new File(getCodePath()); 14036 if (codeFile != null && codeFile.exists()) { 14037 try { 14038 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14039 return pkg.getAllCodePaths(); 14040 } catch (PackageParserException e) { 14041 // Ignored; we tried our best 14042 } 14043 } 14044 return Collections.EMPTY_LIST; 14045 } 14046 14047 void cleanUpResourcesLI() { 14048 // Enumerate all code paths before deleting 14049 cleanUpResourcesLI(getAllCodePaths()); 14050 } 14051 14052 private void cleanUpResourcesLI(List<String> allCodePaths) { 14053 cleanUp(); 14054 removeDexFiles(allCodePaths, instructionSets); 14055 } 14056 14057 String getPackageName() { 14058 return getAsecPackageName(cid); 14059 } 14060 14061 boolean doPostDeleteLI(boolean delete) { 14062 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14063 final List<String> allCodePaths = getAllCodePaths(); 14064 boolean mounted = PackageHelper.isContainerMounted(cid); 14065 if (mounted) { 14066 // Unmount first 14067 if (PackageHelper.unMountSdDir(cid)) { 14068 mounted = false; 14069 } 14070 } 14071 if (!mounted && delete) { 14072 cleanUpResourcesLI(allCodePaths); 14073 } 14074 return !mounted; 14075 } 14076 14077 @Override 14078 int doPreCopy() { 14079 if (isFwdLocked()) { 14080 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14081 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14082 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14083 } 14084 } 14085 14086 return PackageManager.INSTALL_SUCCEEDED; 14087 } 14088 14089 @Override 14090 int doPostCopy(int uid) { 14091 if (isFwdLocked()) { 14092 if (uid < Process.FIRST_APPLICATION_UID 14093 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14094 RES_FILE_NAME)) { 14095 Slog.e(TAG, "Failed to finalize " + cid); 14096 PackageHelper.destroySdDir(cid); 14097 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14098 } 14099 } 14100 14101 return PackageManager.INSTALL_SUCCEEDED; 14102 } 14103 } 14104 14105 /** 14106 * Logic to handle movement of existing installed applications. 14107 */ 14108 class MoveInstallArgs extends InstallArgs { 14109 private File codeFile; 14110 private File resourceFile; 14111 14112 /** New install */ 14113 MoveInstallArgs(InstallParams params) { 14114 super(params.origin, params.move, params.observer, params.installFlags, 14115 params.installerPackageName, params.volumeUuid, 14116 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14117 params.grantedRuntimePermissions, 14118 params.traceMethod, params.traceCookie, params.certificates); 14119 } 14120 14121 int copyApk(IMediaContainerService imcs, boolean temp) { 14122 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14123 + move.fromUuid + " to " + move.toUuid); 14124 synchronized (mInstaller) { 14125 try { 14126 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14127 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14128 } catch (InstallerException e) { 14129 Slog.w(TAG, "Failed to move app", e); 14130 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14131 } 14132 } 14133 14134 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14135 resourceFile = codeFile; 14136 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14137 14138 return PackageManager.INSTALL_SUCCEEDED; 14139 } 14140 14141 int doPreInstall(int status) { 14142 if (status != PackageManager.INSTALL_SUCCEEDED) { 14143 cleanUp(move.toUuid); 14144 } 14145 return status; 14146 } 14147 14148 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14149 if (status != PackageManager.INSTALL_SUCCEEDED) { 14150 cleanUp(move.toUuid); 14151 return false; 14152 } 14153 14154 // Reflect the move in app info 14155 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14156 pkg.setApplicationInfoCodePath(pkg.codePath); 14157 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14158 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14159 pkg.setApplicationInfoResourcePath(pkg.codePath); 14160 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14161 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14162 14163 return true; 14164 } 14165 14166 int doPostInstall(int status, int uid) { 14167 if (status == PackageManager.INSTALL_SUCCEEDED) { 14168 cleanUp(move.fromUuid); 14169 } else { 14170 cleanUp(move.toUuid); 14171 } 14172 return status; 14173 } 14174 14175 @Override 14176 String getCodePath() { 14177 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14178 } 14179 14180 @Override 14181 String getResourcePath() { 14182 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14183 } 14184 14185 private boolean cleanUp(String volumeUuid) { 14186 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14187 move.dataAppName); 14188 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14189 final int[] userIds = sUserManager.getUserIds(); 14190 synchronized (mInstallLock) { 14191 // Clean up both app data and code 14192 // All package moves are frozen until finished 14193 for (int userId : userIds) { 14194 try { 14195 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14196 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14197 } catch (InstallerException e) { 14198 Slog.w(TAG, String.valueOf(e)); 14199 } 14200 } 14201 removeCodePathLI(codeFile); 14202 } 14203 return true; 14204 } 14205 14206 void cleanUpResourcesLI() { 14207 throw new UnsupportedOperationException(); 14208 } 14209 14210 boolean doPostDeleteLI(boolean delete) { 14211 throw new UnsupportedOperationException(); 14212 } 14213 } 14214 14215 static String getAsecPackageName(String packageCid) { 14216 int idx = packageCid.lastIndexOf("-"); 14217 if (idx == -1) { 14218 return packageCid; 14219 } 14220 return packageCid.substring(0, idx); 14221 } 14222 14223 // Utility method used to create code paths based on package name and available index. 14224 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14225 String idxStr = ""; 14226 int idx = 1; 14227 // Fall back to default value of idx=1 if prefix is not 14228 // part of oldCodePath 14229 if (oldCodePath != null) { 14230 String subStr = oldCodePath; 14231 // Drop the suffix right away 14232 if (suffix != null && subStr.endsWith(suffix)) { 14233 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14234 } 14235 // If oldCodePath already contains prefix find out the 14236 // ending index to either increment or decrement. 14237 int sidx = subStr.lastIndexOf(prefix); 14238 if (sidx != -1) { 14239 subStr = subStr.substring(sidx + prefix.length()); 14240 if (subStr != null) { 14241 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14242 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14243 } 14244 try { 14245 idx = Integer.parseInt(subStr); 14246 if (idx <= 1) { 14247 idx++; 14248 } else { 14249 idx--; 14250 } 14251 } catch(NumberFormatException e) { 14252 } 14253 } 14254 } 14255 } 14256 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14257 return prefix + idxStr; 14258 } 14259 14260 private File getNextCodePath(File targetDir, String packageName) { 14261 int suffix = 1; 14262 File result; 14263 do { 14264 result = new File(targetDir, packageName + "-" + suffix); 14265 suffix++; 14266 } while (result.exists()); 14267 return result; 14268 } 14269 14270 // Utility method that returns the relative package path with respect 14271 // to the installation directory. Like say for /data/data/com.test-1.apk 14272 // string com.test-1 is returned. 14273 static String deriveCodePathName(String codePath) { 14274 if (codePath == null) { 14275 return null; 14276 } 14277 final File codeFile = new File(codePath); 14278 final String name = codeFile.getName(); 14279 if (codeFile.isDirectory()) { 14280 return name; 14281 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14282 final int lastDot = name.lastIndexOf('.'); 14283 return name.substring(0, lastDot); 14284 } else { 14285 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14286 return null; 14287 } 14288 } 14289 14290 static class PackageInstalledInfo { 14291 String name; 14292 int uid; 14293 // The set of users that originally had this package installed. 14294 int[] origUsers; 14295 // The set of users that now have this package installed. 14296 int[] newUsers; 14297 PackageParser.Package pkg; 14298 int returnCode; 14299 String returnMsg; 14300 PackageRemovedInfo removedInfo; 14301 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14302 14303 public void setError(int code, String msg) { 14304 setReturnCode(code); 14305 setReturnMessage(msg); 14306 Slog.w(TAG, msg); 14307 } 14308 14309 public void setError(String msg, PackageParserException e) { 14310 setReturnCode(e.error); 14311 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14312 Slog.w(TAG, msg, e); 14313 } 14314 14315 public void setError(String msg, PackageManagerException e) { 14316 returnCode = e.error; 14317 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14318 Slog.w(TAG, msg, e); 14319 } 14320 14321 public void setReturnCode(int returnCode) { 14322 this.returnCode = returnCode; 14323 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14324 for (int i = 0; i < childCount; i++) { 14325 addedChildPackages.valueAt(i).returnCode = returnCode; 14326 } 14327 } 14328 14329 private void setReturnMessage(String returnMsg) { 14330 this.returnMsg = returnMsg; 14331 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14332 for (int i = 0; i < childCount; i++) { 14333 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14334 } 14335 } 14336 14337 // In some error cases we want to convey more info back to the observer 14338 String origPackage; 14339 String origPermission; 14340 } 14341 14342 /* 14343 * Install a non-existing package. 14344 */ 14345 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14346 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14347 PackageInstalledInfo res) { 14348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14349 14350 // Remember this for later, in case we need to rollback this install 14351 String pkgName = pkg.packageName; 14352 14353 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14354 14355 synchronized(mPackages) { 14356 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14357 if (renamedPackage != null) { 14358 // A package with the same name is already installed, though 14359 // it has been renamed to an older name. The package we 14360 // are trying to install should be installed as an update to 14361 // the existing one, but that has not been requested, so bail. 14362 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14363 + " without first uninstalling package running as " 14364 + renamedPackage); 14365 return; 14366 } 14367 if (mPackages.containsKey(pkgName)) { 14368 // Don't allow installation over an existing package with the same name. 14369 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14370 + " without first uninstalling."); 14371 return; 14372 } 14373 } 14374 14375 try { 14376 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14377 System.currentTimeMillis(), user); 14378 14379 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14380 14381 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14382 prepareAppDataAfterInstallLIF(newPackage); 14383 14384 } else { 14385 // Remove package from internal structures, but keep around any 14386 // data that might have already existed 14387 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14388 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14389 } 14390 } catch (PackageManagerException e) { 14391 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14392 } 14393 14394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14395 } 14396 14397 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14398 // Can't rotate keys during boot or if sharedUser. 14399 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14400 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14401 return false; 14402 } 14403 // app is using upgradeKeySets; make sure all are valid 14404 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14405 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14406 for (int i = 0; i < upgradeKeySets.length; i++) { 14407 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14408 Slog.wtf(TAG, "Package " 14409 + (oldPs.name != null ? oldPs.name : "<null>") 14410 + " contains upgrade-key-set reference to unknown key-set: " 14411 + upgradeKeySets[i] 14412 + " reverting to signatures check."); 14413 return false; 14414 } 14415 } 14416 return true; 14417 } 14418 14419 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14420 // Upgrade keysets are being used. Determine if new package has a superset of the 14421 // required keys. 14422 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14423 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14424 for (int i = 0; i < upgradeKeySets.length; i++) { 14425 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14426 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14427 return true; 14428 } 14429 } 14430 return false; 14431 } 14432 14433 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14434 try (DigestInputStream digestStream = 14435 new DigestInputStream(new FileInputStream(file), digest)) { 14436 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14437 } 14438 } 14439 14440 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14441 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14442 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14443 14444 final PackageParser.Package oldPackage; 14445 final String pkgName = pkg.packageName; 14446 final int[] allUsers; 14447 final int[] installedUsers; 14448 14449 synchronized(mPackages) { 14450 oldPackage = mPackages.get(pkgName); 14451 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14452 14453 // don't allow upgrade to target a release SDK from a pre-release SDK 14454 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14455 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14456 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14457 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14458 if (oldTargetsPreRelease 14459 && !newTargetsPreRelease 14460 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14461 Slog.w(TAG, "Can't install package targeting released sdk"); 14462 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14463 return; 14464 } 14465 14466 // don't allow an upgrade from full to ephemeral 14467 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14468 if (isEphemeral && !oldIsEphemeral) { 14469 // can't downgrade from full to ephemeral 14470 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14471 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14472 return; 14473 } 14474 14475 // verify signatures are valid 14476 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14477 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14478 if (!checkUpgradeKeySetLP(ps, pkg)) { 14479 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14480 "New package not signed by keys specified by upgrade-keysets: " 14481 + pkgName); 14482 return; 14483 } 14484 } else { 14485 // default to original signature matching 14486 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14487 != PackageManager.SIGNATURE_MATCH) { 14488 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14489 "New package has a different signature: " + pkgName); 14490 return; 14491 } 14492 } 14493 14494 // don't allow a system upgrade unless the upgrade hash matches 14495 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14496 byte[] digestBytes = null; 14497 try { 14498 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14499 updateDigest(digest, new File(pkg.baseCodePath)); 14500 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14501 for (String path : pkg.splitCodePaths) { 14502 updateDigest(digest, new File(path)); 14503 } 14504 } 14505 digestBytes = digest.digest(); 14506 } catch (NoSuchAlgorithmException | IOException e) { 14507 res.setError(INSTALL_FAILED_INVALID_APK, 14508 "Could not compute hash: " + pkgName); 14509 return; 14510 } 14511 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14512 res.setError(INSTALL_FAILED_INVALID_APK, 14513 "New package fails restrict-update check: " + pkgName); 14514 return; 14515 } 14516 // retain upgrade restriction 14517 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14518 } 14519 14520 // Check for shared user id changes 14521 String invalidPackageName = 14522 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14523 if (invalidPackageName != null) { 14524 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14525 "Package " + invalidPackageName + " tried to change user " 14526 + oldPackage.mSharedUserId); 14527 return; 14528 } 14529 14530 // In case of rollback, remember per-user/profile install state 14531 allUsers = sUserManager.getUserIds(); 14532 installedUsers = ps.queryInstalledUsers(allUsers, true); 14533 } 14534 14535 // Update what is removed 14536 res.removedInfo = new PackageRemovedInfo(); 14537 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14538 res.removedInfo.removedPackage = oldPackage.packageName; 14539 res.removedInfo.isUpdate = true; 14540 res.removedInfo.origUsers = installedUsers; 14541 final int childCount = (oldPackage.childPackages != null) 14542 ? oldPackage.childPackages.size() : 0; 14543 for (int i = 0; i < childCount; i++) { 14544 boolean childPackageUpdated = false; 14545 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14546 if (res.addedChildPackages != null) { 14547 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14548 if (childRes != null) { 14549 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14550 childRes.removedInfo.removedPackage = childPkg.packageName; 14551 childRes.removedInfo.isUpdate = true; 14552 childPackageUpdated = true; 14553 } 14554 } 14555 if (!childPackageUpdated) { 14556 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14557 childRemovedRes.removedPackage = childPkg.packageName; 14558 childRemovedRes.isUpdate = false; 14559 childRemovedRes.dataRemoved = true; 14560 synchronized (mPackages) { 14561 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14562 if (childPs != null) { 14563 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14564 } 14565 } 14566 if (res.removedInfo.removedChildPackages == null) { 14567 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14568 } 14569 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14570 } 14571 } 14572 14573 boolean sysPkg = (isSystemApp(oldPackage)); 14574 if (sysPkg) { 14575 // Set the system/privileged flags as needed 14576 final boolean privileged = 14577 (oldPackage.applicationInfo.privateFlags 14578 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14579 final int systemPolicyFlags = policyFlags 14580 | PackageParser.PARSE_IS_SYSTEM 14581 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14582 14583 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14584 user, allUsers, installerPackageName, res); 14585 } else { 14586 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14587 user, allUsers, installerPackageName, res); 14588 } 14589 } 14590 14591 public List<String> getPreviousCodePaths(String packageName) { 14592 final PackageSetting ps = mSettings.mPackages.get(packageName); 14593 final List<String> result = new ArrayList<String>(); 14594 if (ps != null && ps.oldCodePaths != null) { 14595 result.addAll(ps.oldCodePaths); 14596 } 14597 return result; 14598 } 14599 14600 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14601 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14602 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14603 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14604 + deletedPackage); 14605 14606 String pkgName = deletedPackage.packageName; 14607 boolean deletedPkg = true; 14608 boolean addedPkg = false; 14609 boolean updatedSettings = false; 14610 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14611 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14612 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14613 14614 final long origUpdateTime = (pkg.mExtras != null) 14615 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14616 14617 // First delete the existing package while retaining the data directory 14618 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14619 res.removedInfo, true, pkg)) { 14620 // If the existing package wasn't successfully deleted 14621 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14622 deletedPkg = false; 14623 } else { 14624 // Successfully deleted the old package; proceed with replace. 14625 14626 // If deleted package lived in a container, give users a chance to 14627 // relinquish resources before killing. 14628 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14629 if (DEBUG_INSTALL) { 14630 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14631 } 14632 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14633 final ArrayList<String> pkgList = new ArrayList<String>(1); 14634 pkgList.add(deletedPackage.applicationInfo.packageName); 14635 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14636 } 14637 14638 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14639 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14640 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14641 14642 try { 14643 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14644 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14645 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14646 14647 // Update the in-memory copy of the previous code paths. 14648 PackageSetting ps = mSettings.mPackages.get(pkgName); 14649 if (!killApp) { 14650 if (ps.oldCodePaths == null) { 14651 ps.oldCodePaths = new ArraySet<>(); 14652 } 14653 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14654 if (deletedPackage.splitCodePaths != null) { 14655 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14656 } 14657 } else { 14658 ps.oldCodePaths = null; 14659 } 14660 if (ps.childPackageNames != null) { 14661 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14662 final String childPkgName = ps.childPackageNames.get(i); 14663 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14664 childPs.oldCodePaths = ps.oldCodePaths; 14665 } 14666 } 14667 prepareAppDataAfterInstallLIF(newPackage); 14668 addedPkg = true; 14669 } catch (PackageManagerException e) { 14670 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14671 } 14672 } 14673 14674 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14675 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14676 14677 // Revert all internal state mutations and added folders for the failed install 14678 if (addedPkg) { 14679 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14680 res.removedInfo, true, null); 14681 } 14682 14683 // Restore the old package 14684 if (deletedPkg) { 14685 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14686 File restoreFile = new File(deletedPackage.codePath); 14687 // Parse old package 14688 boolean oldExternal = isExternal(deletedPackage); 14689 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14690 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14691 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14692 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14693 try { 14694 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14695 null); 14696 } catch (PackageManagerException e) { 14697 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14698 + e.getMessage()); 14699 return; 14700 } 14701 14702 synchronized (mPackages) { 14703 // Ensure the installer package name up to date 14704 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14705 14706 // Update permissions for restored package 14707 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14708 14709 mSettings.writeLPr(); 14710 } 14711 14712 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14713 } 14714 } else { 14715 synchronized (mPackages) { 14716 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 14717 if (ps != null) { 14718 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14719 if (res.removedInfo.removedChildPackages != null) { 14720 final int childCount = res.removedInfo.removedChildPackages.size(); 14721 // Iterate in reverse as we may modify the collection 14722 for (int i = childCount - 1; i >= 0; i--) { 14723 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14724 if (res.addedChildPackages.containsKey(childPackageName)) { 14725 res.removedInfo.removedChildPackages.removeAt(i); 14726 } else { 14727 PackageRemovedInfo childInfo = res.removedInfo 14728 .removedChildPackages.valueAt(i); 14729 childInfo.removedForAllUsers = mPackages.get( 14730 childInfo.removedPackage) == null; 14731 } 14732 } 14733 } 14734 } 14735 } 14736 } 14737 } 14738 14739 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14740 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14741 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14742 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14743 + ", old=" + deletedPackage); 14744 14745 final boolean disabledSystem; 14746 14747 // Remove existing system package 14748 removePackageLI(deletedPackage, true); 14749 14750 synchronized (mPackages) { 14751 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14752 } 14753 if (!disabledSystem) { 14754 // We didn't need to disable the .apk as a current system package, 14755 // which means we are replacing another update that is already 14756 // installed. We need to make sure to delete the older one's .apk. 14757 res.removedInfo.args = createInstallArgsForExisting(0, 14758 deletedPackage.applicationInfo.getCodePath(), 14759 deletedPackage.applicationInfo.getResourcePath(), 14760 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14761 } else { 14762 res.removedInfo.args = null; 14763 } 14764 14765 // Successfully disabled the old package. Now proceed with re-installation 14766 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14767 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14768 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14769 14770 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14771 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14772 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14773 14774 PackageParser.Package newPackage = null; 14775 try { 14776 // Add the package to the internal data structures 14777 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14778 14779 // Set the update and install times 14780 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14781 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14782 System.currentTimeMillis()); 14783 14784 // Update the package dynamic state if succeeded 14785 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14786 // Now that the install succeeded make sure we remove data 14787 // directories for any child package the update removed. 14788 final int deletedChildCount = (deletedPackage.childPackages != null) 14789 ? deletedPackage.childPackages.size() : 0; 14790 final int newChildCount = (newPackage.childPackages != null) 14791 ? newPackage.childPackages.size() : 0; 14792 for (int i = 0; i < deletedChildCount; i++) { 14793 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14794 boolean childPackageDeleted = true; 14795 for (int j = 0; j < newChildCount; j++) { 14796 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14797 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14798 childPackageDeleted = false; 14799 break; 14800 } 14801 } 14802 if (childPackageDeleted) { 14803 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14804 deletedChildPkg.packageName); 14805 if (ps != null && res.removedInfo.removedChildPackages != null) { 14806 PackageRemovedInfo removedChildRes = res.removedInfo 14807 .removedChildPackages.get(deletedChildPkg.packageName); 14808 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14809 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14810 } 14811 } 14812 } 14813 14814 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14815 prepareAppDataAfterInstallLIF(newPackage); 14816 } 14817 } catch (PackageManagerException e) { 14818 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14819 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14820 } 14821 14822 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14823 // Re installation failed. Restore old information 14824 // Remove new pkg information 14825 if (newPackage != null) { 14826 removeInstalledPackageLI(newPackage, true); 14827 } 14828 // Add back the old system package 14829 try { 14830 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14831 } catch (PackageManagerException e) { 14832 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14833 } 14834 14835 synchronized (mPackages) { 14836 if (disabledSystem) { 14837 enableSystemPackageLPw(deletedPackage); 14838 } 14839 14840 // Ensure the installer package name up to date 14841 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14842 14843 // Update permissions for restored package 14844 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14845 14846 mSettings.writeLPr(); 14847 } 14848 14849 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14850 + " after failed upgrade"); 14851 } 14852 } 14853 14854 /** 14855 * Checks whether the parent or any of the child packages have a change shared 14856 * user. For a package to be a valid update the shred users of the parent and 14857 * the children should match. We may later support changing child shared users. 14858 * @param oldPkg The updated package. 14859 * @param newPkg The update package. 14860 * @return The shared user that change between the versions. 14861 */ 14862 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14863 PackageParser.Package newPkg) { 14864 // Check parent shared user 14865 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14866 return newPkg.packageName; 14867 } 14868 // Check child shared users 14869 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14870 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14871 for (int i = 0; i < newChildCount; i++) { 14872 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14873 // If this child was present, did it have the same shared user? 14874 for (int j = 0; j < oldChildCount; j++) { 14875 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14876 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14877 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14878 return newChildPkg.packageName; 14879 } 14880 } 14881 } 14882 return null; 14883 } 14884 14885 private void removeNativeBinariesLI(PackageSetting ps) { 14886 // Remove the lib path for the parent package 14887 if (ps != null) { 14888 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14889 // Remove the lib path for the child packages 14890 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14891 for (int i = 0; i < childCount; i++) { 14892 PackageSetting childPs = null; 14893 synchronized (mPackages) { 14894 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 14895 } 14896 if (childPs != null) { 14897 NativeLibraryHelper.removeNativeBinariesLI(childPs 14898 .legacyNativeLibraryPathString); 14899 } 14900 } 14901 } 14902 } 14903 14904 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14905 // Enable the parent package 14906 mSettings.enableSystemPackageLPw(pkg.packageName); 14907 // Enable the child packages 14908 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14909 for (int i = 0; i < childCount; i++) { 14910 PackageParser.Package childPkg = pkg.childPackages.get(i); 14911 mSettings.enableSystemPackageLPw(childPkg.packageName); 14912 } 14913 } 14914 14915 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14916 PackageParser.Package newPkg) { 14917 // Disable the parent package (parent always replaced) 14918 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14919 // Disable the child packages 14920 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14921 for (int i = 0; i < childCount; i++) { 14922 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14923 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14924 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14925 } 14926 return disabled; 14927 } 14928 14929 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14930 String installerPackageName) { 14931 // Enable the parent package 14932 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14933 // Enable the child packages 14934 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14935 for (int i = 0; i < childCount; i++) { 14936 PackageParser.Package childPkg = pkg.childPackages.get(i); 14937 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14938 } 14939 } 14940 14941 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14942 // Collect all used permissions in the UID 14943 ArraySet<String> usedPermissions = new ArraySet<>(); 14944 final int packageCount = su.packages.size(); 14945 for (int i = 0; i < packageCount; i++) { 14946 PackageSetting ps = su.packages.valueAt(i); 14947 if (ps.pkg == null) { 14948 continue; 14949 } 14950 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14951 for (int j = 0; j < requestedPermCount; j++) { 14952 String permission = ps.pkg.requestedPermissions.get(j); 14953 BasePermission bp = mSettings.mPermissions.get(permission); 14954 if (bp != null) { 14955 usedPermissions.add(permission); 14956 } 14957 } 14958 } 14959 14960 PermissionsState permissionsState = su.getPermissionsState(); 14961 // Prune install permissions 14962 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14963 final int installPermCount = installPermStates.size(); 14964 for (int i = installPermCount - 1; i >= 0; i--) { 14965 PermissionState permissionState = installPermStates.get(i); 14966 if (!usedPermissions.contains(permissionState.getName())) { 14967 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14968 if (bp != null) { 14969 permissionsState.revokeInstallPermission(bp); 14970 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14971 PackageManager.MASK_PERMISSION_FLAGS, 0); 14972 } 14973 } 14974 } 14975 14976 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14977 14978 // Prune runtime permissions 14979 for (int userId : allUserIds) { 14980 List<PermissionState> runtimePermStates = permissionsState 14981 .getRuntimePermissionStates(userId); 14982 final int runtimePermCount = runtimePermStates.size(); 14983 for (int i = runtimePermCount - 1; i >= 0; i--) { 14984 PermissionState permissionState = runtimePermStates.get(i); 14985 if (!usedPermissions.contains(permissionState.getName())) { 14986 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14987 if (bp != null) { 14988 permissionsState.revokeRuntimePermission(bp, userId); 14989 permissionsState.updatePermissionFlags(bp, userId, 14990 PackageManager.MASK_PERMISSION_FLAGS, 0); 14991 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14992 runtimePermissionChangedUserIds, userId); 14993 } 14994 } 14995 } 14996 } 14997 14998 return runtimePermissionChangedUserIds; 14999 } 15000 15001 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15002 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15003 // Update the parent package setting 15004 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15005 res, user); 15006 // Update the child packages setting 15007 final int childCount = (newPackage.childPackages != null) 15008 ? newPackage.childPackages.size() : 0; 15009 for (int i = 0; i < childCount; i++) { 15010 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15011 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15012 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15013 childRes.origUsers, childRes, user); 15014 } 15015 } 15016 15017 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15018 String installerPackageName, int[] allUsers, int[] installedForUsers, 15019 PackageInstalledInfo res, UserHandle user) { 15020 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15021 15022 String pkgName = newPackage.packageName; 15023 synchronized (mPackages) { 15024 //write settings. the installStatus will be incomplete at this stage. 15025 //note that the new package setting would have already been 15026 //added to mPackages. It hasn't been persisted yet. 15027 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15028 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15029 mSettings.writeLPr(); 15030 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15031 } 15032 15033 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15034 synchronized (mPackages) { 15035 updatePermissionsLPw(newPackage.packageName, newPackage, 15036 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15037 ? UPDATE_PERMISSIONS_ALL : 0)); 15038 // For system-bundled packages, we assume that installing an upgraded version 15039 // of the package implies that the user actually wants to run that new code, 15040 // so we enable the package. 15041 PackageSetting ps = mSettings.mPackages.get(pkgName); 15042 final int userId = user.getIdentifier(); 15043 if (ps != null) { 15044 if (isSystemApp(newPackage)) { 15045 if (DEBUG_INSTALL) { 15046 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15047 } 15048 // Enable system package for requested users 15049 if (res.origUsers != null) { 15050 for (int origUserId : res.origUsers) { 15051 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15052 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15053 origUserId, installerPackageName); 15054 } 15055 } 15056 } 15057 // Also convey the prior install/uninstall state 15058 if (allUsers != null && installedForUsers != null) { 15059 for (int currentUserId : allUsers) { 15060 final boolean installed = ArrayUtils.contains( 15061 installedForUsers, currentUserId); 15062 if (DEBUG_INSTALL) { 15063 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15064 } 15065 ps.setInstalled(installed, currentUserId); 15066 } 15067 // these install state changes will be persisted in the 15068 // upcoming call to mSettings.writeLPr(). 15069 } 15070 } 15071 // It's implied that when a user requests installation, they want the app to be 15072 // installed and enabled. 15073 if (userId != UserHandle.USER_ALL) { 15074 ps.setInstalled(true, userId); 15075 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15076 } 15077 } 15078 res.name = pkgName; 15079 res.uid = newPackage.applicationInfo.uid; 15080 res.pkg = newPackage; 15081 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15082 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15083 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15084 //to update install status 15085 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15086 mSettings.writeLPr(); 15087 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15088 } 15089 15090 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15091 } 15092 15093 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15094 try { 15095 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15096 installPackageLI(args, res); 15097 } finally { 15098 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15099 } 15100 } 15101 15102 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15103 final int installFlags = args.installFlags; 15104 final String installerPackageName = args.installerPackageName; 15105 final String volumeUuid = args.volumeUuid; 15106 final File tmpPackageFile = new File(args.getCodePath()); 15107 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15108 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15109 || (args.volumeUuid != null)); 15110 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15111 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15112 boolean replace = false; 15113 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15114 if (args.move != null) { 15115 // moving a complete application; perform an initial scan on the new install location 15116 scanFlags |= SCAN_INITIAL; 15117 } 15118 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15119 scanFlags |= SCAN_DONT_KILL_APP; 15120 } 15121 15122 // Result object to be returned 15123 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15124 15125 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15126 15127 // Sanity check 15128 if (ephemeral && (forwardLocked || onExternal)) { 15129 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15130 + " external=" + onExternal); 15131 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15132 return; 15133 } 15134 15135 // Retrieve PackageSettings and parse package 15136 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15137 | PackageParser.PARSE_ENFORCE_CODE 15138 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15139 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15140 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15141 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15142 PackageParser pp = new PackageParser(); 15143 pp.setSeparateProcesses(mSeparateProcesses); 15144 pp.setDisplayMetrics(mMetrics); 15145 15146 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15147 final PackageParser.Package pkg; 15148 try { 15149 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15150 } catch (PackageParserException e) { 15151 res.setError("Failed parse during installPackageLI", e); 15152 return; 15153 } finally { 15154 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15155 } 15156 15157 // If we are installing a clustered package add results for the children 15158 if (pkg.childPackages != null) { 15159 synchronized (mPackages) { 15160 final int childCount = pkg.childPackages.size(); 15161 for (int i = 0; i < childCount; i++) { 15162 PackageParser.Package childPkg = pkg.childPackages.get(i); 15163 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15164 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15165 childRes.pkg = childPkg; 15166 childRes.name = childPkg.packageName; 15167 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15168 if (childPs != null) { 15169 childRes.origUsers = childPs.queryInstalledUsers( 15170 sUserManager.getUserIds(), true); 15171 } 15172 if ((mPackages.containsKey(childPkg.packageName))) { 15173 childRes.removedInfo = new PackageRemovedInfo(); 15174 childRes.removedInfo.removedPackage = childPkg.packageName; 15175 } 15176 if (res.addedChildPackages == null) { 15177 res.addedChildPackages = new ArrayMap<>(); 15178 } 15179 res.addedChildPackages.put(childPkg.packageName, childRes); 15180 } 15181 } 15182 } 15183 15184 // If package doesn't declare API override, mark that we have an install 15185 // time CPU ABI override. 15186 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15187 pkg.cpuAbiOverride = args.abiOverride; 15188 } 15189 15190 String pkgName = res.name = pkg.packageName; 15191 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15192 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15193 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15194 return; 15195 } 15196 } 15197 15198 try { 15199 // either use what we've been given or parse directly from the APK 15200 if (args.certificates != null) { 15201 try { 15202 PackageParser.populateCertificates(pkg, args.certificates); 15203 } catch (PackageParserException e) { 15204 // there was something wrong with the certificates we were given; 15205 // try to pull them from the APK 15206 PackageParser.collectCertificates(pkg, parseFlags); 15207 } 15208 } else { 15209 PackageParser.collectCertificates(pkg, parseFlags); 15210 } 15211 } catch (PackageParserException e) { 15212 res.setError("Failed collect during installPackageLI", e); 15213 return; 15214 } 15215 15216 // Get rid of all references to package scan path via parser. 15217 pp = null; 15218 String oldCodePath = null; 15219 boolean systemApp = false; 15220 synchronized (mPackages) { 15221 // Check if installing already existing package 15222 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15223 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15224 if (pkg.mOriginalPackages != null 15225 && pkg.mOriginalPackages.contains(oldName) 15226 && mPackages.containsKey(oldName)) { 15227 // This package is derived from an original package, 15228 // and this device has been updating from that original 15229 // name. We must continue using the original name, so 15230 // rename the new package here. 15231 pkg.setPackageName(oldName); 15232 pkgName = pkg.packageName; 15233 replace = true; 15234 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15235 + oldName + " pkgName=" + pkgName); 15236 } else if (mPackages.containsKey(pkgName)) { 15237 // This package, under its official name, already exists 15238 // on the device; we should replace it. 15239 replace = true; 15240 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15241 } 15242 15243 // Child packages are installed through the parent package 15244 if (pkg.parentPackage != null) { 15245 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15246 "Package " + pkg.packageName + " is child of package " 15247 + pkg.parentPackage.parentPackage + ". Child packages " 15248 + "can be updated only through the parent package."); 15249 return; 15250 } 15251 15252 if (replace) { 15253 // Prevent apps opting out from runtime permissions 15254 PackageParser.Package oldPackage = mPackages.get(pkgName); 15255 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15256 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15257 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15258 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15259 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15260 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15261 + " doesn't support runtime permissions but the old" 15262 + " target SDK " + oldTargetSdk + " does."); 15263 return; 15264 } 15265 15266 // Prevent installing of child packages 15267 if (oldPackage.parentPackage != null) { 15268 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15269 "Package " + pkg.packageName + " is child of package " 15270 + oldPackage.parentPackage + ". Child packages " 15271 + "can be updated only through the parent package."); 15272 return; 15273 } 15274 } 15275 } 15276 15277 PackageSetting ps = mSettings.mPackages.get(pkgName); 15278 if (ps != null) { 15279 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15280 15281 // Quick sanity check that we're signed correctly if updating; 15282 // we'll check this again later when scanning, but we want to 15283 // bail early here before tripping over redefined permissions. 15284 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15285 if (!checkUpgradeKeySetLP(ps, pkg)) { 15286 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15287 + pkg.packageName + " upgrade keys do not match the " 15288 + "previously installed version"); 15289 return; 15290 } 15291 } else { 15292 try { 15293 verifySignaturesLP(ps, pkg); 15294 } catch (PackageManagerException e) { 15295 res.setError(e.error, e.getMessage()); 15296 return; 15297 } 15298 } 15299 15300 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15301 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15302 systemApp = (ps.pkg.applicationInfo.flags & 15303 ApplicationInfo.FLAG_SYSTEM) != 0; 15304 } 15305 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15306 } 15307 15308 // Check whether the newly-scanned package wants to define an already-defined perm 15309 int N = pkg.permissions.size(); 15310 for (int i = N-1; i >= 0; i--) { 15311 PackageParser.Permission perm = pkg.permissions.get(i); 15312 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15313 if (bp != null) { 15314 // If the defining package is signed with our cert, it's okay. This 15315 // also includes the "updating the same package" case, of course. 15316 // "updating same package" could also involve key-rotation. 15317 final boolean sigsOk; 15318 if (bp.sourcePackage.equals(pkg.packageName) 15319 && (bp.packageSetting instanceof PackageSetting) 15320 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15321 scanFlags))) { 15322 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15323 } else { 15324 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15325 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15326 } 15327 if (!sigsOk) { 15328 // If the owning package is the system itself, we log but allow 15329 // install to proceed; we fail the install on all other permission 15330 // redefinitions. 15331 if (!bp.sourcePackage.equals("android")) { 15332 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15333 + pkg.packageName + " attempting to redeclare permission " 15334 + perm.info.name + " already owned by " + bp.sourcePackage); 15335 res.origPermission = perm.info.name; 15336 res.origPackage = bp.sourcePackage; 15337 return; 15338 } else { 15339 Slog.w(TAG, "Package " + pkg.packageName 15340 + " attempting to redeclare system permission " 15341 + perm.info.name + "; ignoring new declaration"); 15342 pkg.permissions.remove(i); 15343 } 15344 } 15345 } 15346 } 15347 } 15348 15349 if (systemApp) { 15350 if (onExternal) { 15351 // Abort update; system app can't be replaced with app on sdcard 15352 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15353 "Cannot install updates to system apps on sdcard"); 15354 return; 15355 } else if (ephemeral) { 15356 // Abort update; system app can't be replaced with an ephemeral app 15357 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15358 "Cannot update a system app with an ephemeral app"); 15359 return; 15360 } 15361 } 15362 15363 if (args.move != null) { 15364 // We did an in-place move, so dex is ready to roll 15365 scanFlags |= SCAN_NO_DEX; 15366 scanFlags |= SCAN_MOVE; 15367 15368 synchronized (mPackages) { 15369 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15370 if (ps == null) { 15371 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15372 "Missing settings for moved package " + pkgName); 15373 } 15374 15375 // We moved the entire application as-is, so bring over the 15376 // previously derived ABI information. 15377 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15378 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15379 } 15380 15381 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15382 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15383 scanFlags |= SCAN_NO_DEX; 15384 15385 try { 15386 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15387 args.abiOverride : pkg.cpuAbiOverride); 15388 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15389 true /*extractLibs*/, mAppLib32InstallDir); 15390 } catch (PackageManagerException pme) { 15391 Slog.e(TAG, "Error deriving application ABI", pme); 15392 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15393 return; 15394 } 15395 15396 // Shared libraries for the package need to be updated. 15397 synchronized (mPackages) { 15398 try { 15399 updateSharedLibrariesLPr(pkg, null); 15400 } catch (PackageManagerException e) { 15401 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15402 } 15403 } 15404 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15405 // Do not run PackageDexOptimizer through the local performDexOpt 15406 // method because `pkg` may not be in `mPackages` yet. 15407 // 15408 // Also, don't fail application installs if the dexopt step fails. 15409 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15410 null /* instructionSets */, false /* checkProfiles */, 15411 getCompilerFilterForReason(REASON_INSTALL), 15412 getOrCreateCompilerPackageStats(pkg)); 15413 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15414 15415 // Notify BackgroundDexOptService that the package has been changed. 15416 // If this is an update of a package which used to fail to compile, 15417 // BDOS will remove it from its blacklist. 15418 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15419 } 15420 15421 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15422 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15423 return; 15424 } 15425 15426 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15427 15428 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15429 "installPackageLI")) { 15430 if (replace) { 15431 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15432 installerPackageName, res); 15433 } else { 15434 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15435 args.user, installerPackageName, volumeUuid, res); 15436 } 15437 } 15438 synchronized (mPackages) { 15439 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15440 if (ps != null) { 15441 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15442 } 15443 15444 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15445 for (int i = 0; i < childCount; i++) { 15446 PackageParser.Package childPkg = pkg.childPackages.get(i); 15447 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15448 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15449 if (childPs != null) { 15450 childRes.newUsers = childPs.queryInstalledUsers( 15451 sUserManager.getUserIds(), true); 15452 } 15453 } 15454 } 15455 } 15456 15457 private void startIntentFilterVerifications(int userId, boolean replacing, 15458 PackageParser.Package pkg) { 15459 if (mIntentFilterVerifierComponent == null) { 15460 Slog.w(TAG, "No IntentFilter verification will not be done as " 15461 + "there is no IntentFilterVerifier available!"); 15462 return; 15463 } 15464 15465 final int verifierUid = getPackageUid( 15466 mIntentFilterVerifierComponent.getPackageName(), 15467 MATCH_DEBUG_TRIAGED_MISSING, 15468 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15469 15470 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15471 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15472 mHandler.sendMessage(msg); 15473 15474 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15475 for (int i = 0; i < childCount; i++) { 15476 PackageParser.Package childPkg = pkg.childPackages.get(i); 15477 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15478 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15479 mHandler.sendMessage(msg); 15480 } 15481 } 15482 15483 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15484 PackageParser.Package pkg) { 15485 int size = pkg.activities.size(); 15486 if (size == 0) { 15487 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15488 "No activity, so no need to verify any IntentFilter!"); 15489 return; 15490 } 15491 15492 final boolean hasDomainURLs = hasDomainURLs(pkg); 15493 if (!hasDomainURLs) { 15494 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15495 "No domain URLs, so no need to verify any IntentFilter!"); 15496 return; 15497 } 15498 15499 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15500 + " if any IntentFilter from the " + size 15501 + " Activities needs verification ..."); 15502 15503 int count = 0; 15504 final String packageName = pkg.packageName; 15505 15506 synchronized (mPackages) { 15507 // If this is a new install and we see that we've already run verification for this 15508 // package, we have nothing to do: it means the state was restored from backup. 15509 if (!replacing) { 15510 IntentFilterVerificationInfo ivi = 15511 mSettings.getIntentFilterVerificationLPr(packageName); 15512 if (ivi != null) { 15513 if (DEBUG_DOMAIN_VERIFICATION) { 15514 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15515 + ivi.getStatusString()); 15516 } 15517 return; 15518 } 15519 } 15520 15521 // If any filters need to be verified, then all need to be. 15522 boolean needToVerify = false; 15523 for (PackageParser.Activity a : pkg.activities) { 15524 for (ActivityIntentInfo filter : a.intents) { 15525 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15526 if (DEBUG_DOMAIN_VERIFICATION) { 15527 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15528 } 15529 needToVerify = true; 15530 break; 15531 } 15532 } 15533 } 15534 15535 if (needToVerify) { 15536 final int verificationId = mIntentFilterVerificationToken++; 15537 for (PackageParser.Activity a : pkg.activities) { 15538 for (ActivityIntentInfo filter : a.intents) { 15539 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15540 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15541 "Verification needed for IntentFilter:" + filter.toString()); 15542 mIntentFilterVerifier.addOneIntentFilterVerification( 15543 verifierUid, userId, verificationId, filter, packageName); 15544 count++; 15545 } 15546 } 15547 } 15548 } 15549 } 15550 15551 if (count > 0) { 15552 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15553 + " IntentFilter verification" + (count > 1 ? "s" : "") 15554 + " for userId:" + userId); 15555 mIntentFilterVerifier.startVerifications(userId); 15556 } else { 15557 if (DEBUG_DOMAIN_VERIFICATION) { 15558 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15559 } 15560 } 15561 } 15562 15563 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15564 final ComponentName cn = filter.activity.getComponentName(); 15565 final String packageName = cn.getPackageName(); 15566 15567 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15568 packageName); 15569 if (ivi == null) { 15570 return true; 15571 } 15572 int status = ivi.getStatus(); 15573 switch (status) { 15574 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15575 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15576 return true; 15577 15578 default: 15579 // Nothing to do 15580 return false; 15581 } 15582 } 15583 15584 private static boolean isMultiArch(ApplicationInfo info) { 15585 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15586 } 15587 15588 private static boolean isExternal(PackageParser.Package pkg) { 15589 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15590 } 15591 15592 private static boolean isExternal(PackageSetting ps) { 15593 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15594 } 15595 15596 private static boolean isEphemeral(PackageParser.Package pkg) { 15597 return pkg.applicationInfo.isEphemeralApp(); 15598 } 15599 15600 private static boolean isEphemeral(PackageSetting ps) { 15601 return ps.pkg != null && isEphemeral(ps.pkg); 15602 } 15603 15604 private static boolean isSystemApp(PackageParser.Package pkg) { 15605 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15606 } 15607 15608 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15609 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15610 } 15611 15612 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15613 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15614 } 15615 15616 private static boolean isSystemApp(PackageSetting ps) { 15617 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15618 } 15619 15620 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15621 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15622 } 15623 15624 private int packageFlagsToInstallFlags(PackageSetting ps) { 15625 int installFlags = 0; 15626 if (isEphemeral(ps)) { 15627 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15628 } 15629 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15630 // This existing package was an external ASEC install when we have 15631 // the external flag without a UUID 15632 installFlags |= PackageManager.INSTALL_EXTERNAL; 15633 } 15634 if (ps.isForwardLocked()) { 15635 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15636 } 15637 return installFlags; 15638 } 15639 15640 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15641 if (isExternal(pkg)) { 15642 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15643 return StorageManager.UUID_PRIMARY_PHYSICAL; 15644 } else { 15645 return pkg.volumeUuid; 15646 } 15647 } else { 15648 return StorageManager.UUID_PRIVATE_INTERNAL; 15649 } 15650 } 15651 15652 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15653 if (isExternal(pkg)) { 15654 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15655 return mSettings.getExternalVersion(); 15656 } else { 15657 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15658 } 15659 } else { 15660 return mSettings.getInternalVersion(); 15661 } 15662 } 15663 15664 private void deleteTempPackageFiles() { 15665 final FilenameFilter filter = new FilenameFilter() { 15666 public boolean accept(File dir, String name) { 15667 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15668 } 15669 }; 15670 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15671 file.delete(); 15672 } 15673 } 15674 15675 @Override 15676 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15677 int flags) { 15678 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15679 flags); 15680 } 15681 15682 @Override 15683 public void deletePackage(final String packageName, 15684 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15685 mContext.enforceCallingOrSelfPermission( 15686 android.Manifest.permission.DELETE_PACKAGES, null); 15687 Preconditions.checkNotNull(packageName); 15688 Preconditions.checkNotNull(observer); 15689 final int uid = Binder.getCallingUid(); 15690 if (!isOrphaned(packageName) 15691 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15692 try { 15693 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15694 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15695 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15696 observer.onUserActionRequired(intent); 15697 } catch (RemoteException re) { 15698 } 15699 return; 15700 } 15701 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15702 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15703 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15704 mContext.enforceCallingOrSelfPermission( 15705 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15706 "deletePackage for user " + userId); 15707 } 15708 15709 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15710 try { 15711 observer.onPackageDeleted(packageName, 15712 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15713 } catch (RemoteException re) { 15714 } 15715 return; 15716 } 15717 15718 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15719 try { 15720 observer.onPackageDeleted(packageName, 15721 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15722 } catch (RemoteException re) { 15723 } 15724 return; 15725 } 15726 15727 if (DEBUG_REMOVE) { 15728 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15729 + " deleteAllUsers: " + deleteAllUsers ); 15730 } 15731 // Queue up an async operation since the package deletion may take a little while. 15732 mHandler.post(new Runnable() { 15733 public void run() { 15734 mHandler.removeCallbacks(this); 15735 int returnCode; 15736 if (!deleteAllUsers) { 15737 returnCode = deletePackageX(packageName, userId, deleteFlags); 15738 } else { 15739 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15740 // If nobody is blocking uninstall, proceed with delete for all users 15741 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15742 returnCode = deletePackageX(packageName, userId, deleteFlags); 15743 } else { 15744 // Otherwise uninstall individually for users with blockUninstalls=false 15745 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15746 for (int userId : users) { 15747 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15748 returnCode = deletePackageX(packageName, userId, userFlags); 15749 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15750 Slog.w(TAG, "Package delete failed for user " + userId 15751 + ", returnCode " + returnCode); 15752 } 15753 } 15754 } 15755 // The app has only been marked uninstalled for certain users. 15756 // We still need to report that delete was blocked 15757 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15758 } 15759 } 15760 try { 15761 observer.onPackageDeleted(packageName, returnCode, null); 15762 } catch (RemoteException e) { 15763 Log.i(TAG, "Observer no longer exists."); 15764 } //end catch 15765 } //end run 15766 }); 15767 } 15768 15769 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15770 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15771 || callingUid == Process.SYSTEM_UID) { 15772 return true; 15773 } 15774 final int callingUserId = UserHandle.getUserId(callingUid); 15775 // If the caller installed the pkgName, then allow it to silently uninstall. 15776 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15777 return true; 15778 } 15779 15780 // Allow package verifier to silently uninstall. 15781 if (mRequiredVerifierPackage != null && 15782 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15783 return true; 15784 } 15785 15786 // Allow package uninstaller to silently uninstall. 15787 if (mRequiredUninstallerPackage != null && 15788 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15789 return true; 15790 } 15791 15792 // Allow storage manager to silently uninstall. 15793 if (mStorageManagerPackage != null && 15794 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15795 return true; 15796 } 15797 return false; 15798 } 15799 15800 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15801 int[] result = EMPTY_INT_ARRAY; 15802 for (int userId : userIds) { 15803 if (getBlockUninstallForUser(packageName, userId)) { 15804 result = ArrayUtils.appendInt(result, userId); 15805 } 15806 } 15807 return result; 15808 } 15809 15810 @Override 15811 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15812 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15813 } 15814 15815 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15816 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15817 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15818 try { 15819 if (dpm != null) { 15820 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15821 /* callingUserOnly =*/ false); 15822 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15823 : deviceOwnerComponentName.getPackageName(); 15824 // Does the package contains the device owner? 15825 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15826 // this check is probably not needed, since DO should be registered as a device 15827 // admin on some user too. (Original bug for this: b/17657954) 15828 if (packageName.equals(deviceOwnerPackageName)) { 15829 return true; 15830 } 15831 // Does it contain a device admin for any user? 15832 int[] users; 15833 if (userId == UserHandle.USER_ALL) { 15834 users = sUserManager.getUserIds(); 15835 } else { 15836 users = new int[]{userId}; 15837 } 15838 for (int i = 0; i < users.length; ++i) { 15839 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15840 return true; 15841 } 15842 } 15843 } 15844 } catch (RemoteException e) { 15845 } 15846 return false; 15847 } 15848 15849 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15850 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15851 } 15852 15853 /** 15854 * This method is an internal method that could be get invoked either 15855 * to delete an installed package or to clean up a failed installation. 15856 * After deleting an installed package, a broadcast is sent to notify any 15857 * listeners that the package has been removed. For cleaning up a failed 15858 * installation, the broadcast is not necessary since the package's 15859 * installation wouldn't have sent the initial broadcast either 15860 * The key steps in deleting a package are 15861 * deleting the package information in internal structures like mPackages, 15862 * deleting the packages base directories through installd 15863 * updating mSettings to reflect current status 15864 * persisting settings for later use 15865 * sending a broadcast if necessary 15866 */ 15867 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15868 final PackageRemovedInfo info = new PackageRemovedInfo(); 15869 final boolean res; 15870 15871 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15872 ? UserHandle.USER_ALL : userId; 15873 15874 if (isPackageDeviceAdmin(packageName, removeUser)) { 15875 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15876 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15877 } 15878 15879 PackageSetting uninstalledPs = null; 15880 15881 // for the uninstall-updates case and restricted profiles, remember the per- 15882 // user handle installed state 15883 int[] allUsers; 15884 synchronized (mPackages) { 15885 uninstalledPs = mSettings.mPackages.get(packageName); 15886 if (uninstalledPs == null) { 15887 Slog.w(TAG, "Not removing non-existent package " + packageName); 15888 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15889 } 15890 allUsers = sUserManager.getUserIds(); 15891 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15892 } 15893 15894 final int freezeUser; 15895 if (isUpdatedSystemApp(uninstalledPs) 15896 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15897 // We're downgrading a system app, which will apply to all users, so 15898 // freeze them all during the downgrade 15899 freezeUser = UserHandle.USER_ALL; 15900 } else { 15901 freezeUser = removeUser; 15902 } 15903 15904 synchronized (mInstallLock) { 15905 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15906 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15907 deleteFlags, "deletePackageX")) { 15908 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15909 deleteFlags | REMOVE_CHATTY, info, true, null); 15910 } 15911 synchronized (mPackages) { 15912 if (res) { 15913 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15914 } 15915 } 15916 } 15917 15918 if (res) { 15919 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15920 info.sendPackageRemovedBroadcasts(killApp); 15921 info.sendSystemPackageUpdatedBroadcasts(); 15922 info.sendSystemPackageAppearedBroadcasts(); 15923 } 15924 // Force a gc here. 15925 Runtime.getRuntime().gc(); 15926 // Delete the resources here after sending the broadcast to let 15927 // other processes clean up before deleting resources. 15928 if (info.args != null) { 15929 synchronized (mInstallLock) { 15930 info.args.doPostDeleteLI(true); 15931 } 15932 } 15933 15934 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15935 } 15936 15937 class PackageRemovedInfo { 15938 String removedPackage; 15939 int uid = -1; 15940 int removedAppId = -1; 15941 int[] origUsers; 15942 int[] removedUsers = null; 15943 boolean isRemovedPackageSystemUpdate = false; 15944 boolean isUpdate; 15945 boolean dataRemoved; 15946 boolean removedForAllUsers; 15947 // Clean up resources deleted packages. 15948 InstallArgs args = null; 15949 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15950 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15951 15952 void sendPackageRemovedBroadcasts(boolean killApp) { 15953 sendPackageRemovedBroadcastInternal(killApp); 15954 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15955 for (int i = 0; i < childCount; i++) { 15956 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15957 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15958 } 15959 } 15960 15961 void sendSystemPackageUpdatedBroadcasts() { 15962 if (isRemovedPackageSystemUpdate) { 15963 sendSystemPackageUpdatedBroadcastsInternal(); 15964 final int childCount = (removedChildPackages != null) 15965 ? removedChildPackages.size() : 0; 15966 for (int i = 0; i < childCount; i++) { 15967 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15968 if (childInfo.isRemovedPackageSystemUpdate) { 15969 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15970 } 15971 } 15972 } 15973 } 15974 15975 void sendSystemPackageAppearedBroadcasts() { 15976 final int packageCount = (appearedChildPackages != null) 15977 ? appearedChildPackages.size() : 0; 15978 for (int i = 0; i < packageCount; i++) { 15979 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15980 sendPackageAddedForNewUsers(installedInfo.name, true, 15981 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 15982 } 15983 } 15984 15985 private void sendSystemPackageUpdatedBroadcastsInternal() { 15986 Bundle extras = new Bundle(2); 15987 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15988 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15989 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15990 extras, 0, null, null, null); 15991 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15992 extras, 0, null, null, null); 15993 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15994 null, 0, removedPackage, null, null); 15995 } 15996 15997 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15998 Bundle extras = new Bundle(2); 15999 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16000 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16001 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16002 if (isUpdate || isRemovedPackageSystemUpdate) { 16003 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16004 } 16005 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16006 if (removedPackage != null) { 16007 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16008 extras, 0, null, null, removedUsers); 16009 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16010 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16011 removedPackage, extras, 0, null, null, removedUsers); 16012 } 16013 } 16014 if (removedAppId >= 0) { 16015 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16016 removedUsers); 16017 } 16018 } 16019 } 16020 16021 /* 16022 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16023 * flag is not set, the data directory is removed as well. 16024 * make sure this flag is set for partially installed apps. If not its meaningless to 16025 * delete a partially installed application. 16026 */ 16027 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16028 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16029 String packageName = ps.name; 16030 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16031 // Retrieve object to delete permissions for shared user later on 16032 final PackageParser.Package deletedPkg; 16033 final PackageSetting deletedPs; 16034 // reader 16035 synchronized (mPackages) { 16036 deletedPkg = mPackages.get(packageName); 16037 deletedPs = mSettings.mPackages.get(packageName); 16038 if (outInfo != null) { 16039 outInfo.removedPackage = packageName; 16040 outInfo.removedUsers = deletedPs != null 16041 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16042 : null; 16043 } 16044 } 16045 16046 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16047 16048 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16049 final PackageParser.Package resolvedPkg; 16050 if (deletedPkg != null) { 16051 resolvedPkg = deletedPkg; 16052 } else { 16053 // We don't have a parsed package when it lives on an ejected 16054 // adopted storage device, so fake something together 16055 resolvedPkg = new PackageParser.Package(ps.name); 16056 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16057 } 16058 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16059 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16060 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16061 if (outInfo != null) { 16062 outInfo.dataRemoved = true; 16063 } 16064 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16065 } 16066 16067 // writer 16068 synchronized (mPackages) { 16069 if (deletedPs != null) { 16070 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16071 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16072 clearDefaultBrowserIfNeeded(packageName); 16073 if (outInfo != null) { 16074 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16075 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16076 } 16077 updatePermissionsLPw(deletedPs.name, null, 0); 16078 if (deletedPs.sharedUser != null) { 16079 // Remove permissions associated with package. Since runtime 16080 // permissions are per user we have to kill the removed package 16081 // or packages running under the shared user of the removed 16082 // package if revoking the permissions requested only by the removed 16083 // package is successful and this causes a change in gids. 16084 for (int userId : UserManagerService.getInstance().getUserIds()) { 16085 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16086 userId); 16087 if (userIdToKill == UserHandle.USER_ALL 16088 || userIdToKill >= UserHandle.USER_SYSTEM) { 16089 // If gids changed for this user, kill all affected packages. 16090 mHandler.post(new Runnable() { 16091 @Override 16092 public void run() { 16093 // This has to happen with no lock held. 16094 killApplication(deletedPs.name, deletedPs.appId, 16095 KILL_APP_REASON_GIDS_CHANGED); 16096 } 16097 }); 16098 break; 16099 } 16100 } 16101 } 16102 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16103 } 16104 // make sure to preserve per-user disabled state if this removal was just 16105 // a downgrade of a system app to the factory package 16106 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16107 if (DEBUG_REMOVE) { 16108 Slog.d(TAG, "Propagating install state across downgrade"); 16109 } 16110 for (int userId : allUserHandles) { 16111 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16112 if (DEBUG_REMOVE) { 16113 Slog.d(TAG, " user " + userId + " => " + installed); 16114 } 16115 ps.setInstalled(installed, userId); 16116 } 16117 } 16118 } 16119 // can downgrade to reader 16120 if (writeSettings) { 16121 // Save settings now 16122 mSettings.writeLPr(); 16123 } 16124 } 16125 if (outInfo != null) { 16126 // A user ID was deleted here. Go through all users and remove it 16127 // from KeyStore. 16128 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16129 } 16130 } 16131 16132 static boolean locationIsPrivileged(File path) { 16133 try { 16134 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16135 .getCanonicalPath(); 16136 return path.getCanonicalPath().startsWith(privilegedAppDir); 16137 } catch (IOException e) { 16138 Slog.e(TAG, "Unable to access code path " + path); 16139 } 16140 return false; 16141 } 16142 16143 /* 16144 * Tries to delete system package. 16145 */ 16146 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16147 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16148 boolean writeSettings) { 16149 if (deletedPs.parentPackageName != null) { 16150 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16151 return false; 16152 } 16153 16154 final boolean applyUserRestrictions 16155 = (allUserHandles != null) && (outInfo.origUsers != null); 16156 final PackageSetting disabledPs; 16157 // Confirm if the system package has been updated 16158 // An updated system app can be deleted. This will also have to restore 16159 // the system pkg from system partition 16160 // reader 16161 synchronized (mPackages) { 16162 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16163 } 16164 16165 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16166 + " disabledPs=" + disabledPs); 16167 16168 if (disabledPs == null) { 16169 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16170 return false; 16171 } else if (DEBUG_REMOVE) { 16172 Slog.d(TAG, "Deleting system pkg from data partition"); 16173 } 16174 16175 if (DEBUG_REMOVE) { 16176 if (applyUserRestrictions) { 16177 Slog.d(TAG, "Remembering install states:"); 16178 for (int userId : allUserHandles) { 16179 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16180 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16181 } 16182 } 16183 } 16184 16185 // Delete the updated package 16186 outInfo.isRemovedPackageSystemUpdate = true; 16187 if (outInfo.removedChildPackages != null) { 16188 final int childCount = (deletedPs.childPackageNames != null) 16189 ? deletedPs.childPackageNames.size() : 0; 16190 for (int i = 0; i < childCount; i++) { 16191 String childPackageName = deletedPs.childPackageNames.get(i); 16192 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16193 .contains(childPackageName)) { 16194 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16195 childPackageName); 16196 if (childInfo != null) { 16197 childInfo.isRemovedPackageSystemUpdate = true; 16198 } 16199 } 16200 } 16201 } 16202 16203 if (disabledPs.versionCode < deletedPs.versionCode) { 16204 // Delete data for downgrades 16205 flags &= ~PackageManager.DELETE_KEEP_DATA; 16206 } else { 16207 // Preserve data by setting flag 16208 flags |= PackageManager.DELETE_KEEP_DATA; 16209 } 16210 16211 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16212 outInfo, writeSettings, disabledPs.pkg); 16213 if (!ret) { 16214 return false; 16215 } 16216 16217 // writer 16218 synchronized (mPackages) { 16219 // Reinstate the old system package 16220 enableSystemPackageLPw(disabledPs.pkg); 16221 // Remove any native libraries from the upgraded package. 16222 removeNativeBinariesLI(deletedPs); 16223 } 16224 16225 // Install the system package 16226 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16227 int parseFlags = mDefParseFlags 16228 | PackageParser.PARSE_MUST_BE_APK 16229 | PackageParser.PARSE_IS_SYSTEM 16230 | PackageParser.PARSE_IS_SYSTEM_DIR; 16231 if (locationIsPrivileged(disabledPs.codePath)) { 16232 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16233 } 16234 16235 final PackageParser.Package newPkg; 16236 try { 16237 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16238 } catch (PackageManagerException e) { 16239 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16240 + e.getMessage()); 16241 return false; 16242 } 16243 try { 16244 // update shared libraries for the newly re-installed system package 16245 updateSharedLibrariesLPr(newPkg, null); 16246 } catch (PackageManagerException e) { 16247 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16248 } 16249 16250 prepareAppDataAfterInstallLIF(newPkg); 16251 16252 // writer 16253 synchronized (mPackages) { 16254 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16255 16256 // Propagate the permissions state as we do not want to drop on the floor 16257 // runtime permissions. The update permissions method below will take 16258 // care of removing obsolete permissions and grant install permissions. 16259 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16260 updatePermissionsLPw(newPkg.packageName, newPkg, 16261 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16262 16263 if (applyUserRestrictions) { 16264 if (DEBUG_REMOVE) { 16265 Slog.d(TAG, "Propagating install state across reinstall"); 16266 } 16267 for (int userId : allUserHandles) { 16268 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16269 if (DEBUG_REMOVE) { 16270 Slog.d(TAG, " user " + userId + " => " + installed); 16271 } 16272 ps.setInstalled(installed, userId); 16273 16274 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16275 } 16276 // Regardless of writeSettings we need to ensure that this restriction 16277 // state propagation is persisted 16278 mSettings.writeAllUsersPackageRestrictionsLPr(); 16279 } 16280 // can downgrade to reader here 16281 if (writeSettings) { 16282 mSettings.writeLPr(); 16283 } 16284 } 16285 return true; 16286 } 16287 16288 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16289 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16290 PackageRemovedInfo outInfo, boolean writeSettings, 16291 PackageParser.Package replacingPackage) { 16292 synchronized (mPackages) { 16293 if (outInfo != null) { 16294 outInfo.uid = ps.appId; 16295 } 16296 16297 if (outInfo != null && outInfo.removedChildPackages != null) { 16298 final int childCount = (ps.childPackageNames != null) 16299 ? ps.childPackageNames.size() : 0; 16300 for (int i = 0; i < childCount; i++) { 16301 String childPackageName = ps.childPackageNames.get(i); 16302 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16303 if (childPs == null) { 16304 return false; 16305 } 16306 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16307 childPackageName); 16308 if (childInfo != null) { 16309 childInfo.uid = childPs.appId; 16310 } 16311 } 16312 } 16313 } 16314 16315 // Delete package data from internal structures and also remove data if flag is set 16316 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16317 16318 // Delete the child packages data 16319 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16320 for (int i = 0; i < childCount; i++) { 16321 PackageSetting childPs; 16322 synchronized (mPackages) { 16323 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16324 } 16325 if (childPs != null) { 16326 PackageRemovedInfo childOutInfo = (outInfo != null 16327 && outInfo.removedChildPackages != null) 16328 ? outInfo.removedChildPackages.get(childPs.name) : null; 16329 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16330 && (replacingPackage != null 16331 && !replacingPackage.hasChildPackage(childPs.name)) 16332 ? flags & ~DELETE_KEEP_DATA : flags; 16333 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16334 deleteFlags, writeSettings); 16335 } 16336 } 16337 16338 // Delete application code and resources only for parent packages 16339 if (ps.parentPackageName == null) { 16340 if (deleteCodeAndResources && (outInfo != null)) { 16341 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16342 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16343 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16344 } 16345 } 16346 16347 return true; 16348 } 16349 16350 @Override 16351 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16352 int userId) { 16353 mContext.enforceCallingOrSelfPermission( 16354 android.Manifest.permission.DELETE_PACKAGES, null); 16355 synchronized (mPackages) { 16356 PackageSetting ps = mSettings.mPackages.get(packageName); 16357 if (ps == null) { 16358 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16359 return false; 16360 } 16361 if (!ps.getInstalled(userId)) { 16362 // Can't block uninstall for an app that is not installed or enabled. 16363 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16364 return false; 16365 } 16366 ps.setBlockUninstall(blockUninstall, userId); 16367 mSettings.writePackageRestrictionsLPr(userId); 16368 } 16369 return true; 16370 } 16371 16372 @Override 16373 public boolean getBlockUninstallForUser(String packageName, int userId) { 16374 synchronized (mPackages) { 16375 PackageSetting ps = mSettings.mPackages.get(packageName); 16376 if (ps == null) { 16377 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16378 return false; 16379 } 16380 return ps.getBlockUninstall(userId); 16381 } 16382 } 16383 16384 @Override 16385 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16386 int callingUid = Binder.getCallingUid(); 16387 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16388 throw new SecurityException( 16389 "setRequiredForSystemUser can only be run by the system or root"); 16390 } 16391 synchronized (mPackages) { 16392 PackageSetting ps = mSettings.mPackages.get(packageName); 16393 if (ps == null) { 16394 Log.w(TAG, "Package doesn't exist: " + packageName); 16395 return false; 16396 } 16397 if (systemUserApp) { 16398 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16399 } else { 16400 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16401 } 16402 mSettings.writeLPr(); 16403 } 16404 return true; 16405 } 16406 16407 /* 16408 * This method handles package deletion in general 16409 */ 16410 private boolean deletePackageLIF(String packageName, UserHandle user, 16411 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16412 PackageRemovedInfo outInfo, boolean writeSettings, 16413 PackageParser.Package replacingPackage) { 16414 if (packageName == null) { 16415 Slog.w(TAG, "Attempt to delete null packageName."); 16416 return false; 16417 } 16418 16419 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16420 16421 PackageSetting ps; 16422 16423 synchronized (mPackages) { 16424 ps = mSettings.mPackages.get(packageName); 16425 if (ps == null) { 16426 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16427 return false; 16428 } 16429 16430 if (ps.parentPackageName != null && (!isSystemApp(ps) 16431 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16432 if (DEBUG_REMOVE) { 16433 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16434 + ((user == null) ? UserHandle.USER_ALL : user)); 16435 } 16436 final int removedUserId = (user != null) ? user.getIdentifier() 16437 : UserHandle.USER_ALL; 16438 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16439 return false; 16440 } 16441 markPackageUninstalledForUserLPw(ps, user); 16442 scheduleWritePackageRestrictionsLocked(user); 16443 return true; 16444 } 16445 } 16446 16447 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16448 && user.getIdentifier() != UserHandle.USER_ALL)) { 16449 // The caller is asking that the package only be deleted for a single 16450 // user. To do this, we just mark its uninstalled state and delete 16451 // its data. If this is a system app, we only allow this to happen if 16452 // they have set the special DELETE_SYSTEM_APP which requests different 16453 // semantics than normal for uninstalling system apps. 16454 markPackageUninstalledForUserLPw(ps, user); 16455 16456 if (!isSystemApp(ps)) { 16457 // Do not uninstall the APK if an app should be cached 16458 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16459 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16460 // Other user still have this package installed, so all 16461 // we need to do is clear this user's data and save that 16462 // it is uninstalled. 16463 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16464 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16465 return false; 16466 } 16467 scheduleWritePackageRestrictionsLocked(user); 16468 return true; 16469 } else { 16470 // We need to set it back to 'installed' so the uninstall 16471 // broadcasts will be sent correctly. 16472 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16473 ps.setInstalled(true, user.getIdentifier()); 16474 } 16475 } else { 16476 // This is a system app, so we assume that the 16477 // other users still have this package installed, so all 16478 // we need to do is clear this user's data and save that 16479 // it is uninstalled. 16480 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16481 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16482 return false; 16483 } 16484 scheduleWritePackageRestrictionsLocked(user); 16485 return true; 16486 } 16487 } 16488 16489 // If we are deleting a composite package for all users, keep track 16490 // of result for each child. 16491 if (ps.childPackageNames != null && outInfo != null) { 16492 synchronized (mPackages) { 16493 final int childCount = ps.childPackageNames.size(); 16494 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16495 for (int i = 0; i < childCount; i++) { 16496 String childPackageName = ps.childPackageNames.get(i); 16497 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16498 childInfo.removedPackage = childPackageName; 16499 outInfo.removedChildPackages.put(childPackageName, childInfo); 16500 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16501 if (childPs != null) { 16502 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16503 } 16504 } 16505 } 16506 } 16507 16508 boolean ret = false; 16509 if (isSystemApp(ps)) { 16510 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16511 // When an updated system application is deleted we delete the existing resources 16512 // as well and fall back to existing code in system partition 16513 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16514 } else { 16515 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16516 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16517 outInfo, writeSettings, replacingPackage); 16518 } 16519 16520 // Take a note whether we deleted the package for all users 16521 if (outInfo != null) { 16522 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16523 if (outInfo.removedChildPackages != null) { 16524 synchronized (mPackages) { 16525 final int childCount = outInfo.removedChildPackages.size(); 16526 for (int i = 0; i < childCount; i++) { 16527 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16528 if (childInfo != null) { 16529 childInfo.removedForAllUsers = mPackages.get( 16530 childInfo.removedPackage) == null; 16531 } 16532 } 16533 } 16534 } 16535 // If we uninstalled an update to a system app there may be some 16536 // child packages that appeared as they are declared in the system 16537 // app but were not declared in the update. 16538 if (isSystemApp(ps)) { 16539 synchronized (mPackages) { 16540 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16541 final int childCount = (updatedPs.childPackageNames != null) 16542 ? updatedPs.childPackageNames.size() : 0; 16543 for (int i = 0; i < childCount; i++) { 16544 String childPackageName = updatedPs.childPackageNames.get(i); 16545 if (outInfo.removedChildPackages == null 16546 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16547 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16548 if (childPs == null) { 16549 continue; 16550 } 16551 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16552 installRes.name = childPackageName; 16553 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16554 installRes.pkg = mPackages.get(childPackageName); 16555 installRes.uid = childPs.pkg.applicationInfo.uid; 16556 if (outInfo.appearedChildPackages == null) { 16557 outInfo.appearedChildPackages = new ArrayMap<>(); 16558 } 16559 outInfo.appearedChildPackages.put(childPackageName, installRes); 16560 } 16561 } 16562 } 16563 } 16564 } 16565 16566 return ret; 16567 } 16568 16569 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16570 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16571 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16572 for (int nextUserId : userIds) { 16573 if (DEBUG_REMOVE) { 16574 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16575 } 16576 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16577 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16578 false /*hidden*/, false /*suspended*/, null, null, null, 16579 false /*blockUninstall*/, 16580 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16581 } 16582 } 16583 16584 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16585 PackageRemovedInfo outInfo) { 16586 final PackageParser.Package pkg; 16587 synchronized (mPackages) { 16588 pkg = mPackages.get(ps.name); 16589 } 16590 16591 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16592 : new int[] {userId}; 16593 for (int nextUserId : userIds) { 16594 if (DEBUG_REMOVE) { 16595 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16596 + nextUserId); 16597 } 16598 16599 destroyAppDataLIF(pkg, userId, 16600 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16601 destroyAppProfilesLIF(pkg, userId); 16602 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16603 schedulePackageCleaning(ps.name, nextUserId, false); 16604 synchronized (mPackages) { 16605 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16606 scheduleWritePackageRestrictionsLocked(nextUserId); 16607 } 16608 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16609 } 16610 } 16611 16612 if (outInfo != null) { 16613 outInfo.removedPackage = ps.name; 16614 outInfo.removedAppId = ps.appId; 16615 outInfo.removedUsers = userIds; 16616 } 16617 16618 return true; 16619 } 16620 16621 private final class ClearStorageConnection implements ServiceConnection { 16622 IMediaContainerService mContainerService; 16623 16624 @Override 16625 public void onServiceConnected(ComponentName name, IBinder service) { 16626 synchronized (this) { 16627 mContainerService = IMediaContainerService.Stub.asInterface(service); 16628 notifyAll(); 16629 } 16630 } 16631 16632 @Override 16633 public void onServiceDisconnected(ComponentName name) { 16634 } 16635 } 16636 16637 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16638 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16639 16640 final boolean mounted; 16641 if (Environment.isExternalStorageEmulated()) { 16642 mounted = true; 16643 } else { 16644 final String status = Environment.getExternalStorageState(); 16645 16646 mounted = status.equals(Environment.MEDIA_MOUNTED) 16647 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16648 } 16649 16650 if (!mounted) { 16651 return; 16652 } 16653 16654 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16655 int[] users; 16656 if (userId == UserHandle.USER_ALL) { 16657 users = sUserManager.getUserIds(); 16658 } else { 16659 users = new int[] { userId }; 16660 } 16661 final ClearStorageConnection conn = new ClearStorageConnection(); 16662 if (mContext.bindServiceAsUser( 16663 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16664 try { 16665 for (int curUser : users) { 16666 long timeout = SystemClock.uptimeMillis() + 5000; 16667 synchronized (conn) { 16668 long now; 16669 while (conn.mContainerService == null && 16670 (now = SystemClock.uptimeMillis()) < timeout) { 16671 try { 16672 conn.wait(timeout - now); 16673 } catch (InterruptedException e) { 16674 } 16675 } 16676 } 16677 if (conn.mContainerService == null) { 16678 return; 16679 } 16680 16681 final UserEnvironment userEnv = new UserEnvironment(curUser); 16682 clearDirectory(conn.mContainerService, 16683 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16684 if (allData) { 16685 clearDirectory(conn.mContainerService, 16686 userEnv.buildExternalStorageAppDataDirs(packageName)); 16687 clearDirectory(conn.mContainerService, 16688 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16689 } 16690 } 16691 } finally { 16692 mContext.unbindService(conn); 16693 } 16694 } 16695 } 16696 16697 @Override 16698 public void clearApplicationProfileData(String packageName) { 16699 enforceSystemOrRoot("Only the system can clear all profile data"); 16700 16701 final PackageParser.Package pkg; 16702 synchronized (mPackages) { 16703 pkg = mPackages.get(packageName); 16704 } 16705 16706 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16707 synchronized (mInstallLock) { 16708 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16709 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16710 true /* removeBaseMarker */); 16711 } 16712 } 16713 } 16714 16715 @Override 16716 public void clearApplicationUserData(final String packageName, 16717 final IPackageDataObserver observer, final int userId) { 16718 mContext.enforceCallingOrSelfPermission( 16719 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16720 16721 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16722 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16723 16724 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16725 throw new SecurityException("Cannot clear data for a protected package: " 16726 + packageName); 16727 } 16728 // Queue up an async operation since the package deletion may take a little while. 16729 mHandler.post(new Runnable() { 16730 public void run() { 16731 mHandler.removeCallbacks(this); 16732 final boolean succeeded; 16733 try (PackageFreezer freezer = freezePackage(packageName, 16734 "clearApplicationUserData")) { 16735 synchronized (mInstallLock) { 16736 succeeded = clearApplicationUserDataLIF(packageName, userId); 16737 } 16738 clearExternalStorageDataSync(packageName, userId, true); 16739 } 16740 if (succeeded) { 16741 // invoke DeviceStorageMonitor's update method to clear any notifications 16742 DeviceStorageMonitorInternal dsm = LocalServices 16743 .getService(DeviceStorageMonitorInternal.class); 16744 if (dsm != null) { 16745 dsm.checkMemory(); 16746 } 16747 } 16748 if(observer != null) { 16749 try { 16750 observer.onRemoveCompleted(packageName, succeeded); 16751 } catch (RemoteException e) { 16752 Log.i(TAG, "Observer no longer exists."); 16753 } 16754 } //end if observer 16755 } //end run 16756 }); 16757 } 16758 16759 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16760 if (packageName == null) { 16761 Slog.w(TAG, "Attempt to delete null packageName."); 16762 return false; 16763 } 16764 16765 // Try finding details about the requested package 16766 PackageParser.Package pkg; 16767 synchronized (mPackages) { 16768 pkg = mPackages.get(packageName); 16769 if (pkg == null) { 16770 final PackageSetting ps = mSettings.mPackages.get(packageName); 16771 if (ps != null) { 16772 pkg = ps.pkg; 16773 } 16774 } 16775 16776 if (pkg == null) { 16777 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16778 return false; 16779 } 16780 16781 PackageSetting ps = (PackageSetting) pkg.mExtras; 16782 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16783 } 16784 16785 clearAppDataLIF(pkg, userId, 16786 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16787 16788 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16789 removeKeystoreDataIfNeeded(userId, appId); 16790 16791 UserManagerInternal umInternal = getUserManagerInternal(); 16792 final int flags; 16793 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16794 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16795 } else if (umInternal.isUserRunning(userId)) { 16796 flags = StorageManager.FLAG_STORAGE_DE; 16797 } else { 16798 flags = 0; 16799 } 16800 prepareAppDataContentsLIF(pkg, userId, flags); 16801 16802 return true; 16803 } 16804 16805 /** 16806 * Reverts user permission state changes (permissions and flags) in 16807 * all packages for a given user. 16808 * 16809 * @param userId The device user for which to do a reset. 16810 */ 16811 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16812 final int packageCount = mPackages.size(); 16813 for (int i = 0; i < packageCount; i++) { 16814 PackageParser.Package pkg = mPackages.valueAt(i); 16815 PackageSetting ps = (PackageSetting) pkg.mExtras; 16816 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16817 } 16818 } 16819 16820 private void resetNetworkPolicies(int userId) { 16821 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16822 } 16823 16824 /** 16825 * Reverts user permission state changes (permissions and flags). 16826 * 16827 * @param ps The package for which to reset. 16828 * @param userId The device user for which to do a reset. 16829 */ 16830 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16831 final PackageSetting ps, final int userId) { 16832 if (ps.pkg == null) { 16833 return; 16834 } 16835 16836 // These are flags that can change base on user actions. 16837 final int userSettableMask = FLAG_PERMISSION_USER_SET 16838 | FLAG_PERMISSION_USER_FIXED 16839 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16840 | FLAG_PERMISSION_REVIEW_REQUIRED; 16841 16842 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16843 | FLAG_PERMISSION_POLICY_FIXED; 16844 16845 boolean writeInstallPermissions = false; 16846 boolean writeRuntimePermissions = false; 16847 16848 final int permissionCount = ps.pkg.requestedPermissions.size(); 16849 for (int i = 0; i < permissionCount; i++) { 16850 String permission = ps.pkg.requestedPermissions.get(i); 16851 16852 BasePermission bp = mSettings.mPermissions.get(permission); 16853 if (bp == null) { 16854 continue; 16855 } 16856 16857 // If shared user we just reset the state to which only this app contributed. 16858 if (ps.sharedUser != null) { 16859 boolean used = false; 16860 final int packageCount = ps.sharedUser.packages.size(); 16861 for (int j = 0; j < packageCount; j++) { 16862 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16863 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16864 && pkg.pkg.requestedPermissions.contains(permission)) { 16865 used = true; 16866 break; 16867 } 16868 } 16869 if (used) { 16870 continue; 16871 } 16872 } 16873 16874 PermissionsState permissionsState = ps.getPermissionsState(); 16875 16876 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16877 16878 // Always clear the user settable flags. 16879 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16880 bp.name) != null; 16881 // If permission review is enabled and this is a legacy app, mark the 16882 // permission as requiring a review as this is the initial state. 16883 int flags = 0; 16884 if (mPermissionReviewRequired 16885 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16886 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16887 } 16888 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16889 if (hasInstallState) { 16890 writeInstallPermissions = true; 16891 } else { 16892 writeRuntimePermissions = true; 16893 } 16894 } 16895 16896 // Below is only runtime permission handling. 16897 if (!bp.isRuntime()) { 16898 continue; 16899 } 16900 16901 // Never clobber system or policy. 16902 if ((oldFlags & policyOrSystemFlags) != 0) { 16903 continue; 16904 } 16905 16906 // If this permission was granted by default, make sure it is. 16907 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16908 if (permissionsState.grantRuntimePermission(bp, userId) 16909 != PERMISSION_OPERATION_FAILURE) { 16910 writeRuntimePermissions = true; 16911 } 16912 // If permission review is enabled the permissions for a legacy apps 16913 // are represented as constantly granted runtime ones, so don't revoke. 16914 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16915 // Otherwise, reset the permission. 16916 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16917 switch (revokeResult) { 16918 case PERMISSION_OPERATION_SUCCESS: 16919 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16920 writeRuntimePermissions = true; 16921 final int appId = ps.appId; 16922 mHandler.post(new Runnable() { 16923 @Override 16924 public void run() { 16925 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16926 } 16927 }); 16928 } break; 16929 } 16930 } 16931 } 16932 16933 // Synchronously write as we are taking permissions away. 16934 if (writeRuntimePermissions) { 16935 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16936 } 16937 16938 // Synchronously write as we are taking permissions away. 16939 if (writeInstallPermissions) { 16940 mSettings.writeLPr(); 16941 } 16942 } 16943 16944 /** 16945 * Remove entries from the keystore daemon. Will only remove it if the 16946 * {@code appId} is valid. 16947 */ 16948 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16949 if (appId < 0) { 16950 return; 16951 } 16952 16953 final KeyStore keyStore = KeyStore.getInstance(); 16954 if (keyStore != null) { 16955 if (userId == UserHandle.USER_ALL) { 16956 for (final int individual : sUserManager.getUserIds()) { 16957 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16958 } 16959 } else { 16960 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16961 } 16962 } else { 16963 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16964 } 16965 } 16966 16967 @Override 16968 public void deleteApplicationCacheFiles(final String packageName, 16969 final IPackageDataObserver observer) { 16970 final int userId = UserHandle.getCallingUserId(); 16971 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16972 } 16973 16974 @Override 16975 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16976 final IPackageDataObserver observer) { 16977 mContext.enforceCallingOrSelfPermission( 16978 android.Manifest.permission.DELETE_CACHE_FILES, null); 16979 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16980 /* requireFullPermission= */ true, /* checkShell= */ false, 16981 "delete application cache files"); 16982 16983 final PackageParser.Package pkg; 16984 synchronized (mPackages) { 16985 pkg = mPackages.get(packageName); 16986 } 16987 16988 // Queue up an async operation since the package deletion may take a little while. 16989 mHandler.post(new Runnable() { 16990 public void run() { 16991 synchronized (mInstallLock) { 16992 final int flags = StorageManager.FLAG_STORAGE_DE 16993 | StorageManager.FLAG_STORAGE_CE; 16994 // We're only clearing cache files, so we don't care if the 16995 // app is unfrozen and still able to run 16996 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16997 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16998 } 16999 clearExternalStorageDataSync(packageName, userId, false); 17000 if (observer != null) { 17001 try { 17002 observer.onRemoveCompleted(packageName, true); 17003 } catch (RemoteException e) { 17004 Log.i(TAG, "Observer no longer exists."); 17005 } 17006 } 17007 } 17008 }); 17009 } 17010 17011 @Override 17012 public void getPackageSizeInfo(final String packageName, int userHandle, 17013 final IPackageStatsObserver observer) { 17014 mContext.enforceCallingOrSelfPermission( 17015 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17016 if (packageName == null) { 17017 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17018 } 17019 17020 PackageStats stats = new PackageStats(packageName, userHandle); 17021 17022 /* 17023 * Queue up an async operation since the package measurement may take a 17024 * little while. 17025 */ 17026 Message msg = mHandler.obtainMessage(INIT_COPY); 17027 msg.obj = new MeasureParams(stats, observer); 17028 mHandler.sendMessage(msg); 17029 } 17030 17031 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17032 final PackageSetting ps; 17033 synchronized (mPackages) { 17034 ps = mSettings.mPackages.get(packageName); 17035 if (ps == null) { 17036 Slog.w(TAG, "Failed to find settings for " + packageName); 17037 return false; 17038 } 17039 } 17040 try { 17041 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17042 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17043 ps.getCeDataInode(userId), ps.codePathString, stats); 17044 } catch (InstallerException e) { 17045 Slog.w(TAG, String.valueOf(e)); 17046 return false; 17047 } 17048 17049 // For now, ignore code size of packages on system partition 17050 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17051 stats.codeSize = 0; 17052 } 17053 17054 return true; 17055 } 17056 17057 private int getUidTargetSdkVersionLockedLPr(int uid) { 17058 Object obj = mSettings.getUserIdLPr(uid); 17059 if (obj instanceof SharedUserSetting) { 17060 final SharedUserSetting sus = (SharedUserSetting) obj; 17061 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17062 final Iterator<PackageSetting> it = sus.packages.iterator(); 17063 while (it.hasNext()) { 17064 final PackageSetting ps = it.next(); 17065 if (ps.pkg != null) { 17066 int v = ps.pkg.applicationInfo.targetSdkVersion; 17067 if (v < vers) vers = v; 17068 } 17069 } 17070 return vers; 17071 } else if (obj instanceof PackageSetting) { 17072 final PackageSetting ps = (PackageSetting) obj; 17073 if (ps.pkg != null) { 17074 return ps.pkg.applicationInfo.targetSdkVersion; 17075 } 17076 } 17077 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17078 } 17079 17080 @Override 17081 public void addPreferredActivity(IntentFilter filter, int match, 17082 ComponentName[] set, ComponentName activity, int userId) { 17083 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17084 "Adding preferred"); 17085 } 17086 17087 private void addPreferredActivityInternal(IntentFilter filter, int match, 17088 ComponentName[] set, ComponentName activity, boolean always, int userId, 17089 String opname) { 17090 // writer 17091 int callingUid = Binder.getCallingUid(); 17092 enforceCrossUserPermission(callingUid, userId, 17093 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17094 if (filter.countActions() == 0) { 17095 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17096 return; 17097 } 17098 synchronized (mPackages) { 17099 if (mContext.checkCallingOrSelfPermission( 17100 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17101 != PackageManager.PERMISSION_GRANTED) { 17102 if (getUidTargetSdkVersionLockedLPr(callingUid) 17103 < Build.VERSION_CODES.FROYO) { 17104 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17105 + callingUid); 17106 return; 17107 } 17108 mContext.enforceCallingOrSelfPermission( 17109 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17110 } 17111 17112 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17113 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17114 + userId + ":"); 17115 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17116 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17117 scheduleWritePackageRestrictionsLocked(userId); 17118 postPreferredActivityChangedBroadcast(userId); 17119 } 17120 } 17121 17122 private void postPreferredActivityChangedBroadcast(int userId) { 17123 mHandler.post(() -> { 17124 final IActivityManager am = ActivityManagerNative.getDefault(); 17125 if (am == null) { 17126 return; 17127 } 17128 17129 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17130 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17131 try { 17132 am.broadcastIntent(null, intent, null, null, 17133 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17134 null, false, false, userId); 17135 } catch (RemoteException e) { 17136 } 17137 }); 17138 } 17139 17140 @Override 17141 public void replacePreferredActivity(IntentFilter filter, int match, 17142 ComponentName[] set, ComponentName activity, int userId) { 17143 if (filter.countActions() != 1) { 17144 throw new IllegalArgumentException( 17145 "replacePreferredActivity expects filter to have only 1 action."); 17146 } 17147 if (filter.countDataAuthorities() != 0 17148 || filter.countDataPaths() != 0 17149 || filter.countDataSchemes() > 1 17150 || filter.countDataTypes() != 0) { 17151 throw new IllegalArgumentException( 17152 "replacePreferredActivity expects filter to have no data authorities, " + 17153 "paths, or types; and at most one scheme."); 17154 } 17155 17156 final int callingUid = Binder.getCallingUid(); 17157 enforceCrossUserPermission(callingUid, userId, 17158 true /* requireFullPermission */, false /* checkShell */, 17159 "replace preferred activity"); 17160 synchronized (mPackages) { 17161 if (mContext.checkCallingOrSelfPermission( 17162 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17163 != PackageManager.PERMISSION_GRANTED) { 17164 if (getUidTargetSdkVersionLockedLPr(callingUid) 17165 < Build.VERSION_CODES.FROYO) { 17166 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17167 + Binder.getCallingUid()); 17168 return; 17169 } 17170 mContext.enforceCallingOrSelfPermission( 17171 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17172 } 17173 17174 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17175 if (pir != null) { 17176 // Get all of the existing entries that exactly match this filter. 17177 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17178 if (existing != null && existing.size() == 1) { 17179 PreferredActivity cur = existing.get(0); 17180 if (DEBUG_PREFERRED) { 17181 Slog.i(TAG, "Checking replace of preferred:"); 17182 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17183 if (!cur.mPref.mAlways) { 17184 Slog.i(TAG, " -- CUR; not mAlways!"); 17185 } else { 17186 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17187 Slog.i(TAG, " -- CUR: mSet=" 17188 + Arrays.toString(cur.mPref.mSetComponents)); 17189 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17190 Slog.i(TAG, " -- NEW: mMatch=" 17191 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17192 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17193 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17194 } 17195 } 17196 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17197 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17198 && cur.mPref.sameSet(set)) { 17199 // Setting the preferred activity to what it happens to be already 17200 if (DEBUG_PREFERRED) { 17201 Slog.i(TAG, "Replacing with same preferred activity " 17202 + cur.mPref.mShortComponent + " for user " 17203 + userId + ":"); 17204 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17205 } 17206 return; 17207 } 17208 } 17209 17210 if (existing != null) { 17211 if (DEBUG_PREFERRED) { 17212 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17213 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17214 } 17215 for (int i = 0; i < existing.size(); i++) { 17216 PreferredActivity pa = existing.get(i); 17217 if (DEBUG_PREFERRED) { 17218 Slog.i(TAG, "Removing existing preferred activity " 17219 + pa.mPref.mComponent + ":"); 17220 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17221 } 17222 pir.removeFilter(pa); 17223 } 17224 } 17225 } 17226 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17227 "Replacing preferred"); 17228 } 17229 } 17230 17231 @Override 17232 public void clearPackagePreferredActivities(String packageName) { 17233 final int uid = Binder.getCallingUid(); 17234 // writer 17235 synchronized (mPackages) { 17236 PackageParser.Package pkg = mPackages.get(packageName); 17237 if (pkg == null || pkg.applicationInfo.uid != uid) { 17238 if (mContext.checkCallingOrSelfPermission( 17239 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17240 != PackageManager.PERMISSION_GRANTED) { 17241 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17242 < Build.VERSION_CODES.FROYO) { 17243 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17244 + Binder.getCallingUid()); 17245 return; 17246 } 17247 mContext.enforceCallingOrSelfPermission( 17248 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17249 } 17250 } 17251 17252 int user = UserHandle.getCallingUserId(); 17253 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17254 scheduleWritePackageRestrictionsLocked(user); 17255 } 17256 } 17257 } 17258 17259 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17260 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17261 ArrayList<PreferredActivity> removed = null; 17262 boolean changed = false; 17263 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17264 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17265 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17266 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17267 continue; 17268 } 17269 Iterator<PreferredActivity> it = pir.filterIterator(); 17270 while (it.hasNext()) { 17271 PreferredActivity pa = it.next(); 17272 // Mark entry for removal only if it matches the package name 17273 // and the entry is of type "always". 17274 if (packageName == null || 17275 (pa.mPref.mComponent.getPackageName().equals(packageName) 17276 && pa.mPref.mAlways)) { 17277 if (removed == null) { 17278 removed = new ArrayList<PreferredActivity>(); 17279 } 17280 removed.add(pa); 17281 } 17282 } 17283 if (removed != null) { 17284 for (int j=0; j<removed.size(); j++) { 17285 PreferredActivity pa = removed.get(j); 17286 pir.removeFilter(pa); 17287 } 17288 changed = true; 17289 } 17290 } 17291 if (changed) { 17292 postPreferredActivityChangedBroadcast(userId); 17293 } 17294 return changed; 17295 } 17296 17297 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17298 private void clearIntentFilterVerificationsLPw(int userId) { 17299 final int packageCount = mPackages.size(); 17300 for (int i = 0; i < packageCount; i++) { 17301 PackageParser.Package pkg = mPackages.valueAt(i); 17302 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17303 } 17304 } 17305 17306 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17307 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17308 if (userId == UserHandle.USER_ALL) { 17309 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17310 sUserManager.getUserIds())) { 17311 for (int oneUserId : sUserManager.getUserIds()) { 17312 scheduleWritePackageRestrictionsLocked(oneUserId); 17313 } 17314 } 17315 } else { 17316 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17317 scheduleWritePackageRestrictionsLocked(userId); 17318 } 17319 } 17320 } 17321 17322 void clearDefaultBrowserIfNeeded(String packageName) { 17323 for (int oneUserId : sUserManager.getUserIds()) { 17324 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17325 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17326 if (packageName.equals(defaultBrowserPackageName)) { 17327 setDefaultBrowserPackageName(null, oneUserId); 17328 } 17329 } 17330 } 17331 17332 @Override 17333 public void resetApplicationPreferences(int userId) { 17334 mContext.enforceCallingOrSelfPermission( 17335 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17336 final long identity = Binder.clearCallingIdentity(); 17337 // writer 17338 try { 17339 synchronized (mPackages) { 17340 clearPackagePreferredActivitiesLPw(null, userId); 17341 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17342 // TODO: We have to reset the default SMS and Phone. This requires 17343 // significant refactoring to keep all default apps in the package 17344 // manager (cleaner but more work) or have the services provide 17345 // callbacks to the package manager to request a default app reset. 17346 applyFactoryDefaultBrowserLPw(userId); 17347 clearIntentFilterVerificationsLPw(userId); 17348 primeDomainVerificationsLPw(userId); 17349 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17350 scheduleWritePackageRestrictionsLocked(userId); 17351 } 17352 resetNetworkPolicies(userId); 17353 } finally { 17354 Binder.restoreCallingIdentity(identity); 17355 } 17356 } 17357 17358 @Override 17359 public int getPreferredActivities(List<IntentFilter> outFilters, 17360 List<ComponentName> outActivities, String packageName) { 17361 17362 int num = 0; 17363 final int userId = UserHandle.getCallingUserId(); 17364 // reader 17365 synchronized (mPackages) { 17366 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17367 if (pir != null) { 17368 final Iterator<PreferredActivity> it = pir.filterIterator(); 17369 while (it.hasNext()) { 17370 final PreferredActivity pa = it.next(); 17371 if (packageName == null 17372 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17373 && pa.mPref.mAlways)) { 17374 if (outFilters != null) { 17375 outFilters.add(new IntentFilter(pa)); 17376 } 17377 if (outActivities != null) { 17378 outActivities.add(pa.mPref.mComponent); 17379 } 17380 } 17381 } 17382 } 17383 } 17384 17385 return num; 17386 } 17387 17388 @Override 17389 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17390 int userId) { 17391 int callingUid = Binder.getCallingUid(); 17392 if (callingUid != Process.SYSTEM_UID) { 17393 throw new SecurityException( 17394 "addPersistentPreferredActivity can only be run by the system"); 17395 } 17396 if (filter.countActions() == 0) { 17397 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17398 return; 17399 } 17400 synchronized (mPackages) { 17401 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17402 ":"); 17403 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17404 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17405 new PersistentPreferredActivity(filter, activity)); 17406 scheduleWritePackageRestrictionsLocked(userId); 17407 postPreferredActivityChangedBroadcast(userId); 17408 } 17409 } 17410 17411 @Override 17412 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17413 int callingUid = Binder.getCallingUid(); 17414 if (callingUid != Process.SYSTEM_UID) { 17415 throw new SecurityException( 17416 "clearPackagePersistentPreferredActivities can only be run by the system"); 17417 } 17418 ArrayList<PersistentPreferredActivity> removed = null; 17419 boolean changed = false; 17420 synchronized (mPackages) { 17421 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17422 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17423 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17424 .valueAt(i); 17425 if (userId != thisUserId) { 17426 continue; 17427 } 17428 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17429 while (it.hasNext()) { 17430 PersistentPreferredActivity ppa = it.next(); 17431 // Mark entry for removal only if it matches the package name. 17432 if (ppa.mComponent.getPackageName().equals(packageName)) { 17433 if (removed == null) { 17434 removed = new ArrayList<PersistentPreferredActivity>(); 17435 } 17436 removed.add(ppa); 17437 } 17438 } 17439 if (removed != null) { 17440 for (int j=0; j<removed.size(); j++) { 17441 PersistentPreferredActivity ppa = removed.get(j); 17442 ppir.removeFilter(ppa); 17443 } 17444 changed = true; 17445 } 17446 } 17447 17448 if (changed) { 17449 scheduleWritePackageRestrictionsLocked(userId); 17450 postPreferredActivityChangedBroadcast(userId); 17451 } 17452 } 17453 } 17454 17455 /** 17456 * Common machinery for picking apart a restored XML blob and passing 17457 * it to a caller-supplied functor to be applied to the running system. 17458 */ 17459 private void restoreFromXml(XmlPullParser parser, int userId, 17460 String expectedStartTag, BlobXmlRestorer functor) 17461 throws IOException, XmlPullParserException { 17462 int type; 17463 while ((type = parser.next()) != XmlPullParser.START_TAG 17464 && type != XmlPullParser.END_DOCUMENT) { 17465 } 17466 if (type != XmlPullParser.START_TAG) { 17467 // oops didn't find a start tag?! 17468 if (DEBUG_BACKUP) { 17469 Slog.e(TAG, "Didn't find start tag during restore"); 17470 } 17471 return; 17472 } 17473Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17474 // this is supposed to be TAG_PREFERRED_BACKUP 17475 if (!expectedStartTag.equals(parser.getName())) { 17476 if (DEBUG_BACKUP) { 17477 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17478 } 17479 return; 17480 } 17481 17482 // skip interfering stuff, then we're aligned with the backing implementation 17483 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17484Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17485 functor.apply(parser, userId); 17486 } 17487 17488 private interface BlobXmlRestorer { 17489 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17490 } 17491 17492 /** 17493 * Non-Binder method, support for the backup/restore mechanism: write the 17494 * full set of preferred activities in its canonical XML format. Returns the 17495 * XML output as a byte array, or null if there is none. 17496 */ 17497 @Override 17498 public byte[] getPreferredActivityBackup(int userId) { 17499 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17500 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17501 } 17502 17503 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17504 try { 17505 final XmlSerializer serializer = new FastXmlSerializer(); 17506 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17507 serializer.startDocument(null, true); 17508 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17509 17510 synchronized (mPackages) { 17511 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17512 } 17513 17514 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17515 serializer.endDocument(); 17516 serializer.flush(); 17517 } catch (Exception e) { 17518 if (DEBUG_BACKUP) { 17519 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17520 } 17521 return null; 17522 } 17523 17524 return dataStream.toByteArray(); 17525 } 17526 17527 @Override 17528 public void restorePreferredActivities(byte[] backup, int userId) { 17529 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17530 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17531 } 17532 17533 try { 17534 final XmlPullParser parser = Xml.newPullParser(); 17535 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17536 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17537 new BlobXmlRestorer() { 17538 @Override 17539 public void apply(XmlPullParser parser, int userId) 17540 throws XmlPullParserException, IOException { 17541 synchronized (mPackages) { 17542 mSettings.readPreferredActivitiesLPw(parser, userId); 17543 } 17544 } 17545 } ); 17546 } catch (Exception e) { 17547 if (DEBUG_BACKUP) { 17548 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17549 } 17550 } 17551 } 17552 17553 /** 17554 * Non-Binder method, support for the backup/restore mechanism: write the 17555 * default browser (etc) settings in its canonical XML format. Returns the default 17556 * browser XML representation as a byte array, or null if there is none. 17557 */ 17558 @Override 17559 public byte[] getDefaultAppsBackup(int userId) { 17560 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17561 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17562 } 17563 17564 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17565 try { 17566 final XmlSerializer serializer = new FastXmlSerializer(); 17567 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17568 serializer.startDocument(null, true); 17569 serializer.startTag(null, TAG_DEFAULT_APPS); 17570 17571 synchronized (mPackages) { 17572 mSettings.writeDefaultAppsLPr(serializer, userId); 17573 } 17574 17575 serializer.endTag(null, TAG_DEFAULT_APPS); 17576 serializer.endDocument(); 17577 serializer.flush(); 17578 } catch (Exception e) { 17579 if (DEBUG_BACKUP) { 17580 Slog.e(TAG, "Unable to write default apps for backup", e); 17581 } 17582 return null; 17583 } 17584 17585 return dataStream.toByteArray(); 17586 } 17587 17588 @Override 17589 public void restoreDefaultApps(byte[] backup, int userId) { 17590 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17591 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17592 } 17593 17594 try { 17595 final XmlPullParser parser = Xml.newPullParser(); 17596 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17597 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17598 new BlobXmlRestorer() { 17599 @Override 17600 public void apply(XmlPullParser parser, int userId) 17601 throws XmlPullParserException, IOException { 17602 synchronized (mPackages) { 17603 mSettings.readDefaultAppsLPw(parser, userId); 17604 } 17605 } 17606 } ); 17607 } catch (Exception e) { 17608 if (DEBUG_BACKUP) { 17609 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17610 } 17611 } 17612 } 17613 17614 @Override 17615 public byte[] getIntentFilterVerificationBackup(int userId) { 17616 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17617 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17618 } 17619 17620 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17621 try { 17622 final XmlSerializer serializer = new FastXmlSerializer(); 17623 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17624 serializer.startDocument(null, true); 17625 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17626 17627 synchronized (mPackages) { 17628 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17629 } 17630 17631 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17632 serializer.endDocument(); 17633 serializer.flush(); 17634 } catch (Exception e) { 17635 if (DEBUG_BACKUP) { 17636 Slog.e(TAG, "Unable to write default apps for backup", e); 17637 } 17638 return null; 17639 } 17640 17641 return dataStream.toByteArray(); 17642 } 17643 17644 @Override 17645 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17646 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17647 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17648 } 17649 17650 try { 17651 final XmlPullParser parser = Xml.newPullParser(); 17652 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17653 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17654 new BlobXmlRestorer() { 17655 @Override 17656 public void apply(XmlPullParser parser, int userId) 17657 throws XmlPullParserException, IOException { 17658 synchronized (mPackages) { 17659 mSettings.readAllDomainVerificationsLPr(parser, userId); 17660 mSettings.writeLPr(); 17661 } 17662 } 17663 } ); 17664 } catch (Exception e) { 17665 if (DEBUG_BACKUP) { 17666 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17667 } 17668 } 17669 } 17670 17671 @Override 17672 public byte[] getPermissionGrantBackup(int userId) { 17673 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17674 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17675 } 17676 17677 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17678 try { 17679 final XmlSerializer serializer = new FastXmlSerializer(); 17680 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17681 serializer.startDocument(null, true); 17682 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17683 17684 synchronized (mPackages) { 17685 serializeRuntimePermissionGrantsLPr(serializer, userId); 17686 } 17687 17688 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17689 serializer.endDocument(); 17690 serializer.flush(); 17691 } catch (Exception e) { 17692 if (DEBUG_BACKUP) { 17693 Slog.e(TAG, "Unable to write default apps for backup", e); 17694 } 17695 return null; 17696 } 17697 17698 return dataStream.toByteArray(); 17699 } 17700 17701 @Override 17702 public void restorePermissionGrants(byte[] backup, int userId) { 17703 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17704 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17705 } 17706 17707 try { 17708 final XmlPullParser parser = Xml.newPullParser(); 17709 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17710 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17711 new BlobXmlRestorer() { 17712 @Override 17713 public void apply(XmlPullParser parser, int userId) 17714 throws XmlPullParserException, IOException { 17715 synchronized (mPackages) { 17716 processRestoredPermissionGrantsLPr(parser, userId); 17717 } 17718 } 17719 } ); 17720 } catch (Exception e) { 17721 if (DEBUG_BACKUP) { 17722 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17723 } 17724 } 17725 } 17726 17727 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17728 throws IOException { 17729 serializer.startTag(null, TAG_ALL_GRANTS); 17730 17731 final int N = mSettings.mPackages.size(); 17732 for (int i = 0; i < N; i++) { 17733 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17734 boolean pkgGrantsKnown = false; 17735 17736 PermissionsState packagePerms = ps.getPermissionsState(); 17737 17738 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17739 final int grantFlags = state.getFlags(); 17740 // only look at grants that are not system/policy fixed 17741 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17742 final boolean isGranted = state.isGranted(); 17743 // And only back up the user-twiddled state bits 17744 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17745 final String packageName = mSettings.mPackages.keyAt(i); 17746 if (!pkgGrantsKnown) { 17747 serializer.startTag(null, TAG_GRANT); 17748 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17749 pkgGrantsKnown = true; 17750 } 17751 17752 final boolean userSet = 17753 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17754 final boolean userFixed = 17755 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17756 final boolean revoke = 17757 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17758 17759 serializer.startTag(null, TAG_PERMISSION); 17760 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17761 if (isGranted) { 17762 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17763 } 17764 if (userSet) { 17765 serializer.attribute(null, ATTR_USER_SET, "true"); 17766 } 17767 if (userFixed) { 17768 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17769 } 17770 if (revoke) { 17771 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17772 } 17773 serializer.endTag(null, TAG_PERMISSION); 17774 } 17775 } 17776 } 17777 17778 if (pkgGrantsKnown) { 17779 serializer.endTag(null, TAG_GRANT); 17780 } 17781 } 17782 17783 serializer.endTag(null, TAG_ALL_GRANTS); 17784 } 17785 17786 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17787 throws XmlPullParserException, IOException { 17788 String pkgName = null; 17789 int outerDepth = parser.getDepth(); 17790 int type; 17791 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17792 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17793 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17794 continue; 17795 } 17796 17797 final String tagName = parser.getName(); 17798 if (tagName.equals(TAG_GRANT)) { 17799 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17800 if (DEBUG_BACKUP) { 17801 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17802 } 17803 } else if (tagName.equals(TAG_PERMISSION)) { 17804 17805 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17806 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17807 17808 int newFlagSet = 0; 17809 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17810 newFlagSet |= FLAG_PERMISSION_USER_SET; 17811 } 17812 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17813 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17814 } 17815 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17816 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17817 } 17818 if (DEBUG_BACKUP) { 17819 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17820 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17821 } 17822 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17823 if (ps != null) { 17824 // Already installed so we apply the grant immediately 17825 if (DEBUG_BACKUP) { 17826 Slog.v(TAG, " + already installed; applying"); 17827 } 17828 PermissionsState perms = ps.getPermissionsState(); 17829 BasePermission bp = mSettings.mPermissions.get(permName); 17830 if (bp != null) { 17831 if (isGranted) { 17832 perms.grantRuntimePermission(bp, userId); 17833 } 17834 if (newFlagSet != 0) { 17835 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17836 } 17837 } 17838 } else { 17839 // Need to wait for post-restore install to apply the grant 17840 if (DEBUG_BACKUP) { 17841 Slog.v(TAG, " - not yet installed; saving for later"); 17842 } 17843 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17844 isGranted, newFlagSet, userId); 17845 } 17846 } else { 17847 PackageManagerService.reportSettingsProblem(Log.WARN, 17848 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17849 XmlUtils.skipCurrentTag(parser); 17850 } 17851 } 17852 17853 scheduleWriteSettingsLocked(); 17854 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17855 } 17856 17857 @Override 17858 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17859 int sourceUserId, int targetUserId, int flags) { 17860 mContext.enforceCallingOrSelfPermission( 17861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17862 int callingUid = Binder.getCallingUid(); 17863 enforceOwnerRights(ownerPackage, callingUid); 17864 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17865 if (intentFilter.countActions() == 0) { 17866 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17867 return; 17868 } 17869 synchronized (mPackages) { 17870 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17871 ownerPackage, targetUserId, flags); 17872 CrossProfileIntentResolver resolver = 17873 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17874 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17875 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17876 if (existing != null) { 17877 int size = existing.size(); 17878 for (int i = 0; i < size; i++) { 17879 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17880 return; 17881 } 17882 } 17883 } 17884 resolver.addFilter(newFilter); 17885 scheduleWritePackageRestrictionsLocked(sourceUserId); 17886 } 17887 } 17888 17889 @Override 17890 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17891 mContext.enforceCallingOrSelfPermission( 17892 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17893 int callingUid = Binder.getCallingUid(); 17894 enforceOwnerRights(ownerPackage, callingUid); 17895 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17896 synchronized (mPackages) { 17897 CrossProfileIntentResolver resolver = 17898 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17899 ArraySet<CrossProfileIntentFilter> set = 17900 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17901 for (CrossProfileIntentFilter filter : set) { 17902 if (filter.getOwnerPackage().equals(ownerPackage)) { 17903 resolver.removeFilter(filter); 17904 } 17905 } 17906 scheduleWritePackageRestrictionsLocked(sourceUserId); 17907 } 17908 } 17909 17910 // Enforcing that callingUid is owning pkg on userId 17911 private void enforceOwnerRights(String pkg, int callingUid) { 17912 // The system owns everything. 17913 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17914 return; 17915 } 17916 int callingUserId = UserHandle.getUserId(callingUid); 17917 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17918 if (pi == null) { 17919 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17920 + callingUserId); 17921 } 17922 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17923 throw new SecurityException("Calling uid " + callingUid 17924 + " does not own package " + pkg); 17925 } 17926 } 17927 17928 @Override 17929 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17930 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17931 } 17932 17933 private Intent getHomeIntent() { 17934 Intent intent = new Intent(Intent.ACTION_MAIN); 17935 intent.addCategory(Intent.CATEGORY_HOME); 17936 intent.addCategory(Intent.CATEGORY_DEFAULT); 17937 return intent; 17938 } 17939 17940 private IntentFilter getHomeFilter() { 17941 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17942 filter.addCategory(Intent.CATEGORY_HOME); 17943 filter.addCategory(Intent.CATEGORY_DEFAULT); 17944 return filter; 17945 } 17946 17947 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17948 int userId) { 17949 Intent intent = getHomeIntent(); 17950 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17951 PackageManager.GET_META_DATA, userId); 17952 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17953 true, false, false, userId); 17954 17955 allHomeCandidates.clear(); 17956 if (list != null) { 17957 for (ResolveInfo ri : list) { 17958 allHomeCandidates.add(ri); 17959 } 17960 } 17961 return (preferred == null || preferred.activityInfo == null) 17962 ? null 17963 : new ComponentName(preferred.activityInfo.packageName, 17964 preferred.activityInfo.name); 17965 } 17966 17967 @Override 17968 public void setHomeActivity(ComponentName comp, int userId) { 17969 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17970 getHomeActivitiesAsUser(homeActivities, userId); 17971 17972 boolean found = false; 17973 17974 final int size = homeActivities.size(); 17975 final ComponentName[] set = new ComponentName[size]; 17976 for (int i = 0; i < size; i++) { 17977 final ResolveInfo candidate = homeActivities.get(i); 17978 final ActivityInfo info = candidate.activityInfo; 17979 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17980 set[i] = activityName; 17981 if (!found && activityName.equals(comp)) { 17982 found = true; 17983 } 17984 } 17985 if (!found) { 17986 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17987 + userId); 17988 } 17989 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17990 set, comp, userId); 17991 } 17992 17993 private @Nullable String getSetupWizardPackageName() { 17994 final Intent intent = new Intent(Intent.ACTION_MAIN); 17995 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17996 17997 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17998 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17999 | MATCH_DISABLED_COMPONENTS, 18000 UserHandle.myUserId()); 18001 if (matches.size() == 1) { 18002 return matches.get(0).getComponentInfo().packageName; 18003 } else { 18004 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18005 + ": matches=" + matches); 18006 return null; 18007 } 18008 } 18009 18010 private @Nullable String getStorageManagerPackageName() { 18011 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18012 18013 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18014 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18015 | MATCH_DISABLED_COMPONENTS, 18016 UserHandle.myUserId()); 18017 if (matches.size() == 1) { 18018 return matches.get(0).getComponentInfo().packageName; 18019 } else { 18020 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18021 + matches.size() + ": matches=" + matches); 18022 return null; 18023 } 18024 } 18025 18026 @Override 18027 public void setApplicationEnabledSetting(String appPackageName, 18028 int newState, int flags, int userId, String callingPackage) { 18029 if (!sUserManager.exists(userId)) return; 18030 if (callingPackage == null) { 18031 callingPackage = Integer.toString(Binder.getCallingUid()); 18032 } 18033 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18034 } 18035 18036 @Override 18037 public void setComponentEnabledSetting(ComponentName componentName, 18038 int newState, int flags, int userId) { 18039 if (!sUserManager.exists(userId)) return; 18040 setEnabledSetting(componentName.getPackageName(), 18041 componentName.getClassName(), newState, flags, userId, null); 18042 } 18043 18044 private void setEnabledSetting(final String packageName, String className, int newState, 18045 final int flags, int userId, String callingPackage) { 18046 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18047 || newState == COMPONENT_ENABLED_STATE_ENABLED 18048 || newState == COMPONENT_ENABLED_STATE_DISABLED 18049 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18050 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18051 throw new IllegalArgumentException("Invalid new component state: " 18052 + newState); 18053 } 18054 PackageSetting pkgSetting; 18055 final int uid = Binder.getCallingUid(); 18056 final int permission; 18057 if (uid == Process.SYSTEM_UID) { 18058 permission = PackageManager.PERMISSION_GRANTED; 18059 } else { 18060 permission = mContext.checkCallingOrSelfPermission( 18061 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18062 } 18063 enforceCrossUserPermission(uid, userId, 18064 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18065 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18066 boolean sendNow = false; 18067 boolean isApp = (className == null); 18068 String componentName = isApp ? packageName : className; 18069 int packageUid = -1; 18070 ArrayList<String> components; 18071 18072 // writer 18073 synchronized (mPackages) { 18074 pkgSetting = mSettings.mPackages.get(packageName); 18075 if (pkgSetting == null) { 18076 if (className == null) { 18077 throw new IllegalArgumentException("Unknown package: " + packageName); 18078 } 18079 throw new IllegalArgumentException( 18080 "Unknown component: " + packageName + "/" + className); 18081 } 18082 } 18083 18084 // Limit who can change which apps 18085 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18086 // Don't allow apps that don't have permission to modify other apps 18087 if (!allowedByPermission) { 18088 throw new SecurityException( 18089 "Permission Denial: attempt to change component state from pid=" 18090 + Binder.getCallingPid() 18091 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18092 } 18093 // Don't allow changing protected packages. 18094 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18095 throw new SecurityException("Cannot disable a protected package: " + packageName); 18096 } 18097 } 18098 18099 synchronized (mPackages) { 18100 if (uid == Process.SHELL_UID) { 18101 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18102 int oldState = pkgSetting.getEnabled(userId); 18103 if (className == null 18104 && 18105 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18106 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18107 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18108 && 18109 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18110 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18111 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18112 // ok 18113 } else { 18114 throw new SecurityException( 18115 "Shell cannot change component state for " + packageName + "/" 18116 + className + " to " + newState); 18117 } 18118 } 18119 if (className == null) { 18120 // We're dealing with an application/package level state change 18121 if (pkgSetting.getEnabled(userId) == newState) { 18122 // Nothing to do 18123 return; 18124 } 18125 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18126 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18127 // Don't care about who enables an app. 18128 callingPackage = null; 18129 } 18130 pkgSetting.setEnabled(newState, userId, callingPackage); 18131 // pkgSetting.pkg.mSetEnabled = newState; 18132 } else { 18133 // We're dealing with a component level state change 18134 // First, verify that this is a valid class name. 18135 PackageParser.Package pkg = pkgSetting.pkg; 18136 if (pkg == null || !pkg.hasComponentClassName(className)) { 18137 if (pkg != null && 18138 pkg.applicationInfo.targetSdkVersion >= 18139 Build.VERSION_CODES.JELLY_BEAN) { 18140 throw new IllegalArgumentException("Component class " + className 18141 + " does not exist in " + packageName); 18142 } else { 18143 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18144 + className + " does not exist in " + packageName); 18145 } 18146 } 18147 switch (newState) { 18148 case COMPONENT_ENABLED_STATE_ENABLED: 18149 if (!pkgSetting.enableComponentLPw(className, userId)) { 18150 return; 18151 } 18152 break; 18153 case COMPONENT_ENABLED_STATE_DISABLED: 18154 if (!pkgSetting.disableComponentLPw(className, userId)) { 18155 return; 18156 } 18157 break; 18158 case COMPONENT_ENABLED_STATE_DEFAULT: 18159 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18160 return; 18161 } 18162 break; 18163 default: 18164 Slog.e(TAG, "Invalid new component state: " + newState); 18165 return; 18166 } 18167 } 18168 scheduleWritePackageRestrictionsLocked(userId); 18169 components = mPendingBroadcasts.get(userId, packageName); 18170 final boolean newPackage = components == null; 18171 if (newPackage) { 18172 components = new ArrayList<String>(); 18173 } 18174 if (!components.contains(componentName)) { 18175 components.add(componentName); 18176 } 18177 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18178 sendNow = true; 18179 // Purge entry from pending broadcast list if another one exists already 18180 // since we are sending one right away. 18181 mPendingBroadcasts.remove(userId, packageName); 18182 } else { 18183 if (newPackage) { 18184 mPendingBroadcasts.put(userId, packageName, components); 18185 } 18186 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18187 // Schedule a message 18188 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18189 } 18190 } 18191 } 18192 18193 long callingId = Binder.clearCallingIdentity(); 18194 try { 18195 if (sendNow) { 18196 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18197 sendPackageChangedBroadcast(packageName, 18198 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18199 } 18200 } finally { 18201 Binder.restoreCallingIdentity(callingId); 18202 } 18203 } 18204 18205 @Override 18206 public void flushPackageRestrictionsAsUser(int userId) { 18207 if (!sUserManager.exists(userId)) { 18208 return; 18209 } 18210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18211 false /* checkShell */, "flushPackageRestrictions"); 18212 synchronized (mPackages) { 18213 mSettings.writePackageRestrictionsLPr(userId); 18214 mDirtyUsers.remove(userId); 18215 if (mDirtyUsers.isEmpty()) { 18216 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18217 } 18218 } 18219 } 18220 18221 private void sendPackageChangedBroadcast(String packageName, 18222 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18223 if (DEBUG_INSTALL) 18224 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18225 + componentNames); 18226 Bundle extras = new Bundle(4); 18227 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18228 String nameList[] = new String[componentNames.size()]; 18229 componentNames.toArray(nameList); 18230 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18231 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18232 extras.putInt(Intent.EXTRA_UID, packageUid); 18233 // If this is not reporting a change of the overall package, then only send it 18234 // to registered receivers. We don't want to launch a swath of apps for every 18235 // little component state change. 18236 final int flags = !componentNames.contains(packageName) 18237 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18238 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18239 new int[] {UserHandle.getUserId(packageUid)}); 18240 } 18241 18242 @Override 18243 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18244 if (!sUserManager.exists(userId)) return; 18245 final int uid = Binder.getCallingUid(); 18246 final int permission = mContext.checkCallingOrSelfPermission( 18247 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18248 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18249 enforceCrossUserPermission(uid, userId, 18250 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18251 // writer 18252 synchronized (mPackages) { 18253 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18254 allowedByPermission, uid, userId)) { 18255 scheduleWritePackageRestrictionsLocked(userId); 18256 } 18257 } 18258 } 18259 18260 @Override 18261 public String getInstallerPackageName(String packageName) { 18262 // reader 18263 synchronized (mPackages) { 18264 return mSettings.getInstallerPackageNameLPr(packageName); 18265 } 18266 } 18267 18268 public boolean isOrphaned(String packageName) { 18269 // reader 18270 synchronized (mPackages) { 18271 return mSettings.isOrphaned(packageName); 18272 } 18273 } 18274 18275 @Override 18276 public int getApplicationEnabledSetting(String packageName, int userId) { 18277 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18278 int uid = Binder.getCallingUid(); 18279 enforceCrossUserPermission(uid, userId, 18280 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18281 // reader 18282 synchronized (mPackages) { 18283 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18284 } 18285 } 18286 18287 @Override 18288 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18289 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18290 int uid = Binder.getCallingUid(); 18291 enforceCrossUserPermission(uid, userId, 18292 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18293 // reader 18294 synchronized (mPackages) { 18295 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18296 } 18297 } 18298 18299 @Override 18300 public void enterSafeMode() { 18301 enforceSystemOrRoot("Only the system can request entering safe mode"); 18302 18303 if (!mSystemReady) { 18304 mSafeMode = true; 18305 } 18306 } 18307 18308 @Override 18309 public void systemReady() { 18310 mSystemReady = true; 18311 18312 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18313 // disabled after already being started. 18314 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18315 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18316 18317 // Read the compatibilty setting when the system is ready. 18318 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18319 mContext.getContentResolver(), 18320 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18321 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18322 if (DEBUG_SETTINGS) { 18323 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18324 } 18325 18326 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18327 18328 synchronized (mPackages) { 18329 // Verify that all of the preferred activity components actually 18330 // exist. It is possible for applications to be updated and at 18331 // that point remove a previously declared activity component that 18332 // had been set as a preferred activity. We try to clean this up 18333 // the next time we encounter that preferred activity, but it is 18334 // possible for the user flow to never be able to return to that 18335 // situation so here we do a sanity check to make sure we haven't 18336 // left any junk around. 18337 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18338 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18339 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18340 removed.clear(); 18341 for (PreferredActivity pa : pir.filterSet()) { 18342 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18343 removed.add(pa); 18344 } 18345 } 18346 if (removed.size() > 0) { 18347 for (int r=0; r<removed.size(); r++) { 18348 PreferredActivity pa = removed.get(r); 18349 Slog.w(TAG, "Removing dangling preferred activity: " 18350 + pa.mPref.mComponent); 18351 pir.removeFilter(pa); 18352 } 18353 mSettings.writePackageRestrictionsLPr( 18354 mSettings.mPreferredActivities.keyAt(i)); 18355 } 18356 } 18357 18358 for (int userId : UserManagerService.getInstance().getUserIds()) { 18359 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18360 grantPermissionsUserIds = ArrayUtils.appendInt( 18361 grantPermissionsUserIds, userId); 18362 } 18363 } 18364 } 18365 sUserManager.systemReady(); 18366 18367 // If we upgraded grant all default permissions before kicking off. 18368 for (int userId : grantPermissionsUserIds) { 18369 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18370 } 18371 18372 // If we did not grant default permissions, we preload from this the 18373 // default permission exceptions lazily to ensure we don't hit the 18374 // disk on a new user creation. 18375 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18376 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18377 } 18378 18379 // Kick off any messages waiting for system ready 18380 if (mPostSystemReadyMessages != null) { 18381 for (Message msg : mPostSystemReadyMessages) { 18382 msg.sendToTarget(); 18383 } 18384 mPostSystemReadyMessages = null; 18385 } 18386 18387 // Watch for external volumes that come and go over time 18388 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18389 storage.registerListener(mStorageListener); 18390 18391 mInstallerService.systemReady(); 18392 mPackageDexOptimizer.systemReady(); 18393 18394 MountServiceInternal mountServiceInternal = LocalServices.getService( 18395 MountServiceInternal.class); 18396 mountServiceInternal.addExternalStoragePolicy( 18397 new MountServiceInternal.ExternalStorageMountPolicy() { 18398 @Override 18399 public int getMountMode(int uid, String packageName) { 18400 if (Process.isIsolated(uid)) { 18401 return Zygote.MOUNT_EXTERNAL_NONE; 18402 } 18403 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18404 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18405 } 18406 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18407 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18408 } 18409 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18410 return Zygote.MOUNT_EXTERNAL_READ; 18411 } 18412 return Zygote.MOUNT_EXTERNAL_WRITE; 18413 } 18414 18415 @Override 18416 public boolean hasExternalStorage(int uid, String packageName) { 18417 return true; 18418 } 18419 }); 18420 18421 // Now that we're mostly running, clean up stale users and apps 18422 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18423 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18424 } 18425 18426 @Override 18427 public boolean isSafeMode() { 18428 return mSafeMode; 18429 } 18430 18431 @Override 18432 public boolean hasSystemUidErrors() { 18433 return mHasSystemUidErrors; 18434 } 18435 18436 static String arrayToString(int[] array) { 18437 StringBuffer buf = new StringBuffer(128); 18438 buf.append('['); 18439 if (array != null) { 18440 for (int i=0; i<array.length; i++) { 18441 if (i > 0) buf.append(", "); 18442 buf.append(array[i]); 18443 } 18444 } 18445 buf.append(']'); 18446 return buf.toString(); 18447 } 18448 18449 static class DumpState { 18450 public static final int DUMP_LIBS = 1 << 0; 18451 public static final int DUMP_FEATURES = 1 << 1; 18452 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18453 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18454 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18455 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18456 public static final int DUMP_PERMISSIONS = 1 << 6; 18457 public static final int DUMP_PACKAGES = 1 << 7; 18458 public static final int DUMP_SHARED_USERS = 1 << 8; 18459 public static final int DUMP_MESSAGES = 1 << 9; 18460 public static final int DUMP_PROVIDERS = 1 << 10; 18461 public static final int DUMP_VERIFIERS = 1 << 11; 18462 public static final int DUMP_PREFERRED = 1 << 12; 18463 public static final int DUMP_PREFERRED_XML = 1 << 13; 18464 public static final int DUMP_KEYSETS = 1 << 14; 18465 public static final int DUMP_VERSION = 1 << 15; 18466 public static final int DUMP_INSTALLS = 1 << 16; 18467 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18468 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18469 public static final int DUMP_FROZEN = 1 << 19; 18470 public static final int DUMP_DEXOPT = 1 << 20; 18471 public static final int DUMP_COMPILER_STATS = 1 << 21; 18472 18473 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18474 18475 private int mTypes; 18476 18477 private int mOptions; 18478 18479 private boolean mTitlePrinted; 18480 18481 private SharedUserSetting mSharedUser; 18482 18483 public boolean isDumping(int type) { 18484 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18485 return true; 18486 } 18487 18488 return (mTypes & type) != 0; 18489 } 18490 18491 public void setDump(int type) { 18492 mTypes |= type; 18493 } 18494 18495 public boolean isOptionEnabled(int option) { 18496 return (mOptions & option) != 0; 18497 } 18498 18499 public void setOptionEnabled(int option) { 18500 mOptions |= option; 18501 } 18502 18503 public boolean onTitlePrinted() { 18504 final boolean printed = mTitlePrinted; 18505 mTitlePrinted = true; 18506 return printed; 18507 } 18508 18509 public boolean getTitlePrinted() { 18510 return mTitlePrinted; 18511 } 18512 18513 public void setTitlePrinted(boolean enabled) { 18514 mTitlePrinted = enabled; 18515 } 18516 18517 public SharedUserSetting getSharedUser() { 18518 return mSharedUser; 18519 } 18520 18521 public void setSharedUser(SharedUserSetting user) { 18522 mSharedUser = user; 18523 } 18524 } 18525 18526 @Override 18527 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18528 FileDescriptor err, String[] args, ShellCallback callback, 18529 ResultReceiver resultReceiver) { 18530 (new PackageManagerShellCommand(this)).exec( 18531 this, in, out, err, args, callback, resultReceiver); 18532 } 18533 18534 @Override 18535 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18536 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18537 != PackageManager.PERMISSION_GRANTED) { 18538 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18539 + Binder.getCallingPid() 18540 + ", uid=" + Binder.getCallingUid() 18541 + " without permission " 18542 + android.Manifest.permission.DUMP); 18543 return; 18544 } 18545 18546 DumpState dumpState = new DumpState(); 18547 boolean fullPreferred = false; 18548 boolean checkin = false; 18549 18550 String packageName = null; 18551 ArraySet<String> permissionNames = null; 18552 18553 int opti = 0; 18554 while (opti < args.length) { 18555 String opt = args[opti]; 18556 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18557 break; 18558 } 18559 opti++; 18560 18561 if ("-a".equals(opt)) { 18562 // Right now we only know how to print all. 18563 } else if ("-h".equals(opt)) { 18564 pw.println("Package manager dump options:"); 18565 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18566 pw.println(" --checkin: dump for a checkin"); 18567 pw.println(" -f: print details of intent filters"); 18568 pw.println(" -h: print this help"); 18569 pw.println(" cmd may be one of:"); 18570 pw.println(" l[ibraries]: list known shared libraries"); 18571 pw.println(" f[eatures]: list device features"); 18572 pw.println(" k[eysets]: print known keysets"); 18573 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18574 pw.println(" perm[issions]: dump permissions"); 18575 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18576 pw.println(" pref[erred]: print preferred package settings"); 18577 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18578 pw.println(" prov[iders]: dump content providers"); 18579 pw.println(" p[ackages]: dump installed packages"); 18580 pw.println(" s[hared-users]: dump shared user IDs"); 18581 pw.println(" m[essages]: print collected runtime messages"); 18582 pw.println(" v[erifiers]: print package verifier info"); 18583 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18584 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18585 pw.println(" version: print database version info"); 18586 pw.println(" write: write current settings now"); 18587 pw.println(" installs: details about install sessions"); 18588 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18589 pw.println(" dexopt: dump dexopt state"); 18590 pw.println(" compiler-stats: dump compiler statistics"); 18591 pw.println(" <package.name>: info about given package"); 18592 return; 18593 } else if ("--checkin".equals(opt)) { 18594 checkin = true; 18595 } else if ("-f".equals(opt)) { 18596 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18597 } else { 18598 pw.println("Unknown argument: " + opt + "; use -h for help"); 18599 } 18600 } 18601 18602 // Is the caller requesting to dump a particular piece of data? 18603 if (opti < args.length) { 18604 String cmd = args[opti]; 18605 opti++; 18606 // Is this a package name? 18607 if ("android".equals(cmd) || cmd.contains(".")) { 18608 packageName = cmd; 18609 // When dumping a single package, we always dump all of its 18610 // filter information since the amount of data will be reasonable. 18611 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18612 } else if ("check-permission".equals(cmd)) { 18613 if (opti >= args.length) { 18614 pw.println("Error: check-permission missing permission argument"); 18615 return; 18616 } 18617 String perm = args[opti]; 18618 opti++; 18619 if (opti >= args.length) { 18620 pw.println("Error: check-permission missing package argument"); 18621 return; 18622 } 18623 String pkg = args[opti]; 18624 opti++; 18625 int user = UserHandle.getUserId(Binder.getCallingUid()); 18626 if (opti < args.length) { 18627 try { 18628 user = Integer.parseInt(args[opti]); 18629 } catch (NumberFormatException e) { 18630 pw.println("Error: check-permission user argument is not a number: " 18631 + args[opti]); 18632 return; 18633 } 18634 } 18635 pw.println(checkPermission(perm, pkg, user)); 18636 return; 18637 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18638 dumpState.setDump(DumpState.DUMP_LIBS); 18639 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18640 dumpState.setDump(DumpState.DUMP_FEATURES); 18641 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18642 if (opti >= args.length) { 18643 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18644 | DumpState.DUMP_SERVICE_RESOLVERS 18645 | DumpState.DUMP_RECEIVER_RESOLVERS 18646 | DumpState.DUMP_CONTENT_RESOLVERS); 18647 } else { 18648 while (opti < args.length) { 18649 String name = args[opti]; 18650 if ("a".equals(name) || "activity".equals(name)) { 18651 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18652 } else if ("s".equals(name) || "service".equals(name)) { 18653 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18654 } else if ("r".equals(name) || "receiver".equals(name)) { 18655 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18656 } else if ("c".equals(name) || "content".equals(name)) { 18657 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18658 } else { 18659 pw.println("Error: unknown resolver table type: " + name); 18660 return; 18661 } 18662 opti++; 18663 } 18664 } 18665 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18666 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18667 } else if ("permission".equals(cmd)) { 18668 if (opti >= args.length) { 18669 pw.println("Error: permission requires permission name"); 18670 return; 18671 } 18672 permissionNames = new ArraySet<>(); 18673 while (opti < args.length) { 18674 permissionNames.add(args[opti]); 18675 opti++; 18676 } 18677 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18678 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18679 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18680 dumpState.setDump(DumpState.DUMP_PREFERRED); 18681 } else if ("preferred-xml".equals(cmd)) { 18682 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18683 if (opti < args.length && "--full".equals(args[opti])) { 18684 fullPreferred = true; 18685 opti++; 18686 } 18687 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18688 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18689 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18690 dumpState.setDump(DumpState.DUMP_PACKAGES); 18691 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18692 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18693 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18694 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18695 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18696 dumpState.setDump(DumpState.DUMP_MESSAGES); 18697 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18698 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18699 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18700 || "intent-filter-verifiers".equals(cmd)) { 18701 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18702 } else if ("version".equals(cmd)) { 18703 dumpState.setDump(DumpState.DUMP_VERSION); 18704 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18705 dumpState.setDump(DumpState.DUMP_KEYSETS); 18706 } else if ("installs".equals(cmd)) { 18707 dumpState.setDump(DumpState.DUMP_INSTALLS); 18708 } else if ("frozen".equals(cmd)) { 18709 dumpState.setDump(DumpState.DUMP_FROZEN); 18710 } else if ("dexopt".equals(cmd)) { 18711 dumpState.setDump(DumpState.DUMP_DEXOPT); 18712 } else if ("compiler-stats".equals(cmd)) { 18713 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18714 } else if ("write".equals(cmd)) { 18715 synchronized (mPackages) { 18716 mSettings.writeLPr(); 18717 pw.println("Settings written."); 18718 return; 18719 } 18720 } 18721 } 18722 18723 if (checkin) { 18724 pw.println("vers,1"); 18725 } 18726 18727 // reader 18728 synchronized (mPackages) { 18729 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18730 if (!checkin) { 18731 if (dumpState.onTitlePrinted()) 18732 pw.println(); 18733 pw.println("Database versions:"); 18734 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18735 } 18736 } 18737 18738 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18739 if (!checkin) { 18740 if (dumpState.onTitlePrinted()) 18741 pw.println(); 18742 pw.println("Verifiers:"); 18743 pw.print(" Required: "); 18744 pw.print(mRequiredVerifierPackage); 18745 pw.print(" (uid="); 18746 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18747 UserHandle.USER_SYSTEM)); 18748 pw.println(")"); 18749 } else if (mRequiredVerifierPackage != null) { 18750 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18751 pw.print(","); 18752 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18753 UserHandle.USER_SYSTEM)); 18754 } 18755 } 18756 18757 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18758 packageName == null) { 18759 if (mIntentFilterVerifierComponent != null) { 18760 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18761 if (!checkin) { 18762 if (dumpState.onTitlePrinted()) 18763 pw.println(); 18764 pw.println("Intent Filter Verifier:"); 18765 pw.print(" Using: "); 18766 pw.print(verifierPackageName); 18767 pw.print(" (uid="); 18768 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18769 UserHandle.USER_SYSTEM)); 18770 pw.println(")"); 18771 } else if (verifierPackageName != null) { 18772 pw.print("ifv,"); pw.print(verifierPackageName); 18773 pw.print(","); 18774 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18775 UserHandle.USER_SYSTEM)); 18776 } 18777 } else { 18778 pw.println(); 18779 pw.println("No Intent Filter Verifier available!"); 18780 } 18781 } 18782 18783 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18784 boolean printedHeader = false; 18785 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18786 while (it.hasNext()) { 18787 String name = it.next(); 18788 SharedLibraryEntry ent = mSharedLibraries.get(name); 18789 if (!checkin) { 18790 if (!printedHeader) { 18791 if (dumpState.onTitlePrinted()) 18792 pw.println(); 18793 pw.println("Libraries:"); 18794 printedHeader = true; 18795 } 18796 pw.print(" "); 18797 } else { 18798 pw.print("lib,"); 18799 } 18800 pw.print(name); 18801 if (!checkin) { 18802 pw.print(" -> "); 18803 } 18804 if (ent.path != null) { 18805 if (!checkin) { 18806 pw.print("(jar) "); 18807 pw.print(ent.path); 18808 } else { 18809 pw.print(",jar,"); 18810 pw.print(ent.path); 18811 } 18812 } else { 18813 if (!checkin) { 18814 pw.print("(apk) "); 18815 pw.print(ent.apk); 18816 } else { 18817 pw.print(",apk,"); 18818 pw.print(ent.apk); 18819 } 18820 } 18821 pw.println(); 18822 } 18823 } 18824 18825 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18826 if (dumpState.onTitlePrinted()) 18827 pw.println(); 18828 if (!checkin) { 18829 pw.println("Features:"); 18830 } 18831 18832 for (FeatureInfo feat : mAvailableFeatures.values()) { 18833 if (checkin) { 18834 pw.print("feat,"); 18835 pw.print(feat.name); 18836 pw.print(","); 18837 pw.println(feat.version); 18838 } else { 18839 pw.print(" "); 18840 pw.print(feat.name); 18841 if (feat.version > 0) { 18842 pw.print(" version="); 18843 pw.print(feat.version); 18844 } 18845 pw.println(); 18846 } 18847 } 18848 } 18849 18850 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18851 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18852 : "Activity Resolver Table:", " ", packageName, 18853 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18854 dumpState.setTitlePrinted(true); 18855 } 18856 } 18857 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18858 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18859 : "Receiver Resolver Table:", " ", packageName, 18860 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18861 dumpState.setTitlePrinted(true); 18862 } 18863 } 18864 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18865 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18866 : "Service Resolver Table:", " ", packageName, 18867 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18868 dumpState.setTitlePrinted(true); 18869 } 18870 } 18871 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18872 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18873 : "Provider Resolver Table:", " ", packageName, 18874 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18875 dumpState.setTitlePrinted(true); 18876 } 18877 } 18878 18879 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18880 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18881 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18882 int user = mSettings.mPreferredActivities.keyAt(i); 18883 if (pir.dump(pw, 18884 dumpState.getTitlePrinted() 18885 ? "\nPreferred Activities User " + user + ":" 18886 : "Preferred Activities User " + user + ":", " ", 18887 packageName, true, false)) { 18888 dumpState.setTitlePrinted(true); 18889 } 18890 } 18891 } 18892 18893 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18894 pw.flush(); 18895 FileOutputStream fout = new FileOutputStream(fd); 18896 BufferedOutputStream str = new BufferedOutputStream(fout); 18897 XmlSerializer serializer = new FastXmlSerializer(); 18898 try { 18899 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18900 serializer.startDocument(null, true); 18901 serializer.setFeature( 18902 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18903 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18904 serializer.endDocument(); 18905 serializer.flush(); 18906 } catch (IllegalArgumentException e) { 18907 pw.println("Failed writing: " + e); 18908 } catch (IllegalStateException e) { 18909 pw.println("Failed writing: " + e); 18910 } catch (IOException e) { 18911 pw.println("Failed writing: " + e); 18912 } 18913 } 18914 18915 if (!checkin 18916 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18917 && packageName == null) { 18918 pw.println(); 18919 int count = mSettings.mPackages.size(); 18920 if (count == 0) { 18921 pw.println("No applications!"); 18922 pw.println(); 18923 } else { 18924 final String prefix = " "; 18925 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18926 if (allPackageSettings.size() == 0) { 18927 pw.println("No domain preferred apps!"); 18928 pw.println(); 18929 } else { 18930 pw.println("App verification status:"); 18931 pw.println(); 18932 count = 0; 18933 for (PackageSetting ps : allPackageSettings) { 18934 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18935 if (ivi == null || ivi.getPackageName() == null) continue; 18936 pw.println(prefix + "Package: " + ivi.getPackageName()); 18937 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18938 pw.println(prefix + "Status: " + ivi.getStatusString()); 18939 pw.println(); 18940 count++; 18941 } 18942 if (count == 0) { 18943 pw.println(prefix + "No app verification established."); 18944 pw.println(); 18945 } 18946 for (int userId : sUserManager.getUserIds()) { 18947 pw.println("App linkages for user " + userId + ":"); 18948 pw.println(); 18949 count = 0; 18950 for (PackageSetting ps : allPackageSettings) { 18951 final long status = ps.getDomainVerificationStatusForUser(userId); 18952 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18953 continue; 18954 } 18955 pw.println(prefix + "Package: " + ps.name); 18956 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18957 String statusStr = IntentFilterVerificationInfo. 18958 getStatusStringFromValue(status); 18959 pw.println(prefix + "Status: " + statusStr); 18960 pw.println(); 18961 count++; 18962 } 18963 if (count == 0) { 18964 pw.println(prefix + "No configured app linkages."); 18965 pw.println(); 18966 } 18967 } 18968 } 18969 } 18970 } 18971 18972 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18973 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18974 if (packageName == null && permissionNames == null) { 18975 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18976 if (iperm == 0) { 18977 if (dumpState.onTitlePrinted()) 18978 pw.println(); 18979 pw.println("AppOp Permissions:"); 18980 } 18981 pw.print(" AppOp Permission "); 18982 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18983 pw.println(":"); 18984 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18985 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18986 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18987 } 18988 } 18989 } 18990 } 18991 18992 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18993 boolean printedSomething = false; 18994 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18995 if (packageName != null && !packageName.equals(p.info.packageName)) { 18996 continue; 18997 } 18998 if (!printedSomething) { 18999 if (dumpState.onTitlePrinted()) 19000 pw.println(); 19001 pw.println("Registered ContentProviders:"); 19002 printedSomething = true; 19003 } 19004 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19005 pw.print(" "); pw.println(p.toString()); 19006 } 19007 printedSomething = false; 19008 for (Map.Entry<String, PackageParser.Provider> entry : 19009 mProvidersByAuthority.entrySet()) { 19010 PackageParser.Provider p = entry.getValue(); 19011 if (packageName != null && !packageName.equals(p.info.packageName)) { 19012 continue; 19013 } 19014 if (!printedSomething) { 19015 if (dumpState.onTitlePrinted()) 19016 pw.println(); 19017 pw.println("ContentProvider Authorities:"); 19018 printedSomething = true; 19019 } 19020 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19021 pw.print(" "); pw.println(p.toString()); 19022 if (p.info != null && p.info.applicationInfo != null) { 19023 final String appInfo = p.info.applicationInfo.toString(); 19024 pw.print(" applicationInfo="); pw.println(appInfo); 19025 } 19026 } 19027 } 19028 19029 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19030 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19031 } 19032 19033 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19034 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19035 } 19036 19037 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19038 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19039 } 19040 19041 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19042 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19043 } 19044 19045 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19046 // XXX should handle packageName != null by dumping only install data that 19047 // the given package is involved with. 19048 if (dumpState.onTitlePrinted()) pw.println(); 19049 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19050 } 19051 19052 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19053 // XXX should handle packageName != null by dumping only install data that 19054 // the given package is involved with. 19055 if (dumpState.onTitlePrinted()) pw.println(); 19056 19057 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19058 ipw.println(); 19059 ipw.println("Frozen packages:"); 19060 ipw.increaseIndent(); 19061 if (mFrozenPackages.size() == 0) { 19062 ipw.println("(none)"); 19063 } else { 19064 for (int i = 0; i < mFrozenPackages.size(); i++) { 19065 ipw.println(mFrozenPackages.valueAt(i)); 19066 } 19067 } 19068 ipw.decreaseIndent(); 19069 } 19070 19071 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19072 if (dumpState.onTitlePrinted()) pw.println(); 19073 dumpDexoptStateLPr(pw, packageName); 19074 } 19075 19076 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19077 if (dumpState.onTitlePrinted()) pw.println(); 19078 dumpCompilerStatsLPr(pw, packageName); 19079 } 19080 19081 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19082 if (dumpState.onTitlePrinted()) pw.println(); 19083 mSettings.dumpReadMessagesLPr(pw, dumpState); 19084 19085 pw.println(); 19086 pw.println("Package warning messages:"); 19087 BufferedReader in = null; 19088 String line = null; 19089 try { 19090 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19091 while ((line = in.readLine()) != null) { 19092 if (line.contains("ignored: updated version")) continue; 19093 pw.println(line); 19094 } 19095 } catch (IOException ignored) { 19096 } finally { 19097 IoUtils.closeQuietly(in); 19098 } 19099 } 19100 19101 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19102 BufferedReader in = null; 19103 String line = null; 19104 try { 19105 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19106 while ((line = in.readLine()) != null) { 19107 if (line.contains("ignored: updated version")) continue; 19108 pw.print("msg,"); 19109 pw.println(line); 19110 } 19111 } catch (IOException ignored) { 19112 } finally { 19113 IoUtils.closeQuietly(in); 19114 } 19115 } 19116 } 19117 } 19118 19119 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19120 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19121 ipw.println(); 19122 ipw.println("Dexopt state:"); 19123 ipw.increaseIndent(); 19124 Collection<PackageParser.Package> packages = null; 19125 if (packageName != null) { 19126 PackageParser.Package targetPackage = mPackages.get(packageName); 19127 if (targetPackage != null) { 19128 packages = Collections.singletonList(targetPackage); 19129 } else { 19130 ipw.println("Unable to find package: " + packageName); 19131 return; 19132 } 19133 } else { 19134 packages = mPackages.values(); 19135 } 19136 19137 for (PackageParser.Package pkg : packages) { 19138 ipw.println("[" + pkg.packageName + "]"); 19139 ipw.increaseIndent(); 19140 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19141 ipw.decreaseIndent(); 19142 } 19143 } 19144 19145 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19146 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19147 ipw.println(); 19148 ipw.println("Compiler stats:"); 19149 ipw.increaseIndent(); 19150 Collection<PackageParser.Package> packages = null; 19151 if (packageName != null) { 19152 PackageParser.Package targetPackage = mPackages.get(packageName); 19153 if (targetPackage != null) { 19154 packages = Collections.singletonList(targetPackage); 19155 } else { 19156 ipw.println("Unable to find package: " + packageName); 19157 return; 19158 } 19159 } else { 19160 packages = mPackages.values(); 19161 } 19162 19163 for (PackageParser.Package pkg : packages) { 19164 ipw.println("[" + pkg.packageName + "]"); 19165 ipw.increaseIndent(); 19166 19167 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19168 if (stats == null) { 19169 ipw.println("(No recorded stats)"); 19170 } else { 19171 stats.dump(ipw); 19172 } 19173 ipw.decreaseIndent(); 19174 } 19175 } 19176 19177 private String dumpDomainString(String packageName) { 19178 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19179 .getList(); 19180 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19181 19182 ArraySet<String> result = new ArraySet<>(); 19183 if (iviList.size() > 0) { 19184 for (IntentFilterVerificationInfo ivi : iviList) { 19185 for (String host : ivi.getDomains()) { 19186 result.add(host); 19187 } 19188 } 19189 } 19190 if (filters != null && filters.size() > 0) { 19191 for (IntentFilter filter : filters) { 19192 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19193 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19194 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19195 result.addAll(filter.getHostsList()); 19196 } 19197 } 19198 } 19199 19200 StringBuilder sb = new StringBuilder(result.size() * 16); 19201 for (String domain : result) { 19202 if (sb.length() > 0) sb.append(" "); 19203 sb.append(domain); 19204 } 19205 return sb.toString(); 19206 } 19207 19208 // ------- apps on sdcard specific code ------- 19209 static final boolean DEBUG_SD_INSTALL = false; 19210 19211 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19212 19213 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19214 19215 private boolean mMediaMounted = false; 19216 19217 static String getEncryptKey() { 19218 try { 19219 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19220 SD_ENCRYPTION_KEYSTORE_NAME); 19221 if (sdEncKey == null) { 19222 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19223 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19224 if (sdEncKey == null) { 19225 Slog.e(TAG, "Failed to create encryption keys"); 19226 return null; 19227 } 19228 } 19229 return sdEncKey; 19230 } catch (NoSuchAlgorithmException nsae) { 19231 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19232 return null; 19233 } catch (IOException ioe) { 19234 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19235 return null; 19236 } 19237 } 19238 19239 /* 19240 * Update media status on PackageManager. 19241 */ 19242 @Override 19243 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19244 int callingUid = Binder.getCallingUid(); 19245 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19246 throw new SecurityException("Media status can only be updated by the system"); 19247 } 19248 // reader; this apparently protects mMediaMounted, but should probably 19249 // be a different lock in that case. 19250 synchronized (mPackages) { 19251 Log.i(TAG, "Updating external media status from " 19252 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19253 + (mediaStatus ? "mounted" : "unmounted")); 19254 if (DEBUG_SD_INSTALL) 19255 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19256 + ", mMediaMounted=" + mMediaMounted); 19257 if (mediaStatus == mMediaMounted) { 19258 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19259 : 0, -1); 19260 mHandler.sendMessage(msg); 19261 return; 19262 } 19263 mMediaMounted = mediaStatus; 19264 } 19265 // Queue up an async operation since the package installation may take a 19266 // little while. 19267 mHandler.post(new Runnable() { 19268 public void run() { 19269 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19270 } 19271 }); 19272 } 19273 19274 /** 19275 * Called by MountService when the initial ASECs to scan are available. 19276 * Should block until all the ASEC containers are finished being scanned. 19277 */ 19278 public void scanAvailableAsecs() { 19279 updateExternalMediaStatusInner(true, false, false); 19280 } 19281 19282 /* 19283 * Collect information of applications on external media, map them against 19284 * existing containers and update information based on current mount status. 19285 * Please note that we always have to report status if reportStatus has been 19286 * set to true especially when unloading packages. 19287 */ 19288 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19289 boolean externalStorage) { 19290 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19291 int[] uidArr = EmptyArray.INT; 19292 19293 final String[] list = PackageHelper.getSecureContainerList(); 19294 if (ArrayUtils.isEmpty(list)) { 19295 Log.i(TAG, "No secure containers found"); 19296 } else { 19297 // Process list of secure containers and categorize them 19298 // as active or stale based on their package internal state. 19299 19300 // reader 19301 synchronized (mPackages) { 19302 for (String cid : list) { 19303 // Leave stages untouched for now; installer service owns them 19304 if (PackageInstallerService.isStageName(cid)) continue; 19305 19306 if (DEBUG_SD_INSTALL) 19307 Log.i(TAG, "Processing container " + cid); 19308 String pkgName = getAsecPackageName(cid); 19309 if (pkgName == null) { 19310 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19311 continue; 19312 } 19313 if (DEBUG_SD_INSTALL) 19314 Log.i(TAG, "Looking for pkg : " + pkgName); 19315 19316 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19317 if (ps == null) { 19318 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19319 continue; 19320 } 19321 19322 /* 19323 * Skip packages that are not external if we're unmounting 19324 * external storage. 19325 */ 19326 if (externalStorage && !isMounted && !isExternal(ps)) { 19327 continue; 19328 } 19329 19330 final AsecInstallArgs args = new AsecInstallArgs(cid, 19331 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19332 // The package status is changed only if the code path 19333 // matches between settings and the container id. 19334 if (ps.codePathString != null 19335 && ps.codePathString.startsWith(args.getCodePath())) { 19336 if (DEBUG_SD_INSTALL) { 19337 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19338 + " at code path: " + ps.codePathString); 19339 } 19340 19341 // We do have a valid package installed on sdcard 19342 processCids.put(args, ps.codePathString); 19343 final int uid = ps.appId; 19344 if (uid != -1) { 19345 uidArr = ArrayUtils.appendInt(uidArr, uid); 19346 } 19347 } else { 19348 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19349 + ps.codePathString); 19350 } 19351 } 19352 } 19353 19354 Arrays.sort(uidArr); 19355 } 19356 19357 // Process packages with valid entries. 19358 if (isMounted) { 19359 if (DEBUG_SD_INSTALL) 19360 Log.i(TAG, "Loading packages"); 19361 loadMediaPackages(processCids, uidArr, externalStorage); 19362 startCleaningPackages(); 19363 mInstallerService.onSecureContainersAvailable(); 19364 } else { 19365 if (DEBUG_SD_INSTALL) 19366 Log.i(TAG, "Unloading packages"); 19367 unloadMediaPackages(processCids, uidArr, reportStatus); 19368 } 19369 } 19370 19371 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19372 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19373 final int size = infos.size(); 19374 final String[] packageNames = new String[size]; 19375 final int[] packageUids = new int[size]; 19376 for (int i = 0; i < size; i++) { 19377 final ApplicationInfo info = infos.get(i); 19378 packageNames[i] = info.packageName; 19379 packageUids[i] = info.uid; 19380 } 19381 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19382 finishedReceiver); 19383 } 19384 19385 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19386 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19387 sendResourcesChangedBroadcast(mediaStatus, replacing, 19388 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19389 } 19390 19391 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19392 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19393 int size = pkgList.length; 19394 if (size > 0) { 19395 // Send broadcasts here 19396 Bundle extras = new Bundle(); 19397 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19398 if (uidArr != null) { 19399 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19400 } 19401 if (replacing) { 19402 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19403 } 19404 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19405 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19406 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19407 } 19408 } 19409 19410 /* 19411 * Look at potentially valid container ids from processCids If package 19412 * information doesn't match the one on record or package scanning fails, 19413 * the cid is added to list of removeCids. We currently don't delete stale 19414 * containers. 19415 */ 19416 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19417 boolean externalStorage) { 19418 ArrayList<String> pkgList = new ArrayList<String>(); 19419 Set<AsecInstallArgs> keys = processCids.keySet(); 19420 19421 for (AsecInstallArgs args : keys) { 19422 String codePath = processCids.get(args); 19423 if (DEBUG_SD_INSTALL) 19424 Log.i(TAG, "Loading container : " + args.cid); 19425 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19426 try { 19427 // Make sure there are no container errors first. 19428 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19429 Slog.e(TAG, "Failed to mount cid : " + args.cid 19430 + " when installing from sdcard"); 19431 continue; 19432 } 19433 // Check code path here. 19434 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19435 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19436 + " does not match one in settings " + codePath); 19437 continue; 19438 } 19439 // Parse package 19440 int parseFlags = mDefParseFlags; 19441 if (args.isExternalAsec()) { 19442 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19443 } 19444 if (args.isFwdLocked()) { 19445 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19446 } 19447 19448 synchronized (mInstallLock) { 19449 PackageParser.Package pkg = null; 19450 try { 19451 // Sadly we don't know the package name yet to freeze it 19452 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19453 SCAN_IGNORE_FROZEN, 0, null); 19454 } catch (PackageManagerException e) { 19455 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19456 } 19457 // Scan the package 19458 if (pkg != null) { 19459 /* 19460 * TODO why is the lock being held? doPostInstall is 19461 * called in other places without the lock. This needs 19462 * to be straightened out. 19463 */ 19464 // writer 19465 synchronized (mPackages) { 19466 retCode = PackageManager.INSTALL_SUCCEEDED; 19467 pkgList.add(pkg.packageName); 19468 // Post process args 19469 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19470 pkg.applicationInfo.uid); 19471 } 19472 } else { 19473 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19474 } 19475 } 19476 19477 } finally { 19478 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19479 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19480 } 19481 } 19482 } 19483 // writer 19484 synchronized (mPackages) { 19485 // If the platform SDK has changed since the last time we booted, 19486 // we need to re-grant app permission to catch any new ones that 19487 // appear. This is really a hack, and means that apps can in some 19488 // cases get permissions that the user didn't initially explicitly 19489 // allow... it would be nice to have some better way to handle 19490 // this situation. 19491 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19492 : mSettings.getInternalVersion(); 19493 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19494 : StorageManager.UUID_PRIVATE_INTERNAL; 19495 19496 int updateFlags = UPDATE_PERMISSIONS_ALL; 19497 if (ver.sdkVersion != mSdkVersion) { 19498 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19499 + mSdkVersion + "; regranting permissions for external"); 19500 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19501 } 19502 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19503 19504 // Yay, everything is now upgraded 19505 ver.forceCurrent(); 19506 19507 // can downgrade to reader 19508 // Persist settings 19509 mSettings.writeLPr(); 19510 } 19511 // Send a broadcast to let everyone know we are done processing 19512 if (pkgList.size() > 0) { 19513 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19514 } 19515 } 19516 19517 /* 19518 * Utility method to unload a list of specified containers 19519 */ 19520 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19521 // Just unmount all valid containers. 19522 for (AsecInstallArgs arg : cidArgs) { 19523 synchronized (mInstallLock) { 19524 arg.doPostDeleteLI(false); 19525 } 19526 } 19527 } 19528 19529 /* 19530 * Unload packages mounted on external media. This involves deleting package 19531 * data from internal structures, sending broadcasts about disabled packages, 19532 * gc'ing to free up references, unmounting all secure containers 19533 * corresponding to packages on external media, and posting a 19534 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19535 * that we always have to post this message if status has been requested no 19536 * matter what. 19537 */ 19538 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19539 final boolean reportStatus) { 19540 if (DEBUG_SD_INSTALL) 19541 Log.i(TAG, "unloading media packages"); 19542 ArrayList<String> pkgList = new ArrayList<String>(); 19543 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19544 final Set<AsecInstallArgs> keys = processCids.keySet(); 19545 for (AsecInstallArgs args : keys) { 19546 String pkgName = args.getPackageName(); 19547 if (DEBUG_SD_INSTALL) 19548 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19549 // Delete package internally 19550 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19551 synchronized (mInstallLock) { 19552 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19553 final boolean res; 19554 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19555 "unloadMediaPackages")) { 19556 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19557 null); 19558 } 19559 if (res) { 19560 pkgList.add(pkgName); 19561 } else { 19562 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19563 failedList.add(args); 19564 } 19565 } 19566 } 19567 19568 // reader 19569 synchronized (mPackages) { 19570 // We didn't update the settings after removing each package; 19571 // write them now for all packages. 19572 mSettings.writeLPr(); 19573 } 19574 19575 // We have to absolutely send UPDATED_MEDIA_STATUS only 19576 // after confirming that all the receivers processed the ordered 19577 // broadcast when packages get disabled, force a gc to clean things up. 19578 // and unload all the containers. 19579 if (pkgList.size() > 0) { 19580 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19581 new IIntentReceiver.Stub() { 19582 public void performReceive(Intent intent, int resultCode, String data, 19583 Bundle extras, boolean ordered, boolean sticky, 19584 int sendingUser) throws RemoteException { 19585 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19586 reportStatus ? 1 : 0, 1, keys); 19587 mHandler.sendMessage(msg); 19588 } 19589 }); 19590 } else { 19591 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19592 keys); 19593 mHandler.sendMessage(msg); 19594 } 19595 } 19596 19597 private void loadPrivatePackages(final VolumeInfo vol) { 19598 mHandler.post(new Runnable() { 19599 @Override 19600 public void run() { 19601 loadPrivatePackagesInner(vol); 19602 } 19603 }); 19604 } 19605 19606 private void loadPrivatePackagesInner(VolumeInfo vol) { 19607 final String volumeUuid = vol.fsUuid; 19608 if (TextUtils.isEmpty(volumeUuid)) { 19609 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19610 return; 19611 } 19612 19613 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19614 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19615 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19616 19617 final VersionInfo ver; 19618 final List<PackageSetting> packages; 19619 synchronized (mPackages) { 19620 ver = mSettings.findOrCreateVersion(volumeUuid); 19621 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19622 } 19623 19624 for (PackageSetting ps : packages) { 19625 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19626 synchronized (mInstallLock) { 19627 final PackageParser.Package pkg; 19628 try { 19629 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19630 loaded.add(pkg.applicationInfo); 19631 19632 } catch (PackageManagerException e) { 19633 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19634 } 19635 19636 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19637 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19638 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19639 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19640 } 19641 } 19642 } 19643 19644 // Reconcile app data for all started/unlocked users 19645 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19646 final UserManager um = mContext.getSystemService(UserManager.class); 19647 UserManagerInternal umInternal = getUserManagerInternal(); 19648 for (UserInfo user : um.getUsers()) { 19649 final int flags; 19650 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19651 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19652 } else if (umInternal.isUserRunning(user.id)) { 19653 flags = StorageManager.FLAG_STORAGE_DE; 19654 } else { 19655 continue; 19656 } 19657 19658 try { 19659 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19660 synchronized (mInstallLock) { 19661 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19662 } 19663 } catch (IllegalStateException e) { 19664 // Device was probably ejected, and we'll process that event momentarily 19665 Slog.w(TAG, "Failed to prepare storage: " + e); 19666 } 19667 } 19668 19669 synchronized (mPackages) { 19670 int updateFlags = UPDATE_PERMISSIONS_ALL; 19671 if (ver.sdkVersion != mSdkVersion) { 19672 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19673 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19674 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19675 } 19676 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19677 19678 // Yay, everything is now upgraded 19679 ver.forceCurrent(); 19680 19681 mSettings.writeLPr(); 19682 } 19683 19684 for (PackageFreezer freezer : freezers) { 19685 freezer.close(); 19686 } 19687 19688 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19689 sendResourcesChangedBroadcast(true, false, loaded, null); 19690 } 19691 19692 private void unloadPrivatePackages(final VolumeInfo vol) { 19693 mHandler.post(new Runnable() { 19694 @Override 19695 public void run() { 19696 unloadPrivatePackagesInner(vol); 19697 } 19698 }); 19699 } 19700 19701 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19702 final String volumeUuid = vol.fsUuid; 19703 if (TextUtils.isEmpty(volumeUuid)) { 19704 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19705 return; 19706 } 19707 19708 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19709 synchronized (mInstallLock) { 19710 synchronized (mPackages) { 19711 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19712 for (PackageSetting ps : packages) { 19713 if (ps.pkg == null) continue; 19714 19715 final ApplicationInfo info = ps.pkg.applicationInfo; 19716 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19717 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19718 19719 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19720 "unloadPrivatePackagesInner")) { 19721 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19722 false, null)) { 19723 unloaded.add(info); 19724 } else { 19725 Slog.w(TAG, "Failed to unload " + ps.codePath); 19726 } 19727 } 19728 19729 // Try very hard to release any references to this package 19730 // so we don't risk the system server being killed due to 19731 // open FDs 19732 AttributeCache.instance().removePackage(ps.name); 19733 } 19734 19735 mSettings.writeLPr(); 19736 } 19737 } 19738 19739 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19740 sendResourcesChangedBroadcast(false, false, unloaded, null); 19741 19742 // Try very hard to release any references to this path so we don't risk 19743 // the system server being killed due to open FDs 19744 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19745 19746 for (int i = 0; i < 3; i++) { 19747 System.gc(); 19748 System.runFinalization(); 19749 } 19750 } 19751 19752 /** 19753 * Prepare storage areas for given user on all mounted devices. 19754 */ 19755 void prepareUserData(int userId, int userSerial, int flags) { 19756 synchronized (mInstallLock) { 19757 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19758 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19759 final String volumeUuid = vol.getFsUuid(); 19760 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19761 } 19762 } 19763 } 19764 19765 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19766 boolean allowRecover) { 19767 // Prepare storage and verify that serial numbers are consistent; if 19768 // there's a mismatch we need to destroy to avoid leaking data 19769 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19770 try { 19771 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19772 19773 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19774 UserManagerService.enforceSerialNumber( 19775 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19776 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19777 UserManagerService.enforceSerialNumber( 19778 Environment.getDataSystemDeDirectory(userId), userSerial); 19779 } 19780 } 19781 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19782 UserManagerService.enforceSerialNumber( 19783 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19784 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19785 UserManagerService.enforceSerialNumber( 19786 Environment.getDataSystemCeDirectory(userId), userSerial); 19787 } 19788 } 19789 19790 synchronized (mInstallLock) { 19791 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19792 } 19793 } catch (Exception e) { 19794 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19795 + " because we failed to prepare: " + e); 19796 destroyUserDataLI(volumeUuid, userId, 19797 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19798 19799 if (allowRecover) { 19800 // Try one last time; if we fail again we're really in trouble 19801 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19802 } 19803 } 19804 } 19805 19806 /** 19807 * Destroy storage areas for given user on all mounted devices. 19808 */ 19809 void destroyUserData(int userId, int flags) { 19810 synchronized (mInstallLock) { 19811 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19812 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19813 final String volumeUuid = vol.getFsUuid(); 19814 destroyUserDataLI(volumeUuid, userId, flags); 19815 } 19816 } 19817 } 19818 19819 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19820 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19821 try { 19822 // Clean up app data, profile data, and media data 19823 mInstaller.destroyUserData(volumeUuid, userId, flags); 19824 19825 // Clean up system data 19826 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19827 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19828 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19829 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19830 } 19831 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19832 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19833 } 19834 } 19835 19836 // Data with special labels is now gone, so finish the job 19837 storage.destroyUserStorage(volumeUuid, userId, flags); 19838 19839 } catch (Exception e) { 19840 logCriticalInfo(Log.WARN, 19841 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19842 } 19843 } 19844 19845 /** 19846 * Examine all users present on given mounted volume, and destroy data 19847 * belonging to users that are no longer valid, or whose user ID has been 19848 * recycled. 19849 */ 19850 private void reconcileUsers(String volumeUuid) { 19851 final List<File> files = new ArrayList<>(); 19852 Collections.addAll(files, FileUtils 19853 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19854 Collections.addAll(files, FileUtils 19855 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19856 Collections.addAll(files, FileUtils 19857 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19858 Collections.addAll(files, FileUtils 19859 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19860 for (File file : files) { 19861 if (!file.isDirectory()) continue; 19862 19863 final int userId; 19864 final UserInfo info; 19865 try { 19866 userId = Integer.parseInt(file.getName()); 19867 info = sUserManager.getUserInfo(userId); 19868 } catch (NumberFormatException e) { 19869 Slog.w(TAG, "Invalid user directory " + file); 19870 continue; 19871 } 19872 19873 boolean destroyUser = false; 19874 if (info == null) { 19875 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19876 + " because no matching user was found"); 19877 destroyUser = true; 19878 } else if (!mOnlyCore) { 19879 try { 19880 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19881 } catch (IOException e) { 19882 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19883 + " because we failed to enforce serial number: " + e); 19884 destroyUser = true; 19885 } 19886 } 19887 19888 if (destroyUser) { 19889 synchronized (mInstallLock) { 19890 destroyUserDataLI(volumeUuid, userId, 19891 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19892 } 19893 } 19894 } 19895 } 19896 19897 private void assertPackageKnown(String volumeUuid, String packageName) 19898 throws PackageManagerException { 19899 synchronized (mPackages) { 19900 final PackageSetting ps = mSettings.mPackages.get(packageName); 19901 if (ps == null) { 19902 throw new PackageManagerException("Package " + packageName + " is unknown"); 19903 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19904 throw new PackageManagerException( 19905 "Package " + packageName + " found on unknown volume " + volumeUuid 19906 + "; expected volume " + ps.volumeUuid); 19907 } 19908 } 19909 } 19910 19911 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19912 throws PackageManagerException { 19913 synchronized (mPackages) { 19914 final PackageSetting ps = mSettings.mPackages.get(packageName); 19915 if (ps == null) { 19916 throw new PackageManagerException("Package " + packageName + " is unknown"); 19917 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19918 throw new PackageManagerException( 19919 "Package " + packageName + " found on unknown volume " + volumeUuid 19920 + "; expected volume " + ps.volumeUuid); 19921 } else if (!ps.getInstalled(userId)) { 19922 throw new PackageManagerException( 19923 "Package " + packageName + " not installed for user " + userId); 19924 } 19925 } 19926 } 19927 19928 /** 19929 * Examine all apps present on given mounted volume, and destroy apps that 19930 * aren't expected, either due to uninstallation or reinstallation on 19931 * another volume. 19932 */ 19933 private void reconcileApps(String volumeUuid) { 19934 final File[] files = FileUtils 19935 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19936 for (File file : files) { 19937 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19938 && !PackageInstallerService.isStageName(file.getName()); 19939 if (!isPackage) { 19940 // Ignore entries which are not packages 19941 continue; 19942 } 19943 19944 try { 19945 final PackageLite pkg = PackageParser.parsePackageLite(file, 19946 PackageParser.PARSE_MUST_BE_APK); 19947 assertPackageKnown(volumeUuid, pkg.packageName); 19948 19949 } catch (PackageParserException | PackageManagerException e) { 19950 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19951 synchronized (mInstallLock) { 19952 removeCodePathLI(file); 19953 } 19954 } 19955 } 19956 } 19957 19958 /** 19959 * Reconcile all app data for the given user. 19960 * <p> 19961 * Verifies that directories exist and that ownership and labeling is 19962 * correct for all installed apps on all mounted volumes. 19963 */ 19964 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 19965 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19966 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19967 final String volumeUuid = vol.getFsUuid(); 19968 synchronized (mInstallLock) { 19969 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 19970 } 19971 } 19972 } 19973 19974 /** 19975 * Reconcile all app data on given mounted volume. 19976 * <p> 19977 * Destroys app data that isn't expected, either due to uninstallation or 19978 * reinstallation on another volume. 19979 * <p> 19980 * Verifies that directories exist and that ownership and labeling is 19981 * correct for all installed apps. 19982 */ 19983 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 19984 boolean migrateAppData) { 19985 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19986 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 19987 19988 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19989 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19990 19991 // First look for stale data that doesn't belong, and check if things 19992 // have changed since we did our last restorecon 19993 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19994 if (StorageManager.isFileEncryptedNativeOrEmulated() 19995 && !StorageManager.isUserKeyUnlocked(userId)) { 19996 throw new RuntimeException( 19997 "Yikes, someone asked us to reconcile CE storage while " + userId 19998 + " was still locked; this would have caused massive data loss!"); 19999 } 20000 20001 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20002 for (File file : files) { 20003 final String packageName = file.getName(); 20004 try { 20005 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20006 } catch (PackageManagerException e) { 20007 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20008 try { 20009 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20010 StorageManager.FLAG_STORAGE_CE, 0); 20011 } catch (InstallerException e2) { 20012 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20013 } 20014 } 20015 } 20016 } 20017 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20018 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20019 for (File file : files) { 20020 final String packageName = file.getName(); 20021 try { 20022 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20023 } catch (PackageManagerException e) { 20024 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20025 try { 20026 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20027 StorageManager.FLAG_STORAGE_DE, 0); 20028 } catch (InstallerException e2) { 20029 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20030 } 20031 } 20032 } 20033 } 20034 20035 // Ensure that data directories are ready to roll for all packages 20036 // installed for this volume and user 20037 final List<PackageSetting> packages; 20038 synchronized (mPackages) { 20039 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20040 } 20041 int preparedCount = 0; 20042 for (PackageSetting ps : packages) { 20043 final String packageName = ps.name; 20044 if (ps.pkg == null) { 20045 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20046 // TODO: might be due to legacy ASEC apps; we should circle back 20047 // and reconcile again once they're scanned 20048 continue; 20049 } 20050 20051 if (ps.getInstalled(userId)) { 20052 prepareAppDataLIF(ps.pkg, userId, flags); 20053 20054 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20055 // We may have just shuffled around app data directories, so 20056 // prepare them one more time 20057 prepareAppDataLIF(ps.pkg, userId, flags); 20058 } 20059 20060 preparedCount++; 20061 } 20062 } 20063 20064 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20065 } 20066 20067 /** 20068 * Prepare app data for the given app just after it was installed or 20069 * upgraded. This method carefully only touches users that it's installed 20070 * for, and it forces a restorecon to handle any seinfo changes. 20071 * <p> 20072 * Verifies that directories exist and that ownership and labeling is 20073 * correct for all installed apps. If there is an ownership mismatch, it 20074 * will try recovering system apps by wiping data; third-party app data is 20075 * left intact. 20076 * <p> 20077 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20078 */ 20079 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20080 final PackageSetting ps; 20081 synchronized (mPackages) { 20082 ps = mSettings.mPackages.get(pkg.packageName); 20083 mSettings.writeKernelMappingLPr(ps); 20084 } 20085 20086 final UserManager um = mContext.getSystemService(UserManager.class); 20087 UserManagerInternal umInternal = getUserManagerInternal(); 20088 for (UserInfo user : um.getUsers()) { 20089 final int flags; 20090 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20091 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20092 } else if (umInternal.isUserRunning(user.id)) { 20093 flags = StorageManager.FLAG_STORAGE_DE; 20094 } else { 20095 continue; 20096 } 20097 20098 if (ps.getInstalled(user.id)) { 20099 // TODO: when user data is locked, mark that we're still dirty 20100 prepareAppDataLIF(pkg, user.id, flags); 20101 } 20102 } 20103 } 20104 20105 /** 20106 * Prepare app data for the given app. 20107 * <p> 20108 * Verifies that directories exist and that ownership and labeling is 20109 * correct for all installed apps. If there is an ownership mismatch, this 20110 * will try recovering system apps by wiping data; third-party app data is 20111 * left intact. 20112 */ 20113 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20114 if (pkg == null) { 20115 Slog.wtf(TAG, "Package was null!", new Throwable()); 20116 return; 20117 } 20118 prepareAppDataLeafLIF(pkg, userId, flags); 20119 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20120 for (int i = 0; i < childCount; i++) { 20121 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20122 } 20123 } 20124 20125 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20126 if (DEBUG_APP_DATA) { 20127 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20128 + Integer.toHexString(flags)); 20129 } 20130 20131 final String volumeUuid = pkg.volumeUuid; 20132 final String packageName = pkg.packageName; 20133 final ApplicationInfo app = pkg.applicationInfo; 20134 final int appId = UserHandle.getAppId(app.uid); 20135 20136 Preconditions.checkNotNull(app.seinfo); 20137 20138 try { 20139 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20140 appId, app.seinfo, app.targetSdkVersion); 20141 } catch (InstallerException e) { 20142 if (app.isSystemApp()) { 20143 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20144 + ", but trying to recover: " + e); 20145 destroyAppDataLeafLIF(pkg, userId, flags); 20146 try { 20147 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20148 appId, app.seinfo, app.targetSdkVersion); 20149 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20150 } catch (InstallerException e2) { 20151 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20152 } 20153 } else { 20154 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20155 } 20156 } 20157 20158 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20159 try { 20160 // CE storage is unlocked right now, so read out the inode and 20161 // remember for use later when it's locked 20162 // TODO: mark this structure as dirty so we persist it! 20163 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20164 StorageManager.FLAG_STORAGE_CE); 20165 synchronized (mPackages) { 20166 final PackageSetting ps = mSettings.mPackages.get(packageName); 20167 if (ps != null) { 20168 ps.setCeDataInode(ceDataInode, userId); 20169 } 20170 } 20171 } catch (InstallerException e) { 20172 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20173 } 20174 } 20175 20176 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20177 } 20178 20179 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20180 if (pkg == null) { 20181 Slog.wtf(TAG, "Package was null!", new Throwable()); 20182 return; 20183 } 20184 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20185 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20186 for (int i = 0; i < childCount; i++) { 20187 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20188 } 20189 } 20190 20191 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20192 final String volumeUuid = pkg.volumeUuid; 20193 final String packageName = pkg.packageName; 20194 final ApplicationInfo app = pkg.applicationInfo; 20195 20196 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20197 // Create a native library symlink only if we have native libraries 20198 // and if the native libraries are 32 bit libraries. We do not provide 20199 // this symlink for 64 bit libraries. 20200 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20201 final String nativeLibPath = app.nativeLibraryDir; 20202 try { 20203 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20204 nativeLibPath, userId); 20205 } catch (InstallerException e) { 20206 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20207 } 20208 } 20209 } 20210 } 20211 20212 /** 20213 * For system apps on non-FBE devices, this method migrates any existing 20214 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20215 * requested by the app. 20216 */ 20217 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20218 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20219 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20220 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20221 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20222 try { 20223 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20224 storageTarget); 20225 } catch (InstallerException e) { 20226 logCriticalInfo(Log.WARN, 20227 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20228 } 20229 return true; 20230 } else { 20231 return false; 20232 } 20233 } 20234 20235 public PackageFreezer freezePackage(String packageName, String killReason) { 20236 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20237 } 20238 20239 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20240 return new PackageFreezer(packageName, userId, killReason); 20241 } 20242 20243 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20244 String killReason) { 20245 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20246 } 20247 20248 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20249 String killReason) { 20250 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20251 return new PackageFreezer(); 20252 } else { 20253 return freezePackage(packageName, userId, killReason); 20254 } 20255 } 20256 20257 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20258 String killReason) { 20259 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20260 } 20261 20262 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20263 String killReason) { 20264 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20265 return new PackageFreezer(); 20266 } else { 20267 return freezePackage(packageName, userId, killReason); 20268 } 20269 } 20270 20271 /** 20272 * Class that freezes and kills the given package upon creation, and 20273 * unfreezes it upon closing. This is typically used when doing surgery on 20274 * app code/data to prevent the app from running while you're working. 20275 */ 20276 private class PackageFreezer implements AutoCloseable { 20277 private final String mPackageName; 20278 private final PackageFreezer[] mChildren; 20279 20280 private final boolean mWeFroze; 20281 20282 private final AtomicBoolean mClosed = new AtomicBoolean(); 20283 private final CloseGuard mCloseGuard = CloseGuard.get(); 20284 20285 /** 20286 * Create and return a stub freezer that doesn't actually do anything, 20287 * typically used when someone requested 20288 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20289 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20290 */ 20291 public PackageFreezer() { 20292 mPackageName = null; 20293 mChildren = null; 20294 mWeFroze = false; 20295 mCloseGuard.open("close"); 20296 } 20297 20298 public PackageFreezer(String packageName, int userId, String killReason) { 20299 synchronized (mPackages) { 20300 mPackageName = packageName; 20301 mWeFroze = mFrozenPackages.add(mPackageName); 20302 20303 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20304 if (ps != null) { 20305 killApplication(ps.name, ps.appId, userId, killReason); 20306 } 20307 20308 final PackageParser.Package p = mPackages.get(packageName); 20309 if (p != null && p.childPackages != null) { 20310 final int N = p.childPackages.size(); 20311 mChildren = new PackageFreezer[N]; 20312 for (int i = 0; i < N; i++) { 20313 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20314 userId, killReason); 20315 } 20316 } else { 20317 mChildren = null; 20318 } 20319 } 20320 mCloseGuard.open("close"); 20321 } 20322 20323 @Override 20324 protected void finalize() throws Throwable { 20325 try { 20326 mCloseGuard.warnIfOpen(); 20327 close(); 20328 } finally { 20329 super.finalize(); 20330 } 20331 } 20332 20333 @Override 20334 public void close() { 20335 mCloseGuard.close(); 20336 if (mClosed.compareAndSet(false, true)) { 20337 synchronized (mPackages) { 20338 if (mWeFroze) { 20339 mFrozenPackages.remove(mPackageName); 20340 } 20341 20342 if (mChildren != null) { 20343 for (PackageFreezer freezer : mChildren) { 20344 freezer.close(); 20345 } 20346 } 20347 } 20348 } 20349 } 20350 } 20351 20352 /** 20353 * Verify that given package is currently frozen. 20354 */ 20355 private void checkPackageFrozen(String packageName) { 20356 synchronized (mPackages) { 20357 if (!mFrozenPackages.contains(packageName)) { 20358 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20359 } 20360 } 20361 } 20362 20363 @Override 20364 public int movePackage(final String packageName, final String volumeUuid) { 20365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20366 20367 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20368 final int moveId = mNextMoveId.getAndIncrement(); 20369 mHandler.post(new Runnable() { 20370 @Override 20371 public void run() { 20372 try { 20373 movePackageInternal(packageName, volumeUuid, moveId, user); 20374 } catch (PackageManagerException e) { 20375 Slog.w(TAG, "Failed to move " + packageName, e); 20376 mMoveCallbacks.notifyStatusChanged(moveId, 20377 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20378 } 20379 } 20380 }); 20381 return moveId; 20382 } 20383 20384 private void movePackageInternal(final String packageName, final String volumeUuid, 20385 final int moveId, UserHandle user) throws PackageManagerException { 20386 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20387 final PackageManager pm = mContext.getPackageManager(); 20388 20389 final boolean currentAsec; 20390 final String currentVolumeUuid; 20391 final File codeFile; 20392 final String installerPackageName; 20393 final String packageAbiOverride; 20394 final int appId; 20395 final String seinfo; 20396 final String label; 20397 final int targetSdkVersion; 20398 final PackageFreezer freezer; 20399 final int[] installedUserIds; 20400 20401 // reader 20402 synchronized (mPackages) { 20403 final PackageParser.Package pkg = mPackages.get(packageName); 20404 final PackageSetting ps = mSettings.mPackages.get(packageName); 20405 if (pkg == null || ps == null) { 20406 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20407 } 20408 20409 if (pkg.applicationInfo.isSystemApp()) { 20410 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20411 "Cannot move system application"); 20412 } 20413 20414 if (pkg.applicationInfo.isExternalAsec()) { 20415 currentAsec = true; 20416 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20417 } else if (pkg.applicationInfo.isForwardLocked()) { 20418 currentAsec = true; 20419 currentVolumeUuid = "forward_locked"; 20420 } else { 20421 currentAsec = false; 20422 currentVolumeUuid = ps.volumeUuid; 20423 20424 final File probe = new File(pkg.codePath); 20425 final File probeOat = new File(probe, "oat"); 20426 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20427 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20428 "Move only supported for modern cluster style installs"); 20429 } 20430 } 20431 20432 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20433 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20434 "Package already moved to " + volumeUuid); 20435 } 20436 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20437 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20438 "Device admin cannot be moved"); 20439 } 20440 20441 if (mFrozenPackages.contains(packageName)) { 20442 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20443 "Failed to move already frozen package"); 20444 } 20445 20446 codeFile = new File(pkg.codePath); 20447 installerPackageName = ps.installerPackageName; 20448 packageAbiOverride = ps.cpuAbiOverrideString; 20449 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20450 seinfo = pkg.applicationInfo.seinfo; 20451 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20452 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20453 freezer = freezePackage(packageName, "movePackageInternal"); 20454 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20455 } 20456 20457 final Bundle extras = new Bundle(); 20458 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20459 extras.putString(Intent.EXTRA_TITLE, label); 20460 mMoveCallbacks.notifyCreated(moveId, extras); 20461 20462 int installFlags; 20463 final boolean moveCompleteApp; 20464 final File measurePath; 20465 20466 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20467 installFlags = INSTALL_INTERNAL; 20468 moveCompleteApp = !currentAsec; 20469 measurePath = Environment.getDataAppDirectory(volumeUuid); 20470 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20471 installFlags = INSTALL_EXTERNAL; 20472 moveCompleteApp = false; 20473 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20474 } else { 20475 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20476 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20477 || !volume.isMountedWritable()) { 20478 freezer.close(); 20479 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20480 "Move location not mounted private volume"); 20481 } 20482 20483 Preconditions.checkState(!currentAsec); 20484 20485 installFlags = INSTALL_INTERNAL; 20486 moveCompleteApp = true; 20487 measurePath = Environment.getDataAppDirectory(volumeUuid); 20488 } 20489 20490 final PackageStats stats = new PackageStats(null, -1); 20491 synchronized (mInstaller) { 20492 for (int userId : installedUserIds) { 20493 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20494 freezer.close(); 20495 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20496 "Failed to measure package size"); 20497 } 20498 } 20499 } 20500 20501 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20502 + stats.dataSize); 20503 20504 final long startFreeBytes = measurePath.getFreeSpace(); 20505 final long sizeBytes; 20506 if (moveCompleteApp) { 20507 sizeBytes = stats.codeSize + stats.dataSize; 20508 } else { 20509 sizeBytes = stats.codeSize; 20510 } 20511 20512 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20513 freezer.close(); 20514 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20515 "Not enough free space to move"); 20516 } 20517 20518 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20519 20520 final CountDownLatch installedLatch = new CountDownLatch(1); 20521 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20522 @Override 20523 public void onUserActionRequired(Intent intent) throws RemoteException { 20524 throw new IllegalStateException(); 20525 } 20526 20527 @Override 20528 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20529 Bundle extras) throws RemoteException { 20530 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20531 + PackageManager.installStatusToString(returnCode, msg)); 20532 20533 installedLatch.countDown(); 20534 freezer.close(); 20535 20536 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20537 switch (status) { 20538 case PackageInstaller.STATUS_SUCCESS: 20539 mMoveCallbacks.notifyStatusChanged(moveId, 20540 PackageManager.MOVE_SUCCEEDED); 20541 break; 20542 case PackageInstaller.STATUS_FAILURE_STORAGE: 20543 mMoveCallbacks.notifyStatusChanged(moveId, 20544 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20545 break; 20546 default: 20547 mMoveCallbacks.notifyStatusChanged(moveId, 20548 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20549 break; 20550 } 20551 } 20552 }; 20553 20554 final MoveInfo move; 20555 if (moveCompleteApp) { 20556 // Kick off a thread to report progress estimates 20557 new Thread() { 20558 @Override 20559 public void run() { 20560 while (true) { 20561 try { 20562 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20563 break; 20564 } 20565 } catch (InterruptedException ignored) { 20566 } 20567 20568 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20569 final int progress = 10 + (int) MathUtils.constrain( 20570 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20571 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20572 } 20573 } 20574 }.start(); 20575 20576 final String dataAppName = codeFile.getName(); 20577 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20578 dataAppName, appId, seinfo, targetSdkVersion); 20579 } else { 20580 move = null; 20581 } 20582 20583 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20584 20585 final Message msg = mHandler.obtainMessage(INIT_COPY); 20586 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20587 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20588 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20589 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20590 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20591 msg.obj = params; 20592 20593 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20594 System.identityHashCode(msg.obj)); 20595 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20596 System.identityHashCode(msg.obj)); 20597 20598 mHandler.sendMessage(msg); 20599 } 20600 20601 @Override 20602 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20603 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20604 20605 final int realMoveId = mNextMoveId.getAndIncrement(); 20606 final Bundle extras = new Bundle(); 20607 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20608 mMoveCallbacks.notifyCreated(realMoveId, extras); 20609 20610 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20611 @Override 20612 public void onCreated(int moveId, Bundle extras) { 20613 // Ignored 20614 } 20615 20616 @Override 20617 public void onStatusChanged(int moveId, int status, long estMillis) { 20618 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20619 } 20620 }; 20621 20622 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20623 storage.setPrimaryStorageUuid(volumeUuid, callback); 20624 return realMoveId; 20625 } 20626 20627 @Override 20628 public int getMoveStatus(int moveId) { 20629 mContext.enforceCallingOrSelfPermission( 20630 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20631 return mMoveCallbacks.mLastStatus.get(moveId); 20632 } 20633 20634 @Override 20635 public void registerMoveCallback(IPackageMoveObserver callback) { 20636 mContext.enforceCallingOrSelfPermission( 20637 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20638 mMoveCallbacks.register(callback); 20639 } 20640 20641 @Override 20642 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20643 mContext.enforceCallingOrSelfPermission( 20644 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20645 mMoveCallbacks.unregister(callback); 20646 } 20647 20648 @Override 20649 public boolean setInstallLocation(int loc) { 20650 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20651 null); 20652 if (getInstallLocation() == loc) { 20653 return true; 20654 } 20655 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20656 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20657 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20658 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20659 return true; 20660 } 20661 return false; 20662 } 20663 20664 @Override 20665 public int getInstallLocation() { 20666 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20667 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20668 PackageHelper.APP_INSTALL_AUTO); 20669 } 20670 20671 /** Called by UserManagerService */ 20672 void cleanUpUser(UserManagerService userManager, int userHandle) { 20673 synchronized (mPackages) { 20674 mDirtyUsers.remove(userHandle); 20675 mUserNeedsBadging.delete(userHandle); 20676 mSettings.removeUserLPw(userHandle); 20677 mPendingBroadcasts.remove(userHandle); 20678 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20679 removeUnusedPackagesLPw(userManager, userHandle); 20680 } 20681 } 20682 20683 /** 20684 * We're removing userHandle and would like to remove any downloaded packages 20685 * that are no longer in use by any other user. 20686 * @param userHandle the user being removed 20687 */ 20688 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20689 final boolean DEBUG_CLEAN_APKS = false; 20690 int [] users = userManager.getUserIds(); 20691 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20692 while (psit.hasNext()) { 20693 PackageSetting ps = psit.next(); 20694 if (ps.pkg == null) { 20695 continue; 20696 } 20697 final String packageName = ps.pkg.packageName; 20698 // Skip over if system app 20699 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20700 continue; 20701 } 20702 if (DEBUG_CLEAN_APKS) { 20703 Slog.i(TAG, "Checking package " + packageName); 20704 } 20705 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20706 if (keep) { 20707 if (DEBUG_CLEAN_APKS) { 20708 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20709 } 20710 } else { 20711 for (int i = 0; i < users.length; i++) { 20712 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20713 keep = true; 20714 if (DEBUG_CLEAN_APKS) { 20715 Slog.i(TAG, " Keeping package " + packageName + " for user " 20716 + users[i]); 20717 } 20718 break; 20719 } 20720 } 20721 } 20722 if (!keep) { 20723 if (DEBUG_CLEAN_APKS) { 20724 Slog.i(TAG, " Removing package " + packageName); 20725 } 20726 mHandler.post(new Runnable() { 20727 public void run() { 20728 deletePackageX(packageName, userHandle, 0); 20729 } //end run 20730 }); 20731 } 20732 } 20733 } 20734 20735 /** Called by UserManagerService */ 20736 void createNewUser(int userId, String[] disallowedPackages) { 20737 synchronized (mInstallLock) { 20738 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 20739 } 20740 synchronized (mPackages) { 20741 scheduleWritePackageRestrictionsLocked(userId); 20742 scheduleWritePackageListLocked(userId); 20743 applyFactoryDefaultBrowserLPw(userId); 20744 primeDomainVerificationsLPw(userId); 20745 } 20746 } 20747 20748 void onNewUserCreated(final int userId) { 20749 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20750 // If permission review for legacy apps is required, we represent 20751 // dagerous permissions for such apps as always granted runtime 20752 // permissions to keep per user flag state whether review is needed. 20753 // Hence, if a new user is added we have to propagate dangerous 20754 // permission grants for these legacy apps. 20755 if (mPermissionReviewRequired) { 20756 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20757 | UPDATE_PERMISSIONS_REPLACE_ALL); 20758 } 20759 } 20760 20761 @Override 20762 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20763 mContext.enforceCallingOrSelfPermission( 20764 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20765 "Only package verification agents can read the verifier device identity"); 20766 20767 synchronized (mPackages) { 20768 return mSettings.getVerifierDeviceIdentityLPw(); 20769 } 20770 } 20771 20772 @Override 20773 public void setPermissionEnforced(String permission, boolean enforced) { 20774 // TODO: Now that we no longer change GID for storage, this should to away. 20775 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20776 "setPermissionEnforced"); 20777 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20778 synchronized (mPackages) { 20779 if (mSettings.mReadExternalStorageEnforced == null 20780 || mSettings.mReadExternalStorageEnforced != enforced) { 20781 mSettings.mReadExternalStorageEnforced = enforced; 20782 mSettings.writeLPr(); 20783 } 20784 } 20785 // kill any non-foreground processes so we restart them and 20786 // grant/revoke the GID. 20787 final IActivityManager am = ActivityManagerNative.getDefault(); 20788 if (am != null) { 20789 final long token = Binder.clearCallingIdentity(); 20790 try { 20791 am.killProcessesBelowForeground("setPermissionEnforcement"); 20792 } catch (RemoteException e) { 20793 } finally { 20794 Binder.restoreCallingIdentity(token); 20795 } 20796 } 20797 } else { 20798 throw new IllegalArgumentException("No selective enforcement for " + permission); 20799 } 20800 } 20801 20802 @Override 20803 @Deprecated 20804 public boolean isPermissionEnforced(String permission) { 20805 return true; 20806 } 20807 20808 @Override 20809 public boolean isStorageLow() { 20810 final long token = Binder.clearCallingIdentity(); 20811 try { 20812 final DeviceStorageMonitorInternal 20813 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20814 if (dsm != null) { 20815 return dsm.isMemoryLow(); 20816 } else { 20817 return false; 20818 } 20819 } finally { 20820 Binder.restoreCallingIdentity(token); 20821 } 20822 } 20823 20824 @Override 20825 public IPackageInstaller getPackageInstaller() { 20826 return mInstallerService; 20827 } 20828 20829 private boolean userNeedsBadging(int userId) { 20830 int index = mUserNeedsBadging.indexOfKey(userId); 20831 if (index < 0) { 20832 final UserInfo userInfo; 20833 final long token = Binder.clearCallingIdentity(); 20834 try { 20835 userInfo = sUserManager.getUserInfo(userId); 20836 } finally { 20837 Binder.restoreCallingIdentity(token); 20838 } 20839 final boolean b; 20840 if (userInfo != null && userInfo.isManagedProfile()) { 20841 b = true; 20842 } else { 20843 b = false; 20844 } 20845 mUserNeedsBadging.put(userId, b); 20846 return b; 20847 } 20848 return mUserNeedsBadging.valueAt(index); 20849 } 20850 20851 @Override 20852 public KeySet getKeySetByAlias(String packageName, String alias) { 20853 if (packageName == null || alias == null) { 20854 return null; 20855 } 20856 synchronized(mPackages) { 20857 final PackageParser.Package pkg = mPackages.get(packageName); 20858 if (pkg == null) { 20859 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20860 throw new IllegalArgumentException("Unknown package: " + packageName); 20861 } 20862 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20863 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20864 } 20865 } 20866 20867 @Override 20868 public KeySet getSigningKeySet(String packageName) { 20869 if (packageName == null) { 20870 return null; 20871 } 20872 synchronized(mPackages) { 20873 final PackageParser.Package pkg = mPackages.get(packageName); 20874 if (pkg == null) { 20875 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20876 throw new IllegalArgumentException("Unknown package: " + packageName); 20877 } 20878 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20879 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20880 throw new SecurityException("May not access signing KeySet of other apps."); 20881 } 20882 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20883 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20884 } 20885 } 20886 20887 @Override 20888 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20889 if (packageName == null || ks == null) { 20890 return false; 20891 } 20892 synchronized(mPackages) { 20893 final PackageParser.Package pkg = mPackages.get(packageName); 20894 if (pkg == null) { 20895 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20896 throw new IllegalArgumentException("Unknown package: " + packageName); 20897 } 20898 IBinder ksh = ks.getToken(); 20899 if (ksh instanceof KeySetHandle) { 20900 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20901 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20902 } 20903 return false; 20904 } 20905 } 20906 20907 @Override 20908 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20909 if (packageName == null || ks == null) { 20910 return false; 20911 } 20912 synchronized(mPackages) { 20913 final PackageParser.Package pkg = mPackages.get(packageName); 20914 if (pkg == null) { 20915 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20916 throw new IllegalArgumentException("Unknown package: " + packageName); 20917 } 20918 IBinder ksh = ks.getToken(); 20919 if (ksh instanceof KeySetHandle) { 20920 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20921 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20922 } 20923 return false; 20924 } 20925 } 20926 20927 private void deletePackageIfUnusedLPr(final String packageName) { 20928 PackageSetting ps = mSettings.mPackages.get(packageName); 20929 if (ps == null) { 20930 return; 20931 } 20932 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20933 // TODO Implement atomic delete if package is unused 20934 // It is currently possible that the package will be deleted even if it is installed 20935 // after this method returns. 20936 mHandler.post(new Runnable() { 20937 public void run() { 20938 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20939 } 20940 }); 20941 } 20942 } 20943 20944 /** 20945 * Check and throw if the given before/after packages would be considered a 20946 * downgrade. 20947 */ 20948 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20949 throws PackageManagerException { 20950 if (after.versionCode < before.mVersionCode) { 20951 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20952 "Update version code " + after.versionCode + " is older than current " 20953 + before.mVersionCode); 20954 } else if (after.versionCode == before.mVersionCode) { 20955 if (after.baseRevisionCode < before.baseRevisionCode) { 20956 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20957 "Update base revision code " + after.baseRevisionCode 20958 + " is older than current " + before.baseRevisionCode); 20959 } 20960 20961 if (!ArrayUtils.isEmpty(after.splitNames)) { 20962 for (int i = 0; i < after.splitNames.length; i++) { 20963 final String splitName = after.splitNames[i]; 20964 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20965 if (j != -1) { 20966 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20967 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20968 "Update split " + splitName + " revision code " 20969 + after.splitRevisionCodes[i] + " is older than current " 20970 + before.splitRevisionCodes[j]); 20971 } 20972 } 20973 } 20974 } 20975 } 20976 } 20977 20978 private static class MoveCallbacks extends Handler { 20979 private static final int MSG_CREATED = 1; 20980 private static final int MSG_STATUS_CHANGED = 2; 20981 20982 private final RemoteCallbackList<IPackageMoveObserver> 20983 mCallbacks = new RemoteCallbackList<>(); 20984 20985 private final SparseIntArray mLastStatus = new SparseIntArray(); 20986 20987 public MoveCallbacks(Looper looper) { 20988 super(looper); 20989 } 20990 20991 public void register(IPackageMoveObserver callback) { 20992 mCallbacks.register(callback); 20993 } 20994 20995 public void unregister(IPackageMoveObserver callback) { 20996 mCallbacks.unregister(callback); 20997 } 20998 20999 @Override 21000 public void handleMessage(Message msg) { 21001 final SomeArgs args = (SomeArgs) msg.obj; 21002 final int n = mCallbacks.beginBroadcast(); 21003 for (int i = 0; i < n; i++) { 21004 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21005 try { 21006 invokeCallback(callback, msg.what, args); 21007 } catch (RemoteException ignored) { 21008 } 21009 } 21010 mCallbacks.finishBroadcast(); 21011 args.recycle(); 21012 } 21013 21014 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21015 throws RemoteException { 21016 switch (what) { 21017 case MSG_CREATED: { 21018 callback.onCreated(args.argi1, (Bundle) args.arg2); 21019 break; 21020 } 21021 case MSG_STATUS_CHANGED: { 21022 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21023 break; 21024 } 21025 } 21026 } 21027 21028 private void notifyCreated(int moveId, Bundle extras) { 21029 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21030 21031 final SomeArgs args = SomeArgs.obtain(); 21032 args.argi1 = moveId; 21033 args.arg2 = extras; 21034 obtainMessage(MSG_CREATED, args).sendToTarget(); 21035 } 21036 21037 private void notifyStatusChanged(int moveId, int status) { 21038 notifyStatusChanged(moveId, status, -1); 21039 } 21040 21041 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21042 Slog.v(TAG, "Move " + moveId + " status " + status); 21043 21044 final SomeArgs args = SomeArgs.obtain(); 21045 args.argi1 = moveId; 21046 args.argi2 = status; 21047 args.arg3 = estMillis; 21048 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21049 21050 synchronized (mLastStatus) { 21051 mLastStatus.put(moveId, status); 21052 } 21053 } 21054 } 21055 21056 private final static class OnPermissionChangeListeners extends Handler { 21057 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21058 21059 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21060 new RemoteCallbackList<>(); 21061 21062 public OnPermissionChangeListeners(Looper looper) { 21063 super(looper); 21064 } 21065 21066 @Override 21067 public void handleMessage(Message msg) { 21068 switch (msg.what) { 21069 case MSG_ON_PERMISSIONS_CHANGED: { 21070 final int uid = msg.arg1; 21071 handleOnPermissionsChanged(uid); 21072 } break; 21073 } 21074 } 21075 21076 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21077 mPermissionListeners.register(listener); 21078 21079 } 21080 21081 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21082 mPermissionListeners.unregister(listener); 21083 } 21084 21085 public void onPermissionsChanged(int uid) { 21086 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21087 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21088 } 21089 } 21090 21091 private void handleOnPermissionsChanged(int uid) { 21092 final int count = mPermissionListeners.beginBroadcast(); 21093 try { 21094 for (int i = 0; i < count; i++) { 21095 IOnPermissionsChangeListener callback = mPermissionListeners 21096 .getBroadcastItem(i); 21097 try { 21098 callback.onPermissionsChanged(uid); 21099 } catch (RemoteException e) { 21100 Log.e(TAG, "Permission listener is dead", e); 21101 } 21102 } 21103 } finally { 21104 mPermissionListeners.finishBroadcast(); 21105 } 21106 } 21107 } 21108 21109 private class PackageManagerInternalImpl extends PackageManagerInternal { 21110 @Override 21111 public void setLocationPackagesProvider(PackagesProvider provider) { 21112 synchronized (mPackages) { 21113 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21114 } 21115 } 21116 21117 @Override 21118 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21119 synchronized (mPackages) { 21120 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21121 } 21122 } 21123 21124 @Override 21125 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21126 synchronized (mPackages) { 21127 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21128 } 21129 } 21130 21131 @Override 21132 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21133 synchronized (mPackages) { 21134 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21135 } 21136 } 21137 21138 @Override 21139 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21140 synchronized (mPackages) { 21141 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21142 } 21143 } 21144 21145 @Override 21146 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21147 synchronized (mPackages) { 21148 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21149 } 21150 } 21151 21152 @Override 21153 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21154 synchronized (mPackages) { 21155 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21156 packageName, userId); 21157 } 21158 } 21159 21160 @Override 21161 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21162 synchronized (mPackages) { 21163 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21164 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21165 packageName, userId); 21166 } 21167 } 21168 21169 @Override 21170 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21171 synchronized (mPackages) { 21172 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21173 packageName, userId); 21174 } 21175 } 21176 21177 @Override 21178 public void setKeepUninstalledPackages(final List<String> packageList) { 21179 Preconditions.checkNotNull(packageList); 21180 List<String> removedFromList = null; 21181 synchronized (mPackages) { 21182 if (mKeepUninstalledPackages != null) { 21183 final int packagesCount = mKeepUninstalledPackages.size(); 21184 for (int i = 0; i < packagesCount; i++) { 21185 String oldPackage = mKeepUninstalledPackages.get(i); 21186 if (packageList != null && packageList.contains(oldPackage)) { 21187 continue; 21188 } 21189 if (removedFromList == null) { 21190 removedFromList = new ArrayList<>(); 21191 } 21192 removedFromList.add(oldPackage); 21193 } 21194 } 21195 mKeepUninstalledPackages = new ArrayList<>(packageList); 21196 if (removedFromList != null) { 21197 final int removedCount = removedFromList.size(); 21198 for (int i = 0; i < removedCount; i++) { 21199 deletePackageIfUnusedLPr(removedFromList.get(i)); 21200 } 21201 } 21202 } 21203 } 21204 21205 @Override 21206 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21207 synchronized (mPackages) { 21208 // If we do not support permission review, done. 21209 if (!mPermissionReviewRequired) { 21210 return false; 21211 } 21212 21213 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21214 if (packageSetting == null) { 21215 return false; 21216 } 21217 21218 // Permission review applies only to apps not supporting the new permission model. 21219 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21220 return false; 21221 } 21222 21223 // Legacy apps have the permission and get user consent on launch. 21224 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21225 return permissionsState.isPermissionReviewRequired(userId); 21226 } 21227 } 21228 21229 @Override 21230 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21231 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21232 } 21233 21234 @Override 21235 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21236 int userId) { 21237 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21238 } 21239 21240 @Override 21241 public void setDeviceAndProfileOwnerPackages( 21242 int deviceOwnerUserId, String deviceOwnerPackage, 21243 SparseArray<String> profileOwnerPackages) { 21244 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21245 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21246 } 21247 21248 @Override 21249 public boolean isPackageDataProtected(int userId, String packageName) { 21250 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21251 } 21252 21253 @Override 21254 public boolean wasPackageEverLaunched(String packageName, int userId) { 21255 synchronized (mPackages) { 21256 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21257 } 21258 } 21259 21260 @Override 21261 public void grantRuntimePermission(String packageName, String name, int userId, 21262 boolean overridePolicy) { 21263 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21264 overridePolicy); 21265 } 21266 21267 @Override 21268 public void revokeRuntimePermission(String packageName, String name, int userId, 21269 boolean overridePolicy) { 21270 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21271 overridePolicy); 21272 } 21273 21274 @Override 21275 public String getNameForUid(int uid) { 21276 return PackageManagerService.this.getNameForUid(uid); 21277 } 21278 } 21279 21280 @Override 21281 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21282 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21283 synchronized (mPackages) { 21284 final long identity = Binder.clearCallingIdentity(); 21285 try { 21286 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21287 packageNames, userId); 21288 } finally { 21289 Binder.restoreCallingIdentity(identity); 21290 } 21291 } 21292 } 21293 21294 private static void enforceSystemOrPhoneCaller(String tag) { 21295 int callingUid = Binder.getCallingUid(); 21296 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21297 throw new SecurityException( 21298 "Cannot call " + tag + " from UID " + callingUid); 21299 } 21300 } 21301 21302 boolean isHistoricalPackageUsageAvailable() { 21303 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21304 } 21305 21306 /** 21307 * Return a <b>copy</b> of the collection of packages known to the package manager. 21308 * @return A copy of the values of mPackages. 21309 */ 21310 Collection<PackageParser.Package> getPackages() { 21311 synchronized (mPackages) { 21312 return new ArrayList<>(mPackages.values()); 21313 } 21314 } 21315 21316 /** 21317 * Logs process start information (including base APK hash) to the security log. 21318 * @hide 21319 */ 21320 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21321 String apkFile, int pid) { 21322 if (!SecurityLog.isLoggingEnabled()) { 21323 return; 21324 } 21325 Bundle data = new Bundle(); 21326 data.putLong("startTimestamp", System.currentTimeMillis()); 21327 data.putString("processName", processName); 21328 data.putInt("uid", uid); 21329 data.putString("seinfo", seinfo); 21330 data.putString("apkFile", apkFile); 21331 data.putInt("pid", pid); 21332 Message msg = mProcessLoggingHandler.obtainMessage( 21333 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21334 msg.setData(data); 21335 mProcessLoggingHandler.sendMessage(msg); 21336 } 21337 21338 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21339 return mCompilerStats.getPackageStats(pkgName); 21340 } 21341 21342 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21343 return getOrCreateCompilerPackageStats(pkg.packageName); 21344 } 21345 21346 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21347 return mCompilerStats.getOrCreatePackageStats(pkgName); 21348 } 21349 21350 public void deleteCompilerPackageStats(String pkgName) { 21351 mCompilerStats.deletePackageStats(pkgName); 21352 } 21353} 21354